Skip to content

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

feat: add projects to organisation from organisation settings page

Blue Mousef4f8d36745ee
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index 96e27d83d..a54dbf165 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -141,10 +141,7 @@ export class ProjectController {
@Get('/')
@ApiQuery({ name: 'take', required: false })
@ApiQuery({ name: 'skip', required: false })
- @ApiQuery({ name: 'isCaptcha', required: false, type: Boolean })
- @ApiQuery({ name: 'relatedonly', required: false, type: Boolean })
@ApiQuery({ name: 'search', required: false, type: String })
- @ApiQuery({ name: 'showArchived', required: false, type: Boolean })
@ApiResponse({ status: 200, type: [Project] })
@Auth([], true)
async get(
@@ -209,6 +206,33 @@ export class ProjectController {
}
}
+ @ApiBearerAuth()
+ @Get('/available-for-organisation')
+ @ApiQuery({ name: 'take', required: false })
+ @ApiQuery({ name: 'skip', required: false })
+ @ApiQuery({ name: 'search', required: false, type: String })
+ @ApiResponse({ status: 200, type: [Project] })
+ @Auth([], true)
+ async getAvailableProjectsForOrganization(
+ @CurrentUserId() userId: string,
+ @Query('take') take: number | undefined,
+ @Query('skip') skip: number | undefined,
+ @Query('search') search: string | undefined,
+ ): Promise<Pagination<Project> | Project[] | object> {
+ this.logger.log(
+ { userId, take, skip },
+ 'GET /project/available-for-organisation',
+ )
+
+ const paginated = await this.projectService.paginateForOrganisation(
+ { take, skip },
+ userId,
+ search,
+ )
+
+ return paginated
+ }
+
@ApiBearerAuth()
@Post('/admin/:id')
@ApiResponse({ status: 201, type: Project })
@@ -819,7 +843,7 @@ export class ProjectController {
const organisation = await this.organisationService.findOne({
where: { id: orgId },
- relations: ['members', 'projects'],
+ relations: ['members', 'members.user', 'projects'],
})
if (_isEmpty(organisation)) {
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index b21f807dc..601a26c9d 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -137,24 +137,35 @@ const deleteProjectsRedis = async (ids: string[]) => {
await Promise.all(_map(ids, deleteProjectRedis))
}
-export const processProjectUser = (project: Project): Project => {
- const { share } = project
-
- for (let j = 0; j < _size(share); ++j) {
- const { user } = share[j]
-
- if (user) {
- // @ts-expect-error _pick(user, ['email']) is partial but share[j].user expects full User entity
- share[j].user = _pick(user, ['email', 'id'])
+export const processProjectUser = (
+ project: Project,
+ properties: Array<'share' | 'organisation.members'> = ['share'],
+): Project => {
+ _map(properties, property => {
+ const array =
+ property === 'share' ? project.share : project.organisation?.members
+
+ if (array) {
+ for (let j = 0; j < _size(array); ++j) {
+ const { user } = array[j]
+
+ if (user) {
+ // @ts-expect-error _pick(user, ['email']) is partial but array[j].user expects full User entity
+ array[j].user = _pick(user, ['email', 'id'])
+ }
+ }
}
- }
+ })
return project
}
-const processProjectsUser = (projects: Project[]): Project[] => {
+const processProjectsUser = (
+ projects: Project[],
+ properties: Array<'share' | 'organisation.members'> = ['share'],
+): Project[] => {
for (let i = 0; i < _size(projects); ++i) {
- projects[i] = processProjectUser(projects[i])
+ projects[i] = processProjectUser(projects[i], properties)
}
return projects
@@ -409,6 +420,7 @@ export class ProjectService {
share: {
id: true,
role: true,
+ confirmed: true,
user: {
id: true,
email: true,
@@ -469,7 +481,46 @@ export class ProjectService {
)
if (search?.trim()) {
- queryBuilder.andWhere('(project.name ILIKE :search)', {
+ queryBuilder.andWhere('LOWER(project.name) LIKE LOWER(:search)', {
+ search: `%${search.trim()}%`,
+ })
+ }
+
+ queryBuilder
+ .orderBy('project.name', 'ASC')
+ .skip(options.skip || 0)
+ .take(options.take || 100)
+
+ const [results, total] = await queryBuilder.getManyAndCount()
+
+ return new Pagination<Project>({
+ results: processProjectsUser(results, ['share', 'organisation.members']),
+ total,
+ })
+ }
+
+ async paginateForOrganisation(
+ options: PaginationOptionsInterface,
+ userId: string,
+ search?: string,
+ ): Promise<Pagination<Project>> {
+ const queryBuilder = this.projectsRepository
+ .createQueryBuilder('project')
+ .select(['project.id', 'project.name'])
+ .leftJoin('project.admin', 'admin')
+ .leftJoin('project.share', 'share')
+ .where('project.organisation IS NULL')
+ .andWhere(
+ new Brackets(qb => {
+ qb.where('admin.id = :userId', { userId }).orWhere(
+ 'share.user.id = :userId AND share.role = :adminRole',
+ { userId, adminRole: Role.admin },
+ )
+ }),
+ )
+
+ if (search?.trim()) {
+ queryBuilder.andWhere('LOWER(project.name) LIKE LOWER(:search)', {
search: `%${search.trim()}%`,
})
}
@@ -482,7 +533,7 @@ export class ProjectService {
const [results, total] = await queryBuilder.getManyAndCount()
return new Pagination<Project>({
- results: processProjectsUser(results),
+ results,
total,
})
}
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index fafe50887..411f84740 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -266,6 +266,14 @@ export const getProjects = (take: number = 0, skip: number = 0, search?: string)
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
+export const getProjectsAvailableForOrganisation = (take: number = 0, skip: number = 0, search?: string) =>
+ api
+ .get(`/project/available-for-organisation?take=${take}&skip=${skip}&search=${search}`)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
export const getOrganisations = (take: number = 0, skip: number = 0, search?: string) =>
api
.get(`/organisation?take=${take}&skip=${skip}&search=${search}`)
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index 52ae9dba2..0768290e4 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -37,7 +37,7 @@ const Dashboard = () => {
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 pageAmount = Math.ceil(total / ENTRIES_PER_PAGE_DASHBOARD)
// This search represents what's inside the search input
const [search, setSearch] = useState('')
diff --git a/web/app/pages/Organisations/Settings/People.tsx b/web/app/pages/Organisations/Settings/People.tsx
index 3f4c18ebf..7cf980f07 100644
--- a/web/app/pages/Organisations/Settings/People.tsx
+++ b/web/app/pages/Organisations/Settings/People.tsx
@@ -150,9 +150,10 @@ const UsersList = ({ members, onRemove }: UsersListProps) => {
interface PeopleProps {
organisation: DetailedOrganisation
+ reloadOrganisation: () => Promise<void>
}
-const People = ({ organisation }: PeopleProps): JSX.Element => {
+const People = ({ organisation, reloadOrganisation }: PeopleProps): JSX.Element => {
const [showModal, setShowModal] = useState(false)
const { t } = useTranslation('common')
const [form, setForm] = useState({
@@ -214,6 +215,7 @@ const People = ({ organisation }: PeopleProps): JSX.Element => {
try {
// todo
+ await reloadOrganisation()
toast.success(t('apiNotifications.userInvited'))
} catch (reason) {
console.error(`[ERROR] Error while inviting a user: ${reason}`)
@@ -252,6 +254,7 @@ const People = ({ organisation }: PeopleProps): JSX.Element => {
try {
await removeOrganisationMember(member.id)
+ await reloadOrganisation()
toast.success(t('apiNotifications.orgUserRemoved'))
} catch (reason) {
diff --git a/web/app/pages/Organisations/Settings/Projects.tsx b/web/app/pages/Organisations/Settings/Projects.tsx
index 0e3aa9d57..b7663174f 100644
--- a/web/app/pages/Organisations/Settings/Projects.tsx
+++ b/web/app/pages/Organisations/Settings/Projects.tsx
@@ -1,9 +1,11 @@
-import React, { useState } from 'react'
+import React, { useState, useEffect } from 'react'
import { toast } from 'sonner'
-import { InformationCircleIcon, PlusIcon } from '@heroicons/react/24/outline'
+import { InformationCircleIcon, PlusIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline'
import { useTranslation } from 'react-i18next'
import _isEmpty from 'lodash/isEmpty'
import _replace from 'lodash/replace'
+import _map from 'lodash/map'
+import _filter from 'lodash/filter'
import Button from 'ui/Button'
import Modal from 'ui/Modal'
@@ -11,9 +13,111 @@ import { DetailedOrganisation } from 'redux/models/Organisation'
import { useSelector } from 'react-redux'
import { StateType } from 'redux/store'
import Tooltip from 'ui/Tooltip'
-import { removeProjectFromOrganisation } from 'api'
+import { removeProjectFromOrganisation, getProjectsAvailableForOrganisation, addProjectToOrganisation } from 'api'
import { Link } from '@remix-run/react'
import routes from 'utils/routes'
+import Loader from 'ui/Loader'
+import Pagination from 'ui/Pagination'
+import useDebounce from 'hooks/useDebounce'
+import { IProject } from 'redux/models/IProject'
+
+interface SelectAProjectProps {
+ onSelect: (project: IProject) => void
+}
+
+const PAGINATION_ENTRIES = 5
+
+const SelectAProject = ({ onSelect }: SelectAProjectProps) => {
+ const { t } = useTranslation('common')
+
+ const [currentPage, setCurrentPage] = useState(1)
+ const [search, setSearch] = useState('')
+ const [isLoading, setIsLoading] = useState(false)
+ const [projects, setProjects] = useState<IProject[]>([])
+ const [total, setTotal] = useState(0)
+
+ const debouncedSearch = useDebounce(search, 500)
+ const pageAmount = Math.ceil(total / PAGINATION_ENTRIES)
+
+ useEffect(() => {
+ const loadProjects = async () => {
+ setIsLoading(true)
+ try {
+ const { results, total: totalCount } = await getProjectsAvailableForOrganisation(
+ PAGINATION_ENTRIES,
+ (currentPage - 1) * PAGINATION_ENTRIES,
+ debouncedSearch,
+ )
+ setProjects(results)
+ setTotal(totalCount)
+ } catch (error) {
+ console.error('Failed to load projects:', error)
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ loadProjects()
+ }, [currentPage, debouncedSearch])
+
+ useEffect(() => {
+ setCurrentPage(1)
+ }, [debouncedSearch])
+
+ return (
+ <div className='mt-4 flex flex-col'>
+ <div className='mb-4'>
+ <div className='relative'>
+ <div className='pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3'>
+ <MagnifyingGlassIcon className='h-5 w-5 text-gray-400' />
+ </div>
+ <input
+ type='text'
+ className='block w-full rounded-md border-0 py-1.5 pl-10 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 dark:bg-slate-800 dark:text-white dark:ring-slate-600 dark:focus:ring-slate-400 sm:text-sm sm:leading-6'
+ placeholder={t('project.search')}
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ />
+ </div>
+ </div>
+
+ {isLoading ? (
+ <Loader />
+ ) : (
+ <div className='overflow-hidden rounded-lg border border-gray-200 dark:border-slate-600'>
+ <ul className='divide-y divide-gray-200 dark:divide-slate-600'>
+ {_map(
+ _filter(projects, ({ uiHidden }) => !uiHidden),
+ (project) => (
+ <li
+ key={project.id}
+ className='cursor-pointer hover:bg-gray-50 dark:hover:bg-slate-700'
+ onClick={() => onSelect(project)}
+ >
+ <div className='flex items-center px-4 py-4 sm:px-6'>
+ <div className='min-w-0 flex-1'>
+ <p className='truncate text-sm font-medium text-gray-900 dark:text-white'>{project.name}</p>
+ </div>
+ </div>
+ </li>
+ ),
+ )}
+ </ul>
+ </div>
+ )}
+
+ {pageAmount > 1 ? (
+ <Pagination
+ className='mt-4'
+ page={currentPage}
+ pageAmount={pageAmount}
+ setPage={setCurrentPage}
+ total={total}
+ />
+ ) : null}
+ </div>
+ )
+}
const NoProjects = () => {
const { t } = useTranslation('common')
@@ -64,33 +168,60 @@ const ProjectList = ({ projects, onRemove }: ProjectListProps) => {
interface ProjectsProps {
organisation: DetailedOrganisation
+ reloadOrganisation: () => Promise<void>
}
-export const Projects = ({ organisation }: ProjectsProps): JSX.Element => {
+export const Projects = ({ organisation, reloadOrganisation }: ProjectsProps): JSX.Element => {
const { t } = useTranslation('common')
const [showDeleteModal, setShowDeleteModal] = useState(false)
+ const [showAddProjectModal, setShowAddProjectModal] = useState(false)
const [projectToRemove, setProjectToRemove] = useState<DetailedOrganisation['projects'][number] | null>(null)
- const [removingProject, setRemovingProject] = useState(false)
+
+ const [isActionLoading, setIsActionLoading] = useState(false)
+ const [selectedProject, setSelectedProject] = useState<any>(null)
const { projects } = organisation
const removeProject = async (projectId: string) => {
- if (removingProject) {
+ if (isActionLoading) {
return
}
- setRemovingProject(true)
+ setIsActionLoading(true)
try {
await removeProjectFromOrganisation(organisation.id, projectId)
+ await reloadOrganisation()
toast.success(t('apiNotifications.projectRemovedFromOrganisation'))
} catch (reason) {
console.error(`[ERROR] Error while deleting a project: ${reason}`)
toast.error(t('apiNotifications.projectRemoveError'))
} finally {
setProjectToRemove(null)
- setRemovingProject(false)
+ setIsActionLoading(false)
+ }
+ }
+
+ const onAddProject = async () => {
+ setShowAddProjectModal(false)
+
+ if (isActionLoading) {
+ return
+ }
+
+ setIsActionLoading(true)
+
+ try {
+ await addProjectToOrganisation(organisation.id, selectedProject.id)
+ await reloadOrganisation()
+ toast.success(t('apiNotifications.projectAddedToOrganisation'))
+ } catch (reason) {
+ console.error(`[ERROR] Error while adding a project: ${reason}`)
+ toast.error(t('apiNotifications.projectAddError'))
+ } finally {
+ setSelectedProject(null)
+ setIsActionLoading(false)
}
}
@@ -100,7 +231,15 @@ export const Projects = ({ organisation }: ProjectsProps): JSX.Element => {
<h3 className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('organisations.projects')}
</h3>
- <Button className='h-8 pl-2' primary regular type='button' onClick={() => {}}>
+ <Button
+ className='h-8 pl-2'
+ primary
+ regular
+ type='button'
+ onClick={() => {
+ setShowAddProjectModal(true)
+ }}
+ >
<>
<PlusIcon className='mr-1 h-5 w-5' />
{t('organisations.addProject')}
@@ -144,6 +283,49 @@ export const Projects = ({ organisation }: ProjectsProps): JSX.Element => {
)}
</div>
+ <Modal
+ onClose={() => {
+ setShowAddProjectModal(false)
+ setSelectedProject(null)
+ }}
+ customButtons={
+ <button
+ type='button'
+ className='inline-flex w-full justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-base font-medium text-white shadow-sm hover:bg-indigo-700 sm:ml-3 sm:w-auto sm:text-sm'
+ onClick={onAddProject}
+ disabled={!selectedProject || isActionLoading}
+ >
+ {t('organisations.addProject')}
+ </button>
+ }
+ closeText={t('common.cancel')}
+ title={t('organisations.modals.addProject.title', { organisation: organisation.name })}
+ message={
+ <div>
+ <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
+ {t('organisations.modals.addProject.message')}
+ </p>
+
+ {selectedProject ? (
+ <div className='mt-4 flex items-center justify-between rounded-lg border border-gray-200 p-4 dark:border-slate-600'>
+ <span className='text-sm font-medium text-gray-900 dark:text-white'>{selectedProject.name}</span>
+ <button
+ type='button'
+ onClick={() => setSelectedProject(null)}
+ className='text-sm text-red-600 hover:text-red-500'
+ >
+ {t('common.remove')}
+ </button>
+ </div>
+ ) : (
+ <SelectAProject onSelect={setSelectedProject} />
+ )}
+ </div>
+ }
+ isOpened={showAddProjectModal}
+ isLoading={isActionLoading}
+ />
+
<Modal
onClose={() => {
setShowDeleteModal(false)
@@ -159,7 +341,7 @@ export const Projects = ({ organisation }: ProjectsProps): JSX.Element => {
message={t('organisations.modals.remove.message')}
isOpened={showDeleteModal}
type='warning'
- isLoading={removingProject}
+ isLoading={isActionLoading}
/>
</div>
)
diff --git a/web/app/pages/Organisations/Settings/index.tsx b/web/app/pages/Organisations/Settings/index.tsx
index c4de4dcc1..feaa7a130 100644
--- a/web/app/pages/Organisations/Settings/index.tsx
+++ b/web/app/pages/Organisations/Settings/index.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, memo } from 'react'
+import React, { useState, useEffect, memo, useCallback } from 'react'
import { toast } from 'sonner'
import { Link, useNavigate } from '@remix-run/react'
import { useTranslation } from 'react-i18next'
@@ -72,6 +72,18 @@ const OrganisationSettings = () => {
}
}
+ const reloadOrganisation = useCallback(async () => {
+ try {
+ const result = await getOrganisation(id)
+ setOrganisation(result)
+ setForm({
+ name: result.name,
+ })
+ } catch (reason: any) {
+ console.error(`[ERROR] Error while reloading organisation: ${reason}`)
+ }
+ }, [id])
+
useEffect(() => {
if (authLoading) {
return
@@ -278,8 +290,8 @@ const OrganisationSettings = () => {
)} */}
</div>
<hr className='mt-2 border-gray-200 dark:border-gray-600 sm:mt-5' />
- <People organisation={organisation} />
- <Projects organisation={organisation} />
+ <People organisation={organisation} reloadOrganisation={reloadOrganisation} />
+ <Projects organisation={organisation} reloadOrganisation={reloadOrganisation} />
</form>
<Modal
onClose={() => setShowDelete(false)}
diff --git a/web/app/pages/Organisations/index.tsx b/web/app/pages/Organisations/index.tsx
index b9c61a33c..0f214ac2f 100644
--- a/web/app/pages/Organisations/index.tsx
+++ b/web/app/pages/Organisations/index.tsx
@@ -458,7 +458,7 @@ const Organisations = () => {
)}
</ClientOnly>
)}
- {pageAmount > 1 && (
+ {pageAmount > 1 ? (
<Pagination
className='mt-2'
page={page}
@@ -466,7 +466,7 @@ const Organisations = () => {
setPage={setPage}
total={paginationTotal}
/>
- )}
+ ) : null}
</div>
</div>
</div>
diff --git a/web/app/ui/Pagination.tsx b/web/app/ui/Pagination.tsx
index 738cc87b6..454626d1d 100644
--- a/web/app/ui/Pagination.tsx
+++ b/web/app/ui/Pagination.tsx
@@ -17,6 +17,12 @@ const Pagination = ({ page, setPage, pageAmount, total, className }: IPagination
const { t } = useTranslation('common')
const paginationRange = usePagination(total, page)
+ console.log('total:', total)
+ console.log('page:', page)
+ console.log('pageAmount:', pageAmount)
+
+ console.log('paginationRange:', paginationRange)
+
return (
<nav className={cx('flex items-center justify-between border-t-0 border-gray-200 px-4 sm:px-0', className)}>
<div className='group -mt-px flex w-0 flex-1'>
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 174f6c21a..b32ae7d96 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -51,7 +51,9 @@
"organisationCreated": "Organisation has been created",
"organisationCreateError": "Error occurred while creating the organisation",
"projectRemovedFromOrganisation": "The project has been removed from the organisation",
+ "projectAddedToOrganisation": "The project has been added to the organisation",
"projectRemoveError": "Error occurred while removing the project from the organisation",
+ "projectAddError": "Error occurred while adding the project to 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"
@@ -636,6 +638,10 @@
"remove": {
"title": "Remove {{project}}?",
"message": "Are you sure you want to remove this project from the organisation? Once removed, organisation members will no longer have access to this project unless they are added in the project settings."
+ },
+ "addProject": {
+ "title": "Add project to {{organisation}}",
+ "message": "Select the project you want to add to the organisation. It will be available to all members of the organisation, and the organisation admins will be able to manage the project settings."
}
},
"projectOwnedBy": "This project is owned by {{email}}"