📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
feat: Project management for organisations
Blue Mouse5c931bfae5a9
diff --git a/backend/apps/cloud/src/organisation/dto/organisation.dto.ts b/backend/apps/cloud/src/organisation/dto/organisation.dto.tsindex 95fd4efc1..8b4587ad8 100644--- a/backend/apps/cloud/src/organisation/dto/organisation.dto.ts+++ b/backend/apps/cloud/src/organisation/dto/organisation.dto.ts@@ -19,3 +19,9 @@ export class UpdateMemberRoleDTO {@IsEnum(OrganisationRole)role: OrganisationRole}++export class UpdateOrganisationDTO {+ @IsString()+ @Length(1, 50)+ name: string+}diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.tsindex 98789f8ae..e9bb8d556 100644--- a/backend/apps/cloud/src/organisation/organisation.controller.ts+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts@@ -1,7 +1,6 @@import {Controller,Post,- Put,Delete,Body,Param,@@ -13,9 +12,10 @@ import {Get,Query,ForbiddenException,+ Patch,} from '@nestjs/common'import { ApiBearerAuth, ApiQuery, ApiResponse } from '@nestjs/swagger'-import { isEmpty as _isEmpty, find as _find } from 'lodash'+import { isEmpty as _isEmpty, find as _find, trim as _trim } from 'lodash'import { FindOptionsWhere, ILike, In } from 'typeorm'import { JwtAccessTokenGuard } from '../auth/guards/jwt-access-token.guard'@@ -33,6 +33,7 @@ import {CreateOrganisationDTO,InviteMemberDTO,UpdateMemberRoleDTO,+ UpdateOrganisationDTO,} from './dto/organisation.dto'import { OrganisationRole } from './entity/organisation-member.entity'import { AppLoggerService } from '../logger/logger.service'@@ -267,7 +268,7 @@ export class OrganisationController {}@ApiBearerAuth()- @Put('/member/:memberId')+ @Patch('/member/:memberId')@HttpCode(200)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@@ -279,12 +280,17 @@ export class OrganisationController {) {this.logger.log({ uid, memberId, updateDTO },- 'PUT /organisation/member/:memberId',+ 'PATCH /organisation/member/:memberId',)const membership = await this.organisationService.findOneMembership({where: { id: memberId },- relations: ['organisation', 'organisation.owner', 'user'],+ relations: [+ 'organisation',+ 'organisation.members',+ 'organisation.members.user',+ 'user',+ ],})if (_isEmpty(membership)) {@@ -302,7 +308,10 @@ export class OrganisationController {throw new BadRequestException('You cannot modify your own role')}- if (membership.role === OrganisationRole.owner) {+ if (+ membership.role === OrganisationRole.owner ||+ updateDTO.role === OrganisationRole.owner+ ) {throw new BadRequestException('Cannot modify owner role')}@@ -325,7 +334,12 @@ export class OrganisationController {const membership = await this.organisationService.findOneMembership({where: { id: memberId },- relations: ['organisation', 'organisation.owner', 'user'],+ relations: [+ 'organisation',+ 'organisation.members',+ 'organisation.members.user',+ 'user',+ ],})if (_isEmpty(membership)) {@@ -345,4 +359,39 @@ export class OrganisationController {await this.organisationService.deleteMembership(memberId)}++ @ApiBearerAuth()+ @Patch('/:orgId')+ @ApiResponse({ status: 200, type: Organisation })+ @Auth([], true)+ async update(+ @Param('orgId') orgId: string,+ @Body() updateOrgDTO: UpdateOrganisationDTO,+ @CurrentUserId() userId: string,+ ) {+ this.logger.log(+ { orgId, updateOrgDTO, userId },+ 'PATCH /organisation/:orgId',+ )++ const canManage = await this.organisationService.canManageOrganisation(+ orgId,+ userId,+ )++ if (!canManage) {+ throw new ForbiddenException(+ 'You do not have permission to manage this organisation',+ )+ }++ try {+ await this.organisationService.update(orgId, {+ name: _trim(updateOrgDTO.name),+ })+ } catch (e) {+ console.error('[ERROR] Failed to update organisation:', e)+ throw new BadRequestException('Failed to update organisation')+ }+ }}diff --git a/backend/apps/cloud/src/organisation/organisation.service.ts b/backend/apps/cloud/src/organisation/organisation.service.tsindex e9d40ae84..16bb8536d 100644--- a/backend/apps/cloud/src/organisation/organisation.service.ts+++ b/backend/apps/cloud/src/organisation/organisation.service.ts@@ -29,6 +29,10 @@ export class OrganisationService {return this.organisationRepository.save(org)}+ async update(id: string, data: Partial<Organisation>) {+ return this.organisationRepository.update(id, data)+ }+async findOne(options: FindOneOptions<Organisation>): Promise<Organisation> {return this.organisationRepository.findOne(options)}diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.tsindex 0ca7817aa..96e27d83d 100644--- a/backend/apps/cloud/src/project/project.controller.ts+++ b/backend/apps/cloud/src/project/project.controller.ts@@ -154,10 +154,10 @@ export class ProjectController {@Query('search') search: string | undefined,): Promise<Pagination<Project> | Project[] | object> {this.logger.log({ userId, take, skip }, 'GET /project')- const [paginated, totalMonthlyEvents, user] = await Promise.all([++ const [paginated, totalMonthlyEvents] = await Promise.all([this.projectService.paginate({ take, skip }, userId, search),this.projectService.getRedisCount(userId),- this.userService.findOne({ where: { id: userId } }),])const pidsWithData =@@ -170,17 +170,38 @@ export class ProjectController {_map(paginated.results, ({ id }) => id),)- paginated.results = _map(paginated.results, project => ({- ...project,- isOwner: project.admin.id === userId,- isShareConfirmed: true,- isLocked: !!user?.dashboardBlockReason,- isDataExists: _includes(pidsWithData, project?.id),- isErrorDataExists: _includes(pidsWithErrorData, project?.id),- organisationId: project?.organisation?.id,- passwordHash: undefined,- admin: undefined,- }))+ paginated.results = _map(paginated.results, project => {+ const userShare = project.share.find(share => share.user.id === userId)+ const organisationMembership = project.organisation?.members.find(+ member => member.user.id === userId,+ )++ let role+ let isAccessConfirmed = true++ if (project.admin.id === userId) {+ role = 'owner'+ } else if (userShare) {+ role = userShare.role+ isAccessConfirmed = userShare.confirmed+ } else if (organisationMembership) {+ role = organisationMembership.role+ isAccessConfirmed = organisationMembership.confirmed+ }++ return {+ ...project,+ isOwner: project.admin.id === userId, // deprecated+ isAccessConfirmed,+ isLocked: !!project.admin?.dashboardBlockReason,+ isDataExists: _includes(pidsWithData, project?.id),+ isErrorDataExists: _includes(pidsWithErrorData, project?.id),+ organisationId: project?.organisation?.id,+ role,+ passwordHash: undefined,+ admin: undefined,+ }+ })return {...paginated,@@ -566,15 +587,12 @@ export class ProjectController {)}- const user = await this.userService.findOne({ where: { id: uid } })- const project = await this.projectService.getFullProject(id)+ const project = await this.projectService.getOwnProject(id, uid)if (_isEmpty(project)) {throw new NotFoundException(`Project with ID ${id} does not exist`)}- this.projectService.allowedToManage(project, uid, user.roles)-const queries = ['DELETE FROM analytics WHERE pid={pid:FixedString(12)}','DELETE FROM customEV WHERE pid={pid:FixedString(12)}',@@ -836,7 +854,7 @@ export class ProjectController {const organisation = await this.organisationService.findOne({where: { id: orgId },- relations: ['members', 'projects'],+ relations: ['members', 'members.user', 'projects'],})if (_isEmpty(organisation)) {@@ -1578,15 +1596,13 @@ export class ProjectController {'The provided Project ID (pid) is incorrect',)}- const user = await this.userService.findOne({ where: { id: uid } })- const project = await this.projectService.getFullProject(id)++ const project = await this.projectService.getOwnProject(id, uid)if (_isEmpty(project)) {throw new NotFoundException(`Project with ID ${id} does not exist`)}- this.projectService.allowedToManage(project, uid, user.roles)-const queries = ['DELETE FROM analytics WHERE pid={pid:FixedString(12)}','DELETE FROM customEV WHERE pid={pid:FixedString(12)}',@@ -1922,20 +1938,47 @@ export class ProjectController {this.projectService.allowedToView(project, uid, headers['x-password'])- const isDataExists = !_isEmpty(- await this.projectService.getPIDsWhereAnalyticsDataExists([id]),- )+ const [isDataExists, isErrorDataExists] = await Promise.all([+ !_isEmpty(+ await this.projectService.getPIDsWhereAnalyticsDataExists([id]),+ ),+ !_isEmpty(await this.projectService.getPIDsWhereErrorsDataExists([id])),+ ])- const isErrorDataExists = !_isEmpty(- await this.projectService.getPIDsWhereErrorsDataExists([id]),- )+ let role+ let isAccessConfirmed = true++ if (uid) {+ const userShare = project.share?.find(share => share.user?.id === uid)+ const organisationMembership = project.organisation?.members?.find(+ member => member.user?.id === uid,+ )++ if (project.admin?.id === uid) {+ role = 'owner'+ } else if (userShare) {+ role = userShare.role+ isAccessConfirmed = userShare.confirmed+ } else if (organisationMembership) {+ role = organisationMembership.role+ isAccessConfirmed = organisationMembership.confirmed+ }+ }return {- ..._omit(project, ['admin', 'passwordHash', 'share']),- isOwner: uid === project.admin?.id,+ ..._omit(project, [+ 'admin',+ 'passwordHash',+ 'organisation',+ role !== 'owner' && role !== 'admin' && 'share',+ ]),+ isOwner: uid === project.admin?.id, // deprecated+ isAccessConfirmed,isLocked: !!project.admin?.dashboardBlockReason,isDataExists,isErrorDataExists,+ organisationId: project.organisation?.id,+ role,}}diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.tsindex 45bc0fa52..b21f807dc 100644--- a/backend/apps/cloud/src/project/project.service.ts+++ b/backend/apps/cloud/src/project/project.service.ts@@ -145,7 +145,7 @@ export const processProjectUser = (project: Project): Project => {if (user) {// @ts-expect-error _pick(user, ['email']) is partial but share[j].user expects full User entity- share[j].user = _pick(user, ['email'])+ share[j].user = _pick(user, ['email', 'id'])}}@@ -402,8 +402,35 @@ export class ProjectService {'admin','organisation','organisation.members',+ 'organisation.members.user',...additionalRelations,],+ select: {+ share: {+ id: true,+ role: true,+ user: {+ id: true,+ email: true,+ },+ },+ admin: {+ id: true,+ roles: true,+ dashboardBlockReason: true,+ isAccountBillingSuspended: true,+ },+ organisation: {+ id: true,+ members: {+ id: true,+ role: true,+ user: {+ id: true,+ },+ },+ },+ },}if (userId) {@@ -421,7 +448,6 @@ export class ProjectService {userId: string,search?: string,): Promise<Pagination<Project>> {- // Create query builder starting from Projectconst queryBuilder = this.projectsRepository.createQueryBuilder('project').leftJoinAndSelect('project.admin', 'admin')@@ -1637,6 +1663,7 @@ export class ProjectService {) {const project = await this.findOne({where: { id: projectId },+ relations: ['organisation'],})if (!project) {diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 50650e8b7..fafe50887 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -19,6 +19,7 @@ import { ISubscribers } from 'redux/models/ISubscribers'import { IFilter, IProjectViewCustomEvent } from 'pages/Project/View/interfaces/traffic'import { AIResponse } from 'pages/Project/View/interfaces/ai'import { Monitor, MonitorOverall } from 'redux/models/Uptime'+import { Role } from 'redux/models/Organisation'const api = axios.create({baseURL: API_URL,@@ -289,6 +290,14 @@ export const createOrganisation = (name: string) =>throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})+export const updateOrganisation = (organisationId: string, data: { name: string }) =>+ api+ .patch(`/organisation/${organisationId}`, data)+ .then((response) => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })+export const addProjectToOrganisation = (organisationId: string, projectId: string) =>api.post(`/project/organisation/${organisationId}`, { projectId })@@ -305,10 +314,25 @@ export const removeProjectFromOrganisation = (organisationId: string, projectId:throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-// eslint-disable-next-line default-param-last-export const getProject = (pid: string, isCaptcha: boolean = false, password?: string) =>+export const changeOrganisationRole = (memberId: string, role: Role) =>+ api+ .patch(`/organisation/member/${memberId}`, { role })+ .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}`)+ .then((response) => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })++export const getProject = (pid: string, password?: string) =>api- .get(`/project/${pid}?isCaptcha=${isCaptcha}`, {+ .get(`/project/${pid}`, {headers: {'x-password': password,},@@ -836,9 +860,9 @@ export const deleteShareProject = (pid: string) =>throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})-export const acceptShareProject = (id: string) =>+export const acceptShareProject = (shareId: string) =>api- .get(`user/share/${id}`)+ .get(`user/share/${shareId}`).then((response) => response.data).catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.messagediff --git a/web/app/components/marketing/Pricing.tsx b/web/app/components/marketing/Pricing.tsxindex 0184b76ff..37370921f 100644--- a/web/app/components/marketing/Pricing.tsx+++ b/web/app/components/marketing/Pricing.tsx@@ -57,7 +57,7 @@ const Pricing = ({ authenticated, isBillingPage }: IPricing) => {t,i18n: { language },} = useTranslation('common')- const dispatch: AppDispatch = useDispatch()+ const dispatch = useDispatch<AppDispatch>()const { user } = useSelector((state: StateType) => state.auth)const { theme } = useSelector((state: StateType) => state.ui.theme)const { paddle, metainfo } = useSelector((state: StateType) => state.ui.misc)diff --git a/web/app/hoc/projectProtected.tsx b/web/app/hoc/projectProtected.tsxindex e87195876..0430f3dce 100644--- a/web/app/hoc/projectProtected.tsx+++ b/web/app/hoc/projectProtected.tsx@@ -19,7 +19,9 @@ export const withProjectProtected = <P extends PropsType>(WrappedComponent: any)const { queryPassword } = propsconst project = _find(projects, { id })- if (project?.isOwner) {+ // If project role is present (i.e. viewer, admin, owner), we don't need to check for password+ // as the user has access to the project+ if (project?.role) {return <WrappedComponent {...props} />}diff --git a/web/app/hooks/useOnClickOutside.ts b/web/app/hooks/useOnClickOutside.tsindex 021d2819d..352189101 100644--- a/web/app/hooks/useOnClickOutside.ts+++ b/web/app/hooks/useOnClickOutside.ts@@ -1,6 +1,6 @@import React, { useEffect } from 'react'-const useOnClickOutside = (ref: React.RefObject<HTMLDivElement>, handler: Function) => {+const useOnClickOutside = (ref: React.RefObject<HTMLDivElement | HTMLUListElement>, handler: Function) => {useEffect(() => {const func = (event: MouseEvent | TouchEvent) => {if (!ref.current || ref.current.contains(event.target as Node)) {diff --git a/web/app/pages/Captcha/Settings/CaptchaSettings.container.tsx b/web/app/pages/Captcha/Settings/CaptchaSettings.container.tsxindex 0f7981169..f9df162bd 100644--- a/web/app/pages/Captcha/Settings/CaptchaSettings.container.tsx+++ b/web/app/pages/Captcha/Settings/CaptchaSettings.container.tsx@@ -6,7 +6,6 @@ import CaptchaSettings from './CaptchaSettings'const mapStateToProps = (state: StateType) => ({projects: state.ui.projects.projects,- analyticsProjects: state.ui.projects.projects,isLoading: state.ui.projects.isLoading,loading: state.auth.loading,user: state.auth.user,diff --git a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx b/web/app/pages/Captcha/Settings/CaptchaSettings.tsxindex 09fdd790b..094338c9f 100644--- a/web/app/pages/Captcha/Settings/CaptchaSettings.tsx+++ b/web/app/pages/Captcha/Settings/CaptchaSettings.tsx@@ -31,7 +31,7 @@ import Checkbox from 'ui/Checkbox'import Modal from 'ui/Modal'import { trackCustom } from 'utils/analytics'import routes from 'utils/routes'-import { ICaptchaProject, IProject } from 'redux/models/IProject'+import { ICaptchaProject } from 'redux/models/IProject'import { IUser } from 'redux/models/IUser'const MAX_NAME_LENGTH = 50@@ -54,7 +54,6 @@ interface ICaptchaSettings {removeProject: (pid: string) => voiduser: IUserdeleteProjectCache: (pid: string) => void- analyticsProjects: IProject[]loading: booleanisSettings: boolean}@@ -66,7 +65,6 @@ const CaptchaSettings = ({removeProject,user,deleteProjectCache,- analyticsProjects,loading,isSettings,}: ICaptchaSettings): JSX.Element => {@@ -77,9 +75,9 @@ const CaptchaSettings = ({}: {id: string} = useParams()- const project: ICaptchaProject | IProject = useMemo(- () => _find([...projects, ...analyticsProjects], (p) => p.id === id) || ({} as IProject | ICaptchaProject),- [projects, analyticsProjects, id],+ const project = useMemo<ICaptchaProject>(+ () => _find([...projects], (p) => p.id === id) || ({} as ICaptchaProject),+ [projects, id],)const navigate = useNavigate()const [form, setForm] = useState<IForm>({diff --git a/web/app/pages/Captcha/View/ViewCaptcha.tsx b/web/app/pages/Captcha/View/ViewCaptcha.tsxindex ec9b8e5cd..683a426a5 100644--- a/web/app/pages/Captcha/View/ViewCaptcha.tsx+++ b/web/app/pages/Captcha/View/ViewCaptcha.tsx@@ -29,7 +29,6 @@ import {getProjectCaptchaCacheKey,timeBucketToDays,getProjectCacheCustomKey,- roleAdmin,MAX_MONTHS_IN_PAST,TimeFormat,chartTypes,@@ -116,10 +115,7 @@ const ViewCaptcha = ({id: string} = useParams()const navigate = useNavigate()- const project: ICaptchaProject = useMemo(- () => _find(projects, (p) => p.id === id) || ({} as ICaptchaProject),- [projects, id],- )+ const project = useMemo(() => _find(projects, (p) => p.id === id) || ({} as ICaptchaProject), [projects, id])const [areFiltersParsed, setAreFiltersParsed] = useState<boolean>(false)const [areTimeBucketParsed, setAreTimeBucketParsed] = useState<boolean>(false)const [arePeriodParsed, setArePeriodParsed] = useState<boolean>(false)@@ -184,9 +180,6 @@ const ViewCaptcha = ({document.title = pageTitle}, [name, t])- // @ts-ignore- const sharedRoles = useMemo(() => _find(user.sharedProjects, (p) => p.project.id === id)?.role || {}, [user, id])-const chartMetrics = useMemo(() => {return [{@@ -520,7 +513,7 @@ const ViewCaptcha = ({useEffect(() => {if (!isLoading && _isEmpty(project)) {- getProject(id, true)+ getProject(id).then((projectRes) => {if (!_isEmpty(projectRes)) {setProjects([@@ -781,7 +774,7 @@ const ViewCaptcha = ({}}}/>- {(project?.isOwner || sharedRoles === roleAdmin.role) && (+ {(project.role === 'admin' || project.role === 'owner') && (<buttontype='button'onClick={openSettingsHandler}diff --git a/web/app/pages/Dashboard/AddProject.tsx b/web/app/pages/Dashboard/AddProject.tsxnew file mode 100644index 000000000..a2f0a09fb--- /dev/null+++ b/web/app/pages/Dashboard/AddProject.tsx@@ -0,0 +1,36 @@+import React from 'react'+import { FolderPlusIcon } from '@heroicons/react/24/outline'+import { Link } from '@remix-run/react'+import { useTranslation } from 'react-i18next'+import cx from 'clsx'++import routes from 'utils/routes'++interface AddProjectProps {+ onClick: (e: React.MouseEvent<HTMLAnchorElement>) => void+ sitesCount: number+}++export const AddProject = ({ onClick, sitesCount }: AddProjectProps) => {+ const { t } = useTranslation('common')++ return (+ <Link+ to={routes.new_project}+ 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>+ <FolderPlusIcon 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('dashboard.newProject')}+ </span>+ </div>+ </Link>+ )+}diff --git a/web/app/pages/Dashboard/Dashboard.container.tsx b/web/app/pages/Dashboard/Dashboard.container.tsxdeleted file mode 100644index 74c9cf4de..000000000--- a/web/app/pages/Dashboard/Dashboard.container.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { connect } from 'react-redux'-import UIActions from 'redux/reducers/ui'-import sagaActions from 'redux/sagas/actions'-import { authActions } from 'redux/reducers/auth'-import { StateType, AppDispatch } from 'redux/store'-import { IProject } from 'redux/models/IProject'-import { ISharedProject } from 'redux/models/ISharedProject'-import Dashboard from './Dashboard'--const mapStateToProps = (state: StateType) => ({- projects: state.ui.projects.projects,- user: state.auth.user,- isLoading: state.ui.projects.isLoading,- total: state.ui.projects.total,- error: state.ui.projects.error,- dashboardPaginationPage: state.ui.projects.dashboardPaginationPage,- liveStats: state.ui.projects.liveStats,- birdseye: state.ui.projects.birdseye,-})--const mapDispatchToProps = (dispatch: AppDispatch) => ({- setProjectsShareData: (data: IProject | ISharedProject, id: string, shared?: boolean) => {- dispatch(- UIActions.setProjectsShareData({- data,- id,- }),- )- },- setUserShareData: (data: ISharedProject, id: string) => {- dispatch(- authActions.setUserShareData({- data,- id,- }),- )- },- loadProjects: (take: number, skip: number, search: string) => {- dispatch(sagaActions.loadProjects(take, skip, search))- },- setDashboardPaginationPage: (page: number) => {- dispatch(UIActions.setDashboardPaginationPage(page))- },-})--export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsxindex 9b2a50688..52ae9dba2 100644--- a/web/app/pages/Dashboard/Dashboard.tsx+++ b/web/app/pages/Dashboard/Dashboard.tsx@@ -1,345 +1,54 @@-import React, { memo, useState, useEffect, useMemo } from 'react'+import React, { useState, useEffect } 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 _filter from 'lodash/filter'-import _find from 'lodash/find'import { useTranslation } from 'react-i18next'-import {- FolderPlusIcon,- AdjustmentsVerticalIcon,- ArrowTopRightOnSquareIcon,- MagnifyingGlassIcon,- XMarkIcon,-} from '@heroicons/react/24/outline'+import { FolderPlusIcon, MagnifyingGlassIcon, XMarkIcon } from '@heroicons/react/24/outline'import { XCircleIcon } from '@heroicons/react/24/solid'-import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/20/solid'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 { nFormatter, calculateRelativePercentage } from 'utils/generic'-import { isSelfhosted, ENTRIES_PER_PAGE_DASHBOARD, roleViewer } from 'redux/constants'+import { isSelfhosted, ENTRIES_PER_PAGE_DASHBOARD } from 'redux/constants'import EventsRunningOutBanner from 'components/EventsRunningOutBanner'import DashboardLockedBanner from 'components/DashboardLockedBanner'import useDebounce from 'hooks/useDebounce'-import { acceptShareProject } from 'api'-import Pagination from 'ui/Pagination'-import { ISharedProject } from 'redux/models/ISharedProject'-import { IProject, ILiveStats, IOverall } from 'redux/models/IProject'-import { IUser } from 'redux/models/IUser'--interface ProjectCardProps {- birdseye: IOverall- live?: string | number- sharedProjects: ISharedProject[]- setProjectsShareData: (data: Partial<IProject>, id: string) => void- setUserShareData: (data: Partial<IProject>, id: string) => void- getRole?: (id: string) => string | null- project: IProject-}--interface MiniCardProps {- labelTKey: string- total?: number | string- percChange?: number-}--const MiniCard = ({ labelTKey, total = 0, percChange }: MiniCardProps) => {- const { t } = useTranslation('common')- const statsDidGrowUp = percChange ? percChange >= 0 : false-- return (- <div>- <p className='text-sm text-gray-500 dark:text-gray-300'>{t(labelTKey)}</p>-- <div className='flex font-bold'>- <p className='text-xl text-gray-700 dark:text-gray-100'>{_isNumber(total) ? nFormatter(total) : total}</p>- {_isNumber(percChange) && (- <p- className={cx('flex items-center text-xs', {- 'text-green-600': statsDidGrowUp,- 'text-red-600': !statsDidGrowUp,- })}- >- {statsDidGrowUp ? (- <>- <ChevronUpIcon className='h-4 w-4 flex-shrink-0 self-center text-green-500' />- <span className='sr-only'>{t('dashboard.inc')}</span>- </>- ) : (- <>- <ChevronDownIcon className='h-4 w-4 flex-shrink-0 self-center text-red-500' />- <span className='sr-only'>{t('dashboard.dec')}</span>- </>- )}- {nFormatter(percChange)}%- </p>- )}- </div>- </div>+import { useSelector } from 'react-redux'+import { StateType, useAppDispatch } from 'redux/store'+import UIActions from 'redux/reducers/ui'+import sagaActions from 'redux/sagas/actions'+import { ProjectCard } from './ProjectCard'+import { NoProjects } from './NoProjects'+import { AddProject } from './AddProject'++const Dashboard = () => {+ const { projects, isLoading, error, total, dashboardPaginationPage, liveStats } = useSelector(+ (state: StateType) => state.ui.projects,)-}+ const { user } = useSelector((state: StateType) => state.auth)-const ProjectCard = ({- birdseye,- live = 'N/A',- sharedProjects,- setProjectsShareData,- setUserShareData,- getRole,- project,-}: ProjectCardProps) => {- const { t } = useTranslation('common')- const [showInviteModal, setShowInviteModal] = useState(false)- const role = useMemo(() => getRole && getRole(project.id), [getRole, project.id])-- const { id, name, public: isPublic, active, isTransferring, share, organisation } = project-- const badges = useMemo(() => {- const list: BadgeProps[] = []-- if (!active) {- list.push({ colour: 'red', label: t('dashboard.disabled') })- }-- if (!project.isOwner) {- if (project.isShareConfirmed) {- list.push({ colour: 'indigo', label: t('dashboard.shared') })- } else {- list.push({ colour: 'yellow', label: t('common.pending') })- }- }-- if (project.isCaptchaProject) {- list.push({ colour: 'indigo', label: t('dashboard.captcha') })- }-- if (isTransferring) {- list.push({ colour: 'indigo', label: t('common.transferring') })- }-- if (isPublic) {- list.push({ colour: 'green', label: t('dashboard.public') })- }-- if (organisation) {- list.push({ colour: 'sky', label: organisation.name })- }-- const members = _size(share)-- if (members > 0) {- list.push({ colour: 'slate', label: t('common.xMembers', { number: members + 1 }) })- }-- return list- }, [- t,- active,- isTransferring,- isPublic,- organisation,- share,- project.isShareConfirmed,- project.isOwner,- project.isCaptchaProject,- ])-- const onAccept = async () => {- // @ts-expect-error- 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({ isShareConfirmed: true }, id)- setUserShareData({ isShareConfirmed: true }, pid)- toast.success(t('apiNotifications.acceptInvitation'))- } catch (reason: any) {- toast.error(t('apiNotifications.acceptInvitationError'))- }- }-- const onElementClick = (e: React.MouseEvent<HTMLAnchorElement>) => {- if (project.isOwner || project.isShareConfirmed) {- return- }-- e.preventDefault()- setShowInviteModal(true)- }-- return (- <Link- to={_replace(project.isCaptchaProject ? routes.captcha : routes.project, ':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(project.isCaptchaProject ? routes.captcha_settings : routes.project_settings, ':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>- )}- <a- href={_replace(project.isCaptchaProject ? routes.captcha : routes.project, ':id', id)}- aria-label='name (opens in a new tab)'- target='_blank'- rel='noopener noreferrer'- >- <ArrowTopRightOnSquareIcon className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500' />- </a>- </div>- </div>- <div className='mt-1 flex flex-shrink-0 flex-wrap gap-2'>- {badges.length > 0 ? (- badges.map((badge) => <Badge key={badge.label} {...badge} />)- ) : (- <Badge label='I' colour='slate' className='invisible' />- )}- </div>- <div className='mt-4 flex flex-shrink-0 gap-5'>- {birdseye[id] && (- <MiniCard- labelTKey={project.isCaptchaProject ? 'dashboard.captchaEvents' : 'dashboard.pageviews'}- total={birdseye[id].current.all}- percChange={calculateRelativePercentage(birdseye[id].previous.all, birdseye[id].current.all)}- />- )}- {project.isAnalyticsProject && <MiniCard labelTKey='dashboard.liveVisitors' total={live} />}- </div>- </div>- {!project.isOwner && !project.isShareConfirmed && (- <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 NoProjectsProps {- onClick: (e: React.MouseEvent<HTMLAnchorElement>) => void-}--interface AddProjectProps {- onClick: (e: React.MouseEvent<HTMLAnchorElement>) => void- sitesCount: number-}--const NoProjects = ({ onClick }: NoProjectsProps) => {- const { t } = useTranslation('common')-- return (- <Link- to={routes.new_project}- 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'- >- <FolderPlusIcon 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>- </Link>- )-}--const AddProject = ({ onClick, sitesCount }: AddProjectProps) => {- const { t } = useTranslation('common')-- return (- <Link- to={routes.new_project}- 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>- <FolderPlusIcon 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('dashboard.newProject')}- </span>- </div>- </Link>- )-}--interface DashboardProps {- projects: IProject[]- isLoading: boolean- error: string- user: IUser- setProjectsShareData: (data: Partial<ISharedProject>) => void- setUserShareData: (data: Partial<ISharedProject>) => void- loadProjects: (take: number, skip: number, search: string) => void- total: number- setDashboardPaginationPage: (page: number) => void- dashboardPaginationPage: number- liveStats: ILiveStats- birdseye: IOverall-}--const Dashboard = ({- projects,- isLoading,- error,- user,- setProjectsShareData,- setUserShareData,- loadProjects,- total,- setDashboardPaginationPage,- dashboardPaginationPage,- liveStats,- birdseye,-}: DashboardProps): JSX.Element => {const { t } = useTranslation('common')const [isSearchActive, setIsSearchActive] = useState<boolean>(false)const [showActivateEmailModal, setShowActivateEmailModal] = useState<boolean>(false)const pageAmount: number = Math.ceil(total / ENTRIES_PER_PAGE_DASHBOARD)- // const getRole = (pid: string): string | null =>- // _find([..._map(sharedProjects, (item) => ({ ...item.project, role: item.role }))], (p) => p.id === pid)?.role ||- // null+// This search represents what's inside the search inputconst [search, setSearch] = useState('')const debouncedSearch = useDebounce(search, 500)+ const dispatch = useAppDispatch()++ const setDashboardPaginationPage = (page: number) => {+ dispatch(UIActions.setDashboardPaginationPage(page))+ }+const onNewProject = (e: React.MouseEvent<HTMLAnchorElement>) => {if (user.isActive || isSelfhosted) {return@@ -350,13 +59,14 @@ const Dashboard = ({}useEffect(() => {- loadProjects(- ENTRIES_PER_PAGE_DASHBOARD,- (dashboardPaginationPage - 1) * ENTRIES_PER_PAGE_DASHBOARD,- debouncedSearch,+ dispatch(+ sagaActions.loadProjects(+ ENTRIES_PER_PAGE_DASHBOARD,+ (dashboardPaginationPage - 1) * ENTRIES_PER_PAGE_DASHBOARD,+ debouncedSearch,+ ),)- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [dashboardPaginationPage, debouncedSearch])+ }, [dispatch, dashboardPaginationPage, debouncedSearch])if (error && !isLoading) {return (@@ -458,7 +168,7 @@ const Dashboard = ({</div>{isSearchActive && (<div className='mb-2 flex w-full items-center sm:hidden'>- <label htmlFor='simple-search' className='sr-only'>+ <label htmlFor='search-projects' className='sr-only'>Search</label><div className='relative w-full'>@@ -466,6 +176,7 @@ const Dashboard = ({<MagnifyingGlassIcon className='ml-2 h-5 w-5 cursor-pointer text-gray-900 hover:opacity-80 dark:text-gray-50' /></div><input+ id='search-projects'type='text'onChange={onSearch}value={search}@@ -499,11 +210,7 @@ const Dashboard = ({<ProjectCardkey={project.id}project={project}- birdseye={birdseye}live={_isNumber(liveStats[project.id]) ? liveStats[project.id] : 'N/A'}- setUserShareData={() => {}}- sharedProjects={[]}- setProjectsShareData={() => {}}/>),)}@@ -542,4 +249,4 @@ const Dashboard = ({)}-export default memo(withAuthentication(Dashboard, auth.authenticated))+export default withAuthentication(Dashboard, auth.authenticated)diff --git a/web/app/pages/Dashboard/NoProjects.tsx b/web/app/pages/Dashboard/NoProjects.tsxnew file mode 100644index 000000000..3218f303c--- /dev/null+++ b/web/app/pages/Dashboard/NoProjects.tsx@@ -0,0 +1,27 @@+import React from 'react'+import { FolderPlusIcon } from '@heroicons/react/24/outline'+import { Link } from '@remix-run/react'+import { useTranslation } from 'react-i18next'++import routes from 'utils/routes'++interface NoProjectsProps {+ onClick: (e: React.MouseEvent<HTMLAnchorElement>) => void+}++export const NoProjects = ({ onClick }: NoProjectsProps) => {+ const { t } = useTranslation('common')++ return (+ <Link+ to={routes.new_project}+ 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'+ >+ <FolderPlusIcon 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>+ </Link>+ )+}diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsxnew file mode 100644index 000000000..6f20d13db--- /dev/null+++ b/web/app/pages/Dashboard/ProjectCard.tsx@@ -0,0 +1,232 @@+import React, { useState, useMemo } from 'react'+import { Link } from '@remix-run/react'+import { toast } from 'sonner'+import cx from 'clsx'+import _size from 'lodash/size'+import _isNumber from 'lodash/isNumber'+import _replace from 'lodash/replace'+import _find from 'lodash/find'+import { useTranslation } from 'react-i18next'+import { AdjustmentsVerticalIcon, ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline'+import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/20/solid'++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 { IProject } from 'redux/models/IProject'+import { useSelector } from 'react-redux'+import { StateType, useAppDispatch } from 'redux/store'+import UIActions from 'redux/reducers/ui'+import { authActions } from 'redux/reducers/auth'++interface ProjectCardProps {+ live?: string | number+ project: IProject+}++interface MiniCardProps {+ labelTKey: string+ total?: number | string+ percChange?: number+}++const MiniCard = ({ labelTKey, total = 0, percChange }: MiniCardProps) => {+ const { t } = useTranslation('common')+ const statsDidGrowUp = percChange ? percChange >= 0 : false++ return (+ <div>+ <p className='text-sm text-gray-500 dark:text-gray-300'>{t(labelTKey)}</p>++ <div className='flex font-bold'>+ <p className='text-xl text-gray-700 dark:text-gray-100'>{_isNumber(total) ? nFormatter(total) : total}</p>+ {_isNumber(percChange) && (+ <p+ className={cx('flex items-center text-xs', {+ 'text-green-600': statsDidGrowUp,+ 'text-red-600': !statsDidGrowUp,+ })}+ >+ {statsDidGrowUp ? (+ <>+ <ChevronUpIcon className='h-4 w-4 flex-shrink-0 self-center text-green-500' />+ <span className='sr-only'>{t('dashboard.inc')}</span>+ </>+ ) : (+ <>+ <ChevronDownIcon className='h-4 w-4 flex-shrink-0 self-center text-red-500' />+ <span className='sr-only'>{t('dashboard.dec')}</span>+ </>+ )}+ {nFormatter(percChange)}%+ </p>+ )}+ </div>+ </div>+ )+}++export const ProjectCard = ({ live = 'N/A', project }: ProjectCardProps) => {+ const { t } = useTranslation('common')+ const [showInviteModal, setShowInviteModal] = useState(false)++ const { user } = useSelector((state: StateType) => state.auth)++ const { birdseye } = useSelector((state: StateType) => state.ui.projects)++ const dispatch = useAppDispatch()++ const shareId = useMemo(() => _find(project.share, (item) => item.user.id === user.id)?.id, [project.share, user.id])++ const { id, name, public: isPublic, active, isTransferring, share, organisation, role } = project++ const badges = useMemo(() => {+ const list: BadgeProps[] = []++ if (!active) {+ list.push({ colour: 'red', label: t('dashboard.disabled') })+ }++ if (organisation) {+ list.push({ colour: 'sky', label: organisation.name })+ }++ if (project.role !== 'owner' && shareId) {+ list.push({ colour: 'indigo', label: t('dashboard.shared') })+ }++ if (project.role !== 'owner' && !project.isAccessConfirmed) {+ list.push({ colour: 'yellow', label: t('common.pending') })+ }++ if (project.isCaptchaProject) {+ list.push({ colour: 'indigo', label: t('dashboard.captcha') })+ }++ if (isTransferring) {+ list.push({ colour: 'indigo', label: t('common.transferring') })+ }++ if (isPublic) {+ list.push({ colour: 'green', label: t('dashboard.public') })+ }++ const members = _size(share)++ if (members > 0) {+ list.push({ colour: 'slate', label: t('common.xMembers', { number: members + 1 }) })+ }++ return list+ }, [+ t,+ active,+ isTransferring,+ isPublic,+ organisation,+ share,+ project.isAccessConfirmed,+ project.role,+ project.isCaptchaProject,+ shareId,+ ])++ const onAccept = async () => {+ try {+ if (!shareId) {+ throw new Error('Project share not found')+ }++ await acceptShareProject(shareId)++ dispatch(UIActions.setProjectsShareData({ data: { isAccessConfirmed: true }, id }))+ dispatch(authActions.setUserShareData({ data: { confirmed: true }, id: shareId }))++ toast.success(t('apiNotifications.acceptInvitation'))+ } catch (reason: any) {+ console.error(`[ERROR] Error while accepting project invitation: ${reason}`)+ toast.error(t('apiNotifications.acceptInvitationError'))+ }+ }++ const onElementClick = (e: React.MouseEvent<HTMLAnchorElement>) => {+ if (project.role === 'owner' || project.isAccessConfirmed) {+ return+ }++ e.preventDefault()+ setShowInviteModal(true)+ }++ return (+ <Link+ to={_replace(project.isCaptchaProject ? routes.captcha : routes.project, ':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(project.isCaptchaProject ? routes.captcha_settings : routes.project_settings, ':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>+ )}+ <a+ href={_replace(project.isCaptchaProject ? routes.captcha : routes.project, ':id', id)}+ aria-label='name (opens in a new tab)'+ target='_blank'+ rel='noopener noreferrer'+ >+ <ArrowTopRightOnSquareIcon className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500' />+ </a>+ </div>+ </div>+ <div className='mt-1 flex flex-shrink-0 flex-wrap gap-2'>+ {badges.length > 0 ? (+ badges.map((badge) => <Badge key={badge.label} {...badge} />)+ ) : (+ <Badge label='I' colour='slate' className='invisible' />+ )}+ </div>+ <div className='mt-4 flex flex-shrink-0 gap-5'>+ {birdseye[id] && (+ <MiniCard+ labelTKey={project.isCaptchaProject ? 'dashboard.captchaEvents' : 'dashboard.pageviews'}+ total={birdseye[id].current.all}+ percChange={calculateRelativePercentage(birdseye[id].previous.all, birdseye[id].current.all)}+ />+ )}+ {project.isAnalyticsProject && <MiniCard labelTKey='dashboard.liveVisitors' total={live} />}+ </div>+ </div>+ {project.role !== 'owner' && !project.isAccessConfirmed && (+ <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>+ )+}diff --git a/web/app/pages/Dashboard/index.tsx b/web/app/pages/Dashboard/index.tsxindex 52cf8f17a..f952036fd 100644--- a/web/app/pages/Dashboard/index.tsx+++ b/web/app/pages/Dashboard/index.tsx@@ -1,3 +1,3 @@-import Dashboard from './Dashboard.container'+import Dashboard from './Dashboard'export default Dashboarddiff --git a/web/app/pages/Organisations/Settings/People.tsx b/web/app/pages/Organisations/Settings/People.tsxindex dd46c093e..3f4c18ebf 100644--- a/web/app/pages/Organisations/Settings/People.tsx+++ b/web/app/pages/Organisations/Settings/People.tsx@@ -16,9 +16,10 @@ import Button from 'ui/Button'import Modal from 'ui/Modal'import { roles, roleViewer, roleAdmin, INVITATION_EXPIRES_IN } from 'redux/constants'import useOnClickOutside from 'hooks/useOnClickOutside'-import { DetailedOrganisation } from 'redux/models/Organisation'+import { DetailedOrganisation, Role } from 'redux/models/Organisation'import { useSelector } from 'react-redux'import { StateType } from 'redux/store'+import { changeOrganisationRole, removeOrganisationMember } from 'api'const NoPeople = () => {const { t } = useTranslation('common')@@ -34,7 +35,7 @@ const NoPeople = () => {interface UsersListProps {members: DetailedOrganisation['members']- onRemove: (id: string) => void+ onRemove: (member: DetailedOrganisation['members'][number]) => void}const UsersList = ({ members, onRemove }: UsersListProps) => {@@ -45,13 +46,14 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {const { user } = useSelector((state: StateType) => state.auth)const [roleEditDropdownId, setRoleEditDropdownId] = useState<string | null>(null)- const [showDeleteModal, setShowDeleteModal] = useState(false)- const openRef = useRef<HTMLDivElement>(null)+ const openRef = useRef<HTMLUListElement>(null)useOnClickOutside(openRef, () => setRoleEditDropdownId(null))- const changeRole = async (newRole: string) => {+ const changeRole = async (memberId: string, newRole: Role) => {+ console.log('changeRole', memberId, newRole)+try {- // todo+ await changeOrganisationRole(memberId, newRole)toast.success(t('apiNotifications.roleUpdated'))} catch (reason) {@@ -74,11 +76,11 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {</td><td className='relative whitespace-nowrap py-4 pr-2 text-right text-sm font-medium'>{member.confirmed ? (- <div ref={openRef}>+ <div><buttononClick={() => setRoleEditDropdownId((prev) => (prev === member.id ? null : member.id))}type='button'- disabled={member.user.email === user.email}+ disabled={member.user.email === user.email || member.role === 'owner'}className='inline-flex items-center rounded-full border border-gray-200 bg-white py-0.5 pl-2 pr-1 text-sm font-medium leading-5 text-gray-700 shadow-sm hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-80 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-200 dark:hover:bg-gray-600'>{t(`organisations.role.${member.role}.name`)}@@ -88,10 +90,13 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {/></button>{roleEditDropdownId === member.id ? (- <ul className='absolute right-0 z-10 mt-2 w-72 origin-top-right divide-y divide-gray-200 rounded-md bg-white text-left shadow-lg focus:outline-none dark:divide-gray-700 dark:bg-slate-900'>+ <ul+ ref={openRef}+ className='absolute right-0 z-10 mt-2 w-72 origin-top-right divide-y divide-gray-200 rounded-md bg-white text-left shadow-lg focus:outline-none dark:divide-gray-700 dark:bg-slate-900'+ >{_map(roles, (itRole, index) => (<li- onClick={() => changeRole(itRole)}+ onClick={() => changeRole(member.id, itRole)}className={cx('group relative cursor-pointer p-4 hover:bg-indigo-600',index === 0 && 'rounded-t-md',@@ -115,14 +120,12 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {))}<lionClick={() => {+ onRemove(member)setRoleEditDropdownId(null)- setShowDeleteModal(true)}}className='group flex cursor-pointer items-center justify-between rounded-b-md p-4 hover:bg-gray-200 dark:hover:bg-gray-700'>- <div>- <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p>- </div>+ <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p></li></ul>) : null}@@ -134,30 +137,13 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {type='button'className='rounded-md bg-white text-base font-medium text-indigo-700 hover:bg-indigo-50 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'small- onClick={() => setShowDeleteModal(true)}+ onClick={() => onRemove(member)}><TrashIcon className='h-4 w-4' /></Button></div>)}</td>- <td>- <Modal- onClose={() => {- setShowDeleteModal(false)- }}- onSubmit={() => {- setShowDeleteModal(false)- onRemove(member.id)- }}- submitText={t('common.yes')}- type='confirmed'- closeText={t('common.no')}- title={t('project.settings.removeUser', { user: member.user.email })}- message={t('project.settings.removeConfirm')}- isOpened={showDeleteModal}- />- </td></tr>))}@@ -180,6 +166,10 @@ const People = ({ organisation }: PeopleProps): JSX.Element => {}>({})const [validated, setValidated] = useState(false)+ const [showDeleteModal, setShowDeleteModal] = useState(false)+ const [isDeleting, setIsDeleting] = useState(false)+ const [memberToRemove, setMemberToRemove] = useState<DetailedOrganisation['members'][number] | null>(null)+const { name, members } = organisationconst validate = () => {@@ -253,13 +243,22 @@ const People = ({ organisation }: PeopleProps): JSX.Element => {setErrors({})}- const onRemove = async (userId: string) => {+ const onRemove = async (member: DetailedOrganisation['members'][number]) => {+ if (isDeleting) {+ return+ }++ setIsDeleting(true)+try {- // todo- toast.success(t('apiNotifications.userRemoved'))+ await removeOrganisationMember(member.id)++ toast.success(t('apiNotifications.orgUserRemoved'))} catch (reason) {- console.error(`[ERROR] Error while deleting a user: ${reason}`)- toast.error(t('apiNotifications.userRemoveError'))+ console.error(`[ERROR] Error while removing user from the organisation: ${reason}`)+ toast.error(t('apiNotifications.orgUserRemoveError'))+ } finally {+ setIsDeleting(false)}}@@ -303,11 +302,16 @@ const People = ({ organisation }: PeopleProps): JSX.Element => {{t('profileSettings.sharedTable.joinedOn')}</th><th scope='col' />- <th scope='col' /></tr></thead><tbody className='divide-y divide-gray-300 dark:divide-gray-600'>- <UsersList members={members} onRemove={onRemove} />+ <UsersList+ members={members}+ onRemove={(member) => {+ setMemberToRemove(member)+ setShowDeleteModal(true)+ }}+ /></tbody></table></div>@@ -316,6 +320,23 @@ const People = ({ organisation }: PeopleProps): JSX.Element => {</div>)}</div>+ <Modal+ onClose={() => {+ setShowDeleteModal(false)+ setMemberToRemove(null)+ }}+ onSubmit={async () => {+ await onRemove(memberToRemove!)+ setMemberToRemove(null)+ }}+ submitText={t('common.yes')}+ type='confirmed'+ closeText={t('common.no')}+ title={t('project.settings.removeUser', { user: memberToRemove?.user.email })}+ message={t('project.settings.removeConfirm')}+ isOpened={showDeleteModal}+ isLoading={isDeleting}+ /><ModalonClose={closeModal}customButtons={diff --git a/web/app/pages/Organisations/Settings/Projects.tsx b/web/app/pages/Organisations/Settings/Projects.tsxindex b4cac57a7..0e3aa9d57 100644--- a/web/app/pages/Organisations/Settings/Projects.tsx+++ b/web/app/pages/Organisations/Settings/Projects.tsx@@ -3,6 +3,7 @@ import { toast } from 'sonner'import { InformationCircleIcon, PlusIcon } from '@heroicons/react/24/outline'import { useTranslation } from 'react-i18next'import _isEmpty from 'lodash/isEmpty'+import _replace from 'lodash/replace'import Button from 'ui/Button'import Modal from 'ui/Modal'@@ -11,6 +12,8 @@ import { useSelector } from 'react-redux'import { StateType } from 'redux/store'import Tooltip from 'ui/Tooltip'import { removeProjectFromOrganisation } from 'api'+import { Link } from '@remix-run/react'+import routes from 'utils/routes'const NoProjects = () => {const { t } = useTranslation('common')@@ -36,7 +39,9 @@ const ProjectList = ({ projects, onRemove }: ProjectListProps) => {return projects.map((project) => (<tr key={project.id} className='dark:bg-slate-800'><td className='whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 dark:text-white sm:pl-6'>- {project.name}+ <Link to={_replace(routes.project, ':id', project.id)} className='hover:underline'>+ {project.name}+ </Link></td><td className='relative whitespace-nowrap py-4 pr-2 text-sm font-medium'><div className='flex items-center justify-end'>diff --git a/web/app/pages/Organisations/Settings/index.tsx b/web/app/pages/Organisations/Settings/index.tsxindex 6742ad040..c4de4dcc1 100644--- a/web/app/pages/Organisations/Settings/index.tsx+++ b/web/app/pages/Organisations/Settings/index.tsx@@ -1,15 +1,14 @@import React, { useState, useEffect, memo } from 'react'import { toast } from 'sonner'-import { useNavigate } from '@remix-run/react'+import { Link, useNavigate } from '@remix-run/react'import { useTranslation } from 'react-i18next'import _isEmpty from 'lodash/isEmpty'import _size from 'lodash/size'-import _replace from 'lodash/replace'import _keys from 'lodash/keys'import { withAuthentication, auth } from 'hoc/protected'import { TITLE_SUFFIX } from 'redux/constants'-import { transferProject, getOrganisation } from 'api'+import { transferProject, getOrganisation, updateOrganisation } from 'api'import Input from 'ui/Input'import Button from 'ui/Button'import Loader from 'ui/Loader'@@ -22,10 +21,11 @@ import { DetailedOrganisation } from 'redux/models/Organisation'import { StateType } from 'redux/store'import { useSelector } from 'react-redux'import { Projects } from './Projects'+import { XCircleIcon } from '@heroicons/react/24/outline'const MAX_NAME_LENGTH = 50-const DEFAULT_PROJECT_NAME = 'Untitled Project'+const DEFAULT_ORGANISATION_NAME = 'Untitled Organisation'const OrganisationSettings = () => {const { t } = useTranslation('common')@@ -82,7 +82,21 @@ const OrganisationSettings = () => {// eslint-disable-next-line react-hooks/exhaustive-deps}, [authLoading, id])- const onSubmit = async (form: any) => {}+ const onSubmit = async (data: any) => {+ if (isSaving) {+ return+ }+ setIsSaving(true)++ try {+ await updateOrganisation(id, { name: data.name })+ toast.success(t('apiNotifications.orgSettingsUpdated'))+ } catch (reason: any) {+ toast.error(reason)+ } finally {+ setIsSaving(false)+ }+ }const onDelete = async () => {setShowDelete(false)@@ -149,10 +163,6 @@ const OrganisationSettings = () => {}}- const onCancel = () => {- navigate(_replace(routes.project, ':id', id))- }-const onTransfer = async () => {await transferProject(id, transferEmail).then(() => {@@ -182,6 +192,43 @@ const OrganisationSettings = () => {)}+ if (error && !isLoading) {+ 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>+ )+ }+return (<div className='flex min-h-min-footer flex-col bg-gray-50 px-4 py-6 pb-40 dark:bg-slate-900 sm:px-6 lg:px-8'><form className='mx-auto w-full max-w-7xl' onSubmit={handleSubmit}>@@ -199,7 +246,9 @@ const OrganisationSettings = () => {<div className='flex flex-wrap items-center gap-2'><ButtonclassName='border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'- onClick={onCancel}+ as={Link}+ // @ts-expect-error+ to={routes.organisations}secondaryregular>@@ -254,7 +303,7 @@ const OrganisationSettings = () => {<h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>{t('project.settings.transferTo')}</h2><p className='mt-2 text-base text-gray-700 dark:text-gray-200'>{t('project.settings.transferHint', {- name: form.name || DEFAULT_PROJECT_NAME,+ name: form.name || DEFAULT_ORGANISATION_NAME,})}</p><Inputdiff --git a/web/app/pages/Organisations/index.tsx b/web/app/pages/Organisations/index.tsxindex 130e024c5..b9c61a33c 100644--- a/web/app/pages/Organisations/index.tsx+++ b/web/app/pages/Organisations/index.tsx@@ -97,8 +97,8 @@ const OrganisationCard = ({throw new Error('Project not found')}await acceptShareProject(pid)- setProjectsShareData({ isShareConfirmed: true }, id)- setUserShareData({ isShareConfirmed: true }, pid)+ setProjectsShareData({ isAccessConfirmed: true }, id)+ setUserShareData({ isAccessConfirmed: true }, pid)toast.success(t('apiNotifications.acceptInvitation'))} catch (reason: any) {toast.error(t('apiNotifications.acceptInvitationError'))diff --git a/web/app/pages/Project/New/index.tsx b/web/app/pages/Project/New/index.tsxindex 60748d109..72cf26378 100644--- a/web/app/pages/Project/New/index.tsx+++ b/web/app/pages/Project/New/index.tsx@@ -1,5 +1,5 @@import React, { useState, useEffect, memo, useMemo } from 'react'-import { useNavigate } from '@remix-run/react'+import { Link, useNavigate } from '@remix-run/react'import { useTranslation } from 'react-i18next'import { useSelector, useDispatch } from 'react-redux'import { toast } from 'sonner'@@ -129,10 +129,6 @@ const NewProject = () => {}}- const onCancel = () => {- navigate(routes.dashboard)- }-useEffect(() => {document.title = `${t('project.settings.create')} ${TITLE_SUFFIX}`}, [t])@@ -188,7 +184,9 @@ const NewProject = () => {<div><ButtonclassName='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'- onClick={onCancel}+ as={Link}+ // @ts-expect-error+ to={routes.dashboard}secondaryregular>diff --git a/web/app/pages/Project/ProjectProtectedPassword/index.tsx b/web/app/pages/Project/ProjectProtectedPassword/index.tsxindex fa3dc2423..3cf34d113 100644--- a/web/app/pages/Project/ProjectProtectedPassword/index.tsx+++ b/web/app/pages/Project/ProjectProtectedPassword/index.tsx@@ -1,5 +1,5 @@import React, { useState, useEffect, memo } from 'react'-import { useNavigate, useParams } from '@remix-run/react'+import { Link, useNavigate, useParams } from '@remix-run/react'import { useTranslation } from 'react-i18next'import _keys from 'lodash/keys'import _isEmpty from 'lodash/isEmpty'@@ -114,10 +114,6 @@ const ProjectProtectedPassword = ({}}- const onCancel = () => {- navigate(routes.main)- }-return (<>{!embedded && <Header ssrTheme={ssrTheme} authenticated={isAuth} />}@@ -137,7 +133,9 @@ const ProjectProtectedPassword = ({<div className='mt-5'><ButtonclassName='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'- onClick={onCancel}+ as={Link}+ // @ts-expect-error+ to={routes.main}secondaryregular>diff --git a/web/app/pages/Project/Settings/Emails/Emails.tsx b/web/app/pages/Project/Settings/Emails/Emails.tsxindex 36ea2d31c..1a7a41294 100644--- a/web/app/pages/Project/Settings/Emails/Emails.tsx+++ b/web/app/pages/Project/Settings/Emails/Emails.tsx@@ -1,4 +1,3 @@-import type i18next from 'i18next'import React, { useState, useEffect, useRef } from 'react'import { toast } from 'sonner'import { TrashIcon, InboxStackIcon, ChevronDownIcon, CheckIcon } from '@heroicons/react/24/outline'@@ -24,12 +23,7 @@ import cx from 'clsx'import { Badge } from 'ui/Badge'import { ISubscribers } from 'redux/models/ISubscribers'-const ModalMessage = ({- handleInput,- beenSubmitted,- errors,- form,-}: {+interface ModalMessageProps {handleInput: (e: React.ChangeEvent<HTMLInputElement>) => voidbeenSubmitted: booleanerrors: {@@ -40,7 +34,9 @@ const ModalMessage = ({email: stringreportFrequency: string}-}) => {+}++const ModalMessage = ({ handleInput, beenSubmitted, errors, form }: ModalMessageProps) => {const { t } = useTranslation('common')return (@@ -73,7 +69,6 @@ const ModalMessage = ({index={index}form={form}handleInput={handleInput}- t={t}totalOptions={reportFrequencyForEmailsOptions.length}/>))}@@ -88,55 +83,48 @@ const ModalMessage = ({)}-const ReportFrequencyOption = ({- item,- index,- form,- handleInput,- t,- totalOptions,-}: {+interface ReportFrequencyOptionProps {item: { value: string; label: string }index: numberform: { reportFrequency: string }handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void- t: typeof i18next.ttotalOptions: number-}) => (- <label- className={cx('relative flex cursor-pointer 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':- item.value === form.reportFrequency,- 'border-gray-200': form.reportFrequency !== item.value,- 'rounded-tl-md rounded-tr-md': index === 0,- 'rounded-bl-md rounded-br-md': index === totalOptions - 1,- })}- >- <input- name='reportFrequency'- className='h-4 w-4 border-gray-300 text-indigo-600 focus:ring-indigo-500'- type='radio'- value={item.value}- onChange={handleInput}- checked={form.reportFrequency === item.value}- />- <span- className={cx('ml-3 block text-sm font-medium', {- 'text-indigo-900 dark:text-white': form.reportFrequency === item.value,- 'text-gray-700 dark:text-gray-200': form.reportFrequency !== item.value,+}++const ReportFrequencyOption = ({ item, index, form, handleInput, totalOptions }: ReportFrequencyOptionProps) => {+ const { t } = useTranslation('common')++ return (+ <label+ className={cx('relative flex cursor-pointer 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':+ item.value === form.reportFrequency,+ 'border-gray-200': form.reportFrequency !== item.value,+ 'rounded-t-md': index === 0,+ 'rounded-b-md': index === totalOptions - 1,})}>- {t(`profileSettings.${item.value}`)}- </span>- </label>-)--const EmailList = ({- data,- onRemove,- setEmails,- language,-}: {+ <input+ name='reportFrequency'+ className='h-4 w-4 border-gray-300 text-indigo-600 focus:ring-indigo-500'+ type='radio'+ value={item.value}+ onChange={handleInput}+ checked={form.reportFrequency === item.value}+ />+ <span+ className={cx('ml-3 block text-sm font-medium', {+ 'text-indigo-900 dark:text-white': form.reportFrequency === item.value,+ 'text-gray-700 dark:text-gray-200': form.reportFrequency !== item.value,+ })}+ >+ {t(`profileSettings.${item.value}`)}+ </span>+ </label>+ )+}++interface EmailListProps {data: {id: stringaddedAt: string@@ -145,14 +133,17 @@ const EmailList = ({email: stringreportFrequency: string}- onRemove: (id: string) => void+ onRemove: () => voidsetEmails: (value: ISubscribers[] | ((prevVar: ISubscribers[]) => ISubscribers[])) => void- language: string-}) => {- const { t } = useTranslation('common')- const [open, setOpen] = useState<boolean>(false)- const [showDeleteModal, setShowDeleteModal] = useState<boolean>(false)- const openRef = useRef<HTMLDivElement>(null)+}++const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {+ const {+ t,+ i18n: { language },+ } = useTranslation('common')+ const [open, setOpen] = useState(false)+ const openRef = useRef<HTMLUListElement>(null)useOnClickOutside(openRef, () => setOpen(false))const { id, addedAt, isConfirmed, projectId, email, reportFrequency } = data || {}@@ -189,7 +180,7 @@ const EmailList = ({</td><td className='relative whitespace-nowrap py-4 pr-2 text-right text-sm font-medium'>{isConfirmed ? (- <div ref={openRef}>+ <div><buttononClick={() => setOpen(!open)}type='button'@@ -199,11 +190,17 @@ const EmailList = ({<ChevronDownIcon style={{ transform: open ? 'rotate(180deg)' : '' }} className='ml-0.5 h-4 w-4 pt-px' /></button>{open && (- <ul className='absolute right-0 z-10 mt-2 w-72 origin-top-right divide-y divide-gray-200 rounded-md bg-white text-left shadow-lg focus:outline-none dark:divide-gray-700 dark:bg-slate-900'>- {_map(reportFrequencyForEmailsOptions, (item) => (+ <ul+ ref={openRef}+ className='absolute right-0 z-10 mt-2 w-72 origin-top-right divide-y divide-gray-200 rounded-md bg-white text-left shadow-lg focus:outline-none dark:divide-gray-700 dark:bg-slate-900'+ >+ {_map(reportFrequencyForEmailsOptions, (item, index) => (<lionClick={() => changeRole(item)}- className='group flex cursor-pointer items-center justify-between p-4 hover:bg-indigo-600'+ className={cx(+ 'group flex cursor-pointer items-center justify-between p-4 hover:bg-indigo-600',+ index === 0 && 'rounded-t-md',+ )}key={item.value}><div>@@ -219,15 +216,10 @@ const EmailList = ({</li>))}<li- onClick={() => {- setOpen(false)- setShowDeleteModal(true)- }}- className='group flex cursor-pointer items-center justify-between p-4 hover:bg-gray-200 dark:hover:bg-gray-700'+ onClick={onRemove}+ className='group flex cursor-pointer items-center justify-between rounded-b-md p-4 hover:bg-gray-200 dark:hover:bg-gray-700'>- <div>- <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p>- </div>+ <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p></li></ul>)}@@ -239,48 +231,32 @@ const EmailList = ({type='button'className='rounded-md bg-white text-base font-medium text-indigo-700 hover:bg-indigo-50 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'small- onClick={() => setShowDeleteModal(true)}+ onClick={onRemove}><TrashIcon className='h-4 w-4' /></Button></div>)}</td>- <td>- <Modal- onClose={() => {- setShowDeleteModal(false)- }}- onSubmit={() => {- setShowDeleteModal(false)- onRemove(id)- }}- submitText={t('common.yes')}- type='confirmed'- closeText={t('common.no')}- title={t('project.settings.removeUser', { user: email })}- message={t('project.settings.removeReportConfirm')}- isOpened={showDeleteModal}- />- </td></tr>)}-const NoSubscribers = ({ t }: { t: typeof i18next.t }): JSX.Element => (- <div className='flex flex-col py-6 sm:px-6 lg:px-8'>- <div className='mx-auto w-full max-w-7xl text-gray-900 dark:text-gray-50'>- <h2 className='mb-8 px-4 text-center text-xl leading-snug'>{t('project.settings.noPeople')}</h2>+const NoSubscribers = () => {+ const { t } = useTranslation('common')++ return (+ <div className='flex flex-col py-6 sm:px-6 lg:px-8'>+ <div className='mx-auto w-full max-w-7xl text-gray-900 dark:text-gray-50'>+ <h2 className='mb-8 px-4 text-center text-xl leading-snug'>{t('project.settings.noPeople')}</h2>+ </div></div>- </div>-)+ )+}const Emails = ({ projectId }: { projectId: string }): JSX.Element => {- const [showModal, setShowModal] = useState<boolean>(false)- const {- t,- i18n: { language },- } = useTranslation('common')+ const [showModal, setShowModal] = useState(false)+ const { t } = useTranslation('common')const [form, setForm] = useState<{email: stringreportFrequency: string@@ -288,24 +264,28 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {email: '',reportFrequency: reportFrequencyForEmailsOptions[3].value,})- const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)+ const [beenSubmitted, setBeenSubmitted] = useState(false)const [errors, setErrors] = useState<{email?: stringreportFrequency?: string}>({})- const [validated, setValidated] = useState<boolean>(false)+ const [validated, setValidated] = useState(false)const [emails, setEmails] = useState<ISubscribers[]>([])const [loading, setLoading] = useState(true)- const [paggination, setPaggination] = useState({+ const [pagination, setPagination] = useState({page: 1,limit: 10,total: 0,})+ const [showDeleteModal, setShowDeleteModal] = useState(false)+ const [isDeleting, setIsDeleting] = useState(false)+ const [emailToRemove, setEmailToRemove] = useState<ISubscribers | null>(null)+const getSubcribersAsync = async () => {try {- const { subscribers, count } = await getSubscribers(projectId, paggination.page - 1, paggination.limit)- setPaggination((oldPaggination) => ({+ const { subscribers, count } = await getSubscribers(projectId, pagination.page - 1, pagination.limit)+ setPagination((oldPaggination) => ({...oldPaggination,count,}))@@ -389,15 +369,23 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {setErrors({})}- const onRemove = async (email: string) => {+ const onRemove = async (emailId: string) => {+ if (isDeleting) {+ return+ }++ setIsDeleting(true)+try {- await removeSubscriber(projectId, email)- const results = _filter(emails, (s) => s.id !== email)+ await removeSubscriber(projectId, emailId)+ const results = _filter(emails, (s) => s.id !== emailId)setEmails(results)toast.success(t('apiNotifications.emailDelete'))} catch (reason: any) {console.error(`[ERROR] Error while deleting a email: ${reason}`)toast.error(t('apiNotifications.emailDeleteError'))+ } finally {+ setIsDeleting(false)}}@@ -437,7 +425,6 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {{t('auth.common.addedOn')}</th><th scope='col' />- <th scope='col' /></tr></thead><tbody className='divide-y divide-gray-300 dark:divide-gray-600'>@@ -445,8 +432,10 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {<EmailListdata={email}key={email.id}- onRemove={onRemove}- language={language}+ onRemove={() => {+ setEmailToRemove(email)+ setShowDeleteModal(true)+ }}setEmails={setEmails}/>))}@@ -454,7 +443,7 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {</table></div>)}- {_isEmpty(emails) && <NoSubscribers t={t} />}+ {_isEmpty(emails) && <NoSubscribers />}{loading && <Loader />}</div></div>@@ -475,6 +464,24 @@ const Emails = ({ projectId }: { projectId: string }): JSX.Element => {message={<ModalMessage form={form} handleInput={handleInput} errors={errors} beenSubmitted={beenSubmitted} />}isOpened={showModal}/>++ <Modal+ onClose={() => {+ setShowDeleteModal(false)+ setEmailToRemove(null)+ }}+ onSubmit={async () => {+ await onRemove(emailToRemove!.id)+ setEmailToRemove(null)+ }}+ submitText={t('common.yes')}+ type='confirmed'+ closeText={t('common.no')}+ title={t('project.settings.removeUser', { user: emailToRemove?.email })}+ message={t('project.settings.removeReportConfirm')}+ isOpened={showDeleteModal}+ isLoading={isDeleting}+ /></div>)}diff --git a/web/app/pages/Project/Settings/People/People.tsx b/web/app/pages/Project/Settings/People/People.tsxindex ef1000480..43b1a3e0f 100644--- a/web/app/pages/Project/Settings/People/People.tsx+++ b/web/app/pages/Project/Settings/People/People.tsx@@ -36,7 +36,7 @@ const NoPeople = () => {interface IUsersList {data: IShareOwnerProject- onRemove: (id: string) => void+ onRemove: () => voidshare?: IShareOwnerProject[]setProjectShareData: (item: Partial<IProject>, id: string) => voidpid: string@@ -47,8 +47,7 @@ interface IUsersList {const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language, authedUserEmail }: IUsersList) => {const { t } = useTranslation('common')const [open, setOpen] = useState(false)- const [showDeleteModal, setShowDeleteModal] = useState(false)- const openRef = useRef<HTMLDivElement>(null)+ const openRef = useRef<HTMLUListElement>(null)useOnClickOutside(openRef, () => setOpen(false))const { id, created, confirmed, role, user } = data || {}@@ -83,7 +82,7 @@ const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language,</td><td className='relative whitespace-nowrap py-4 pr-2 text-right text-sm font-medium'>{confirmed ? (- <div ref={openRef}>+ <div><buttononClick={() => setOpen(!open)}type='button'@@ -94,7 +93,10 @@ const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language,<ChevronDownIcon style={{ transform: open ? 'rotate(180deg)' : '' }} className='ml-0.5 h-4 w-4 pt-px' /></button>{open && (- <ul className='absolute right-0 z-10 mt-2 w-72 origin-top-right divide-y divide-gray-200 rounded-md bg-white text-left shadow-lg focus:outline-none dark:divide-gray-700 dark:bg-slate-900'>+ <ul+ ref={openRef}+ className='absolute right-0 z-10 mt-2 w-72 origin-top-right divide-y divide-gray-200 rounded-md bg-white text-left shadow-lg focus:outline-none dark:divide-gray-700 dark:bg-slate-900'+ >{_map(roles, (itRole, index) => (<lionClick={() => changeRole(itRole)}@@ -120,15 +122,10 @@ const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language,</li>))}<li- onClick={() => {- setOpen(false)- setShowDeleteModal(true)- }}+ onClick={onRemove}className='group flex cursor-pointer items-center justify-between rounded-b-md p-4 hover:bg-gray-200 dark:hover:bg-gray-700'>- <div>- <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p>- </div>+ <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p></li></ul>)}@@ -140,30 +137,13 @@ const UsersList = ({ data, onRemove, share, setProjectShareData, pid, language,type='button'className='rounded-md bg-white text-base font-medium text-indigo-700 hover:bg-indigo-50 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'small- onClick={() => setShowDeleteModal(true)}+ onClick={onRemove}><TrashIcon className='h-4 w-4' /></Button></div>)}</td>- <td>- <Modal- onClose={() => {- setShowDeleteModal(false)- }}- onSubmit={() => {- setShowDeleteModal(false)- onRemove(id)- }}- submitText={t('common.yes')}- type='confirmed'- closeText={t('common.no')}- title={t('project.settings.removeUser', { user: user.email })}- message={t('project.settings.removeConfirm')}- isOpened={showDeleteModal}- />- </td></tr>)}@@ -197,6 +177,11 @@ const People: React.FunctionComponent<IPeopleProps> = ({role?: string}>({})const [validated, setValidated] = useState(false)++ const [showDeleteModal, setShowDeleteModal] = useState(false)+ const [isDeleting, setIsDeleting] = useState(false)+ const [memberToRemove, setMemberToRemove] = useState<IShareOwnerProject | null>(null)+const { id, name, share } = projectconst validate = () => {@@ -276,11 +261,17 @@ const People: React.FunctionComponent<IPeopleProps> = ({setErrors({})}- const onRemove = async (userId: string) => {+ const onRemove = async (member: IShareOwnerProject) => {+ if (isDeleting) {+ return+ }++ setIsDeleting(true)+try {- await deleteShareProjectUsers(id, userId)+ await deleteShareProjectUsers(id, member.id)const newShared = _map(- _filter(share, (s) => s.id !== userId),+ _filter(share, (s) => s.id !== member.id),(s) => s,)setProjectShareData({ share: newShared }, id)@@ -288,6 +279,8 @@ const People: React.FunctionComponent<IPeopleProps> = ({} catch (reason) {console.error(`[ERROR] Error while deleting a user: ${reason}`)toast.error(t('apiNotifications.userRemoveError'))+ } finally {+ setIsDeleting(false)}}@@ -331,15 +324,17 @@ const People: React.FunctionComponent<IPeopleProps> = ({{t('profileSettings.sharedTable.joinedOn')}</th><th scope='col' />- <th scope='col' /></tr></thead><tbody className='divide-y divide-gray-300 dark:divide-gray-600'>- {_map(share, (user) => (+ {_map(share, (data) => (<UsersList- data={user}- key={user.id}- onRemove={onRemove}+ data={data}+ key={data.id}+ onRemove={() => {+ setMemberToRemove(data)+ setShowDeleteModal(true)+ }}language={language}share={project.share}setProjectShareData={setProjectShareData}@@ -356,6 +351,23 @@ const People: React.FunctionComponent<IPeopleProps> = ({)}</div><PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} />+ <Modal+ onClose={() => {+ setShowDeleteModal(false)+ setMemberToRemove(null)+ }}+ onSubmit={() => {+ setShowDeleteModal(false)+ onRemove(memberToRemove!)+ }}+ submitText={t('common.yes')}+ type='confirmed'+ closeText={t('common.no')}+ title={t('project.settings.removeUser', { user: memberToRemove?.user.email })}+ message={t('project.settings.removeConfirm')}+ isOpened={showDeleteModal}+ isLoading={isDeleting}+ /><ModalonClose={closeModal}customButtons={diff --git a/web/app/pages/Project/Settings/ProjectSettings.container.tsx b/web/app/pages/Project/Settings/ProjectSettings.container.tsxdeleted file mode 100644index c96fa2ac7..000000000--- a/web/app/pages/Project/Settings/ProjectSettings.container.tsx+++ /dev/null@@ -1,44 +0,0 @@-import { connect } from 'react-redux'-import UIActions from 'redux/reducers/ui'-import sagaActions from 'redux/sagas/actions'-import { StateType, AppDispatch } from 'redux/store'--import ProjectSettings from './ProjectSettings'--const mapStateToProps = (state: StateType) => ({- projects: state.ui.projects.projects,- isLoading: state.ui.projects.isLoading,- authLoading: state.auth.loading,- dashboardPaginationPage: state.ui.projects.dashboardPaginationPage,- user: state.auth.user,-})--const mapDispatchToProps = (dispatch: AppDispatch) => ({- loadProjects: (skip: number) => {- dispatch(sagaActions.loadProjects(skip))- },- removeProject: (pid: string) => {- dispatch(- UIActions.removeProject({- pid,- }),- )- },- deleteProjectCache: (pid: string) => {- dispatch(- UIActions.deleteProjectCache({- pid,- }),- )- },- setProjectProtectedPassword(id: string, password: string) {- dispatch(- UIActions.setProjectProtectedPassword({- id,- password,- }),- )- },-})--export default connect(mapStateToProps, mapDispatchToProps)(ProjectSettings)diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex 4acac707a..ab67a1508 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -1,7 +1,6 @@-import React, { useState, useEffect, useMemo, memo } from 'react'-import type i18next from 'i18next'+import React, { useState, useEffect, useMemo } from 'react'import { toast } from 'sonner'-import { useLoaderData, useNavigate } from '@remix-run/react'+import { useLoaderData, useNavigate, Link } from '@remix-run/react'import { useTranslation } from 'react-i18next'import cx from 'clsx'import _isEmpty from 'lodash/isEmpty'@@ -16,19 +15,11 @@ import _filter from 'lodash/filter'import _map from 'lodash/map'import _toUpper from 'lodash/toUpper'import _includes from 'lodash/includes'-import { TrashIcon } from '@heroicons/react/24/outline'+import { TrashIcon, XCircleIcon } from '@heroicons/react/24/outline'import { withAuthentication, auth } from 'hoc/protected'-import {- isSelfhosted,- TITLE_SUFFIX,- ENTRIES_PER_PAGE_DASHBOARD,- FILTERS_PANELS_ORDER,- isBrowser,-} from 'redux/constants'+import { isSelfhosted, TITLE_SUFFIX, FILTERS_PANELS_ORDER, isBrowser } from 'redux/constants'import { IProject } from 'redux/models/IProject'-import { IUser } from 'redux/models/IUser'-import { IProjectForShared } from 'redux/models/ISharedProject'import {updateProject,deleteProject,@@ -37,6 +28,7 @@ import {deletePartially,getFilters,resetFilters,+ getProject,} from 'api'import Input from 'ui/Input'import Button from 'ui/Button'@@ -56,12 +48,15 @@ import Emails from './Emails'import Select from 'ui/Select'import { useRequiredParams } from 'hooks/useRequiredParams'import { ArrowLeftRight, RotateCcw } from 'lucide-react'+import { StateType, useAppDispatch } from 'redux/store'+import { useSelector } from 'react-redux'+import UIActions from 'redux/reducers/ui'const MAX_NAME_LENGTH = 50const MAX_ORIGINS_LENGTH = 300const MAX_IPBLACKLIST_LENGTH = 300-const tabDeleteDataModal = [+const DELETE_DATA_MODAL_TABS = [{name: 'all',title: 'project.settings.reseted.all',@@ -76,33 +71,33 @@ const tabDeleteDataModal = [},]-interface IModalMessage {+interface ModalMessageProps {dateRange: Date[]setDateRange: (a: Date[]) => voidsetTab: (i: string) => void- t: typeof i18next.ttab: stringpid: stringactiveFilter: string[]setActiveFilter: anyfilterType: stringsetFilterType: (a: string) => void- language: string}const ModalMessage = ({dateRange,setDateRange,setTab,- t,tab,pid,activeFilter,setActiveFilter,filterType,setFilterType,- language,-}: IModalMessage): JSX.Element => {+}: ModalMessageProps) => {+ const {+ t,+ i18n: { language },+ } = useTranslation('common')const [filterList, setFilterList] = useState<string[]>([])const [searchList, setSearchList] = useState<string[]>([])@@ -127,7 +122,7 @@ const ModalMessage = ({<p className='mb-4 mt-1 text-sm italic text-gray-500 dark:text-gray-300'>{t('project.settings.resetHint')}</p><div className='mt-6'><nav className='-mb-px flex space-x-6'>- {_map(tabDeleteDataModal, (tabDelete) => (+ {_map(DELETE_DATA_MODAL_TABS, (tabDelete) => (<buttonkey={tabDelete.name}type='button'@@ -143,7 +138,7 @@ const ModalMessage = ({))}</nav></div>- {tab === tabDeleteDataModal[1].name && (+ {tab === DELETE_DATA_MODAL_TABS[1].name && (<><p className='mb-2 mt-4 text-sm text-gray-500 dark:text-gray-300'>{t('project.settings.reseted.partiallyDesc')}@@ -165,12 +160,12 @@ const ModalMessage = ({/></>)}- {tab === tabDeleteDataModal[0].name && (+ {tab === DELETE_DATA_MODAL_TABS[0].name && (<p className='mb-4 mt-4 text-sm italic text-gray-500 dark:text-gray-300'>{t('project.settings.reseted.allHint')}</p>)}- {tab === tabDeleteDataModal[2].name && (+ {tab === DELETE_DATA_MODAL_TABS[2].name && (<div className='min-h-[410px]'><p className='mb-4 mt-4 text-sm italic text-gray-500 dark:text-gray-300'>{t('project.settings.reseted.viaFiltersHint')}@@ -258,41 +253,17 @@ interface IForm extends Partial<IProject> {const DEFAULT_PROJECT_NAME = 'Untitled Project'-interface IProjectSettings {- loadProjects: (skip: number) => void- isLoading: boolean- projects: IProject[]- removeProject: (pid: string) => void- user: IUser- deleteProjectCache: (pid: string) => void- setProjectProtectedPassword: (pid: string, password: string) => void- dashboardPaginationPage: number- authLoading: boolean-}+const ProjectSettings = () => {+ const { user, loading: authLoading } = useSelector((state: StateType) => state.auth)-const ProjectSettings = ({- loadProjects,- isLoading,- projects,- removeProject,- user,- deleteProjectCache,- setProjectProtectedPassword,- dashboardPaginationPage,- authLoading,-}: IProjectSettings) => {- const {- t,- i18n: { language },- } = useTranslation('common')+ const dispatch = useAppDispatch()++ const { t } = useTranslation('common')const { id } = useRequiredParams<{ id: string }>()- const project: IProjectForShared = useMemo(- () => _find(projects, (p) => p.id === id) || ({} as IProjectForShared),- [projects, id],- )const navigate = useNavigate()const { requestOrigin } = useLoaderData<{ requestOrigin: string | null }>()+ const [project, setProject] = useState<IProject | null>(null)const [form, setForm] = useState<IForm>({name: '',id,@@ -302,31 +273,31 @@ const ProjectSettings = ({ipBlacklist: null,botsProtectionLevel: 'basic',})- const [validated, setValidated] = useState<boolean>(false)+ const [validated, setValidated] = useState(false)const [errors, setErrors] = useState<{name?: stringorigins?: stringipBlacklist?: stringpassword?: string}>({})- const [beenSubmitted, setBeenSubmitted] = useState<boolean>(false)- const [showDelete, setShowDelete] = useState<boolean>(false)- const [showReset, setShowReset] = useState<boolean>(false)- const [projectDeleting, setProjectDeleting] = useState<boolean>(false)- const [projectResetting, setProjectResetting] = useState<boolean>(false)- const [projectSaving, setProjectSaving] = useState<boolean>(false)- const [showTransfer, setShowTransfer] = useState<boolean>(false)- const [transferEmail, setTransferEmail] = useState<string>('')+ const [beenSubmitted, setBeenSubmitted] = useState(false)+ const [showDelete, setShowDelete] = useState(false)+ const [showReset, setShowReset] = useState(false)+ const [isDeleting, setIsDeleting] = useState(false)+ const [setResetting, setIsResetting] = useState(false)+ const [isSaving, setIsSaving] = useState(false)+ const [showTransfer, setShowTransfer] = useState(false)+ const [transferEmail, setTransferEmail] = useState('')const [dateRange, setDateRange] = useState<Date[]>([])- const [tab, setTab] = useState<string>(tabDeleteDataModal[0].name)- const [showProtected, setShowProtected] = useState<boolean>(false)- const [initialised, setInitialised] = useState(false)+ const [tab, setTab] = useState(DELETE_DATA_MODAL_TABS[0].name)+ const [showProtected, setShowProtected] = useState(false)++ const [isLoading, setIsLoading] = useState<boolean | null>(null)+ const [error, setError] = useState<any>(null)// for reset data via filtersconst [activeFilter, setActiveFilter] = useState<string[]>([])- const [filterType, setFilterType] = useState<string>('')-- const paginationSkip = dashboardPaginationPage * ENTRIES_PER_PAGE_DASHBOARD+ const [filterType, setFilterType] = useState('')const botsProtectionLevels = useMemo(() => {return [@@ -358,34 +329,40 @@ const ProjectSettings = ({return `${origin}/projects/${id}`}, [requestOrigin, id])- useEffect(() => {- if (authLoading || initialised) {+ const loadProject = async (projectId: string) => {+ if (isLoading) {return}-- if (!user.isActive && !isSelfhosted) {- toast.error(t('project.settings.verify'))- navigate(routes.dashboard)+ setIsLoading(true)++ try {+ const result = await getProject(projectId)+ setProject(result)+ setForm({+ ...result,+ ipBlacklist: _isString(result.ipBlacklist) ? result.ipBlacklist : _join(result.ipBlacklist, ', '),+ origins: _isString(result.origins) ? result.origins : _join(result.origins, ', '),+ })+ } catch (reason: any) {+ setError(reason)+ } finally {+ setIsLoading(false)}+ }- if (!isLoading && !projectDeleting) {- if (_isEmpty(project) || project?.uiHidden) {- toast.error(t('project.noExist'))- navigate(routes.dashboard)- } else {- setForm({- ...project,- ipBlacklist: _isString(project.ipBlacklist) ? project.ipBlacklist : _join(project.ipBlacklist, ', '),- origins: _isString(project.origins) ? project.origins : _join(project.origins, ', '),- })- setInitialised(true)- }+ useEffect(() => {+ if (authLoading) {+ return}- }, [user, project, initialised, isLoading, navigate, projectDeleting, t, authLoading])++ loadProject(id)++ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [authLoading, id])const onSubmit = async (data: IForm) => {- if (!projectSaving) {- setProjectSaving(true)+ if (!isSaving) {+ setIsSaving(true)try {const formalisedData = {...data,@@ -405,67 +382,80 @@ const ProjectSettings = ({}await updateProject(id, formalisedData as Partial<IProject>)toast.success(t('project.settings.updated'))-- loadProjects(paginationSkip)} catch (reason: any) {toast.error(reason)} finally {- setProjectSaving(false)+ setIsSaving(false)}}}const onDelete = async () => {setShowDelete(false)- if (!projectDeleting) {- setProjectDeleting(true)- try {- await deleteProject(id)- removeProject(id)- toast.success(t('project.settings.deleted'))- navigate(routes.dashboard)- } catch (reason: any) {- toast.error(reason)- } finally {- setProjectDeleting(false)- }++ if (isDeleting) {+ return+ }++ setIsDeleting(true)+ try {+ await deleteProject(id)+ dispatch(+ UIActions.removeProject({+ pid: id,+ }),+ )+ toast.success(t('project.settings.deleted'))+ navigate(routes.dashboard)+ } catch (reason: any) {+ toast.error(reason)+ } finally {+ setIsDeleting(false)}}const onReset = async () => {setShowReset(false)- if (!projectResetting) {- setProjectResetting(true)- try {- if (tab === tabDeleteDataModal[1].name) {- if (_isEmpty(dateRange)) {- toast.error(t('project.settings.noDateRange'))- setProjectResetting(false)- return- }- await deletePartially(id, {- from: getFormatDate(dateRange[0]),- to: getFormatDate(dateRange[1]),- })- } else if (tab === tabDeleteDataModal[2].name) {- if (_isEmpty(activeFilter)) {- toast.error(t('project.settings.noFilters'))- setProjectResetting(false)- return- }- await resetFilters(id, filterType, activeFilter)- } else {- await resetProject(id)+ if (setResetting) {+ return+ }++ setIsResetting(true)++ try {+ if (tab === DELETE_DATA_MODAL_TABS[1].name) {+ if (_isEmpty(dateRange)) {+ toast.error(t('project.settings.noDateRange'))+ setIsResetting(false)+ return}- deleteProjectCache(id)- toast.success(t('project.settings.resetted'))- navigate(routes.dashboard)- } catch (reason: any) {- toast.error(reason)- } finally {- setProjectResetting(false)+ await deletePartially(id, {+ from: getFormatDate(dateRange[0]),+ to: getFormatDate(dateRange[1]),+ })+ } else if (tab === DELETE_DATA_MODAL_TABS[2].name) {+ if (_isEmpty(activeFilter)) {+ toast.error(t('project.settings.noFilters'))+ setIsResetting(false)+ return+ }++ await resetFilters(id, filterType, activeFilter)+ } else {+ await resetProject(id)}+ dispatch(+ UIActions.deleteProjectCache({+ pid: id,+ }),+ )+ toast.success(t('project.settings.resetted'))+ navigate(routes.dashboard)+ } catch (reason: any) {+ toast.error(reason)+ } finally {+ setIsResetting(false)}}@@ -523,10 +513,6 @@ const ProjectSettings = ({}}- const onCancel = () => {- navigate(_replace(routes.project, ':id', id))- }-const onTransfer = async () => {await transferProject(id, transferEmail).then(() => {@@ -552,7 +538,12 @@ const ProjectSettings = ({})if (!_isEmpty(form.password) && !_isEmpty(form.id)) {- setProjectProtectedPassword(form?.id || '', form?.password || '')+ dispatch(+ UIActions.setProjectProtectedPassword({+ id: form?.id || '',+ password: form?.password || '',+ }),+ )}setForm((prev) => ({@@ -570,7 +561,7 @@ const ProjectSettings = ({document.title = `${t('project.settings.settings')} ${form.name} ${TITLE_SUFFIX}`}, [form, t])- if (authLoading || !initialised) {+ if (isLoading || isLoading === null || !project) {return (<div className='flex min-h-min-footer flex-col bg-gray-50 px-4 py-6 dark:bg-slate-900 sm:px-6 lg:px-8'><Loader />@@ -578,6 +569,43 @@ const ProjectSettings = ({)}+ if (error && !isLoading) {+ 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>+ )+ }+return (<div className='flex min-h-min-footer flex-col bg-gray-50 px-4 py-6 pb-40 dark:bg-slate-900 sm:px-6 lg:px-8'><form className='mx-auto w-full max-w-7xl' onSubmit={handleSubmit}>@@ -725,17 +753,19 @@ const ProjectSettings = ({<div className='flex flex-wrap items-center gap-2'><ButtonclassName='border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'- onClick={onCancel}+ as={Link}+ // @ts-expect-error+ to={_replace(routes.project, ':id', id)}secondaryregular>{t('common.cancel')}</Button>- <Button type='submit' loading={projectSaving} primary regular>+ <Button type='submit' loading={isSaving} primary regular>{t('common.save')}</Button></div>- {!project?.shared && (+ {project.role === 'owner' ? (<div className='flex flex-wrap justify-center gap-2'>{!isSelfhosted && (<Button onClick={() => setShowTransfer(true)} semiDanger semiSmall>@@ -745,30 +775,20 @@ const ProjectSettings = ({</></Button>)}- <Button- onClick={() => !projectResetting && setShowReset(true)}- loading={projectDeleting}- semiDanger- semiSmall- >+ <Button onClick={() => !setResetting && setShowReset(true)} loading={isDeleting} semiDanger semiSmall><><RotateCcw className='mr-1 h-5 w-5' />{t('project.settings.reset')}</></Button>- <Button- onClick={() => !projectDeleting && setShowDelete(true)}- loading={projectDeleting}- danger- semiSmall- >+ <Button onClick={() => !isDeleting && setShowDelete(true)} loading={isDeleting} danger semiSmall><><TrashIcon className='mr-1 h-5 w-5' />{t('project.settings.delete')}</></Button></div>- )}+ ) : null}</div>{!isSelfhosted && (<>@@ -807,13 +827,11 @@ const ProjectSettings = ({dateRange={dateRange}setTab={setTab}tab={tab}- t={t}pid={id}activeFilter={activeFilter}setActiveFilter={setActiveFilter}filterType={filterType}setFilterType={setFilterType}- language={language}/>}submitType='danger'@@ -880,4 +898,4 @@ const ProjectSettings = ({)}-export default memo(withAuthentication(ProjectSettings, auth.authenticated))+export default withAuthentication(ProjectSettings, auth.authenticated)diff --git a/web/app/pages/Project/Settings/index.tsx b/web/app/pages/Project/Settings/index.tsxindex 91c7f9508..2d2e7f1a4 100644--- a/web/app/pages/Project/Settings/index.tsx+++ b/web/app/pages/Project/Settings/index.tsx@@ -1,3 +1,3 @@-import ProjectSettings from './ProjectSettings.container'+import ProjectSettings from './ProjectSettings'export default ProjectSettingsdiff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex a048e75e6..87f598c5c 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -82,7 +82,6 @@ import {TimeFormat,getProjectForcastCacheKey,chartTypes,- roleAdmin,TRAFFIC_PANELS_ORDER,PERFORMANCE_PANELS_ORDER,isSelfhosted,@@ -801,9 +800,6 @@ const ViewProject = ({document.title = pageTitle}, [name, user, liveStats, id, t])- // sharedRoles is a role for shared project- const sharedRoles = useMemo(() => _find(user.sharedProjects, (p) => p.project.id === id)?.role || {}, [user, id])-const timeBucketSelectorItems = useMemo(() => {if (activeTab === PROJECT_TABS.errors) {return _filter(periodPairs, (el) => {@@ -1006,7 +1002,7 @@ const ViewProject = ({[t],)- const allowedToManage = useMemo(() => project?.isOwner || sharedRoles === roleAdmin.role, [project, sharedRoles])+ const allowedToManage = project.role === 'owner' || project.role === 'admin'const dataNamesFunnel = useMemo(() => ({@@ -3018,13 +3014,13 @@ const ViewProject = ({return}- getProject(id, false, projectPassword)+ getProject(id, projectPassword).then((projectRes) => {if (_isEmpty(projectRes)) {onErrorLoading()}- if (projectRes.isPasswordProtected && !projectRes.isOwner && _isEmpty(projectPassword)) {+ if (projectRes.isPasswordProtected && !projectRes.role && _isEmpty(projectPassword)) {navigate({pathname: _replace(routes.project_protected_password, ':id', id),search: `?theme=${ssrTheme}&embedded=${embedded}`,@@ -3032,9 +3028,10 @@ const ViewProject = ({return}- if ((projectRes.isPublic || projectRes?.isPasswordProtected) && !projectRes.isOwner) {+ if ((projectRes.isPublic || projectRes?.isPasswordProtected) && !projectRes.role) {setPublicProject(projectRes)} else {+ // TODO: Check, do we really need to add this project to the projects list?setProjects([...(projects as any[]), projectRes])if (projectRes.isLocked) {@@ -3051,8 +3048,8 @@ const ViewProject = ({})}})- .catch((e) => {- console.error('[ERROR] (getProject)', e)+ .catch((reason) => {+ console.error('[ERROR] (getProject)', reason)onErrorLoading()})}, [isLoading, project, id, setPublicProject]) // eslint-disable-line@@ -4164,8 +4161,7 @@ const ViewProject = ({)}</>)}- {/* TODO: PROPERLY CHECK IF PROJECT IS SHARED */}- {activeTab === PROJECT_TABS.alerts && (!project?.isOwner || !authenticated) && (+ {activeTab === PROJECT_TABS.alerts && (project.role !== 'owner' || !authenticated) && (<div className='mt-5 rounded-xl bg-gray-700 p-5'><div className='flex items-center text-gray-50'><BellIcon className='mr-2 h-8 w-8' />@@ -4591,8 +4587,7 @@ const ViewProject = ({{!errorLoading && _isEmpty(activeError) && <NoErrorDetails />}</>)}- {/* TODO: PROPERLY CHECK IF PROJECT IS SHARED */}- {activeTab === PROJECT_TABS.alerts && project?.isOwner && authenticated && (+ {activeTab === PROJECT_TABS.alerts && project.role === 'owner' && authenticated && (<ProjectAlertsView projectId={id} />)}{activeTab === PROJECT_TABS.uptime && <Uptime />}@@ -5049,10 +5044,7 @@ const ViewProject = ({customTabs={customTabs}// @ts-expect-errorvalueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}- rowMapper={({ name: entryName }) => {- // todo: add uppercase- return entryName || t('project.redactedPage')- }}+ rowMapper={({ name: entryName }) => entryName || t('project.redactedPage')}/>)}diff --git a/web/app/pages/Project/View/components/LockedDashboard.tsx b/web/app/pages/Project/View/components/LockedDashboard.tsxindex 474223d82..39bdb4afb 100644--- a/web/app/pages/Project/View/components/LockedDashboard.tsx+++ b/web/app/pages/Project/View/components/LockedDashboard.tsx@@ -15,7 +15,7 @@ const LockedDashboard = ({ user, project }: ILockedDashboard) => {const { t } = useTranslation('common')const message = useMemo(() => {- if (project?.isOwner) {+ if (project.role === 'owner') {if (user?.dashboardBlockReason === DashboardBlockReason.exceeding_plan_limits) {return t('project.locked.descExceedingTier')}@@ -30,8 +30,7 @@ const LockedDashboard = ({ user, project }: ILockedDashboard) => {}}- // TODO: PROPERLY CHECK IF PROJECT IS SHARED- if (!project.isOwner) {+ if (project.role === 'admin' || project.role === 'viewer') {return t('project.locked.descSharedProject')}@@ -50,7 +49,7 @@ const LockedDashboard = ({ user, project }: ILockedDashboard) => {</h1><p className='mt-1 max-w-prose whitespace-pre-line text-base text-gray-700 dark:text-gray-300'>{message}- {project?.isOwner && (+ {project.role === 'owner' && (<><br /><br />@@ -59,7 +58,7 @@ const LockedDashboard = ({ user, project }: ILockedDashboard) => {)}</p></div>- {project?.isOwner && (+ {project.role === 'owner' && (<div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'><Linkto={routes.billing}diff --git a/web/app/pages/UserSettings/components/ProjectList.tsx b/web/app/pages/UserSettings/components/ProjectList.tsxindex 0678eb0b8..d10bd460f 100644--- a/web/app/pages/UserSettings/components/ProjectList.tsx+++ b/web/app/pages/UserSettings/components/ProjectList.tsx@@ -47,8 +47,8 @@ const ProjectList = ({const onAccept = async () => {try {await acceptShareProject(id)- setProjectsShareData({ isShareConfirmed: true }, project.id)- setUserShareData({ isShareConfirmed: true }, id)+ setProjectsShareData({ isAccessConfirmed: true }, project.id)+ setUserShareData({ confirmed: true }, id)toast.success(t('apiNotifications.acceptInvitation'))} catch (e) {console.error(`[ERROR] Error while accepting project invitation: ${e}`)diff --git a/web/app/redux/constants/index.ts b/web/app/redux/constants/index.tsindex bc874a474..63b6e6881 100644--- a/web/app/redux/constants/index.ts+++ b/web/app/redux/constants/index.ts@@ -1,5 +1,6 @@/* eslint-disable no-undef */import _endsWith from 'lodash/endsWith'+import { Role } from 'redux/models/Organisation'const displayDateOptions: Intl.DateTimeFormatOptions = {year: 'numeric',@@ -488,7 +489,7 @@ export const I18N_CACHE_BREAKER = 9// dashboard && projects-export const roles: string[] = ['admin', 'viewer']+export const roles: Role[] = ['admin', 'viewer']export const roleViewer: {name: stringdiff --git a/web/app/redux/models/IProject.ts b/web/app/redux/models/IProject.tsindex 7db643e69..b5360358a 100644--- a/web/app/redux/models/IProject.ts+++ b/web/app/redux/models/IProject.ts@@ -1,4 +1,4 @@-import { Organisation } from './Organisation'+import { Organisation, Role } from './Organisation'interface _IOverallPeriodStats {all: number@@ -37,8 +37,9 @@ export interface IOverallPerformanceObject {networkChange: number}-interface IUserShareProject {+interface UserShareProject {email: string+ id: string}export interface ILiveStats {@@ -51,7 +52,7 @@ export interface IShareOwnerProject {role: stringcreated: stringupdated: string- user: IUserShareProject+ user: UserShareProject}export interface IFunnel {@@ -83,14 +84,13 @@ export interface IProject {captchaSecretKey: string | nullcreated: stringshare?: IShareOwnerProject[]- isOwner: booleanoverall: IOverallObjectuiHidden: booleanfunnels: IFunnel[]isPublic?: booleanisTransferring?: booleanisPasswordProtected?: boolean- isShareConfirmed?: boolean+ isAccessConfirmed?: booleanorganisationId?: stringorganisation?: Organisationpassword?: string@@ -98,21 +98,10 @@ export interface IProject {isDataExists: booleanisErrorDataExists: booleanbotsProtectionLevel: 'off' | 'basic'+ role?: Role}-export interface ICaptchaProject {- id: string- name: string- origins: string[] | string | null- ipBlacklist: string[] | null | string- active: boolean- public: boolean- isAnalyticsProject: boolean- isCaptchaProject: boolean- isCaptchaEnabled: boolean- captchaSecretKey: string | null- created: string- isOwner: boolean- overall: IOverallObject- uiHidden: boolean+export interface ICaptchaProject extends IProject {+ isCaptchaProject: true+ isCaptchaEnabled: true}diff --git a/web/app/redux/models/ISharedProject.ts b/web/app/redux/models/ISharedProject.tsindex d08e1775c..094789a17 100644--- a/web/app/redux/models/ISharedProject.ts+++ b/web/app/redux/models/ISharedProject.ts@@ -2,7 +2,6 @@ import { IProject } from './IProject'export interface IProjectForShared extends IProject {shared?: boolean- role?: string}export interface ISharedProject {diff --git a/web/app/redux/models/Organisation.ts b/web/app/redux/models/Organisation.tsindex 792da04db..4267a8af7 100644--- a/web/app/redux/models/Organisation.ts+++ b/web/app/redux/models/Organisation.ts@@ -5,10 +5,12 @@ export interface Organisation {updated: string}+export type Role = 'owner' | 'admin' | 'viewer'+export interface DetailedOrganisation extends Organisation {members: {id: string- role: 'admin' | 'viewer'+ role: Rolecreated: stringconfirmed: booleanuser: {diff --git a/web/app/ui/Button.tsx b/web/app/ui/Button.tsxindex 0d8c9feb5..baf54efe2 100644--- a/web/app/ui/Button.tsx+++ b/web/app/ui/Button.tsx@@ -4,35 +4,22 @@ import { Button as HeadlessButton } from '@headlessui/react'import cx from 'clsx'import Spin from './icons/Spin'-// Define the prop types for the component-interface IButton extends React.ButtonHTMLAttributes<HTMLButtonElement> {- // (string): The text to be displayed in the button.+interface IButton extends React.ComponentPropsWithoutRef<typeof HeadlessButton> {text?: string- // (node): The content to be displayed in the button.children?: JSX.Element | stringprimary?: booleansecondary?: booleandanger?: boolean- // (function): The function to be called when the button is clicked.- onClick?: () => voidwhite?: booleansmall?: booleanregular?: booleanlarge?: booleangiant?: boolean- // (string): The type of button to be rendered.- type?: 'button' | 'submit' | 'reset'- // (string): Additional CSS classes to be applied to the button.- className?: string- // (boolean): Whether the button is in a loading state.loading?: booleansemiSmall?: booleansemiDanger?: boolean- // (boolean): Whether the button is in a focus state.focus?: booleannoBorder?: boolean- // (boolean): Whether the button is disabled.- disabled?: boolean}const Button = ({@@ -41,7 +28,6 @@ const Button = ({primary,secondary,danger,- onClick,white,small,regular,@@ -56,12 +42,11 @@ const Button = ({focus = true,disabled,...props-}: IButton): JSX.Element => (+}: IButton) => (<HeadlessButton{...props}disabled={disabled || loading}type={type}- onClick={onClick}className={cx('relative inline-flex select-none items-center rounded-md border font-medium leading-4',{diff --git a/web/app/utils/analytics.ts b/web/app/utils/analytics.tsindex e7b7b87ff..9e420fb6d 100644--- a/web/app/utils/analytics.ts+++ b/web/app/utils/analytics.ts@@ -101,7 +101,7 @@ const getNewPath = (path: string | undefined | null) => {}Swetrix.init(SWETRIX_PID, {- devMode: isDevelopment,+ disabled: isDevelopment,})const BLOG_PAGE_REGEX = /^\/blog\/.+$/diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex c34194dd2..174f6c21a 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -51,7 +51,10 @@"organisationCreated": "Organisation has been created","organisationCreateError": "Error occurred while creating the organisation","projectRemovedFromOrganisation": "The project has been removed from the organisation",- "projectRemoveError": "Error occurred while removing the project from the organisation"+ "projectRemoveError": "Error occurred while removing the project from the organisation",+ "orgUserRemoved": "The user has been removed from the organisation",+ "orgUserRemoveError": "Error occurred while removing the user from the organisation",+ "orgSettingsUpdated": "Organisation settings have been updated"},"common": {"features": "Features",