Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

feat: organisation invitations & refactor redux reducers

Blue Mouse7bf17ba7f864
diff --git a/backend/apps/cloud/src/action-tokens/action-tokens.service.ts b/backend/apps/cloud/src/action-tokens/action-tokens.service.ts
index 487ac4953..2ff4a7be1 100644
--- a/backend/apps/cloud/src/action-tokens/action-tokens.service.ts
+++ b/backend/apps/cloud/src/action-tokens/action-tokens.service.ts
@@ -24,22 +24,22 @@ export class ActionTokensService {
user: User,
action: ActionTokenType,
newValue: string = null,
- ): Promise<ActionToken> {
+ ) {
return this.actionTokensRepository.save({ user, action, newValue })
}
- async find(id: string): Promise<ActionToken> {
+ async find(id: string) {
return this.actionTokensRepository.findOneOrFail({
where: { id },
relations: ['user'],
})
}
- async delete(id: string): Promise<void> {
+ async delete(id: string) {
await this.actionTokensRepository.delete(id)
}
- public async createActionToken(
+ async createActionToken(
userId: string,
action: ActionTokenType,
newValue?: string,
@@ -51,14 +51,14 @@ export class ActionTokensService {
})
}
- public async findActionToken(token: string) {
+ async findActionToken(token: string) {
return this.actionTokensRepository.findOne({
where: { id: token },
relations: ['user'],
})
}
- public async deleteActionToken(token: string) {
+ async deleteActionToken(token: string) {
await this.actionTokensRepository.delete(token)
}
diff --git a/backend/apps/cloud/src/common/templates/en/organization-invitation.html b/backend/apps/cloud/src/common/templates/en/organisation-invitation.html
similarity index 100%
rename from backend/apps/cloud/src/common/templates/en/organization-invitation.html
rename to backend/apps/cloud/src/common/templates/en/organisation-invitation.html
diff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.ts
index b72617eb9..95f387c3c 100644
--- a/backend/apps/cloud/src/mailer/mailer.service.ts
+++ b/backend/apps/cloud/src/mailer/mailer.service.ts
@@ -66,6 +66,11 @@ const metaInfoJson = {
en: () => 'You have been invited to join the project',
},
},
+ [LetterTemplate.OrganisationInvitation]: {
+ subject: {
+ en: () => 'You have been invited to join the organisation',
+ },
+ },
[LetterTemplate.TwoFAOn]: {
subject: {
en: () => '2FA has been enabled on your Swetrix account',
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index 4dd13dbae..75c94ffdd 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -16,7 +16,6 @@ import {
} from '@nestjs/common'
import { ApiBearerAuth, ApiQuery, ApiResponse } from '@nestjs/swagger'
import { isEmpty as _isEmpty, find as _find, trim as _trim } from 'lodash'
-import { FindOptionsWhere, ILike } from 'typeorm'
import { JwtAccessTokenGuard } from '../auth/guards/jwt-access-token.guard'
import { RolesGuard } from '../auth/guards/roles.guard'
@@ -72,29 +71,7 @@ export class OrganisationController {
): Promise<Pagination<Organisation> | Organisation[] | object> {
this.logger.log({ userId, take, skip }, 'GET /organisation')
- let where: FindOptionsWhere<Organisation> | FindOptionsWhere<Organisation>[]
-
- if (search) {
- where = {
- members: {
- user: { id: userId },
- },
- name: ILike(`%${search}%`),
- }
- } else {
- where = {
- members: {
- user: { id: userId },
- },
- }
- }
-
- const paginated = await this.organisationService.paginate(
- { take, skip },
- where,
- )
-
- return paginated
+ return this.organisationService.paginate({ take, skip }, userId, search)
}
@ApiBearerAuth()
diff --git a/backend/apps/cloud/src/organisation/organisation.service.ts b/backend/apps/cloud/src/organisation/organisation.service.ts
index d35100acc..badb4c63f 100644
--- a/backend/apps/cloud/src/organisation/organisation.service.ts
+++ b/backend/apps/cloud/src/organisation/organisation.service.ts
@@ -132,31 +132,44 @@ export class OrganisationService {
async paginate(
options: PaginationOptionsInterface,
- where?: FindOptionsWhere<Organisation> | FindOptionsWhere<Organisation>[],
+ userId: string,
+ search?: string,
) {
- const [results, total] = await this.organisationRepository.findAndCount({
- take: options.take || 100,
- skip: options.skip || 0,
- where,
- order: {
- name: 'ASC',
- },
- relations: ['members', 'members.user'],
- select: {
- id: true,
- name: true,
- members: {
- id: true,
- role: true,
- confirmed: true,
- created: true,
- user: {
- id: true,
- email: true,
- },
- },
- },
- })
+ const queryBuilder = this.organisationRepository
+ .createQueryBuilder('organisation')
+ // We do left join twice to avoid the issue with TypeORM where it does not return
+ // all the relations when filtering by one of them
+ // see: https://github.com/typeorm/typeorm/issues/3731
+ .leftJoin('organisation.members', 'membersFilter')
+ .leftJoin('membersFilter.user', 'userFilter')
+ .leftJoinAndSelect('organisation.members', 'members')
+ .leftJoinAndSelect('members.user', 'user')
+ .select([
+ 'organisation.id',
+ 'organisation.name',
+ 'members.id',
+ 'members.role',
+ 'members.confirmed',
+ 'members.created',
+ 'user.email',
+ ])
+ .orderBy('organisation.name', 'ASC')
+ .take(options.take || 100)
+ .skip(options.skip || 0)
+
+ if (userId) {
+ queryBuilder.andWhere('userFilter.id = :userId', {
+ userId,
+ })
+ }
+
+ if (search) {
+ queryBuilder.andWhere('LOWER(organisation.name) LIKE LOWER(:search)', {
+ search: `%${search.trim()}%`,
+ })
+ }
+
+ const [results, total] = await queryBuilder.getManyAndCount()
return new Pagination<Organisation>({
results,
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index 100c5fc19..fe11316ed 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -37,7 +37,7 @@ import { catchError, firstValueFrom, map, of } from 'rxjs'
import { Markup } from 'telegraf'
import { JwtAccessTokenGuard } from '../auth/guards'
-import { Public, Roles, CurrentUserId } from '../auth/decorators'
+import { Public, Roles, CurrentUserId, Auth } from '../auth/decorators'
import { TelegramService } from '../integrations/telegram/telegram.service'
import { UserService } from './user.service'
import { ProjectService, deleteProjectRedis } from '../project/project.service'
@@ -76,6 +76,7 @@ import {
} from '../common/utils'
import { IUsageInfo, IMetaInfo } from './interfaces'
import { ReportFrequency } from '../project/enums'
+import { OrganisationService } from '../organisation/organisation.service'
dayjs.extend(utc)
@@ -94,6 +95,7 @@ export class UserController {
private readonly logger: AppLoggerService,
private readonly telegramService: TelegramService,
private readonly httpService: HttpService,
+ private readonly organisationService: OrganisationService,
) {}
@ApiBearerAuth()
@@ -424,67 +426,185 @@ export class UserController {
}
@ApiBearerAuth()
- @Delete('/share/:shareId')
+ @Delete('/share/:actionId')
@HttpCode(204)
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204, description: 'Empty body' })
async deleteShare(
- @Param('shareId') shareId: string,
+ @Param('actionId') actionId: string,
@CurrentUserId() uid: string,
- ): Promise<any> {
- this.logger.log({ uid, shareId }, 'DELETE /user/share/:shareId')
+ ) {
+ this.logger.log({ uid, actionId }, 'DELETE /user/share/:actionId')
+
+ let isActionToken = false
+
+ const actionToken = await this.actionTokensService.getActionToken(actionId)
+
+ if (actionToken) {
+ isActionToken = true
+ }
const share = await this.projectService.findOneShare({
- where: { id: shareId },
+ where: { id: actionToken?.newValue || actionId },
relations: ['user', 'project'],
})
if (_isEmpty(share)) {
- throw new BadRequestException('The provided share ID is not valid')
+ throw new BadRequestException(
+ 'This invitation does not exist or is no longer valid',
+ )
}
if (share.user?.id !== uid) {
- throw new BadRequestException('You are not allowed to delete this share')
+ throw new BadRequestException(
+ 'You are not allowed to reject this invitation',
+ )
}
- await this.projectService.deleteShare(shareId)
+ await this.projectService.deleteShare(share.id)
await deleteProjectRedis(share.project.id)
- return 'shareDeleted'
+ if (isActionToken) {
+ await this.actionTokensService.delete(actionId)
+ }
}
@ApiBearerAuth()
- @Get('/share/:shareId')
+ @Get('/share/:actionId')
@HttpCode(204)
@UseGuards(JwtAccessTokenGuard, RolesGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
@ApiResponse({ status: 204, description: 'Empty body' })
async acceptShare(
- @Param('shareId') shareId: string,
+ @Param('actionId') actionId: string,
@CurrentUserId() uid: string,
- ): Promise<any> {
- this.logger.log({ uid, shareId }, 'GET /user/share/:shareId')
+ ) {
+ this.logger.log({ uid, actionId }, 'GET /user/share/:actionId')
+
+ let isActionToken = false
+
+ const actionToken = await this.actionTokensService.getActionToken(actionId)
+
+ if (actionToken) {
+ isActionToken = true
+ }
const share = await this.projectService.findOneShare({
- where: { id: shareId },
+ where: { id: actionToken?.newValue || actionId },
relations: ['user', 'project'],
})
if (_isEmpty(share)) {
- throw new BadRequestException('The provided share ID is not valid')
+ throw new BadRequestException(
+ 'This invitation does not exist or is no longer valid',
+ )
}
if (share.user?.id !== uid) {
- throw new BadRequestException('You are not allowed to delete this share')
+ throw new BadRequestException(
+ 'You are not allowed to accept this invitation',
+ )
}
- share.confirmed = true
-
- await this.projectService.updateShare(shareId, share)
+ await this.projectService.updateShare(share.id, {
+ confirmed: true,
+ })
await deleteProjectRedis(share.project.id)
- return 'shareAccepted'
+ if (isActionToken) {
+ await this.actionTokensService.delete(actionId)
+ }
+ }
+
+ @ApiBearerAuth()
+ @Delete('/organisation/:actionId')
+ @HttpCode(204)
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @ApiResponse({ status: 204, description: 'Empty body' })
+ async rejectOrganisationInvitation(
+ @Param('actionId') actionId: string,
+ @CurrentUserId() uid: string,
+ ) {
+ this.logger.log({ uid, actionId }, 'DELETE /user/organisation/:actionId')
+
+ let isActionToken = false
+
+ const actionToken = await this.actionTokensService.getActionToken(actionId)
+
+ if (actionToken) {
+ isActionToken = true
+ }
+
+ const membership = await this.organisationService.findOneMembership({
+ where: { id: actionToken?.newValue || actionId },
+ relations: ['user'],
+ })
+
+ if (_isEmpty(membership)) {
+ throw new BadRequestException(
+ 'This invitation does not exist or is no longer valid',
+ )
+ }
+
+ if (membership.user?.id !== uid) {
+ throw new BadRequestException(
+ 'You are not allowed to reject this invitation from this account',
+ )
+ }
+
+ await this.organisationService.deleteMembership(membership.id)
+
+ if (isActionToken) {
+ await this.actionTokensService.delete(actionId)
+ }
+ }
+
+ @ApiBearerAuth()
+ @Post('/organisation/:actionId')
+ @HttpCode(204)
+ @UseGuards(JwtAccessTokenGuard, RolesGuard)
+ @Auth([], true)
+ @ApiResponse({ status: 204, description: 'Empty body' })
+ async acceptOrganisationInvitation(
+ @Param('actionId') actionId: string,
+ @CurrentUserId() uid: string,
+ ): Promise<any> {
+ this.logger.log({ uid, actionId }, 'POST /user/organisation/:actionId')
+
+ let isActionToken = false
+
+ const actionToken = await this.actionTokensService.getActionToken(actionId)
+
+ if (actionToken) {
+ isActionToken = true
+ }
+
+ const membership = await this.organisationService.findOneMembership({
+ where: { id: actionToken?.newValue || actionId },
+ relations: ['user'],
+ })
+
+ if (_isEmpty(membership)) {
+ throw new BadRequestException(
+ 'This invitation does not exist or is no longer valid',
+ )
+ }
+
+ if (membership.user?.id !== uid) {
+ throw new BadRequestException(
+ 'You are not allowed to accept this invitation from this account',
+ )
+ }
+
+ await this.organisationService.updateMembership(membership.id, {
+ confirmed: true,
+ })
+
+ if (isActionToken) {
+ await this.actionTokensService.delete(actionId)
+ }
}
@ApiBearerAuth()
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index 16b9025d4..e310eea32 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -40,7 +40,6 @@ import { UserGoogleDTO } from './dto/user-google.dto'
import { UserGithubDTO } from './dto/user-github.dto'
import { EMAIL_ACTION_ENCRYPTION_KEY } from '../common/constants'
import { ReportFrequency } from '../project/enums'
-import { OrganisationService } from '../organisation/organisation.service'
dayjs.extend(utc)
@@ -110,7 +109,6 @@ export class UserService {
@InjectRepository(DeleteFeedback)
private readonly deleteFeedbackRepository: Repository<DeleteFeedback>,
private readonly payoutsService: PayoutsService,
- private readonly organisationService: OrganisationService,
) {}
async create(
diff --git a/web/app/App.tsx b/web/app/App.tsx
index 9aac44a70..d7cac8417 100644
--- a/web/app/App.tsx
+++ b/web/app/App.tsx
@@ -47,7 +47,7 @@ const App = ({ ssrTheme, ssrAuthenticated }: AppProps) => {
if (accessToken && !reduxAuthenticated) {
try {
const me = await authMe()
- dispatch(authActions.loginSuccessful(me))
+ dispatch(authActions.authSuccessful(me))
} catch (reason) {
dispatch(authActions.logout())
dispatch(sagaActions.logout(false, false))
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 6459f0e0d..4fc195ba3 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -346,6 +346,30 @@ export const changeOrganisationRole = (memberId: string, role: Role) =>
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
+export const inviteOrganisationMember = (organisationId: string, data: { email: string; role: Role }) =>
+ api
+ .post(`/organisation/${organisationId}/invite`, data)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
+export const acceptOrganisationInvitation = (tokenId: string) =>
+ api
+ .post(`/user/organisation/${tokenId}`)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
+export const rejectOrganisationInvitation = (tokenId: string) =>
+ api
+ .delete(`/user/organisation/${tokenId}`)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
export const removeOrganisationMember = (memberId: string) =>
api
.delete(`/organisation/member/${memberId}`)
@@ -876,17 +900,17 @@ export const deleteShareProjectUsers = (pid: string, userId: string) =>
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
-export const deleteShareProject = (pid: string) =>
+export const rejectProjectShare = (actionId: string) =>
api
- .delete(`user/share/${pid}`)
+ .delete(`/user/share/${actionId}`)
.then((response) => response.data)
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
-export const acceptShareProject = (shareId: string) =>
+export const acceptProjectShare = (actionId: string) =>
api
- .get(`user/share/${shareId}`)
+ .post(`/user/share/${actionId}`)
.then((response) => response.data)
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
diff --git a/web/app/components/GithubAuth.tsx b/web/app/components/GithubAuth.tsx
index c540ff08a..40b9b0196 100644
--- a/web/app/components/GithubAuth.tsx
+++ b/web/app/components/GithubAuth.tsx
@@ -1,18 +1,17 @@
import React from 'react'
-import type i18next from 'i18next'
import { useTranslation } from 'react-i18next'
import { useSelector } from 'react-redux'
import cx from 'clsx'
import Button from 'ui/Button'
-import { StateType } from 'redux/store/index'
+import { StateType, useAppDispatch } from 'redux/store/index'
import GithubDarkSVG from 'ui/icons/GithubDark'
import GithubLightSVG from 'ui/icons/GithubLight'
import { SSO_PROVIDERS, isBrowser } from 'redux/constants'
+import sagaActions from 'redux/sagas/actions'
interface IGoogleAuth {
setIsLoading: (isLoading: boolean) => void
- authSSO: (provider: string, dontRemember: boolean, t: typeof i18next.t, callback: (res: any) => void) => void
ssrTheme: string
callback?: any
dontRemember?: boolean
@@ -22,7 +21,6 @@ interface IGoogleAuth {
const GithubAuth: React.FC<IGoogleAuth> = ({
setIsLoading,
- authSSO,
dontRemember,
callback = () => {},
isMiniButton,
@@ -30,12 +28,13 @@ const GithubAuth: React.FC<IGoogleAuth> = ({
ssrTheme,
}) => {
const { t } = useTranslation()
+ const dispatch = useAppDispatch()
const reduxTheme = useSelector((state: StateType) => state.ui.theme.theme)
const theme = isBrowser ? reduxTheme : ssrTheme
const googleLogin = async () => {
setIsLoading(true)
- authSSO(SSO_PROVIDERS.GITHUB, dontRemember as boolean, t, callback)
+ dispatch(sagaActions.authSSO(SSO_PROVIDERS.GITHUB, Boolean(dontRemember), t, callback))
}
if (isMiniButton) {
diff --git a/web/app/components/GoogleAuth.tsx b/web/app/components/GoogleAuth.tsx
index c40b3a0df..c138ac28d 100644
--- a/web/app/components/GoogleAuth.tsx
+++ b/web/app/components/GoogleAuth.tsx
@@ -1,15 +1,15 @@
import React from 'react'
-import type i18next from 'i18next'
import { useTranslation } from 'react-i18next'
import cx from 'clsx'
import Button from 'ui/Button'
import GoogleGSVG from 'ui/icons/GoogleG'
import { SSO_PROVIDERS } from 'redux/constants'
+import sagaActions from 'redux/sagas/actions'
+import { useAppDispatch } from 'redux/store'
interface IGoogleAuth {
setIsLoading: (isLoading: boolean) => void
- authSSO: (provider: string, dontRemember: boolean, t: typeof i18next.t, callback: (res: any) => void) => void
callback?: any
dontRemember?: boolean
isMiniButton?: boolean
@@ -18,17 +18,17 @@ interface IGoogleAuth {
const GoogleAuth: React.FC<IGoogleAuth> = ({
setIsLoading,
- authSSO,
dontRemember,
callback = () => {},
isMiniButton,
className,
}) => {
+ const dispatch = useAppDispatch()
const { t } = useTranslation()
const googleLogin = async () => {
setIsLoading(true)
- authSSO(SSO_PROVIDERS.GOOGLE, dontRemember as boolean, t, callback)
+ dispatch(sagaActions.authSSO(SSO_PROVIDERS.GOOGLE, Boolean(dontRemember), t, callback))
}
if (isMiniButton) {
diff --git a/web/app/components/marketing/Pricing.tsx b/web/app/components/marketing/Pricing.tsx
index 6bb93a579..2377c9c04 100644
--- a/web/app/components/marketing/Pricing.tsx
+++ b/web/app/components/marketing/Pricing.tsx
@@ -109,7 +109,7 @@ const Pricing = ({ authenticated, isBillingPage }: IPricing) => {
try {
const me = await authMe()
- dispatch(authActions.loginSuccessful(me))
+ dispatch(authActions.authSuccessful(me))
dispatch(authActions.finishLoading())
} catch (reason) {
dispatch(authActions.logout())
@@ -204,7 +204,7 @@ const Pricing = ({ authenticated, isBillingPage }: IPricing) => {
try {
const me = await authMe()
- dispatch(authActions.loginSuccessful(me))
+ dispatch(authActions.authSuccessful(me))
dispatch(authActions.finishLoading())
} catch (reason) {
dispatch(authActions.logout())
diff --git a/web/app/pages/Auth/Signin/Signin.container.tsx b/web/app/pages/Auth/Signin/Signin.container.tsx
deleted file mode 100644
index d2485eb47..000000000
--- a/web/app/pages/Auth/Signin/Signin.container.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { connect } from 'react-redux'
-import type i18next from 'i18next'
-import sagaActions from 'redux/sagas/actions'
-import { authActions } from 'redux/reducers/auth'
-import { AppDispatch } from 'redux/store'
-import { IUser } from 'redux/models/IUser'
-import Signin from './Signin'
-
-const mapDispatchToProps = (dispatch: AppDispatch) => ({
- login: (
- data: {
- email: string
- password: string
- dontRemember: boolean
- },
- callback: () => void,
- ) => {
- dispatch(sagaActions.loginAsync(data, callback))
- },
- loginSuccess: (user: IUser) => {
- dispatch(authActions.loginSuccessful(user))
- dispatch(sagaActions.loadProjects())
- },
- authSSO: (provider: string, dontRemember: boolean, t: typeof i18next.t, callback: (res: any) => void) => {
- dispatch(sagaActions.authSSO(provider, dontRemember, t, callback))
- },
-})
-
-export default connect(null, mapDispatchToProps)(Signin)
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index 651211882..635abad99 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -1,5 +1,4 @@
import React, { useState, useEffect, memo } from 'react'
-import type i18next from 'i18next'
import { Link } from '@remix-run/react'
import { useTranslation, Trans } from 'react-i18next'
import _keys from 'lodash/keys'
@@ -16,34 +15,27 @@ import Button from 'ui/Button'
import Checkbox from 'ui/Checkbox'
import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from 'utils/validator'
import { isSelfhosted, TRIAL_DAYS } from 'redux/constants'
-import { IUser } from 'redux/models/IUser'
import { submit2FA } from 'api'
import { setAccessToken, removeAccessToken } from 'utils/accessToken'
import { setRefreshToken, removeRefreshToken } from 'utils/refreshToken'
+import { useAppDispatch } from 'redux/store'
+import { authActions } from 'redux/reducers/auth'
+import sagaActions from 'redux/sagas/actions'
-interface ISigninForm {
+interface SigninForm {
email: string
password: string
dontRemember: boolean
}
-interface ISignin {
- login: (
- data: {
- email: string
- password: string
- dontRemember: boolean
- },
- callback: (result: boolean, twoFARequired: boolean) => void,
- ) => void
- loginSuccess: (user: IUser) => void
- authSSO: (provider: string, dontRemember: boolean, t: typeof i18next.t, callback: (res: any) => void) => void
+interface SigninProps {
ssrTheme: string
}
-const Signin = ({ login, loginSuccess, authSSO, ssrTheme }: ISignin): JSX.Element => {
+const Signin = ({ ssrTheme }: SigninProps) => {
+ const dispatch = useAppDispatch()
const { t } = useTranslation('common')
- const [form, setForm] = useState<ISigninForm>({
+ const [form, setForm] = useState<SigninForm>({
email: '',
password: '',
dontRemember: false,
@@ -98,10 +90,10 @@ const Signin = ({ login, loginSuccess, authSSO, ssrTheme }: ISignin): JSX.Elemen
}
}
- const onSubmit = (data: ISigninForm) => {
+ const onSubmit = (data: SigninForm) => {
if (!isLoading) {
setIsLoading(true)
- login(data, loginCallback)
+ dispatch(sagaActions.loginAsync(data, loginCallback))
}
}
@@ -118,7 +110,8 @@ const Signin = ({ login, loginSuccess, authSSO, ssrTheme }: ISignin): JSX.Elemen
removeRefreshToken()
setAccessToken(accessToken)
setRefreshToken(refreshToken)
- loginSuccess(user)
+ dispatch(authActions.authSuccessful(user))
+ dispatch(sagaActions.loadProjects())
} catch (reason) {
if (_isString(reason)) {
toast.error(reason)
@@ -261,15 +254,9 @@ const Signin = ({ login, loginSuccess, authSSO, ssrTheme }: ISignin): JSX.Elemen
</div>
</div>
<div className='mt-6 grid grid-cols-2 gap-4'>
- <GoogleAuth
- setIsLoading={setIsLoading}
- authSSO={authSSO}
- callback={loginCallback}
- dontRemember={false}
- />
+ <GoogleAuth setIsLoading={setIsLoading} callback={loginCallback} dontRemember={false} />
<GithubAuth
setIsLoading={setIsLoading}
- authSSO={authSSO}
callback={loginCallback}
dontRemember={false}
ssrTheme={ssrTheme}
diff --git a/web/app/pages/Auth/Signin/index.tsx b/web/app/pages/Auth/Signin/index.tsx
index 32520e958..521be81b8 100644
--- a/web/app/pages/Auth/Signin/index.tsx
+++ b/web/app/pages/Auth/Signin/index.tsx
@@ -1,3 +1,3 @@
-import Signin from './Signin.container'
+import Signin from './Signin'
export default Signin
diff --git a/web/app/pages/Auth/Signup/Signup.container.tsx b/web/app/pages/Auth/Signup/Signup.container.tsx
deleted file mode 100644
index 764a71798..000000000
--- a/web/app/pages/Auth/Signup/Signup.container.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { connect } from 'react-redux'
-import type i18next from 'i18next'
-import { AppDispatch, StateType } from 'redux/store'
-import sagaActions from 'redux/sagas/actions'
-import Signup from './Signup'
-
-const mapStateToProps = (state: StateType) => {
- return {
- authenticated: state.auth.authenticated,
- loading: state.auth.loading,
- }
-}
-
-const mapDispatchToProps = (dispatch: AppDispatch) => ({
- signup: (
- data: {
- email: string
- password: string
- repeat: string
- dontRemember: boolean
- checkIfLeaked: boolean
- },
- t: typeof i18next.t,
- callback: (res: any) => void,
- ) => {
- dispatch(sagaActions.signupAsync(data, t, callback))
- },
- authSSO: (provider: string, dontRemember: boolean, t: typeof i18next.t, callback: (res: any) => void) => {
- dispatch(sagaActions.authSSO(provider, dontRemember, t, callback))
- },
-})
-
-export default connect(mapStateToProps, mapDispatchToProps)(Signup)
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index c7b2cd015..1eee9dad3 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -1,5 +1,4 @@
import React, { useState, useEffect } from 'react'
-import type i18next from 'i18next'
import { Link, useNavigate } from '@remix-run/react'
import { useTranslation, Trans } from 'react-i18next'
import _size from 'lodash/size'
@@ -18,8 +17,11 @@ import Button from 'ui/Button'
import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from 'utils/validator'
import { HAVE_I_BEEN_PWNED_URL, TRIAL_DAYS } from 'redux/constants'
import { trackCustom } from 'utils/analytics'
+import { StateType, useAppDispatch } from 'redux/store'
+import sagaActions from 'redux/sagas/actions'
+import { useSelector } from 'react-redux'
-interface ISignupForm {
+interface SignupForm {
email: string
password: string
repeat: string
@@ -29,26 +31,14 @@ interface ISignupForm {
}
interface ISignup {
- signup: (
- data: {
- email: string
- password: string
- repeat: string
- dontRemember: boolean
- checkIfLeaked: boolean
- },
- t: typeof i18next.t,
- callback: (res: any) => void,
- ) => void
- authSSO: (provider: string, dontRemember: boolean, t: typeof i18next.t, callback: (res: any) => void) => void
ssrTheme: string
- authenticated: boolean
- loading: boolean
}
-const Signup = ({ signup, authSSO, ssrTheme, authenticated: reduxAuthenticated, loading }: ISignup): JSX.Element => {
+const Signup = ({ ssrTheme }: ISignup) => {
+ const dispatch = useAppDispatch()
+ const { authenticated: reduxAuthenticated, loading } = useSelector((state: StateType) => state.auth)
const { t } = useTranslation('common')
- const [form, setForm] = useState<ISignupForm>({
+ const [form, setForm] = useState<SignupForm>({
email: '',
password: '',
repeat: '',
@@ -125,10 +115,10 @@ const Signup = ({ signup, authSSO, ssrTheme, authenticated: reduxAuthenticated,
}
}
- const onSubmit = (data: ISignupForm) => {
+ const onSubmit = (data: SignupForm) => {
if (!isLoading) {
setIsLoading(true)
- signup(_omit(data, 'tos'), t, signUpCallback)
+ dispatch(sagaActions.signupAsync(_omit(data, 'tos'), t, signUpCallback))
}
}
@@ -282,15 +272,9 @@ const Signup = ({ signup, authSSO, ssrTheme, authenticated: reduxAuthenticated,
</div>
</div>
<div className='mt-6 grid grid-cols-2 gap-4'>
- <GoogleAuth
- setIsLoading={setIsLoading}
- authSSO={authSSO}
- callback={signUpCallback}
- dontRemember={false}
- />
+ <GoogleAuth setIsLoading={setIsLoading} callback={signUpCallback} dontRemember={false} />
<GithubAuth
setIsLoading={setIsLoading}
- authSSO={authSSO}
callback={signUpCallback}
dontRemember={false}
ssrTheme={ssrTheme}
diff --git a/web/app/pages/Auth/Signup/index.tsx b/web/app/pages/Auth/Signup/index.tsx
index 9144b1fd7..687861491 100644
--- a/web/app/pages/Auth/Signup/index.tsx
+++ b/web/app/pages/Auth/Signup/index.tsx
@@ -1,3 +1,3 @@
-import Signup from './Signup.container'
+import Signup from './Signup'
export default Signup
diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsx
index 6f20d13db..88916a724 100644
--- a/web/app/pages/Dashboard/ProjectCard.tsx
+++ b/web/app/pages/Dashboard/ProjectCard.tsx
@@ -14,9 +14,8 @@ import Modal from 'ui/Modal'
import { Badge, BadgeProps } from 'ui/Badge'
import routes from 'utils/routes'
import { nFormatter, calculateRelativePercentage } from 'utils/generic'
-import { roleViewer } from 'redux/constants'
-import { acceptShareProject } from 'api'
+import { acceptProjectShare } from 'api'
import { IProject } from 'redux/models/IProject'
import { useSelector } from 'react-redux'
@@ -142,10 +141,21 @@ export const ProjectCard = ({ live = 'N/A', project }: ProjectCardProps) => {
throw new Error('Project share not found')
}
- await acceptShareProject(shareId)
+ await acceptProjectShare(shareId)
dispatch(UIActions.setProjectsShareData({ data: { isAccessConfirmed: true }, id }))
- dispatch(authActions.setUserShareData({ data: { confirmed: true }, id: shareId }))
+
+ dispatch(
+ authActions.mergeUser({
+ sharedProjects: user.sharedProjects?.map((item) => {
+ if (item.id === shareId) {
+ return { ...item, isAccessConfirmed: true }
+ }
+
+ return item
+ }),
+ }),
+ )
toast.success(t('apiNotifications.acceptInvitation'))
} catch (reason: any) {
@@ -174,13 +184,11 @@ export const ProjectCard = ({ live = 'N/A', project }: ProjectCardProps) => {
<p className='truncate text-lg font-semibold text-slate-900 dark:text-gray-50'>{name}</p>
<div className='flex items-center gap-2' onClick={(e) => e.stopPropagation()}>
- {role !== roleViewer.role && (
- <Link
- to={_replace(project.isCaptchaProject ? routes.captcha_settings : routes.project_settings, ':id', id)}
+ {role !== 'viewer' && (
+ <AdjustmentsVerticalIcon
+ className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500'
aria-label={`${t('project.settings.settings')} ${name}`}
- >
- <AdjustmentsVerticalIcon className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500' />
- </Link>
+ />
)}
<a
href={_replace(project.isCaptchaProject ? routes.captcha : routes.project, ':id', id)}
diff --git a/web/app/pages/Organisations/AddOrganisation.tsx b/web/app/pages/Organisations/AddOrganisation.tsx
new file mode 100644
index 000000000..89a46e45c
--- /dev/null
+++ b/web/app/pages/Organisations/AddOrganisation.tsx
@@ -0,0 +1,32 @@
+import { BuildingOffice2Icon } from '@heroicons/react/24/outline'
+import { useTranslation } from 'react-i18next'
+import cx from 'clsx'
+
+interface AddOrganisationProps {
+ onClick: () => void
+ sitesCount: number
+}
+
+export const AddOrganisation = ({ onClick, sitesCount }: AddOrganisationProps) => {
+ const { t } = useTranslation('common')
+
+ return (
+ <button
+ type='button'
+ onClick={onClick}
+ className={cx(
+ 'group flex h-auto min-h-[153.1px] cursor-pointer items-center justify-center rounded-lg border-2 border-dashed border-gray-300 hover:border-gray-400',
+ {
+ 'lg:min-h-[auto]': sitesCount % 3 !== 0,
+ },
+ )}
+ >
+ <div>
+ <BuildingOffice2Icon className='mx-auto h-12 w-12 text-gray-400 group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
+ <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50 group-hover:dark:text-gray-400'>
+ {t('organisations.new')}
+ </span>
+ </div>
+ </button>
+ )
+}
diff --git a/web/app/pages/Organisations/NoOrganisations.tsx b/web/app/pages/Organisations/NoOrganisations.tsx
new file mode 100644
index 000000000..89c928d1e
--- /dev/null
+++ b/web/app/pages/Organisations/NoOrganisations.tsx
@@ -0,0 +1,23 @@
+import { useTranslation } from 'react-i18next'
+import { BuildingOffice2Icon } from '@heroicons/react/24/outline'
+
+interface NoOrganisationsProps {
+ onClick: () => void
+}
+
+export const NoOrganisations = ({ onClick }: NoOrganisationsProps) => {
+ const { t } = useTranslation('common')
+
+ return (
+ <button
+ type='button'
+ onClick={onClick}
+ className='relative mx-auto block max-w-lg rounded-lg border-2 border-dashed border-gray-300 p-12 text-center hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'
+ >
+ <BuildingOffice2Icon className='mx-auto h-12 w-12 text-gray-400 dark:text-gray-200' />
+ <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50'>
+ {t('dashboard.createProject')}
+ </span>
+ </button>
+ )
+}
diff --git a/web/app/pages/Organisations/OrganisationCard.tsx b/web/app/pages/Organisations/OrganisationCard.tsx
new file mode 100644
index 000000000..7c122270d
--- /dev/null
+++ b/web/app/pages/Organisations/OrganisationCard.tsx
@@ -0,0 +1,168 @@
+import { AdjustmentsVerticalIcon } from '@heroicons/react/24/outline'
+import { Link } from '@remix-run/react'
+import React, { useState, useMemo } from 'react'
+import { toast } from 'sonner'
+import _size from 'lodash/size'
+import _replace from 'lodash/replace'
+import _find from 'lodash/find'
+import _map from 'lodash/map'
+import { useTranslation } from 'react-i18next'
+import cx from 'clsx'
+
+import Modal from 'ui/Modal'
+import { Badge, BadgeProps } from 'ui/Badge'
+import routes from 'utils/routes'
+
+import { DetailedOrganisation } from 'redux/models/Organisation'
+import { useSelector } from 'react-redux'
+import { StateType, useAppDispatch } from 'redux/store'
+import { acceptOrganisationInvitation } from 'api'
+import { authActions } from 'redux/reducers/auth'
+
+interface OrganisationCardProps {
+ organisation: DetailedOrganisation
+ reloadOrganisations: () => Promise<void>
+}
+
+export const OrganisationCard = ({ organisation, reloadOrganisations }: OrganisationCardProps) => {
+ const { t } = useTranslation('common')
+ const { user } = useSelector((state: StateType) => state.auth)
+ const dispatch = useAppDispatch()
+ const [showInviteModal, setShowInviteModal] = useState(false)
+
+ const { name, members } = organisation
+
+ const membership = useMemo(() => _find(members, (member) => member.user.email === user.email), [members, user.email])
+
+ const badges = useMemo(() => {
+ const list: BadgeProps[] = []
+
+ if (membership?.role) {
+ list.push({
+ colour: 'indigo',
+ label: t(`organisations.role.${membership.role}.name`),
+ })
+ }
+
+ if (!membership?.confirmed) {
+ list.push({ colour: 'yellow', label: t('common.pending') })
+ }
+
+ const membersCount = _size(members)
+
+ list.push({
+ colour: 'slate',
+ label: membersCount === 1 ? t('common.oneMember') : t('common.xMembers', { number: membersCount }),
+ })
+
+ return list
+ }, [t, membership, members])
+
+ const onAccept = async () => {
+ try {
+ if (!membership?.id) {
+ throw new Error('Membership not found')
+ }
+
+ await acceptOrganisationInvitation(membership.id)
+
+ await reloadOrganisations()
+
+ dispatch(
+ authActions.mergeUser({
+ organisationMemberships: _map(user.organisationMemberships, (item) => {
+ if (item.id === membership.id) {
+ return { ...item, confirmed: true }
+ }
+ return item
+ }),
+ }),
+ )
+
+ toast.success(t('apiNotifications.acceptOrganisationInvitation'))
+ } catch (reason: any) {
+ console.error(`[ERROR] Error while accepting organisation invitation: ${reason}`)
+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.acceptOrganisationInvitationError'))
+ }
+ }
+
+ const onElementClick = (e: React.MouseEvent<HTMLAnchorElement | HTMLDivElement>) => {
+ if (membership?.confirmed) {
+ return
+ }
+
+ e.preventDefault()
+ setShowInviteModal(true)
+ }
+
+ const CardWrapper = ({
+ children,
+ to,
+ ...props
+ }: {
+ children: React.ReactNode
+ to?: string
+ onClick?: (e: React.MouseEvent<HTMLAnchorElement | HTMLDivElement>) => void
+ className?: string
+ }) => {
+ if (membership?.role === 'viewer') {
+ return <div {...props}>{children}</div>
+ }
+
+ return (
+ <Link to={to!} {...props}>
+ {children}
+ </Link>
+ )
+ }
+
+ return (
+ <CardWrapper
+ to={_replace(routes.organisation, ':id', organisation.id)}
+ onClick={onElementClick}
+ className={cx(
+ 'min-h-[153.1px] overflow-hidden rounded-xl border border-gray-200 bg-gray-50 dark:border-slate-800/25 dark:bg-slate-800',
+ {
+ 'cursor-pointer hover:bg-gray-100 dark:hover:bg-slate-700': membership?.role !== 'viewer',
+ },
+ )}
+ >
+ <div className='px-4 py-4'>
+ <div className='flex items-center justify-between'>
+ <p className='truncate text-lg font-semibold text-slate-900 dark:text-gray-50'>{name}</p>
+
+ <div className='flex items-center gap-2' onClick={(e) => e.stopPropagation()}>
+ {membership?.role === 'viewer' ? null : (
+ <AdjustmentsVerticalIcon
+ className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500'
+ aria-label={`${t('project.settings.settings')} ${name}`}
+ />
+ )}
+ </div>
+ </div>
+ <div className='mt-1 flex flex-shrink-0 flex-wrap gap-2'>
+ {badges.map((badge) => (
+ <Badge key={badge.label} {...badge} />
+ ))}
+ </div>
+ </div>
+ {!membership?.confirmed && (
+ <Modal
+ onClose={() => {
+ setShowInviteModal(false)
+ }}
+ onSubmit={() => {
+ setShowInviteModal(false)
+ onAccept()
+ }}
+ submitText={t('common.accept')}
+ type='confirmed'
+ closeText={t('common.cancel')}
+ title={t('dashboard.invitationFor', { project: name })}
+ message={t('dashboard.invitationDesc', { project: name })}
+ isOpened={showInviteModal}
+ />
+ )}
+ </CardWrapper>
+ )
+}
diff --git a/web/app/pages/Organisations/Organisations.tsx b/web/app/pages/Organisations/Organisations.tsx
new file mode 100644
index 000000000..7556ece2e
--- /dev/null
+++ b/web/app/pages/Organisations/Organisations.tsx
@@ -0,0 +1,330 @@
+import React, { useState, useEffect, useCallback } from 'react'
+import { Link } from '@remix-run/react'
+import { toast } from 'sonner'
+import { ClientOnly } from 'remix-utils/client-only'
+import _isEmpty from 'lodash/isEmpty'
+import _size from 'lodash/size'
+import _map from 'lodash/map'
+import { useTranslation } from 'react-i18next'
+import { MagnifyingGlassIcon, XMarkIcon, BuildingOffice2Icon } from '@heroicons/react/24/outline'
+import { XCircleIcon } from '@heroicons/react/24/solid'
+
+import Modal from 'ui/Modal'
+import { withAuthentication, auth } from 'hoc/protected'
+import Loader from 'ui/Loader'
+import routes from 'utils/routes'
+import { ENTRIES_PER_PAGE_DASHBOARD } from 'redux/constants'
+import EventsRunningOutBanner from 'components/EventsRunningOutBanner'
+import useDebounce from 'hooks/useDebounce'
+
+import { createOrganisation, getOrganisations } from 'api'
+
+import Pagination from 'ui/Pagination'
+import { DetailedOrganisation } from 'redux/models/Organisation'
+import Input from 'ui/Input'
+import { OrganisationCard } from './OrganisationCard'
+import { NoOrganisations } from './NoOrganisations'
+import { AddOrganisation } from './AddOrganisation'
+import { useSelector } from 'react-redux'
+import { StateType } from 'redux/store'
+
+const Organisations = () => {
+ const { loading: authLoading } = useSelector((state: StateType) => state.auth)
+
+ const { t } = useTranslation('common')
+ const [isSearchActive, setIsSearchActive] = useState(false)
+ const [showActivateEmailModal, setShowActivateEmailModal] = useState(false)
+ const [search, setSearch] = useState('')
+ const debouncedSearch = useDebounce<string>(search, 500)
+ const [organisations, setOrganisations] = useState<DetailedOrganisation[]>([])
+ const [paginationTotal, setPaginationTotal] = useState(0)
+ const [page, setPage] = useState(1)
+
+ const [newOrganisationModalOpen, setNewOrganisationModalOpen] = useState(false)
+ const [newOrganisationName, setNewOrganisationName] = useState('')
+
+ const [isLoading, setIsLoading] = useState<boolean | null>(null)
+ const [isNewOrganisationLoading, setIsNewOrganisationLoading] = useState(false)
+
+ const [error, setError] = useState<string | null>(null)
+ const [newOrganisationError, setNewOrganisationError] = useState<string | null>(null)
+
+ const pageAmount = Math.ceil(paginationTotal / ENTRIES_PER_PAGE_DASHBOARD)
+
+ const onNewOrganisation = () => {
+ setNewOrganisationModalOpen(true)
+ }
+
+ const onCreateOrganisation = async () => {
+ if (isNewOrganisationLoading) {
+ return
+ }
+
+ setIsNewOrganisationLoading(true)
+
+ try {
+ await createOrganisation(newOrganisationName)
+
+ const result = await getOrganisations(
+ ENTRIES_PER_PAGE_DASHBOARD,
+ (page - 1) * ENTRIES_PER_PAGE_DASHBOARD,
+ debouncedSearch,
+ )
+ setOrganisations(result.results)
+ setPaginationTotal(result.total)
+
+ toast.success(t('apiNotifications.organisationCreated'))
+
+ closeNewOrganisationModal()
+ } catch (reason: any) {
+ setNewOrganisationError(reason)
+ toast.error(t('apiNotifications.organisationCreateError'))
+ } finally {
+ setIsNewOrganisationLoading(false)
+ }
+ }
+
+ const closeNewOrganisationModal = () => {
+ if (isNewOrganisationLoading) {
+ return
+ }
+
+ setNewOrganisationModalOpen(false)
+ setNewOrganisationError(null)
+ setNewOrganisationName('')
+ }
+
+ const loadOrganisations = async (take: number, skip: number, search?: string) => {
+ if (isLoading) {
+ return
+ }
+ setIsLoading(true)
+
+ try {
+ const result = await getOrganisations(take, skip, search)
+ setOrganisations(result.results)
+ setPaginationTotal(result.total)
+ } catch (reason: any) {
+ setError(reason)
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const reloadOrganisations = useCallback(async () => {
+ try {
+ const result = await getOrganisations(
+ ENTRIES_PER_PAGE_DASHBOARD,
+ (page - 1) * ENTRIES_PER_PAGE_DASHBOARD,
+ debouncedSearch,
+ )
+ setOrganisations(result.results)
+ setPaginationTotal(result.total)
+ } catch (reason: any) {
+ console.error(`[ERROR] Error while reloading organisations: ${reason}`)
+ }
+ }, [debouncedSearch, page])
+
+ useEffect(() => {
+ loadOrganisations(ENTRIES_PER_PAGE_DASHBOARD, (page - 1) * ENTRIES_PER_PAGE_DASHBOARD, debouncedSearch)
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [page, debouncedSearch])
+
+ if (error && isLoading === false) {
+ return (
+ <div className='min-h-page bg-gray-50 px-4 py-16 dark:bg-slate-900 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
+ <div className='mx-auto max-w-max'>
+ <main className='sm:flex'>
+ <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
+ <div className='sm:ml-6'>
+ <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
+ <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 dark:text-gray-50 sm:text-5xl'>
+ {t('apiNotifications.somethingWentWrong')}
+ </h1>
+ <p className='mt-4 text-2xl font-medium tracking-tight text-gray-700 dark:text-gray-200'>
+ {t('apiNotifications.errorCode', { error })}
+ </p>
+ </div>
+ <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
+ <button
+ type='button'
+ onClick={() => window.location.reload()}
+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'
+ >
+ {t('dashboard.reloadPage')}
+ </button>
+ <Link
+ to={routes.contact}
+ className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
+ >
+ {t('notFoundPage.support')}
+ </Link>
+ </div>
+ </div>
+ </main>
+ </div>
+ </div>
+ )
+ }
+
+ const onSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
+ setSearch(e.target.value)
+ }
+
+ return (
+ <>
+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
+ <EventsRunningOutBanner />
+ <div className='flex flex-col px-4 py-6 sm:px-6 lg:px-8'>
+ <div className='mx-auto w-full max-w-7xl'>
+ <div className='mb-6 flex justify-between'>
+ <div className='flex items-end justify-between'>
+ <h2 className='mt-2 flex items-baseline text-3xl font-bold text-gray-900 dark:text-gray-50'>
+ {t('titles.organisations')}
+ {isSearchActive ? (
+ <XMarkIcon
+ className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50'
+ onClick={() => {
+ setSearch('')
+ setIsSearchActive(false)
+ }}
+ />
+ ) : (
+ <MagnifyingGlassIcon
+ className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50'
+ onClick={() => {
+ setIsSearchActive(true)
+ }}
+ />
+ )}
+ </h2>
+ {isSearchActive && (
+ <div className='hidden w-full max-w-md items-center px-2 pb-1 sm:ml-5 sm:flex'>
+ <label htmlFor='simple-search' className='sr-only'>
+ Search
+ </label>
+ <div className='relative w-full'>
+ <div className='pointer-events-none absolute inset-y-0 left-0 hidden items-center sm:flex'>
+ <MagnifyingGlassIcon className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50' />
+ </div>
+ <input
+ type='text'
+ onChange={onSearch}
+ value={search}
+ className='block h-7 w-full rounded-lg border-none bg-gray-50 p-2.5 text-sm text-gray-900 ring-1 ring-gray-300 focus:ring-gray-500 dark:bg-slate-900 dark:text-white dark:placeholder-gray-400 dark:ring-slate-600 dark:focus:ring-slate-200 sm:pl-10'
+ placeholder={t('project.search')}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ <span
+ onClick={onNewOrganisation}
+ className='inline-flex cursor-pointer items-center justify-center rounded-md border border-transparent bg-slate-900 px-3 py-2 !pl-2 text-center text-sm font-medium leading-4 text-white shadow-sm hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-slate-500 focus:ring-offset-2 dark:border-gray-800 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
+ >
+ <BuildingOffice2Icon className='mr-1 h-5 w-5' />
+ {t('organisations.new')}
+ </span>
+ </div>
+ {isSearchActive && (
+ <div className='mb-2 flex w-full items-center sm:hidden'>
+ <label htmlFor='simple-search' className='sr-only'>
+ Search
+ </label>
+ <div className='relative w-full'>
+ <div className='pointer-events-none absolute inset-y-0 left-0 flex items-center'>
+ <MagnifyingGlassIcon className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50' />
+ </div>
+ <input
+ type='text'
+ onChange={onSearch}
+ value={search}
+ className='block h-7 w-full rounded-lg border-none bg-gray-50 p-2.5 py-5 pl-10 text-sm text-gray-900 ring-1 ring-gray-300 focus:ring-gray-500 dark:bg-slate-900 dark:text-white dark:placeholder-gray-400 dark:ring-slate-600 dark:focus:ring-slate-200'
+ placeholder={t('project.search')}
+ />
+ </div>
+ </div>
+ )}
+ {authLoading || isLoading || isLoading === null ? (
+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ ) : (
+ <ClientOnly
+ fallback={
+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
+ <Loader />
+ </div>
+ }
+ >
+ {() => (
+ <div>
+ {_isEmpty(organisations) ? (
+ <NoOrganisations onClick={onNewOrganisation} />
+ ) : (
+ <div className='grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>
+ {_map(organisations, (organisation) => (
+ <OrganisationCard
+ key={organisation.id}
+ organisation={organisation}
+ reloadOrganisations={reloadOrganisations}
+ />
+ ))}
+ <AddOrganisation sitesCount={_size(organisations)} onClick={onNewOrganisation} />
+ </div>
+ )}
+ </div>
+ )}
+ </ClientOnly>
+ )}
+ {pageAmount > 1 ? (
+ <Pagination
+ className='mt-2'
+ page={page}
+ pageAmount={pageAmount}
+ setPage={setPage}
+ total={paginationTotal}
+ />
+ ) : null}
+ </div>
+ </div>
+ </div>
+ <Modal
+ onClose={() => setShowActivateEmailModal(false)}
+ onSubmit={() => setShowActivateEmailModal(false)}
+ submitText={t('common.gotIt')}
+ title={t('dashboard.verifyEmailTitle')}
+ type='info'
+ message={t('dashboard.verifyEmailDesc')}
+ isOpened={showActivateEmailModal}
+ />
+ <Modal
+ isLoading={isNewOrganisationLoading}
+ onClose={closeNewOrganisationModal}
+ onSubmit={onCreateOrganisation}
+ submitText={t('common.continue')}
+ message={
+ <div>
+ <Input
+ name='organisation-name-input'
+ label={t('common.name')}
+ value={newOrganisationName}
+ onChange={(e) => setNewOrganisationName(e.target.value)}
+ />
+ {newOrganisationError && (
+ <p className='mt-2 text-sm font-medium text-red-500'>
+ {t('apiNotifications.errorOccured', { error: newOrganisationError })}
+ </p>
+ )}
+ </div>
+ }
+ title={t('organisations.create')}
+ isOpened={newOrganisationModalOpen}
+ submitDisabled={!newOrganisationName}
+ />
+ </>
+ )
+}
+
+export default withAuthentication(Organisations, auth.authenticated)
diff --git a/web/app/pages/Organisations/Settings/People.tsx b/web/app/pages/Organisations/Settings/People.tsx
index c368db8d9..e96a96cd4 100644
--- a/web/app/pages/Organisations/Settings/People.tsx
+++ b/web/app/pages/Organisations/Settings/People.tsx
@@ -14,12 +14,12 @@ import Input from 'ui/Input'
import { Badge } from 'ui/Badge'
import Button from 'ui/Button'
import Modal from 'ui/Modal'
-import { roles, roleViewer, roleAdmin, INVITATION_EXPIRES_IN } from 'redux/constants'
+import { roles, INVITATION_EXPIRES_IN } from 'redux/constants'
import useOnClickOutside from 'hooks/useOnClickOutside'
import { DetailedOrganisation, Role } from 'redux/models/Organisation'
import { useSelector } from 'react-redux'
import { StateType } from 'redux/store'
-import { changeOrganisationRole, removeOrganisationMember } from 'api'
+import { changeOrganisationRole, inviteOrganisationMember, removeOrganisationMember } from 'api'
const NoPeople = () => {
const { t } = useTranslation('common')
@@ -153,9 +153,12 @@ interface PeopleProps {
const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element => {
const [showModal, setShowModal] = useState(false)
const { t } = useTranslation('common')
- const [form, setForm] = useState({
+ const [form, setForm] = useState<{
+ email: string
+ role: Role
+ }>({
email: '',
- role: '',
+ role: 'viewer',
})
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [errors, setErrors] = useState<{
@@ -205,13 +208,13 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
}))
}
- const onSubmit = async () => {
+ const onInviteToOrganisation = async () => {
setShowModal(false)
setErrors({})
setValidated(false)
try {
- // todo
+ await inviteOrganisationMember(organisation.id, form)
await reloadOrganisation()
toast.success(t('apiNotifications.userInvited'))
} catch (reason) {
@@ -220,7 +223,7 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
}
// a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', role: '' }), 300)
+ setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
}
const handleSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
@@ -229,7 +232,7 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
setBeenSubmitted(true)
if (validated) {
- onSubmit()
+ onInviteToOrganisation()
} else {
validate()
}
@@ -238,10 +241,15 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
const closeModal = () => {
setShowModal(false)
// a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', role: '' }), 300)
+ setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
setErrors({})
}
+ const closeRemoveUserModal = () => {
+ setShowDeleteModal(false)
+ setTimeout(() => setMemberToRemove(null), 300)
+ }
+
const onRemove = async (member: DetailedOrganisation['members'][number]) => {
if (isDeleting) {
return
@@ -321,13 +329,10 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
)}
</div>
<Modal
- onClose={() => {
- setShowDeleteModal(false)
- setMemberToRemove(null)
- }}
+ onClose={closeRemoveUserModal}
onSubmit={async () => {
await onRemove(memberToRemove!)
- setMemberToRemove(null)
+ closeRemoveUserModal()
}}
submitText={t('common.yes')}
type='confirmed'
@@ -387,8 +392,8 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
'relative flex cursor-pointer rounded-tl-md rounded-tr-md border border-gray-200 p-4 dark:border-slate-600',
{
'z-10 border-indigo-200 bg-indigo-50 dark:border-indigo-800/40 dark:bg-indigo-600/40':
- form.role === roleAdmin.role,
- 'border-gray-200': form.role !== roleAdmin.role,
+ form.role === 'admin',
+ 'border-gray-200': form.role !== 'admin',
},
)}
>
@@ -399,20 +404,21 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
type='radio'
value='admin'
onChange={handleInput}
+ checked={form.role === 'admin'}
/>
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === roleAdmin.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleAdmin.role,
+ 'text-indigo-900 dark:text-white': form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
})}
>
{t('organisations.role.admin.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === roleAdmin.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleAdmin.role,
+ 'text-indigo-700 dark:text-gray-100': form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
})}
>
{t('organisations.role.admin.desc')}
@@ -425,8 +431,8 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
'relative flex cursor-pointer rounded-bl-md rounded-br-md border border-gray-200 p-4 dark:border-gray-500',
{
'z-10 border-indigo-200 bg-indigo-50 dark:border-indigo-800/40 dark:bg-indigo-600/40':
- form.role === roleViewer.role,
- 'border-gray-200': form.role !== roleViewer.role,
+ form.role === 'viewer',
+ 'border-gray-200': form.role !== 'viewer',
},
)}
>
@@ -437,20 +443,21 @@ const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element
type='radio'
value='viewer'
onChange={handleInput}
+ checked={form.role === 'viewer'}
/>
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === roleViewer.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleViewer.role,
+ 'text-indigo-900 dark:text-white': form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
})}
>
{t('organisations.role.viewer.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === roleViewer.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleViewer.role,
+ 'text-indigo-700 dark:text-gray-100': form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
})}
>
{t('organisations.role.viewer.desc')}
diff --git a/web/app/pages/Organisations/Settings/TransferProject/TransferProjectReject.tsx b/web/app/pages/Organisations/Settings/TransferProject/TransferProjectReject.tsx
deleted file mode 100644
index d2e73c50c..000000000
--- a/web/app/pages/Organisations/Settings/TransferProject/TransferProjectReject.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import React, { useState, useEffect } from 'react'
-import { Link } from '@remix-run/react'
-import { useTranslation } from 'react-i18next'
-import { XCircleIcon, InformationCircleIcon } from '@heroicons/react/24/solid'
-
-import Loader from 'ui/Loader'
-
-import { rejectTransferProject } from 'api'
-import routes from 'utils/routes'
-
-const TransferProjectReject = () => {
- const { t } = useTranslation('common')
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
-
- const handleConfirm = async (token: string) => {
- try {
- await rejectTransferProject(token)
- } catch {
- setError(t('apiNotifications.invalidToken'))
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- setLoading(true)
- const query = new URLSearchParams(window.location.search)
- const token = query.get('token')
-
- if (!token) {
- setError(t('apiNotifications.invalidToken'))
- setLoading(false)
- return
- }
-
- handleConfirm(token)
- }, []) // eslint-disable-line
-
- if (loading) {
- return (
- <div className='min-h-page bg-gray-50 dark:bg-slate-900'>
- <Loader />
- </div>
- )
- }
-
- if (error) {
- return (
- <div className='min-h-page bg-gray-50 px-4 py-16 dark:bg-slate-900 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
- <div className='mx-auto max-w-max'>
- <main className='sm:flex'>
- <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
- <div className='sm:ml-6'>
- <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
- <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 dark:text-gray-50 sm:text-5xl'>
- {error}
- </h1>
- </div>
- <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
- <Link
- to={routes.dashboard}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'
- >
- {t('common.dashboard')}
- </Link>
- <Link
- to={routes.contact}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
- >
- {t('notFoundPage.support')}
- </Link>
- </div>
- </div>
- </main>
- </div>
- </div>
- )
- }
-
- return (
- <div className='min-h-page bg-gray-50 px-4 py-16 dark:bg-slate-900 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
- <div className='mx-auto max-w-max'>
- <main className='sm:flex'>
- <InformationCircleIcon className='h-12 w-12 text-yellow-400' aria-hidden='true' />
- <div className='sm:ml-6'>
- <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
- <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 dark:text-gray-50 sm:text-5xl'>
- {t('apiNotifications.transferProjectReject')}
- </h1>
- </div>
- <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
- <Link
- to={routes.dashboard}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'
- >
- {t('common.dashboard')}
- </Link>
- </div>
- </div>
- </main>
- </div>
- </div>
- )
-}
-
-export default TransferProjectReject
diff --git a/web/app/pages/Organisations/index.tsx b/web/app/pages/Organisations/index.tsx
index 45df71bbe..9abc1882f 100644
--- a/web/app/pages/Organisations/index.tsx
+++ b/web/app/pages/Organisations/index.tsx
@@ -1,510 +1,3 @@
-import React, { useState, useEffect, useMemo } from 'react'
-import { Link } from '@remix-run/react'
-import { toast } from 'sonner'
-import { ClientOnly } from 'remix-utils/client-only'
-import cx from 'clsx'
-import _isEmpty from 'lodash/isEmpty'
-import _size from 'lodash/size'
-import _isNumber from 'lodash/isNumber'
-import _replace from 'lodash/replace'
-import _map from 'lodash/map'
-import _find from 'lodash/find'
-import { useTranslation } from 'react-i18next'
-import {
- AdjustmentsVerticalIcon,
- MagnifyingGlassIcon,
- XMarkIcon,
- BuildingOffice2Icon,
-} from '@heroicons/react/24/outline'
-import { XCircleIcon } from '@heroicons/react/24/solid'
+import Organisations from './Organisations'
-import Modal from 'ui/Modal'
-import { withAuthentication, auth } from 'hoc/protected'
-import Loader from 'ui/Loader'
-import { Badge, BadgeProps } from 'ui/Badge'
-import routes from 'utils/routes'
-import { ENTRIES_PER_PAGE_DASHBOARD, roleViewer } from 'redux/constants'
-import EventsRunningOutBanner from 'components/EventsRunningOutBanner'
-import useDebounce from 'hooks/useDebounce'
-
-import { acceptShareProject, createOrganisation, getOrganisations } from 'api'
-
-import Pagination from 'ui/Pagination'
-import { ISharedProject } from 'redux/models/ISharedProject'
-import { IProject } from 'redux/models/IProject'
-import { Organisation } from 'redux/models/Organisation'
-import Input from 'ui/Input'
-
-interface OrganisationCardProps {
- name?: string
- active?: boolean
- isPublic?: boolean
- confirmed?: boolean
- id: string
- sharedProjects: ISharedProject[]
- setProjectsShareData: (data: Partial<IProject>, id: string) => void
- setUserShareData: (data: Partial<IProject>, id: string) => void
- shared?: boolean
- isTransferring?: boolean
- getRole?: (id: string) => string | null
- members?: number
-}
-
-const OrganisationCard = ({
- name,
- confirmed,
- id,
- sharedProjects,
- setProjectsShareData,
- setUserShareData,
- shared,
- isTransferring,
- getRole,
- members,
-}: OrganisationCardProps) => {
- const { t } = useTranslation('common')
- const [showInviteModal, setShowInviteModal] = useState(false)
- const role = useMemo(() => getRole && getRole(id), [getRole, id])
-
- const badges = useMemo(() => {
- const list: BadgeProps[] = []
-
- if (shared) {
- if (confirmed) {
- list.push({ colour: 'green', label: t('dashboard.shared') })
- } else {
- list.push({ colour: 'yellow', label: t('common.pending') })
- }
- }
-
- if (isTransferring) {
- list.push({ colour: 'indigo', label: t('common.transferring') })
- }
-
- if (_isNumber(members)) {
- list.push({ colour: 'slate', label: t('common.xMembers', { number: members + 1 }) })
- }
-
- return list
- }, [t, confirmed, shared, isTransferring, members])
-
- const onAccept = async () => {
- // @ts-ignore
- const pid: string = _find(sharedProjects, (item: ISharedProject) => item.project && item.project.id === id)?.id
-
- try {
- if (!pid || !id) {
- throw new Error('Project not found')
- }
- await acceptShareProject(pid)
- setProjectsShareData({ isAccessConfirmed: true }, id)
- setUserShareData({ isAccessConfirmed: true }, pid)
- toast.success(t('apiNotifications.acceptInvitation'))
- } catch (reason: any) {
- toast.error(t('apiNotifications.acceptInvitationError'))
- }
- }
-
- const onElementClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
- if (confirmed) {
- return
- }
-
- e.preventDefault()
- setShowInviteModal(true)
- }
-
- return (
- <Link
- to={_replace(routes.organisation, ':id', id)}
- onClick={onElementClick}
- className='min-h-[153.1px] cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 hover:bg-gray-100 dark:border-slate-800/25 dark:bg-slate-800 dark:hover:bg-slate-700'
- >
- <div className='px-4 py-4'>
- <div className='flex items-center justify-between'>
- <p className='truncate text-lg font-semibold text-slate-900 dark:text-gray-50'>{name}</p>
-
- <div className='flex items-center gap-2' onClick={(e) => e.stopPropagation()}>
- {role !== roleViewer.role && (
- <Link
- to={_replace(routes.organisation, ':id', id)}
- aria-label={`${t('project.settings.settings')} ${name}`}
- >
- <AdjustmentsVerticalIcon className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500' />
- </Link>
- )}
- </div>
- </div>
- <div className='mt-1 flex flex-shrink-0 flex-wrap gap-2'>
- {badges.map((badge) => (
- <Badge key={badge.label} {...badge} />
- ))}
- </div>
- </div>
- {!confirmed && (
- <Modal
- onClose={() => {
- setShowInviteModal(false)
- }}
- onSubmit={() => {
- setShowInviteModal(false)
- onAccept()
- }}
- submitText={t('common.accept')}
- type='confirmed'
- closeText={t('common.cancel')}
- title={t('dashboard.invitationFor', { project: name })}
- message={t('dashboard.invitationDesc', { project: name })}
- isOpened={showInviteModal}
- />
- )}
- </Link>
- )
-}
-
-interface INoOrganisations {
- onClick: () => void
-}
-
-interface IAddOrganisation {
- onClick: () => void
- sitesCount: number
-}
-
-const NoOrganisations = ({ onClick }: INoOrganisations) => {
- const { t } = useTranslation('common')
-
- return (
- <button
- type='button'
- onClick={onClick}
- className='relative mx-auto block max-w-lg rounded-lg border-2 border-dashed border-gray-300 p-12 text-center hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'
- >
- <BuildingOffice2Icon className='mx-auto h-12 w-12 text-gray-400 dark:text-gray-200' />
- <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50'>
- {t('dashboard.createProject')}
- </span>
- </button>
- )
-}
-
-const AddOrganisation = ({ onClick, sitesCount }: IAddOrganisation) => {
- const { t } = useTranslation('common')
-
- return (
- <button
- type='button'
- onClick={onClick}
- className={cx(
- 'group flex h-auto min-h-[153.1px] cursor-pointer items-center justify-center rounded-lg border-2 border-dashed border-gray-300 hover:border-gray-400',
- {
- 'lg:min-h-[auto]': sitesCount % 3 !== 0,
- },
- )}
- >
- <div>
- <BuildingOffice2Icon className='mx-auto h-12 w-12 text-gray-400 group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
- <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50 group-hover:dark:text-gray-400'>
- {t('organisations.new')}
- </span>
- </div>
- </button>
- )
-}
-
-const Organisations = () => {
- const { t } = useTranslation('common')
- const [isSearchActive, setIsSearchActive] = useState(false)
- const [showActivateEmailModal, setShowActivateEmailModal] = useState(false)
- const [search, setSearch] = useState('')
- const debouncedSearch = useDebounce<string>(search, 500)
- const [organisations, setOrganisations] = useState<Organisation[]>([])
- const [paginationTotal, setPaginationTotal] = useState(0)
- const [page, setPage] = useState(1)
-
- const [newOrganisationModalOpen, setNewOrganisationModalOpen] = useState(false)
- const [newOrganisationName, setNewOrganisationName] = useState('')
-
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [isNewOrganisationLoading, setIsNewOrganisationLoading] = useState(false)
-
- const [error, setError] = useState<string | null>(null)
- const [newOrganisationError, setNewOrganisationError] = useState<string | null>(null)
-
- const pageAmount = Math.ceil(paginationTotal / ENTRIES_PER_PAGE_DASHBOARD)
-
- const onNewOrganisation = () => {
- setNewOrganisationModalOpen(true)
- }
-
- const onCreateOrganisation = async () => {
- if (isNewOrganisationLoading) {
- return
- }
-
- setIsNewOrganisationLoading(true)
-
- try {
- await createOrganisation(newOrganisationName)
-
- const result = await getOrganisations(
- ENTRIES_PER_PAGE_DASHBOARD,
- (page - 1) * ENTRIES_PER_PAGE_DASHBOARD,
- debouncedSearch,
- )
- setOrganisations(result.results)
- setPaginationTotal(result.total)
-
- toast.success(t('apiNotifications.organisationCreated'))
-
- closeNewOrganisationModal()
- } catch (reason: any) {
- setNewOrganisationError(reason)
- toast.error(t('apiNotifications.organisationCreateError'))
- } finally {
- setIsNewOrganisationLoading(false)
- }
- }
-
- const closeNewOrganisationModal = () => {
- if (isNewOrganisationLoading) {
- return
- }
-
- setNewOrganisationModalOpen(false)
- setNewOrganisationError(null)
- setNewOrganisationName('')
- }
-
- const loadOrganisations = async (take: number, skip: number, search?: string) => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const result = await getOrganisations(take, skip, search)
- setOrganisations(result.results)
- setPaginationTotal(result.total)
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
- }
-
- useEffect(() => {
- loadOrganisations(ENTRIES_PER_PAGE_DASHBOARD, (page - 1) * ENTRIES_PER_PAGE_DASHBOARD, debouncedSearch)
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page, debouncedSearch])
-
- if (error && isLoading === false) {
- return (
- <div className='min-h-page bg-gray-50 px-4 py-16 dark:bg-slate-900 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
- <div className='mx-auto max-w-max'>
- <main className='sm:flex'>
- <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
- <div className='sm:ml-6'>
- <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
- <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 dark:text-gray-50 sm:text-5xl'>
- {t('apiNotifications.somethingWentWrong')}
- </h1>
- <p className='mt-4 text-2xl font-medium tracking-tight text-gray-700 dark:text-gray-200'>
- {t('apiNotifications.errorCode', { error })}
- </p>
- </div>
- <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
- <button
- type='button'
- onClick={() => window.location.reload()}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2'
- >
- {t('dashboard.reloadPage')}
- </button>
- <Link
- to={routes.contact}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
- >
- {t('notFoundPage.support')}
- </Link>
- </div>
- </div>
- </main>
- </div>
- </div>
- )
- }
-
- const onSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
- setSearch(e.target.value)
- }
-
- return (
- <>
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <EventsRunningOutBanner />
- <div className='flex flex-col px-4 py-6 sm:px-6 lg:px-8'>
- <div className='mx-auto w-full max-w-7xl'>
- <div className='mb-6 flex justify-between'>
- <div className='flex items-end justify-between'>
- <h2 className='mt-2 flex items-baseline text-3xl font-bold text-gray-900 dark:text-gray-50'>
- {t('titles.organisations')}
- {isSearchActive ? (
- <XMarkIcon
- className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50'
- onClick={() => {
- setSearch('')
- setIsSearchActive(false)
- }}
- />
- ) : (
- <MagnifyingGlassIcon
- className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50'
- onClick={() => {
- setIsSearchActive(true)
- }}
- />
- )}
- </h2>
- {isSearchActive && (
- <div className='hidden w-full max-w-md items-center px-2 pb-1 sm:ml-5 sm:flex'>
- <label htmlFor='simple-search' className='sr-only'>
- Search
- </label>
- <div className='relative w-full'>
- <div className='pointer-events-none absolute inset-y-0 left-0 hidden items-center sm:flex'>
- <MagnifyingGlassIcon className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50' />
- </div>
- <input
- type='text'
- onChange={onSearch}
- value={search}
- className='block h-7 w-full rounded-lg border-none bg-gray-50 p-2.5 text-sm text-gray-900 ring-1 ring-gray-300 focus:ring-gray-500 dark:bg-slate-900 dark:text-white dark:placeholder-gray-400 dark:ring-slate-600 dark:focus:ring-slate-200 sm:pl-10'
- placeholder={t('project.search')}
- />
- </div>
- </div>
- )}
- </div>
- <span
- onClick={onNewOrganisation}
- className='inline-flex cursor-pointer items-center justify-center rounded-md border border-transparent bg-slate-900 px-3 py-2 !pl-2 text-center text-sm font-medium leading-4 text-white shadow-sm hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-slate-500 focus:ring-offset-2 dark:border-gray-800 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- >
- <BuildingOffice2Icon className='mr-1 h-5 w-5' />
- {t('organisations.new')}
- </span>
- </div>
- {isSearchActive && (
- <div className='mb-2 flex w-full items-center sm:hidden'>
- <label htmlFor='simple-search' className='sr-only'>
- Search
- </label>
- <div className='relative w-full'>
- <div className='pointer-events-none absolute inset-y-0 left-0 flex items-center'>
- <MagnifyingGlassIcon className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50' />
- </div>
- <input
- type='text'
- onChange={onSearch}
- value={search}
- className='block h-7 w-full rounded-lg border-none bg-gray-50 p-2.5 py-5 pl-10 text-sm text-gray-900 ring-1 ring-gray-300 focus:ring-gray-500 dark:bg-slate-900 dark:text-white dark:placeholder-gray-400 dark:ring-slate-600 dark:focus:ring-slate-200'
- placeholder={t('project.search')}
- />
- </div>
- </div>
- )}
- {isLoading || isLoading === null ? (
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <Loader />
- </div>
- ) : (
- <ClientOnly
- fallback={
- <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
- <Loader />
- </div>
- }
- >
- {() => (
- <div>
- {_isEmpty(organisations) ? (
- <NoOrganisations onClick={onNewOrganisation} />
- ) : (
- <div className='grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>
- {_map(
- organisations,
- // @ts-expect-error
- ({ name, id, active, public: isPublic, isTransferring, share }) => (
- <OrganisationCard
- key={id}
- members={1 + _size(share)}
- id={id}
- name={name}
- active={active}
- isPublic={isPublic}
- setUserShareData={() => {}}
- sharedProjects={[]}
- setProjectsShareData={() => {}}
- isTransferring={isTransferring}
- confirmed
- />
- ),
- )}
- <AddOrganisation sitesCount={_size(organisations)} onClick={onNewOrganisation} />
- </div>
- )}
- </div>
- )}
- </ClientOnly>
- )}
- {pageAmount > 1 ? (
- <Pagination
- className='mt-2'
- page={page}
- pageAmount={pageAmount}
- setPage={setPage}
- total={paginationTotal}
- />
- ) : null}
- </div>
- </div>
- </div>
- <Modal
- onClose={() => setShowActivateEmailModal(false)}
- onSubmit={() => setShowActivateEmailModal(false)}
- submitText={t('common.gotIt')}
- title={t('dashboard.verifyEmailTitle')}
- type='info'
- message={t('dashboard.verifyEmailDesc')}
- isOpened={showActivateEmailModal}
- />
- <Modal
- isLoading={isNewOrganisationLoading}
- onClose={closeNewOrganisationModal}
- onSubmit={onCreateOrganisation}
- submitText={t('common.continue')}
- message={
- <div>
- <Input
- name='organisation-name-input'
- label={t('common.name')}
- value={newOrganisationName}
- onChange={(e) => setNewOrganisationName(e.target.value)}
- />
- {newOrganisationError && (
- <p className='mt-2 text-sm font-medium text-red-500'>
- {t('apiNotifications.errorOccured', { error: newOrganisationError })}
- </p>
- )}
- </div>
- }
- title={t('organisations.create')}
- isOpened={newOrganisationModalOpen}
- submitDisabled={!newOrganisationName}
- />
- </>
- )
-}
-
-export default withAuthentication(Organisations, auth.authenticated)
+export default Organisations
diff --git a/web/app/pages/Project/Settings/People/People.container.tsx b/web/app/pages/Project/Settings/People/People.container.tsx
deleted file mode 100644
index f7bf92b47..000000000
--- a/web/app/pages/Project/Settings/People/People.container.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { connect } from 'react-redux'
-import UIActions from 'redux/reducers/ui'
-import { StateType, AppDispatch } from 'redux/store'
-import { IProject } from 'redux/models/IProject'
-
-import People from './People'
-
-const mapStateToProps = (state: StateType) => ({
- isPaidTierUsed: state.auth.isPaidTierUsed,
- user: state.auth.user,
-})
-
-const mapDispatchToProps = (dispatch: AppDispatch) => ({
- setProjectShareData: (data: Partial<IProject>, projectId: string) => {
- dispatch(
- UIActions.setProjectsShareData({
- data,
- id: projectId,
- }),
- )
- },
-})
-
-export default connect(mapStateToProps, mapDispatchToProps)(People)
diff --git a/web/app/pages/Project/Settings/People/People.tsx b/web/app/pages/Project/Settings/People/People.tsx
index 62813dbbe..98da0efbf 100644
--- a/web/app/pages/Project/Settings/People/People.tsx
+++ b/web/app/pages/Project/Settings/People/People.tsx
@@ -17,10 +17,13 @@ import { Badge } from 'ui/Badge'
import Button from 'ui/Button'
import Modal from 'ui/Modal'
import PaidFeature from 'modals/PaidFeature'
-import { roles, roleViewer, roleAdmin, INVITATION_EXPIRES_IN } from 'redux/constants'
+import { roles, INVITATION_EXPIRES_IN } from 'redux/constants'
import useOnClickOutside from 'hooks/useOnClickOutside'
import { IProject, IShareOwnerProject } from 'redux/models/IProject'
-import { IUser } from 'redux/models/IUser'
+import { Role } from 'redux/models/Organisation'
+import { useSelector } from 'react-redux'
+import { StateType, useAppDispatch } from 'redux/store'
+import UIActions from 'redux/reducers/ui'
const NoPeople = () => {
const { t } = useTranslation('common')
@@ -34,17 +37,17 @@ const NoPeople = () => {
)
}
-interface IUsersList {
+interface UsersListProps {
data: IShareOwnerProject
onRemove: () => void
share?: IShareOwnerProject[]
- setProjectShareData: (item: Partial<IProject>, id: string) => void
pid: string
language: string
authedUserEmail: string | undefined
}
-const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language, authedUserEmail }: IUsersList) => {
+const UsersList = ({ data, onRemove, share, pid, language, authedUserEmail }: UsersListProps) => {
+ const dispatch = useAppDispatch()
const { t } = useTranslation('common')
const [open, setOpen] = useState(false)
const openRef = useRef<HTMLUListElement>(null)
@@ -60,7 +63,12 @@ const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language,
}
return itShare
})
- setProjectShareData({ share: newShared }, pid)
+ dispatch(
+ UIActions.setProjectsShareData({
+ data: { share: newShared },
+ id: pid,
+ }),
+ )
toast.success(t('apiNotifications.roleUpdated'))
} catch (reason) {
console.error(`[ERROR] Error while updating user's role: ${reason}`)
@@ -148,28 +156,26 @@ const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language,
)
}
-interface IPeopleProps {
+interface PeopleProps {
project: IProject
- setProjectShareData: (data: Partial<IProject>, projectId: string) => void
- isPaidTierUsed: boolean
- user: IUser
}
-const People: React.FunctionComponent<IPeopleProps> = ({
- project,
- setProjectShareData,
- isPaidTierUsed,
- user: currentUser,
-}: IPeopleProps) => {
+const People = ({ project }: PeopleProps) => {
+ const { isPaidTierUsed, user: currentUser } = useSelector((state: StateType) => state.auth)
+ const dispatch = useAppDispatch()
+
const [showModal, setShowModal] = useState(false)
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
const {
t,
i18n: { language },
} = useTranslation('common')
- const [form, setForm] = useState({
+ const [form, setForm] = useState<{
+ email: string
+ role: Role
+ }>({
email: '',
- role: '',
+ role: 'viewer',
})
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [errors, setErrors] = useState<{
@@ -226,7 +232,12 @@ const People: React.FunctionComponent<IPeopleProps> = ({
try {
const results = await shareProject(id, { email: form.email, role: form.role })
- setProjectShareData({ share: results.share }, id)
+ dispatch(
+ UIActions.setProjectsShareData({
+ data: { share: results.share },
+ id,
+ }),
+ )
toast.success(t('apiNotifications.userInvited'))
} catch (reason) {
console.error(`[ERROR] Error while inviting a user: ${reason}`)
@@ -234,7 +245,7 @@ const People: React.FunctionComponent<IPeopleProps> = ({
}
// a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', role: '' }), 300)
+ setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
}
const handleSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
@@ -257,7 +268,7 @@ const People: React.FunctionComponent<IPeopleProps> = ({
const closeModal = () => {
setShowModal(false)
// a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', role: '' }), 300)
+ setTimeout(() => setForm({ email: '', role: 'viewer' }), 300)
setErrors({})
}
@@ -274,7 +285,12 @@ const People: React.FunctionComponent<IPeopleProps> = ({
_filter(share, (s) => s.id !== member.id),
(s) => s,
)
- setProjectShareData({ share: newShared }, id)
+ dispatch(
+ UIActions.setProjectsShareData({
+ data: { share: newShared },
+ id,
+ }),
+ )
toast.success(t('apiNotifications.userRemoved'))
} catch (reason) {
console.error(`[ERROR] Error while deleting a user: ${reason}`)
@@ -337,7 +353,6 @@ const People: React.FunctionComponent<IPeopleProps> = ({
}}
language={language}
share={project.share}
- setProjectShareData={setProjectShareData}
pid={id}
authedUserEmail={currentUser?.email}
/>
@@ -421,8 +436,8 @@ const People: React.FunctionComponent<IPeopleProps> = ({
'relative flex cursor-pointer rounded-tl-md rounded-tr-md border border-gray-200 p-4 dark:border-slate-600',
{
'z-10 border-indigo-200 bg-indigo-50 dark:border-indigo-800/40 dark:bg-indigo-600/40':
- form.role === roleAdmin.role,
- 'border-gray-200': form.role !== roleAdmin.role,
+ form.role === 'admin',
+ 'border-gray-200': form.role !== 'admin',
},
)}
>
@@ -433,20 +448,21 @@ const People: React.FunctionComponent<IPeopleProps> = ({
type='radio'
value='admin'
onChange={handleInput}
+ checked={form.role === 'admin'}
/>
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === roleAdmin.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleAdmin.role,
+ 'text-indigo-900 dark:text-white': form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
})}
>
{t('project.settings.roles.admin.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === roleAdmin.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleAdmin.role,
+ 'text-indigo-700 dark:text-gray-100': form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
})}
>
{t('project.settings.roles.admin.desc')}
@@ -459,8 +475,8 @@ const People: React.FunctionComponent<IPeopleProps> = ({
'relative flex cursor-pointer rounded-bl-md rounded-br-md border border-gray-200 p-4 dark:border-gray-500',
{
'z-10 border-indigo-200 bg-indigo-50 dark:border-indigo-800/40 dark:bg-indigo-600/40':
- form.role === roleViewer.role,
- 'border-gray-200': form.role !== roleViewer.role,
+ form.role === 'viewer',
+ 'border-gray-200': form.role !== 'viewer',
},
)}
>
@@ -471,20 +487,21 @@ const People: React.FunctionComponent<IPeopleProps> = ({
type='radio'
value='viewer'
onChange={handleInput}
+ checked={form.role === 'viewer'}
/>
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === roleViewer.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleViewer.role,
+ 'text-indigo-900 dark:text-white': form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
})}
>
{t('project.settings.roles.viewer.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === roleViewer.role,
- 'text-gray-700 dark:text-gray-200': form.role !== roleViewer.role,
+ 'text-indigo-700 dark:text-gray-100': form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
})}
>
{t('project.settings.roles.viewer.desc')}
diff --git a/web/app/pages/Project/Settings/People/index.tsx b/web/app/pages/Project/Settings/People/index.tsx
index e1573d0ef..a9ba14fca 100644
--- a/web/app/pages/Project/Settings/People/index.tsx
+++ b/web/app/pages/Project/Settings/People/index.tsx
@@ -1,3 +1,3 @@
-import People from './People.container'
+import People from './People'
export default People
diff --git a/web/app/pages/UserSettings/UserSettings.container.tsx b/web/app/pages/UserSettings/UserSettings.container.tsx
deleted file mode 100644
index 84c1bff4e..000000000
--- a/web/app/pages/UserSettings/UserSettings.container.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import { connect } from 'react-redux'
-import { toast } from 'sonner'
-import type i18next from 'i18next'
-import UIActions from 'redux/reducers/ui'
-import { authActions } from 'redux/reducers/auth'
-import { trackCustom } from 'utils/analytics'
-import { StateType, AppDispatch } from 'redux/store'
-import sagaActions from 'redux/sagas/actions'
-import { IUser } from 'redux/models/IUser'
-import { ISharedProject } from 'redux/models/ISharedProject'
-import { removeRefreshToken } from 'utils/refreshToken'
-import { removeAccessToken } from 'utils/accessToken'
-import UserSettings from './UserSettings'
-import { IProject } from 'redux/models/IProject'
-
-const mapStateToProps = (state: StateType) => {
- return {
- user: state.auth.user,
- dontRemember: state.auth.dontRemember,
- isPaidTierUsed: state.auth.isPaidTierUsed,
- theme: state.ui.theme.theme,
- loading: state.auth.loading,
- activeReferrals: state.ui.cache.activeReferrals,
- referralStatistics: state.ui.cache.referralStatistics,
- }
-}
-
-const mapDispatchToProps = (dispatch: AppDispatch) => ({
- onDelete: (
- t: typeof i18next.t,
- deletionFeedback: string,
- onSuccess: {
- (): void
- },
- ) => {
- dispatch(
- sagaActions.deleteAccountAsync(
- (error: string) => toast.error(error),
- () => {
- trackCustom('ACCOUNT_DELETED', {
- reason_stated: deletionFeedback ? 'true' : 'false',
- })
- onSuccess()
- },
- deletionFeedback,
- t,
- ),
- )
- },
- updateUserData: (data: IUser) => {
- dispatch(authActions.updateUserData(data))
- },
- onDeleteProjectCache: () => {
- dispatch(UIActions.deleteProjectCache({}))
- },
- setCache: (key: string, value: any) => {
- dispatch(
- UIActions.setCache({
- key,
- value,
- }),
- )
- },
- removeProject: (pid: string) => {
- dispatch(
- UIActions.removeProject({
- pid,
- }),
- )
- },
- removeShareProject: (id: string) => {
- dispatch(authActions.deleteShareProject(id))
- },
- setProjectsShareData: (data: Partial<IProject>, id: string) => {
- dispatch(
- UIActions.setProjectsShareData({
- data,
- id,
- }),
- )
- },
- setUserShareData: (data: Partial<ISharedProject>, id: string) => {
- dispatch(
- authActions.setUserShareData({
- data,
- id,
- }),
- )
- },
- updateUserProfileAsync: (
- data: Partial<IUser>,
- successMessage: string,
- callback: (isSuccess: boolean) => void = () => {},
- ) => {
- dispatch(
- sagaActions.updateUserProfileAsync(data, (res: any) => {
- if (res) {
- toast.success(successMessage)
- }
- callback(res)
- }),
- )
- },
- setAPIKey: (apiKey: string) => {
- dispatch(authActions.setApiKey(apiKey))
- },
- // setThemeType: (theme) => {
- // dispatch(UIActions.setThemeType(theme))
- // },
- linkSSO: (t: typeof i18next.t, callback: (e: any) => void, provider: string) => {
- dispatch(sagaActions.linkSSO(t, callback, provider))
- },
- unlinkSSO: (t: typeof i18next.t, callback: (e: any) => void, provider: string) => {
- dispatch(sagaActions.unlinkSSO(t, callback, provider))
- },
- updateShowLiveVisitorsInTitle: (show: boolean, callback: (isSuccess: boolean) => void) => {
- dispatch(sagaActions.updateShowLiveVisitorsInTitle(show, callback))
- },
- // Reset the user in the regex store and remove tokens
- logoutLocal: () => {
- dispatch(authActions.logout())
- removeRefreshToken()
- removeAccessToken()
- },
- logoutAll: () => {
- dispatch(authActions.logout())
- dispatch(sagaActions.logout(false, true))
- },
-})
-
-export default connect(mapStateToProps, mapDispatchToProps)(UserSettings)
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 32716df66..e26a575c1 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -65,9 +65,15 @@ import Integrations from './components/Integrations'
import Socialisations from './components/Socialisations'
import Referral from './components/Referral'
import NoSharedProjects from './components/NoSharedProjects'
-import { IProject } from 'redux/models/IProject'
import Organisations from './components/Organisations'
import NoOrganisations from './components/NoOrganisations'
+import { useSelector } from 'react-redux'
+import { StateType, useAppDispatch } from 'redux/store'
+import { authActions } from 'redux/reducers/auth'
+import sagaActions from 'redux/sagas/actions'
+import { removeRefreshToken } from 'utils/refreshToken'
+import { removeAccessToken } from 'utils/accessToken'
+import UIActions from 'redux/reducers/ui'
dayjs.extend(utc)
@@ -120,61 +126,16 @@ const getTabs = (t: typeof i18next.t) => {
]
}
-interface IProps {
- onDelete: (t: typeof i18next.t, deletionFeedback: string, callback: () => void) => void
- onDeleteProjectCache: () => void
- removeProject: (id: string) => void
- removeShareProject: (id: string) => void
- setUserShareData: (data: Partial<IProject>, id: string) => void
- setProjectsShareData: (data: Partial<IProject>, id: string) => void
- updateUserData: (data: Partial<IUser>) => void
- updateUserProfileAsync: (data: IUser, successMessage: string, callback?: (isSuccess: boolean) => void) => void
- setAPIKey: (key: string | null) => void
- user: IUser
- dontRemember: boolean
- isPaidTierUsed: boolean
- linkSSO: (t: typeof i18next.t, callback: (e: any) => void, provider: string) => void
- unlinkSSO: (t: typeof i18next.t, callback: (e: any) => void, provider: string) => void
- theme: string
- updateShowLiveVisitorsInTitle: (show: boolean, callback: (isSuccess: boolean) => void) => void
- logoutLocal: () => void
- logoutAll: () => void
- loading: boolean
- setCache: (key: string, value: any) => void
- activeReferrals: any[]
- referralStatistics: any
-}
-
interface IForm extends Partial<IUser> {
repeat: string
password: string
email: string
}
-const UserSettings = ({
- onDelete,
- onDeleteProjectCache,
- removeProject,
- removeShareProject,
- setUserShareData,
- setProjectsShareData,
- updateUserData,
- updateUserProfileAsync,
- setAPIKey,
- user,
- dontRemember,
- isPaidTierUsed,
- linkSSO,
- unlinkSSO,
- theme,
- updateShowLiveVisitorsInTitle,
- logoutAll,
- loading,
- logoutLocal,
- referralStatistics,
- activeReferrals,
- setCache,
-}: IProps): JSX.Element => {
+const UserSettings = () => {
+ const { user, isPaidTierUsed, loading } = useSelector((state: StateType) => state.auth)
+ const dispatch = useAppDispatch()
+
const navigate = useNavigate()
const { t } = useTranslation('common')
const [activeTab, setActiveTab] = useState(TAB_MAPPING.ACCOUNT)
@@ -200,8 +161,8 @@ const UserSettings = ({
const [showAPIDeleteModal, setShowAPIDeleteModal] = useState(false)
const [showExportModal, setShowExportModal] = useState(false)
const [error, setError] = useState<null | string>(null)
- const translatedFrequencies = _map(reportFrequencies, (key) => t(`profileSettings.${key}`)) // useMemo(_map(reportFrequencies, (key) => t(`profileSettings.${key}`)), [t])
- const translatedTimeFormat = _map(TimeFormat, (key) => t(`profileSettings.${key}`)) // useMemo(_map(TimeFormat, (key) => t(`profileSettings.${key}`)), [t])
+ const translatedFrequencies = _map(reportFrequencies, (key) => t(`profileSettings.${key}`))
+ const translatedTimeFormat = _map(TimeFormat, (key) => t(`profileSettings.${key}`))
const [settingUpdating, setSettingUpdating] = useState(false)
const [deletionFeedback, setDeletionFeedback] = useState('')
@@ -243,13 +204,26 @@ const UserSettings = ({
}
}
- updateUserProfileAsync(data, t('profileSettings.updated'), (isSuccess: boolean) => {
- if (isSuccess && data.email && data.email !== user.email) {
- toast.success(t('profileSettings.emailChanged'))
- }
+ dispatch(
+ sagaActions.updateUserProfileAsync(data, (isSuccess: boolean) => {
+ if (isSuccess) {
+ toast.success(t('profileSettings.updated'))
+ } else {
+ toast.error(t('apiNotifications.somethingWentWrong'))
+ }
+ }),
+ )
+ }
+
+ const logoutLocal = () => {
+ dispatch(authActions.logout())
+ removeRefreshToken()
+ removeAccessToken()
+ }
- callback(isSuccess)
- })
+ const logoutAll = () => {
+ dispatch(authActions.logout())
+ dispatch(sagaActions.logout(false, true))
}
useEffect(() => {
@@ -312,7 +286,7 @@ const UserSettings = ({
if (validated) {
// if the timezone updates, we need to delete all project cache to refetch it with the new timezone setting afterwards
if (timezoneChanged) {
- onDeleteProjectCache()
+ dispatch(UIActions.deleteProjectCache({}))
}
onSubmit({
@@ -328,16 +302,19 @@ const UserSettings = ({
}
setSettingUpdating(true)
- updateShowLiveVisitorsInTitle(checked, (isSuccess: boolean) => {
- setSettingUpdating(false)
- if (isSuccess) {
- toast.success(t('profileSettings.updated'))
- return
- }
+ dispatch(
+ sagaActions.updateShowLiveVisitorsInTitle(checked, (isSuccess: boolean) => {
+ setSettingUpdating(false)
- toast.error(t('apiNotifications.somethingWentWrong'))
- })
+ if (isSuccess) {
+ toast.success(t('profileSettings.updated'))
+ return
+ }
+
+ toast.error(t('apiNotifications.somethingWentWrong'))
+ }),
+ )
}
const handleReceiveLoginNotifications = async (checked: boolean) => {
@@ -349,9 +326,7 @@ const UserSettings = ({
try {
await receiveLoginNotification(checked)
- updateUserData({
- receiveLoginNotifications: checked,
- })
+ dispatch(authActions.mergeUser({ receiveLoginNotifications: checked }))
toast.success(t('profileSettings.updated'))
} catch {
toast.error(t('apiNotifications.somethingWentWrong'))
@@ -402,10 +377,20 @@ const UserSettings = ({
return null
}
- const _onDelete = () => {
- onDelete(t, deletionFeedback, () => {
- navigate(routes.main)
- })
+ const onAccountDelete = () => {
+ dispatch(
+ sagaActions.deleteAccountAsync(
+ (error: string) => toast.error(error),
+ () => {
+ trackCustom('ACCOUNT_DELETED', {
+ reason_stated: deletionFeedback ? 'true' : 'false',
+ })
+ navigate(routes.main)
+ },
+ deletionFeedback,
+ t,
+ ),
+ )
}
const onExport = async (exportedAt: string) => {
@@ -453,8 +438,8 @@ const UserSettings = ({
const onApiKeyGenerate = async () => {
try {
- const res = await generateApiKey()
- setAPIKey(res.apiKey)
+ const { apiKey } = await generateApiKey()
+ dispatch(authActions.mergeUser({ apiKey }))
} catch (reason: any) {
toast.error(reason)
}
@@ -463,7 +448,7 @@ const UserSettings = ({
const onApiKeyDelete = async () => {
try {
await deleteApiKey()
- setAPIKey(null)
+ dispatch(authActions.mergeUser({ apiKey: null }))
} catch (reason: any) {
toast.error(reason)
}
@@ -682,7 +667,7 @@ const UserSettings = ({
<h3 className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('profileSettings.2fa')}
</h3>
- <TwoFA user={user} dontRemember={dontRemember} updateUserData={updateUserData} />
+ <TwoFA />
{/* Socialisations setup */}
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
@@ -692,7 +677,7 @@ const UserSettings = ({
>
{t('profileSettings.socialisations')}
</h3>
- <Socialisations user={user} linkSSO={linkSSO} unlinkSSO={unlinkSSO} theme={theme} />
+ <Socialisations />
{/* Shared projects setting */}
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
@@ -731,14 +716,7 @@ const UserSettings = ({
</thead>
<tbody className='divide-y divide-gray-300 dark:divide-gray-600'>
{_map(user.sharedProjects, (item) => (
- <ProjectList
- key={item.id}
- item={item}
- removeProject={removeProject}
- removeShareProject={removeShareProject}
- setUserShareData={setUserShareData}
- setProjectsShareData={setProjectsShareData}
- />
+ <ProjectList key={item.id} item={item} />
))}
</tbody>
</table>
@@ -788,14 +766,7 @@ const UserSettings = ({
</thead>
<tbody className='divide-y divide-gray-300 dark:divide-gray-600'>
{_map(user.organisationMemberships, (membership) => (
- <Organisations
- key={membership.id}
- membership={membership}
- removeProject={removeProject}
- removeShareProject={removeShareProject}
- setUserShareData={setUserShareData}
- setProjectsShareData={setProjectsShareData}
- />
+ <Organisations key={membership.id} membership={membership} />
))}
</tbody>
</table>
@@ -943,11 +914,7 @@ const UserSettings = ({
>
{t('profileSettings.integrations')}
</h3>
- <Integrations
- user={user}
- updateUserData={updateUserData}
- handleIntegrationSave={handleIntegrationSave}
- />
+ <Integrations handleIntegrationSave={handleIntegrationSave} />
{user.isTelegramChatIdConfirmed && (
<Checkbox
checked={user.receiveLoginNotifications}
@@ -973,13 +940,7 @@ const UserSettings = ({
>
{t('profileSettings.referral.title')}
</h3>
- <Referral
- user={user}
- updateUserData={updateUserData}
- referralStatistics={referralStatistics}
- activeReferrals={activeReferrals}
- setCache={setCache}
- />
+ <Referral />
</>
)
}
@@ -1010,7 +971,7 @@ const UserSettings = ({
}}
onSubmit={() => {
setShowModal(false)
- _onDelete()
+ onAccountDelete()
}}
submitText={t('profileSettings.aDelete')}
closeText={t('common.close')}
diff --git a/web/app/pages/UserSettings/components/Integrations.tsx b/web/app/pages/UserSettings/components/Integrations.tsx
index 909e5aea6..862f0d742 100644
--- a/web/app/pages/UserSettings/components/Integrations.tsx
+++ b/web/app/pages/UserSettings/components/Integrations.tsx
@@ -13,6 +13,9 @@ import Slack from 'ui/icons/Slack'
import Discord from 'ui/icons/Discord'
import { removeTgIntegration } from 'api'
import { IUser } from 'redux/models/IUser'
+import { StateType, useAppDispatch } from 'redux/store'
+import { useSelector } from 'react-redux'
+import { authActions } from 'redux/reducers/auth'
const getAvailableIntegrations = (
t: typeof i18next.t,
@@ -48,15 +51,14 @@ const TG_BOT_USERNAME = '@swetrixbot'
const SLACK_WEBHOOKS_HELP = 'https://api.slack.com/messaging/webhooks'
const DISCORD_WEBHOOKS_HELP = 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'
-const Integrations = ({
- user,
- updateUserData,
- handleIntegrationSave,
-}: {
- user: IUser
- updateUserData: (data: Partial<IUser>) => void
+interface IntegrationsProps {
handleIntegrationSave: (data: Partial<IUser>, cb: (isSuccess: boolean) => void) => void
-}) => {
+}
+
+const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
+ const dispatch = useAppDispatch()
+ const { user } = useSelector((state: StateType) => state.auth)
+
const { t } = useTranslation('common')
const available = getAvailableIntegrations(t)
const [integrationConfigurating, setIntegrationConfigurating] = useState<string | null>(null)
@@ -165,10 +167,12 @@ const Integrations = ({
} else {
throw new Error('No chat ID')
}
- updateUserData({
- isTelegramChatIdConfirmed: false,
- telegramChatId: null,
- })
+ dispatch(
+ authActions.mergeUser({
+ isTelegramChatIdConfirmed: false,
+ telegramChatId: null,
+ }),
+ )
} catch (reason) {
if (_isString(reason)) {
toast.error(reason)
@@ -191,9 +195,11 @@ const Integrations = ({
toast.error(t('apiNotifications.integrationRemovalError'))
}
- updateUserData({
- slackWebhookUrl: null,
- })
+ dispatch(
+ authActions.mergeUser({
+ slackWebhookUrl: null,
+ }),
+ )
setIsRemovalLoading(false)
},
)
@@ -209,9 +215,11 @@ const Integrations = ({
toast.error(t('apiNotifications.integrationRemovalError'))
}
- updateUserData({
- discordWebhookUrl: null,
- })
+ dispatch(
+ authActions.mergeUser({
+ discordWebhookUrl: null,
+ }),
+ )
setIsRemovalLoading(false)
},
)
diff --git a/web/app/pages/UserSettings/components/Organisations.tsx b/web/app/pages/UserSettings/components/Organisations.tsx
index 9b5138b3d..ca1689f30 100644
--- a/web/app/pages/UserSettings/components/Organisations.tsx
+++ b/web/app/pages/UserSettings/components/Organisations.tsx
@@ -2,41 +2,45 @@ import React, { memo, useState } from 'react'
import dayjs from 'dayjs'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
+import _map from 'lodash/map'
+import _filter from 'lodash/filter'
import Button from 'ui/Button'
import Modal from 'ui/Modal'
-// import { deleteShareProject, acceptShareProject } from 'api'
-import { IProject } from 'redux/models/IProject'
+import { rejectOrganisationInvitation, acceptOrganisationInvitation } from 'api'
import { OrganisationMembership } from 'redux/models/Organisation'
+import { StateType, useAppDispatch } from 'redux/store'
+import { authActions } from 'redux/reducers/auth'
+import { useSelector } from 'react-redux'
interface OrganisationsProps {
membership: OrganisationMembership
- removeShareProject: (id: string) => void
- removeProject: (id: string) => void
- setProjectsShareData: (data: Partial<IProject>, id: string) => void
- setUserShareData: (data: Partial<IProject>, id: string) => void
}
-const Organisations = ({
- membership,
- removeShareProject,
- removeProject,
- setProjectsShareData,
- setUserShareData,
-}: OrganisationsProps) => {
+const Organisations = ({ membership }: OrganisationsProps) => {
+ const { user } = useSelector((state: StateType) => state.auth)
+ const dispatch = useAppDispatch()
const {
t,
i18n: { language },
} = useTranslation('common')
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const { organisation, confirmed, id, role, created } = membership
+ const { organisation, confirmed, role, created } = membership
- const deleteProject = async (pid: string) => {
+ const onQuit = async () => {
try {
- // await deleteShareProject(pid)
- // removeShareProject(pid)
- // removeProject(project.id)
+ await rejectOrganisationInvitation(membership.id)
+
+ dispatch(
+ authActions.mergeUser({
+ organisationMemberships: _filter(
+ user.organisationMemberships,
+ (userMembership) => userMembership.id !== membership.id,
+ ),
+ }),
+ )
+
toast.success(t('apiNotifications.quitOrganisation'))
} catch (reason) {
console.error(`[ERROR] Error while quitting project: ${reason}`)
@@ -46,9 +50,19 @@ const Organisations = ({
const onAccept = async () => {
try {
- // await acceptShareProject(id)
- // setProjectsShareData({ isAccessConfirmed: true }, project.id)
- // setUserShareData({ isAccessConfirmed: true }, id)
+ await acceptOrganisationInvitation(membership.id)
+
+ dispatch(
+ authActions.mergeUser({
+ organisationMemberships: _map(user.organisationMemberships, (item) => {
+ if (item.id === membership.id) {
+ return { ...item, confirmed: true }
+ }
+ return item
+ }),
+ }),
+ )
+
toast.success(t('apiNotifications.acceptInvitation'))
} catch (reason) {
console.error(`[ERROR] Error while accepting project invitation: ${reason}`)
@@ -79,7 +93,7 @@ const Organisations = ({
<Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>
{t('common.reject')}
</Button>
- <Button onClick={() => onAccept()} primary small>
+ <Button onClick={onAccept} primary small>
{t('common.accept')}
</Button>
</>
@@ -90,7 +104,7 @@ const Organisations = ({
}}
onSubmit={() => {
setShowDeleteModal(false)
- deleteProject(id)
+ onQuit()
}}
submitText={t('common.yes')}
type='confirmed'
diff --git a/web/app/pages/UserSettings/components/ProjectList.tsx b/web/app/pages/UserSettings/components/ProjectList.tsx
index 08981a222..f85807583 100644
--- a/web/app/pages/UserSettings/components/ProjectList.tsx
+++ b/web/app/pages/UserSettings/components/ProjectList.tsx
@@ -2,41 +2,46 @@ import React, { memo, useState } from 'react'
import dayjs from 'dayjs'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
+import _map from 'lodash/map'
+import _filter from 'lodash/filter'
import Button from 'ui/Button'
import Modal from 'ui/Modal'
-import { deleteShareProject, acceptShareProject } from 'api'
+import { rejectProjectShare, acceptProjectShare } from 'api'
import { ISharedProject } from 'redux/models/ISharedProject'
-import { IProject } from 'redux/models/IProject'
+import { StateType, useAppDispatch } from 'redux/store'
+import { authActions } from 'redux/reducers/auth'
+import UIActions from 'redux/reducers/ui'
+import { useSelector } from 'react-redux'
interface ProjectListProps {
item: ISharedProject
- removeShareProject: (id: string) => void
- removeProject: (id: string) => void
- setProjectsShareData: (data: Partial<IProject>, id: string) => void
- setUserShareData: (data: Partial<IProject>, id: string) => void
}
-const ProjectList = ({
- item,
- removeShareProject,
- removeProject,
- setProjectsShareData,
- setUserShareData,
-}: ProjectListProps) => {
+const ProjectList = ({ item }: ProjectListProps) => {
const {
t,
i18n: { language },
} = useTranslation('common')
+ const { user } = useSelector((state: StateType) => state.auth)
+ const dispatch = useAppDispatch()
const [showDeleteModal, setShowDeleteModal] = useState(false)
const { created, confirmed, id, role, project } = item
- const deleteProject = async (pid: string) => {
+ const onQuit = async () => {
try {
- await deleteShareProject(pid)
- removeShareProject(pid)
- removeProject(project.id)
+ await rejectProjectShare(item.id)
+ dispatch(
+ authActions.mergeUser({
+ sharedProjects: _filter(user.sharedProjects, (share) => share.id !== item.id),
+ }),
+ )
+ dispatch(
+ UIActions.removeProject({
+ pid: project.id,
+ }),
+ )
toast.success(t('apiNotifications.quitProject'))
} catch (reason) {
console.error(`[ERROR] Error while quitting project: ${reason}`)
@@ -46,9 +51,26 @@ const ProjectList = ({
const onAccept = async () => {
try {
- await acceptShareProject(id)
- setProjectsShareData({ isAccessConfirmed: true }, project.id)
- setUserShareData({ isAccessConfirmed: true }, id)
+ await acceptProjectShare(id)
+
+ dispatch(
+ UIActions.setProjectsShareData({
+ data: { isAccessConfirmed: true },
+ id: project.id,
+ }),
+ )
+
+ dispatch(
+ authActions.mergeUser({
+ sharedProjects: _map(user.sharedProjects, (item) => {
+ if (item.id === id) {
+ return { ...item, confirmed: true }
+ }
+ return item
+ }),
+ }),
+ )
+
toast.success(t('apiNotifications.acceptInvitation'))
} catch (reason) {
console.error(`[ERROR] Error while accepting project invitation: ${reason}`)
@@ -79,7 +101,7 @@ const ProjectList = ({
<Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>
{t('common.reject')}
</Button>
- <Button onClick={() => onAccept()} primary small>
+ <Button onClick={onAccept} primary small>
{t('common.accept')}
</Button>
</>
@@ -90,7 +112,7 @@ const ProjectList = ({
}}
onSubmit={() => {
setShowDeleteModal(false)
- deleteProject(id)
+ onQuit()
}}
submitText={t('common.yes')}
type='confirmed'
diff --git a/web/app/pages/UserSettings/components/Referral.tsx b/web/app/pages/UserSettings/components/Referral.tsx
index cd15ba278..5639a75ca 100644
--- a/web/app/pages/UserSettings/components/Referral.tsx
+++ b/web/app/pages/UserSettings/components/Referral.tsx
@@ -1,4 +1,4 @@
-import React, { memo, useState, useEffect } from 'react'
+import React, { useState, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
import dayjs from 'dayjs'
import _isEmpty from 'lodash/isEmpty'
@@ -10,7 +10,6 @@ import Tooltip from 'ui/Tooltip'
import Highlighted from 'ui/Highlighted'
import Input from 'ui/Input'
import Button from 'ui/Button'
-import { IUser } from 'redux/models/IUser'
import {
REF_URL_PREFIX,
DOCS_REFERRAL_PROGRAM_URL,
@@ -23,16 +22,16 @@ import {
REFERRAL_CUT,
} from 'redux/constants'
import { isValidEmail } from 'utils/validator'
+import { useSelector } from 'react-redux'
+import { StateType, useAppDispatch } from 'redux/store'
+import UIActions from 'redux/reducers/ui'
+import { authActions } from 'redux/reducers/auth'
-interface IReferral {
- user: IUser
- updateUserData: (data: Partial<IUser>) => void
- setCache: (key: string, value: any) => void
- activeReferrals: any[]
- referralStatistics: any
-}
+const Referral = () => {
+ const { user } = useSelector((state: StateType) => state.auth)
+ const { activeReferrals, referralStatistics } = useSelector((state: StateType) => state.ui.cache)
+ const dispatch = useAppDispatch()
-const Referral = ({ user, updateUserData, referralStatistics, activeReferrals, setCache }: IReferral) => {
const {
t,
i18n: { language },
@@ -50,7 +49,12 @@ const Referral = ({ user, updateUserData, referralStatistics, activeReferrals, s
const getRefStats = async () => {
try {
const info = await getPayoutsInfo()
- setCache('referralStatistics', info)
+ dispatch(
+ UIActions.setCache({
+ key: 'referralStatistics',
+ value: info,
+ }),
+ )
} catch (reason) {
console.error('[Referral][getRefStats] Something went wrong whilst requesting payouts information', reason)
toast.error(t('apiNotifications.payoutInfoError'))
@@ -60,7 +64,12 @@ const Referral = ({ user, updateUserData, referralStatistics, activeReferrals, s
const getActiveReferrals = async () => {
try {
const info = await getReferrals()
- setCache('activeReferrals', info)
+ dispatch(
+ UIActions.setCache({
+ key: 'activeReferrals',
+ value: info,
+ }),
+ )
} catch (reason) {
console.error('[Referral][getActiveReferrals] Something went wrong whilst requesting active referrals', reason)
toast.error(t('apiNotifications.payoutInfoError'))
@@ -76,7 +85,7 @@ const Referral = ({ user, updateUserData, referralStatistics, activeReferrals, s
setActiveReferralsRequested(true)
getActiveReferrals()
}
- }, [referralStatistics, referralStatsRequested, setCache, activeReferralsRequested, activeReferrals, t])
+ }, [referralStatistics, referralStatsRequested, activeReferralsRequested, activeReferrals, t, dispatch])
const onRefCodeGenerate = async () => {
if (refCodeGenerating || user.refCode) {
@@ -87,9 +96,11 @@ const Referral = ({ user, updateUserData, referralStatistics, activeReferrals, s
try {
const { refCode } = await generateRefCode()
- updateUserData({
- refCode,
- })
+ dispatch(
+ authActions.mergeUser({
+ refCode,
+ }),
+ )
} catch {
toast.error(t('apiNotifications.somethingWentWrong'))
} finally {
@@ -116,9 +127,11 @@ const Referral = ({ user, updateUserData, referralStatistics, activeReferrals, s
try {
await setPaypalEmail(paypalEmailAddress)
- updateUserData({
- paypalPaymentsEmail: paypalEmailAddress,
- })
+ dispatch(
+ authActions.mergeUser({
+ paypalPaymentsEmail: paypalEmailAddress,
+ }),
+ )
toast.success(t('profileSettings.referral.payoutEmailUpdated'))
} catch (reason) {
console.error('[Referral][updatePaypalEmail] Something went wrong whilst updating paypal email', reason)
@@ -307,4 +320,4 @@ const Referral = ({ user, updateUserData, referralStatistics, activeReferrals, s
)
}
-export default memo(Referral)
+export default Referral
diff --git a/web/app/pages/UserSettings/components/Socialisations.tsx b/web/app/pages/UserSettings/components/Socialisations.tsx
index 704acb3cd..3142dba60 100644
--- a/web/app/pages/UserSettings/components/Socialisations.tsx
+++ b/web/app/pages/UserSettings/components/Socialisations.tsx
@@ -1,5 +1,4 @@
-import React, { useState, memo } from 'react'
-import type i18next from 'i18next'
+import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import _map from 'lodash/map'
import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
@@ -11,6 +10,9 @@ import GithubDark from 'ui/icons/GithubDark'
import GithubLight from 'ui/icons/GithubLight'
import { IUser } from 'redux/models/IUser'
import { SSO_PROVIDERS } from 'redux/constants'
+import { StateType, useAppDispatch } from 'redux/store'
+import sagaActions from 'redux/sagas/actions'
+import { useSelector } from 'react-redux'
const AVAILABLE_SSO_PROVIDERS = [
{
@@ -48,38 +50,38 @@ const getStatusByUser = (user: IUser, socialisation: string) => {
return [false, false]
}
-interface ISocialisations {
- user: IUser
- linkSSO: (t: typeof i18next.t, callback: (e: any) => void, provider: string) => void
- unlinkSSO: (t: typeof i18next.t, callback: (e: any) => void, provider: string) => void
- theme: string
-}
-
-const Socialisations = ({ user, linkSSO, unlinkSSO, theme }: ISocialisations) => {
+const Socialisations = () => {
+ const { user } = useSelector((state: StateType) => state.auth)
+ const { theme } = useSelector((state: StateType) => state.ui.theme)
+ const dispatch = useAppDispatch()
const { t } = useTranslation('common')
const [isLoading, setIsLoading] = useState(false)
- const _linkSSO = (provider: string) => {
+ const linkSSO = (provider: string) => {
setIsLoading(true)
- linkSSO(
- t,
- () => {
- setIsLoading(false)
- },
- provider,
+ dispatch(
+ sagaActions.linkSSO(
+ t,
+ () => {
+ setIsLoading(false)
+ },
+ provider,
+ ),
)
}
- const _unlinkSSO = (provider: string) => {
+ const unlinkSSO = (provider: string) => {
setIsLoading(true)
- unlinkSSO(
- t,
- () => {
- setIsLoading(false)
- },
- provider,
+ dispatch(
+ sagaActions.unlinkSSO(
+ t,
+ () => {
+ setIsLoading(false)
+ },
+ provider,
+ ),
)
}
@@ -131,13 +133,13 @@ const Socialisations = ({ user, linkSSO, unlinkSSO, theme }: ISocialisations) =>
)}
{connected && unlinkable && (
- <Button onClick={() => _unlinkSSO(key)} loading={isLoading} small danger>
+ <Button onClick={() => unlinkSSO(key)} loading={isLoading} small danger>
{t('common.unlink')}
</Button>
)}
{!connected && (
- <Button onClick={() => _linkSSO(key)} loading={isLoading} small primary>
+ <Button onClick={() => linkSSO(key)} loading={isLoading} small primary>
{t('common.link')}
</Button>
)}
@@ -152,4 +154,4 @@ const Socialisations = ({ user, linkSSO, unlinkSSO, theme }: ISocialisations) =>
)
}
-export default memo(Socialisations)
+export default Socialisations
diff --git a/web/app/pages/UserSettings/components/TwoFA.tsx b/web/app/pages/UserSettings/components/TwoFA.tsx
index a52e91c93..f68165e09 100644
--- a/web/app/pages/UserSettings/components/TwoFA.tsx
+++ b/web/app/pages/UserSettings/components/TwoFA.tsx
@@ -1,4 +1,4 @@
-import React, { useState, memo } from 'react'
+import React, { useState } from 'react'
import QRCode from 'react-qr-code'
import { useTranslation } from 'react-i18next'
import cx from 'clsx'
@@ -11,17 +11,14 @@ import Button from 'ui/Button'
import { generate2FA, enable2FA, disable2FA } from 'api'
import { setAccessToken } from 'utils/accessToken'
import { setRefreshToken } from 'utils/refreshToken'
-import { IUser } from 'redux/models/IUser'
-
-const TwoFA = ({
- user,
- dontRemember,
- updateUserData,
-}: {
- user: IUser
- dontRemember: boolean
- updateUserData: (data: Partial<IUser>) => void
-}): JSX.Element => {
+import { StateType, useAppDispatch } from 'redux/store'
+import { useSelector } from 'react-redux'
+import { authActions } from 'redux/reducers/auth'
+
+const TwoFA = () => {
+ const dispatch = useAppDispatch()
+ const { user, dontRemember } = useSelector((state: StateType) => state.auth)
+
const { t } = useTranslation('common')
const [twoFAConfigurating, setTwoFAConfigurating] = useState(false)
const [twoFADisabling, setTwoFADisabling] = useState(false)
@@ -74,7 +71,7 @@ const TwoFA = ({
const { twoFactorRecoveryCode, accessToken, refreshToken } = await enable2FA(twoFACode)
setRefreshToken(refreshToken)
setAccessToken(accessToken, dontRemember)
- updateUserData({ isTwoFactorAuthenticationEnabled: true })
+ dispatch(authActions.mergeUser({ isTwoFactorAuthenticationEnabled: true }))
setTwoFARecovery(twoFactorRecoveryCode)
} catch (reason) {
if (_isString(reason)) {
@@ -94,7 +91,7 @@ const TwoFA = ({
try {
await disable2FA(twoFACode)
- updateUserData({ isTwoFactorAuthenticationEnabled: false })
+ dispatch(authActions.mergeUser({ isTwoFactorAuthenticationEnabled: false }))
} catch (reason) {
if (_isString(reason)) {
toast.error(reason)
@@ -224,4 +221,4 @@ const TwoFA = ({
)
}
-export default memo(TwoFA)
+export default TwoFA
diff --git a/web/app/pages/UserSettings/index.tsx b/web/app/pages/UserSettings/index.tsx
index f15e496b0..5595866d9 100644
--- a/web/app/pages/UserSettings/index.tsx
+++ b/web/app/pages/UserSettings/index.tsx
@@ -1,3 +1,3 @@
-import UserSettings from './UserSettings.container'
+import UserSettings from './UserSettings'
export default UserSettings
diff --git a/web/app/redux/constants/index.ts b/web/app/redux/constants/index.ts
index f9364d886..a0f4778f6 100644
--- a/web/app/redux/constants/index.ts
+++ b/web/app/redux/constants/index.ts
@@ -481,30 +481,8 @@ export const paddleLanguageMapping: IStringObject = {
// This will prevent cached version or raw locale strings being displayed in production
export const I18N_CACHE_BREAKER = 10
-// dashboard && projects
-
export const roles: Role[] = ['admin', 'viewer']
-export const roleViewer: {
- name: string
- role: string
- description: string
-} = {
- name: 'Viewer',
- role: 'viewer',
- description: 'Can view the project',
-}
-
-export const roleAdmin: {
- name: string
- role: string
- description: string
-} = {
- name: 'Admin',
- role: 'admin',
- description: 'Can manage the project',
-}
-
const SELFHOSTED_PROJECT_TABS = {
traffic: 'traffic',
performance: 'performance',
diff --git a/web/app/redux/reducers/auth.ts b/web/app/redux/reducers/auth.ts
index f17b74340..2d774b6b2 100644
--- a/web/app/redux/reducers/auth.ts
+++ b/web/app/redux/reducers/auth.ts
@@ -1,25 +1,17 @@
-/* eslint-disable @typescript-eslint/no-unused-expressions */
-/* eslint-disable no-unused-expressions */
-/* eslint-disable no-param-reassign */
-import { createSlice, current, PayloadAction } from '@reduxjs/toolkit'
-import _filter from 'lodash/filter'
-import _map from 'lodash/map'
+import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { IUser } from '../models/IUser'
import { FREE_TIER_KEY, isSelfhosted } from '../constants'
-import { ISharedProject } from '../models/ISharedProject'
-interface IAuthState {
+interface AuthState {
user: IUser
- redirectPath: string | null
authenticated: boolean
loading: boolean
dontRemember: boolean
isPaidTierUsed: boolean
}
-const initialState: IAuthState = {
+const initialState: AuthState = {
user: {} as IUser,
- redirectPath: null,
authenticated: false,
loading: true,
dontRemember: false,
@@ -34,62 +26,24 @@ const authSlice = createSlice({
finishLoading: (state) => {
state.loading = false
},
- loginSuccessful: (state, { payload }: PayloadAction<IUser>) => {
+ authSuccessful: (state, { payload }: PayloadAction<IUser>) => {
state.user = payload
state.authenticated = true
state.isPaidTierUsed = isSelfhosted || ((payload?.planCode && payload.planCode !== FREE_TIER_KEY) as boolean)
},
- emailVerifySuccessful: (state) => {
- state.user = { ...state.user, isActive: true }
- },
- signupUpSuccessful: (state, { payload }: PayloadAction<IUser>) => {
- state.user = payload
- state.authenticated = true
- state.isPaidTierUsed = isSelfhosted || ((payload?.planCode && payload.planCode !== FREE_TIER_KEY) as boolean)
- },
- updateUserProfileSuccess: (state, { payload }: PayloadAction<IUser>) => {
- state.user = payload
- },
- partiallyOverwriteUser: (state, { payload }: PayloadAction<Partial<IUser>>) => {
- state.user = { ...state.user, ...payload }
- },
logout: (state) => {
state.user = {} as IUser
state.authenticated = false
state.isPaidTierUsed = isSelfhosted
},
- savePath: (state, { payload }: PayloadAction<string>) => {
- state.redirectPath = payload
- },
- deleteAccountSuccess: (state) => {
- state.user = {} as IUser
- state.authenticated = false
- state.isPaidTierUsed = isSelfhosted
- },
- deleteShareProject: (state, { payload }: PayloadAction<string>) => {
- const projects = _filter(state.user?.sharedProjects, (item) => item.id !== payload)
- state.user = { ...state.user, sharedProjects: projects }
- },
- setUserShareData: (state, { payload }: PayloadAction<{ data: Partial<ISharedProject>; id: string }>) => {
- const projects = _map(current(state.user?.sharedProjects), (item) => {
- if (item.id === payload.id) {
- return { ...item, ...payload.data }
- }
- return item
- })
- state.user = { ...state.user, sharedProjects: projects }
- },
setDontRemember: (state, { payload }: PayloadAction<boolean>) => {
state.dontRemember = payload
},
- updateUserData: (state, { payload }: PayloadAction<IUser>) => {
+ mergeUser: (state, { payload }: PayloadAction<Partial<IUser>>) => {
state.user = { ...state.user, ...payload }
},
- setApiKey: (state, { payload }: PayloadAction<string>) => {
- state.user = { ...state.user, apiKey: payload }
- },
setUser: (state, { payload }: PayloadAction<IUser>) => {
- state.user = { ...state.user, ...payload }
+ state.user = payload
},
},
})
diff --git a/web/app/redux/sagas/actions/index.ts b/web/app/redux/sagas/actions/index.ts
index 5d0a7ee1f..97f0d4b22 100644
--- a/web/app/redux/sagas/actions/index.ts
+++ b/web/app/redux/sagas/actions/index.ts
@@ -39,7 +39,7 @@ const loginAsync = (
password: string
dontRemember: boolean
},
- callback = () => {},
+ callback: (isSuccess: boolean, isTwoFactorAuthenticationEnabled: boolean) => void = () => {},
) => ({
type: types.LOGIN_ASYNC,
payload: {
diff --git a/web/app/redux/sagas/auth/workers/deleteUserAccount.ts b/web/app/redux/sagas/auth/workers/deleteUserAccount.ts
index 594d664f7..a6bf246d2 100644
--- a/web/app/redux/sagas/auth/workers/deleteUserAccount.ts
+++ b/web/app/redux/sagas/auth/workers/deleteUserAccount.ts
@@ -18,7 +18,7 @@ export default function* deleteUserAccountWorker({
try {
yield call(deleteUser, deletionFeedback)
yield call(successCallback)
- yield put(authActions.deleteAccountSuccess())
+ yield put(authActions.logout())
toast.success(t('apiNotifications.accountDeleted'))
} catch (reason) {
let message
diff --git a/web/app/redux/sagas/auth/workers/signin.ts b/web/app/redux/sagas/auth/workers/signin.ts
index e48157c18..0e7f5e4f5 100644
--- a/web/app/redux/sagas/auth/workers/signin.ts
+++ b/web/app/redux/sagas/auth/workers/signin.ts
@@ -31,12 +31,12 @@ export default function* singinWorker({ payload: { credentials, callback } }: IS
if (user.isTwoFactorAuthenticationEnabled) {
yield call(setAccessToken, accessToken, true)
yield call(setRefreshToken, refreshToken, true)
- yield put(authActions.updateUserData(user))
+ yield put(authActions.mergeUser(user))
callback(false, true)
return
}
- yield put(authActions.loginSuccessful(user))
+ yield put(authActions.authSuccessful(user))
yield call(setAccessToken, accessToken, dontRemember)
yield call(setRefreshToken, refreshToken)
yield put(UIActions.setThemeType(user.theme))
diff --git a/web/app/redux/sagas/auth/workers/signup.ts b/web/app/redux/sagas/auth/workers/signup.ts
index 4e279d07d..fa656b269 100644
--- a/web/app/redux/sagas/auth/workers/signup.ts
+++ b/web/app/redux/sagas/auth/workers/signup.ts
@@ -42,7 +42,7 @@ export default function* signupWorder({
deleteCookie(REFERRAL_COOKIE)
}
- yield put(authActions.signupUpSuccessful(user))
+ yield put(authActions.authSuccessful(user))
yield call(setAccessToken, accessToken, dontRemember)
yield call(setRefreshToken, refreshToken)
yield put(authActions.setDontRemember(dontRemember))
diff --git a/web/app/redux/sagas/auth/workers/sso_auth.ts b/web/app/redux/sagas/auth/workers/sso_auth.ts
index 893501909..04c90af80 100644
--- a/web/app/redux/sagas/auth/workers/sso_auth.ts
+++ b/web/app/redux/sagas/auth/workers/sso_auth.ts
@@ -61,12 +61,12 @@ export default function* ssoAuth({ payload: { callback, dontRemember, t, provide
if (user.isTwoFactorAuthenticationEnabled) {
yield call(setAccessToken, accessToken, true)
yield call(setRefreshToken, refreshToken)
- yield put(authActions.updateUserData(user))
+ yield put(authActions.mergeUser(user))
callback(false, true)
return
}
- yield put(authActions.loginSuccessful(user))
+ yield put(authActions.authSuccessful(user))
yield call(setAccessToken, accessToken, dontRemember)
yield call(setRefreshToken, refreshToken)
// yield put(UIActions.setThemeType(user.theme))
diff --git a/web/app/redux/sagas/auth/workers/sso_link.ts b/web/app/redux/sagas/auth/workers/sso_link.ts
index 0c509a282..b58411602 100644
--- a/web/app/redux/sagas/auth/workers/sso_link.ts
+++ b/web/app/redux/sagas/auth/workers/sso_link.ts
@@ -46,7 +46,7 @@ export default function* ssoLink({ payload: { callback, t, provider } }: ISSOLin
// @ts-ignore
const user = yield call(authMe)
- yield put(authActions.loginSuccessful(user))
+ yield put(authActions.authSuccessful(user))
toast.success(t('apiNotifications.socialAccountLinked'))
diff --git a/web/app/redux/sagas/auth/workers/sso_unlink.ts b/web/app/redux/sagas/auth/workers/sso_unlink.ts
index b9868fcbe..39058f559 100644
--- a/web/app/redux/sagas/auth/workers/sso_unlink.ts
+++ b/web/app/redux/sagas/auth/workers/sso_unlink.ts
@@ -27,7 +27,7 @@ export default function* ssoUnlink({ payload: { provider, t, callback } }: ISSOU
// @ts-ignore
const user = yield call(authMe)
- yield put(authActions.loginSuccessful(user))
+ yield put(authActions.authSuccessful(user))
toast.success(t('apiNotifications.socialAccountUninked'))
callback(true)
diff --git a/web/app/redux/sagas/auth/workers/updateUserProfile.ts b/web/app/redux/sagas/auth/workers/updateUserProfile.ts
index fc1897b01..5cbbeefde 100644
--- a/web/app/redux/sagas/auth/workers/updateUserProfile.ts
+++ b/web/app/redux/sagas/auth/workers/updateUserProfile.ts
@@ -17,7 +17,7 @@ export default function* updateUserProfileWorker({
try {
const user: IUser = yield call(changeUserDetails, data)
- yield put(authActions.updateUserProfileSuccess(user))
+ yield put(authActions.setUser(user))
isSuccess = true
} catch (reason: any) {
toast.error(reason?.message || (typeof reason === 'string' ? reason : reason[0]))
diff --git a/web/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts b/web/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts
index cdb9a19a4..f587c3de8 100644
--- a/web/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts
+++ b/web/app/redux/sagas/auth/workers/update_show_live_visitors_in_title.ts
@@ -16,7 +16,7 @@ export default function* updateShowLiveVisitorsInTitle({ payload: { show, callba
try {
const user: Partial<IUser> = yield call(setShowLiveVisitorsInTitle, show)
- yield put(authActions.partiallyOverwriteUser(user))
+ yield put(authActions.mergeUser(user))
isSuccess = true
} catch (reason: any) {
toast.error(reason?.message || (typeof reason === 'string' ? reason : reason[0]))
diff --git a/web/app/redux/sagas/auth/workers/verifyEmail.ts b/web/app/redux/sagas/auth/workers/verifyEmail.ts
index e0dc67ee1..4c40340ca 100644
--- a/web/app/redux/sagas/auth/workers/verifyEmail.ts
+++ b/web/app/redux/sagas/auth/workers/verifyEmail.ts
@@ -17,7 +17,7 @@ export default function* verifyEmailWorker({
try {
// @ts-ignore
yield call(verifyEmail, data)
- yield put(authActions.emailVerifySuccessful())
+ yield put(authActions.mergeUser({ isActive: true }))
successfulCallback()
} catch (reason) {
errorCallback(reason)
diff --git a/web/app/pages/Organisations/Settings/TransferProject/TransferProjectConfirm.tsx b/web/app/routes/organisation.invite.$id.tsx
similarity index 80%
rename from web/app/pages/Organisations/Settings/TransferProject/TransferProjectConfirm.tsx
rename to web/app/routes/organisation.invite.$id.tsx
index 76d06c981..44d68fb6b 100644
--- a/web/app/pages/Organisations/Settings/TransferProject/TransferProjectConfirm.tsx
+++ b/web/app/routes/organisation.invite.$id.tsx
@@ -1,41 +1,39 @@
-import React, { useState, useEffect, memo } from 'react'
-import { Link } from '@remix-run/react'
+import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/outline'
+import { Link, useParams } from '@remix-run/react'
+import { acceptOrganisationInvitation } from 'api'
+import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { CheckCircleIcon, XCircleIcon } from '@heroicons/react/24/solid'
import Loader from 'ui/Loader'
-
-import { confirmTransferProject } from 'api'
import routes from 'utils/routes'
-const TransferProjectConfirm = (): JSX.Element => {
+export default function ConfirmOrganisationInvitation() {
const { t } = useTranslation('common')
+ const { id } = useParams()
const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
-
- const handleConfirm = async (token: string) => {
- try {
- await confirmTransferProject(token)
- } catch {
- setError(t('apiNotifications.invalidToken'))
- } finally {
- setLoading(false)
- }
- }
+ const [error, setError] = useState<string | null>(null)
useEffect(() => {
setLoading(true)
- const query = new URLSearchParams(window.location.search)
- const token = query.get('token')
- if (!token) {
- setError(t('apiNotifications.invalidToken'))
+ if (!id) {
+ setError(t('common.error'))
setLoading(false)
return
}
- handleConfirm(token)
- }, []) // eslint-disable-line
+ const acceptInvitation = async () => {
+ try {
+ await acceptOrganisationInvitation(id)
+ } catch (reason) {
+ setError(typeof reason === 'string' ? reason : t('apiNotifications.acceptOrganisationInvitationError'))
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ acceptInvitation()
+ }, [id]) // eslint-disable-line
if (loading) {
return (
@@ -86,7 +84,7 @@ const TransferProjectConfirm = (): JSX.Element => {
<div className='sm:ml-6'>
<div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
<h1 className='text-4xl font-extrabold tracking-tight text-gray-900 dark:text-gray-50 sm:text-5xl'>
- {t('apiNotifications.acceptInvitation')}
+ {t('apiNotifications.acceptOrganisationInvitation')}
</h1>
</div>
<div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
@@ -103,5 +101,3 @@ const TransferProjectConfirm = (): JSX.Element => {
</div>
)
}
-
-export default memo(TransferProjectConfirm)
diff --git a/web/app/ui/Button.tsx b/web/app/ui/Button.tsx
index 792adc7fb..ce45e8e66 100644
--- a/web/app/ui/Button.tsx
+++ b/web/app/ui/Button.tsx
@@ -20,6 +20,7 @@ interface IButton extends React.ComponentPropsWithoutRef<typeof HeadlessButton>
semiDanger?: boolean
focus?: boolean
noBorder?: boolean
+ title?: string
}
const Button = ({
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 5be9388d3..5900356c5 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -22,6 +22,8 @@
"quitOrganisationError": "Error occurred while quitting the organisation",
"acceptInvitationError": "Error occurred while accepting the project invitation",
"acceptInvitation": "The project invitation has been accepted",
+ "acceptOrganisationInvitation": "The organisation invitation has been accepted",
+ "acceptOrganisationInvitationError": "Error occurred while accepting the organisation invitation",
"subscriptionUpdated": "Your subscription has been updated",
"generate2FAError": "Error occurred while generating 2FA code",
"integrationRemovalError": "Error occurred while removing the integration",