diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.js index dcfe41e72141..43a264b07e8a 100644 --- a/frontend/.eslintrc.js +++ b/frontend/.eslintrc.js @@ -1,6 +1,22 @@ // Patterns we keep catching in review. Warnings only, on changed lines only // (CI and pre-commit), so they never block a PR. For a real exception, // disable the rule on that line and say why. +const restrictedImports = [ + { + group: ['**/ErrorMessage', '**/InfoMessage', '**/WarningMessage'], + message: 'Use the DS Banner (components/base/Banner) instead.', + }, + { + group: ['@ionic/react', 'ionicons', 'ionicons/*'], + message: 'Use components/icons/Icon, our own SVG icons.', + }, +] +const accountStoreImport = { + group: ['**/account-store'], + message: + 'Read the organisation and user with useCurrentOrganisation, useIsOrganisationAdmin or useCurrentUser (common/hooks).', +} + const colourMessage = 'Use a colour token, not a hex, rgb or hsl literal.' const fetchMessage = 'Add an RTK Query endpoint in common/services/ instead of fetch().' @@ -196,6 +212,18 @@ module.exports = { 'no-restricted-syntax': ['warn', ...otherPatterns], }, }, + { + // The store itself and the hooks that wrap it + 'files': [ + 'common/stores/**', + 'common/hooks/useAccountStoreUpdates.ts', + 'common/hooks/useCurrentOrganisation.ts', + 'common/hooks/useCurrentUser.ts', + ], + 'rules': { + 'no-restricted-imports': ['warn', { patterns: restrictedImports }], + }, + }, { // The legacy request layer RTK Query is built on. 'files': ['common/data/base/**'], @@ -259,18 +287,7 @@ module.exports = { ], 'no-restricted-imports': [ 'warn', - { - patterns: [ - { - group: ['**/ErrorMessage', '**/InfoMessage', '**/WarningMessage'], - message: 'Use the DS Banner (components/base/Banner) instead.', - }, - { - group: ['@ionic/react', 'ionicons', 'ionicons/*'], - message: 'Use components/icons/Icon, our own SVG icons.', - }, - ], - }, + { patterns: [...restrictedImports, accountStoreImport] }, ], 'no-restricted-syntax': ['warn', ...colourLiterals, ...otherPatterns], 'no-unused-vars': 'off', diff --git a/frontend/common/hooks/__tests__/currentAccount.test.ts b/frontend/common/hooks/__tests__/currentAccount.test.ts new file mode 100644 index 000000000000..cd413df61f97 --- /dev/null +++ b/frontend/common/hooks/__tests__/currentAccount.test.ts @@ -0,0 +1,89 @@ +import AccountStore from 'common/stores/account-store' +import { + getCurrentOrganisation, + isOrganisationAdmin, +} from 'common/hooks/useCurrentOrganisation' +import { getCurrentUser } from 'common/hooks/useCurrentUser' +import { AccountModel, Organisation } from 'common/types/responses' + +jest.mock('common/stores/account-store', () => ({ + getOrganisation: jest.fn(), + getUser: jest.fn(), +})) + +const store = jest.mocked(AccountStore) + +const organisation = (role: Organisation['role']): Organisation => ({ + api_limit_grace_period_used: false, + api_limit_restriction_enabled: false, + block_access_to_admin: false, + created_date: '2026-01-01T00:00:00Z', + id: 1, + name: 'Acme', + num_seats: 1, + overage_billing_eligible: false, + persist_trait_data: true, + restrict_project_create_to_admin: false, + role, + stop_serving_flags: false, + subscription: { + cancellation_date: null, + current_billing_period: null, + customer_id: '', + has_active_billing_periods: false, + id: 1, + max_api_calls: 50000, + max_seats: 1, + notes: null, + payment_method: null, + plan: null, + subscription_date: '2026-01-01T00:00:00Z', + subscription_id: null, + uuid: 'subscription-uuid', + }, + webhook_notification_email: null, +}) + +describe('getCurrentOrganisation', () => { + it.each([ + ['the organisation', organisation('ADMIN'), organisation('ADMIN')], + ['undefined for null', null, undefined], + ['undefined for undefined', undefined, undefined], + ])('returns %s', (_, stored, expected) => { + store.getOrganisation.mockReturnValue(stored) + expect(getCurrentOrganisation()).toEqual(expected) + }) +}) + +describe('isOrganisationAdmin', () => { + it.each([ + ['an admin', organisation('ADMIN'), true], + ['a user', organisation('USER'), false], + ['no organisation', undefined, false], + ])('for %s returns %s', (_, value, expected) => { + expect(isOrganisationAdmin(value)).toBe(expected) + }) +}) + +describe('getCurrentUser', () => { + const user: AccountModel = { + auth_type: 'EMAIL', + date_joined: '2026-01-01T00:00:00Z', + email: 'ada@example.com', + first_name: 'Ada', + id: 7, + is_superuser: false, + last_name: 'Lovelace', + organisations: [], + pylon_email_signature: '', + sign_up_type: 'NO_INVITE', + uuid: 'user-uuid', + } + it.each([ + ['the user', user, user], + ['undefined for null', null, undefined], + ])('returns %s', (_, stored, expected) => { + store.getUser.mockReturnValue(stored) + expect(getCurrentUser()).toEqual(expected) + }) +}) diff --git a/frontend/common/hooks/useAccountStoreUpdates.ts b/frontend/common/hooks/useAccountStoreUpdates.ts new file mode 100644 index 000000000000..9d1ff4acfd69 --- /dev/null +++ b/frontend/common/hooks/useAccountStoreUpdates.ts @@ -0,0 +1,32 @@ +import { useSyncExternalStore } from 'react' +import AccountStore from 'common/stores/account-store' + +// Bumped on every store change, so React can tell a change happened between +// render and subscribe. Counted from the first render, not at import, so +// tests that mock the store can still load this module. +let version = 0 +let counting = false +const countChanges = () => { + if (counting) return + counting = true + AccountStore.on('change', () => { + version += 1 + }) +} + +const subscribe = (onChange: () => void) => { + AccountStore.on('change', onChange) + return () => { + AccountStore.off('change', onChange) + } +} + +const getVersion = () => version + +// Re-renders the caller whenever the legacy account store changes. +const useAccountStoreUpdates = () => { + countChanges() + useSyncExternalStore(subscribe, getVersion) +} + +export default useAccountStoreUpdates diff --git a/frontend/common/hooks/useCurrentOrganisation.ts b/frontend/common/hooks/useCurrentOrganisation.ts new file mode 100644 index 000000000000..cb4c46cf5c23 --- /dev/null +++ b/frontend/common/hooks/useCurrentOrganisation.ts @@ -0,0 +1,17 @@ +import AccountStore from 'common/stores/account-store' +import { Organisation } from 'common/types/responses' +import useAccountStoreUpdates from './useAccountStoreUpdates' + +export const getCurrentOrganisation = (): Organisation | undefined => + AccountStore.getOrganisation() ?? undefined + +export const isOrganisationAdmin = (organisation?: Organisation): boolean => + organisation?.role === 'ADMIN' + +export const useCurrentOrganisation = (): Organisation | undefined => { + useAccountStoreUpdates() + return getCurrentOrganisation() +} + +export const useIsOrganisationAdmin = (): boolean => + isOrganisationAdmin(useCurrentOrganisation()) diff --git a/frontend/common/hooks/useCurrentUser.ts b/frontend/common/hooks/useCurrentUser.ts new file mode 100644 index 000000000000..3f0eddea8499 --- /dev/null +++ b/frontend/common/hooks/useCurrentUser.ts @@ -0,0 +1,11 @@ +import AccountStore from 'common/stores/account-store' +import { AccountModel } from 'common/types/responses' +import useAccountStoreUpdates from './useAccountStoreUpdates' + +export const getCurrentUser = (): AccountModel | undefined => + AccountStore.getUser() ?? undefined + +export const useCurrentUser = (): AccountModel | undefined => { + useAccountStoreUpdates() + return getCurrentUser() +} diff --git a/frontend/common/hooks/useHasGithubIntegration.ts b/frontend/common/hooks/useHasGithubIntegration.ts index c75cfdafb631..2cc774a331cf 100644 --- a/frontend/common/hooks/useHasGithubIntegration.ts +++ b/frontend/common/hooks/useHasGithubIntegration.ts @@ -1,11 +1,11 @@ -import AccountStore from 'common/stores/account-store' +import { skipToken } from '@reduxjs/toolkit/query' +import { useCurrentOrganisation } from './useCurrentOrganisation' import { useGetGithubIntegrationQuery } from 'common/services/useGithubIntegration' export function useHasGithubIntegration() { - const organisationId = AccountStore.getOrganisation()?.id - const { data } = useGetGithubIntegrationQuery( - { organisation_id: organisationId }, - { skip: !organisationId }, + const organisationId = useCurrentOrganisation()?.id + const { currentData: data } = useGetGithubIntegrationQuery( + organisationId ? { organisation_id: organisationId } : skipToken, ) return { diff --git a/frontend/common/hooks/withCurrentOrganisation.tsx b/frontend/common/hooks/withCurrentOrganisation.tsx new file mode 100644 index 000000000000..a3d0f5af83a8 --- /dev/null +++ b/frontend/common/hooks/withCurrentOrganisation.tsx @@ -0,0 +1,20 @@ +import React, { ComponentType } from 'react' +import { Organisation } from 'common/types/responses' +import { useCurrentOrganisation } from './useCurrentOrganisation' + +export type CurrentOrganisationProps = { + organisation: Organisation | undefined +} + +// For class components, which cannot call the hook. +const withCurrentOrganisation =

( + Component: ComponentType

, +) => { + const WithCurrentOrganisation = (props: P) => { + const organisation = useCurrentOrganisation() + return + } + return WithCurrentOrganisation +} + +export default withCurrentOrganisation diff --git a/frontend/common/loadChat.ts b/frontend/common/loadChat.ts index cc9a9ed972a5..01af07c94548 100644 --- a/frontend/common/loadChat.ts +++ b/frontend/common/loadChat.ts @@ -17,11 +17,11 @@ declare global { } } -import AccountStore from './stores/account-store' +import { getCurrentUser } from './hooks/useCurrentUser' import { getStore } from './store' import { getHubspotChatToken } from './services/useHubspotChatToken' import Utils from './utils/utils' -import { AccountModel, HubspotChatToken } from './types/responses' +import { HubspotChatToken } from './types/responses' const SUPPORT_EMAIL_URL = 'mailto:support@flagsmith.com' @@ -79,7 +79,7 @@ function setHubSpotIdentity(identity?: HubspotChatToken) { // Without a token the widget still loads, just anonymously. A 404 means the // API has no HubSpot token configured (e.g. self-hosted), so it isn't logged. async function fetchHubSpotIdentity(): Promise { - const user = AccountStore.getUser() as AccountModel | undefined + const user = getCurrentUser() if (!user?.id) return try { const { data, error } = await getHubspotChatToken( diff --git a/frontend/common/providers/OrganisationProvider.tsx b/frontend/common/providers/OrganisationProvider.tsx index 4c315b170ec3..f2698b8c7c38 100644 --- a/frontend/common/providers/OrganisationProvider.tsx +++ b/frontend/common/providers/OrganisationProvider.tsx @@ -1,6 +1,7 @@ import { FC, ReactNode, useEffect, useState } from 'react' import OrganisationStore from 'common/stores/organisation-store' import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import AppActions from 'common/dispatcher/app-actions' import { Invite, @@ -39,6 +40,7 @@ const OrganisationProvider: FC = ({ onRemoveProject, onSave, }) => { + const organisation = useCurrentOrganisation() const [_, setUpdate] = useState(Date.now()) const { data: groups } = useGetGroupsQuery( { orgId: id!, page: 1 }, @@ -84,7 +86,7 @@ const OrganisationProvider: FC = ({ invites: OrganisationStore.getInvites(), isLoading: OrganisationStore.isLoading, isSaving: OrganisationStore.isSaving, - name: AccountStore.getOrganisation()?.name || '', + name: organisation?.name || '', project: OrganisationStore.getProject(id), projects: OrganisationStore.getProjects(), subscriptionMeta: OrganisationStore.getSubscriptionMeta(), diff --git a/frontend/common/providers/Permission.tsx b/frontend/common/providers/Permission.tsx index e47323c8a710..46bd2ba4c273 100644 --- a/frontend/common/providers/Permission.tsx +++ b/frontend/common/providers/Permission.tsx @@ -1,6 +1,6 @@ import React, { FC, ReactNode, useMemo } from 'react' import { useGetPermissionQuery } from 'common/services/usePermission' -import AccountStore from 'common/stores/account-store' +import { useIsOrganisationAdmin } from 'common/hooks/useCurrentOrganisation' import { cloneDeep, intersection } from 'lodash' import Utils from 'common/utils/utils' import Constants from 'common/constants' @@ -78,6 +78,7 @@ export const useHasPermission = ({ permission, tags, }: UseHasPermissionParams) => { + const isAdmin = useIsOrganisationAdmin() const { data: permissionsData, isLoading, @@ -103,7 +104,7 @@ export const useHasPermission = ({ return { isLoading, isSuccess, - permission: !!hasPermission || !!AccountStore.isAdmin(), + permission: hasPermission || isAdmin, } } @@ -178,8 +179,6 @@ const Permission: FC = ({ tags, }) - const finalPermission = hasPermission || AccountStore.isAdmin() - const getPermissionDescription = (): string => { switch (level) { case 'environment': @@ -200,26 +199,26 @@ const Permission: FC = ({ if (typeof children === 'function') { const renderedChildren = children({ isLoading, - permission: finalPermission, + permission: hasPermission, }) - if (finalPermission || !showTooltip) { + if (hasPermission || !showTooltip) { return <>{renderedChildren || null} } return Utils.renderWithPermission( - finalPermission, + hasPermission, tooltipMessage, renderedChildren, ) } - if (finalPermission) { + if (hasPermission) { return <>{children} } if (showTooltip) { - return Utils.renderWithPermission(finalPermission, tooltipMessage, children) + return Utils.renderWithPermission(hasPermission, tooltipMessage, children) } return <>{fallback || null} diff --git a/frontend/common/stores/organisation-store.js b/frontend/common/stores/organisation-store.js index 9a1b7499ac92..059e9caecc88 100644 --- a/frontend/common/stores/organisation-store.js +++ b/frontend/common/stores/organisation-store.js @@ -1,8 +1,10 @@ +import { getCurrentUser } from 'common/hooks/useCurrentUser' import Constants from 'common/constants' import { projectService } from 'common/services/useProject' import { getStore } from 'common/store' import sortBy from 'lodash/sortBy' import { getSubscriptionMetadata } from 'common/services/useSubscriptionMetadata' +import { getCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import Dispatcher from 'common/dispatcher/dispatcher' import BaseStore from './base/_store' @@ -145,7 +147,7 @@ const controller = { invites: invites && invites.results, subscriptionMeta, users: sortBy(users, (user) => { - const isYou = user.id === AccountStore.getUser().id + const isYou = user.id === getCurrentUser()?.id if (isYou) { return `` } @@ -202,7 +204,8 @@ const controller = { } }, invalidateInviteLink: (link) => { - const id = AccountStore.getOrganisation().id + const id = getCurrentOrganisation()?.id + if (!id) return const role = link.role data .delete(`${Project.api}organisations/${id}/invite-links/${link.id}/`) diff --git a/frontend/common/utils/utils.tsx b/frontend/common/utils/utils.tsx index eb192472fe0e..88f4a3133e1f 100644 --- a/frontend/common/utils/utils.tsx +++ b/frontend/common/utils/utils.tsx @@ -1,4 +1,5 @@ import AccountStore from 'common/stores/account-store' +import { getCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import ProjectStore from 'common/stores/project-store' import Project from 'common/project' import { @@ -199,7 +200,7 @@ const Utils = Object.assign({}, BaseUtils, { return contentTypes?.find((c: ContentType) => c[model] === type) || null }, getContrastColour, - getCreateProjectPermission(organisation: Organisation) { + getCreateProjectPermission(organisation?: Organisation) { if (organisation?.restrict_project_create_to_admin) { return OrganisationPermission.ADMIN } @@ -397,7 +398,7 @@ const Utils = Object.assign({}, BaseUtils, { }, getOrganisationHomePage(id?: string) { - const orgId = id || AccountStore.getOrganisation()?.id + const orgId = id || getCurrentOrganisation()?.id if (!orgId) { return `/organisations` } diff --git a/frontend/web/components/App.js b/frontend/web/components/App.js index 30b0047e62e5..08b1191f5729 100644 --- a/frontend/web/components/App.js +++ b/frontend/web/components/App.js @@ -22,6 +22,9 @@ import { getStore } from 'common/store' import ConfigProvider from 'common/providers/ConfigProvider' import Constants from 'common/constants' import AccountStore from 'common/stores/account-store' +import { getCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' +import withCurrentOrganisation from 'common/hooks/withCurrentOrganisation' +import { getCurrentUser } from 'common/hooks/useCurrentUser' import OrganisationLimit from './OrganisationLimit' import OrganisationStore from 'common/stores/organisation-store' import ScrollToTop from './ScrollToTop' @@ -155,7 +158,7 @@ const App = class extends Component { // A signup with a consent request waiting keeps its redirect cookie // through the branch below: onboarding provisions the organisation the // client needs, then answers the request itself. - if (!AccountStore.getOrganisation() && !invite) { + if (!getCurrentOrganisation() && !invite) { // New users with no organisation go through the single-page onboarding // flow when it's enabled - it creates the organisation itself, so it // replaces the legacy /create page. Everyone else still gets /create. @@ -165,14 +168,11 @@ const App = class extends Component { // Capped at 2s: a degraded flags API falls back to the legacy page // instead of blocking the redirect. const storedVariant = getStoredOnboardingVariant() - const deciding = - !storedVariant && !!AccountStore.getUser()?.isGettingStarted + const deciding = !storedVariant && !!getCurrentUser()?.isGettingStarted let timedOut = false Promise.race([ deciding - ? decideOnboardingEntry(AccountStore.getUser()?.email).catch( - () => null, - ) + ? decideOnboardingEntry(getCurrentUser()?.email).catch(() => null) : Promise.resolve(null), new Promise((resolve) => setTimeout(() => { @@ -228,7 +228,7 @@ const App = class extends Component { } if (res) { const lastEnv = JSON.parse(res) - const lastOrg = find(AccountStore.getUser().organisations, { + const lastOrg = find(getCurrentUser().organisations, { id: lastEnv.orgId, }) if (!lastOrg) { @@ -236,7 +236,7 @@ const App = class extends Component { return } - const org = AccountStore.getOrganisation() + const org = getCurrentOrganisation() if ( !org || (org.id !== lastOrg.id && this.getEnvironmentId(this.props)) @@ -251,7 +251,7 @@ const App = class extends Component { return } - if (AccountStore.getUser()?.isGettingStarted) { + if (getCurrentUser()?.isGettingStarted) { this.props.history.replace('/getting-started') } else { this.props.history.replace(Utils.getOrganisationHomePage()) @@ -299,7 +299,7 @@ const App = class extends Component { const environmentId = this.getEnvironmentId(this.props) if ( - AccountStore.getOrganisation()?.block_access_to_admin && + this.props.organisation?.block_access_to_admin && !isAllowedWhileBlocked(pathname) ) { return @@ -385,17 +385,16 @@ const App = class extends Component { {user && ( <> {!hasOwnQuotaBanner && ( )} @@ -436,6 +435,7 @@ App.propTypes = { history: RequiredObject, location: RequiredObject, match: RequiredObject, + organisation: OptionalObject, } -export default withRouter(ConfigProvider(App)) +export default withRouter(ConfigProvider(withCurrentOrganisation(App))) diff --git a/frontend/web/components/AuditLog.tsx b/frontend/web/components/AuditLog.tsx index df07986f3583..f54324200e74 100644 --- a/frontend/web/components/AuditLog.tsx +++ b/frontend/web/components/AuditLog.tsx @@ -1,3 +1,4 @@ +import { skipToken } from '@reduxjs/toolkit/query' import React, { FC, ReactNode, useEffect, useRef, useState } from 'react' import Utils from 'common/utils/utils' import { AuditLogItem } from 'common/types/responses' @@ -13,7 +14,7 @@ import JSONReference from './JSONReference' import moment from 'moment' import PlanBasedBanner from './PlanBasedAccess' import { useGetSubscriptionMetadataQuery } from 'common/services/useSubscriptionMetadata' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import { isVersionOverLimit } from 'common/services/useFeatureVersion' import Tooltip from './Tooltip' @@ -29,13 +30,14 @@ type AuditLogType = { const widths = [210, 310, 150] const AuditLog: FC = (props) => { + const organisation = useCurrentOrganisation() const [page, setPage] = useState(Utils.fromParam().page ?? 1) const { search, searchInput, setSearchInput } = useDebouncedSearch( Utils.fromParam().search ?? '', ) - const { data: subscriptionMeta } = useGetSubscriptionMetadataQuery({ - id: AccountStore.getOrganisation()?.id, - }) + const { data: subscriptionMeta } = useGetSubscriptionMetadataQuery( + organisation ? { id: organisation.id } : skipToken, + ) // Same list as the environment filter, so the colours match. const { data: projectEnvironments } = useGetEnvironmentsQuery({ projectId: Number(props.projectId), diff --git a/frontend/web/components/BlockedOrgInfo.tsx b/frontend/web/components/BlockedOrgInfo.tsx index 2a7623cebcab..6931804ca07d 100644 --- a/frontend/web/components/BlockedOrgInfo.tsx +++ b/frontend/web/components/BlockedOrgInfo.tsx @@ -1,16 +1,16 @@ import React from 'react' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import AppActions from 'common/dispatcher/app-actions' export default function BlockedOrgInfo() { + const organisation = useCurrentOrganisation() + if (!organisation) return null return (

-
Organisation name: {AccountStore.getOrganisation().name}
-
Organisation ID: {AccountStore.getOrganisation().id}
+
Organisation name: {organisation.name}
+
Organisation ID: {organisation.id}
- - See your usage - + See your usage
Switch to a different organisation diff --git a/frontend/web/components/BreadcrumbSeparator.tsx b/frontend/web/components/BreadcrumbSeparator.tsx index d87f972d3b41..145065ab29c4 100644 --- a/frontend/web/components/BreadcrumbSeparator.tsx +++ b/frontend/web/components/BreadcrumbSeparator.tsx @@ -16,7 +16,7 @@ import { PagedResponse, Project, } from 'common/types/responses' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import { useGetProjectsQuery } from 'common/services/useProject' import { useGetOrganisationsQuery } from 'common/services/useOrganisation' import { useHistory } from 'react-router-dom' @@ -159,12 +159,13 @@ const BreadcrumbSeparator: FC = ({ const { data: organisationsData } = useGetOrganisationsQuery({}) const organisations = organisationsData?.results || [] + const organisation = useCurrentOrganisation() const [activeOrganisation, setActiveOrganisation] = useState( - `${AccountStore.getOrganisation()?.id}`, - ) - const [hoveredOrganisation, setHoveredOrganisation] = useState( - AccountStore.getOrganisation(), + `${organisation?.id}`, ) + const [hoveredOrganisation, setHoveredOrganisation] = useState< + Organisation | undefined + >(organisation) const [hoveredProject, setHoveredProject] = useState( focus === 'organisation' ? undefined : projectId, ) @@ -172,21 +173,12 @@ const BreadcrumbSeparator: FC = ({ const history = useHistory() useEffect(() => { - const onChangeAccountStore = () => { - if ( - AccountStore.getOrganisation()?.id !== activeOrganisation && - !!AccountStore.getOrganisation()?.id - ) { - setActiveOrganisation(AccountStore.getOrganisation()?.id) - setHoveredOrganisation(AccountStore.getOrganisation()) - } - } - AccountStore.on('change', onChangeAccountStore) - return () => { - AccountStore.off('change', onChangeAccountStore) + if (organisation && `${organisation.id}` !== activeOrganisation) { + setActiveOrganisation(`${organisation.id}`) + setHoveredOrganisation(organisation) } //eslint-disable-next-line - }, []) + }, [organisation?.id]) useEffect(() => { if (!open) { @@ -323,7 +315,7 @@ const BreadcrumbSeparator: FC = ({ setOpen(false) setProjectSearch('') setOrganisationSearch('') - setHoveredOrganisation(AccountStore.getOrganisation()) + setHoveredOrganisation(organisation) }} containerClassName={'p-0'} className={ @@ -418,14 +410,12 @@ const BreadcrumbSeparator: FC = ({ footer={Utils.renderWithPermission( canCreateProject, Constants.organisationPermissions( - Utils.getCreateProjectPermission( - AccountStore.getOrganisation(), - ), + Utils.getCreateProjectPermission(organisation), ),
@@ -1243,7 +1245,7 @@ const EditPermissions: FC = (props) => {
editGroupPermissions(group)} /> diff --git a/frontend/web/components/FeatureHistory.tsx b/frontend/web/components/FeatureHistory.tsx index d174bab8b70d..6f5cb1998ce8 100644 --- a/frontend/web/components/FeatureHistory.tsx +++ b/frontend/web/components/FeatureHistory.tsx @@ -1,8 +1,9 @@ +import { skipToken } from '@reduxjs/toolkit/query' import React, { FC, useState } from 'react' import ConfigProvider from 'common/providers/ConfigProvider' import { useGetFeatureVersionsQuery } from 'common/services/useFeatureVersion' import { useGetUsersQuery } from 'common/services/useUser' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import { FeatureVersion as TFeatureVersion } from 'common/types/responses' import Button from './base/forms/Button' import FeatureVersion from './FeatureVersion' @@ -29,16 +30,17 @@ const FeatureHistory: FC = ({ feature, projectId, }) => { + const organisation = useCurrentOrganisation() const [open, setOpen] = useState(false) - const { data: subscriptionMeta } = useGetSubscriptionMetadataQuery({ - id: AccountStore.getOrganisation()?.id, - }) + const { data: subscriptionMeta } = useGetSubscriptionMetadataQuery( + organisation ? { id: organisation.id } : skipToken, + ) const versionLimitDays = subscriptionMeta?.feature_history_visibility_days // @ts-ignore - const { data: users } = useGetUsersQuery({ - organisationId: AccountStore.getOrganisation().id, - }) + const { data: users } = useGetUsersQuery( + organisation ? { organisationId: organisation.id } : skipToken, + ) const [page, setPage] = useState(1) const { data, isLoading } = useGetFeatureVersionsQuery( { diff --git a/frontend/web/components/FlagOwnerGroups.tsx b/frontend/web/components/FlagOwnerGroups.tsx index a48efb57b5a7..642166fdb700 100644 --- a/frontend/web/components/FlagOwnerGroups.tsx +++ b/frontend/web/components/FlagOwnerGroups.tsx @@ -1,7 +1,7 @@ import React, { FC, useState } from 'react' import ConnectedGroupSelect from './ConnectedGroupSelect' import SettingsButton from './SettingsButton' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' type FlagOwnerGroupsProps = { selectedIds: number[] @@ -14,6 +14,7 @@ const FlagOwnerGroups: FC = ({ onRemove, selectedIds, }) => { + const organisation = useCurrentOrganisation() const [showGroups, setShowGroups] = useState(false) return ( @@ -21,16 +22,18 @@ const FlagOwnerGroups: FC = ({ onAdd(id)} - onRemove={(id: number) => onRemove(id)} - onToggle={() => setShowGroups(!showGroups)} - /> + organisation && ( + onAdd(id)} + onRemove={(id: number) => onRemove(id)} + onToggle={() => setShowGroups(!showGroups)} + /> + ) } onClick={() => setShowGroups(true)} > diff --git a/frontend/web/components/FlagOwners.tsx b/frontend/web/components/FlagOwners.tsx index 9fa5840ddfda..591cb5c9b361 100644 --- a/frontend/web/components/FlagOwners.tsx +++ b/frontend/web/components/FlagOwners.tsx @@ -1,10 +1,11 @@ +import { skipToken } from '@reduxjs/toolkit/query' import React, { FC, useState } from 'react' import UserSelect from './UserSelect' import { IonIcon } from '@ionic/react' import { close } from 'ionicons/icons' import SettingsButton from './SettingsButton' import { useGetUsersQuery } from 'common/services/useUser' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import getUserDisplayName from 'common/utils/getUserDisplayName' type FlagOwnersProps = { @@ -16,10 +17,9 @@ type FlagOwnersProps = { const FlagOwners: FC = ({ onAdd, onRemove, selectedIds }) => { const [showUsers, setShowUsers] = useState(false) - const organisationId = AccountStore.getOrganisation()?.id - const { data: users } = useGetUsersQuery( - { organisationId }, - { skip: !organisationId }, + const organisationId = useCurrentOrganisation()?.id + const { currentData: users } = useGetUsersQuery( + organisationId ? { organisationId } : skipToken, ) const ownerUsers = users diff --git a/frontend/web/components/GithubStar.tsx b/frontend/web/components/GithubStar.tsx index ba82c4000108..c95fe825f53f 100644 --- a/frontend/web/components/GithubStar.tsx +++ b/frontend/web/components/GithubStar.tsx @@ -1,12 +1,12 @@ import React, { FC, useEffect, useState } from 'react' import Utils, { planNames } from 'common/utils/utils' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import { GithubIcon } from './icons/GithubIcon' type GithubStarType = {} const GithubStar: FC = ({}) => { - const organisation = AccountStore.getOrganisation() + const organisation = useCurrentOrganisation() const plan = organisation?.subscription?.plan || '' const planName = Utils.getPlanName(plan) const [stars, setStars] = useState(null) diff --git a/frontend/web/components/IntegrationList.tsx b/frontend/web/components/IntegrationList.tsx index da603c557cc0..9c227af83a7a 100644 --- a/frontend/web/components/IntegrationList.tsx +++ b/frontend/web/components/IntegrationList.tsx @@ -4,7 +4,7 @@ import ProjectStore from 'common/stores/project-store' import ConfigProvider from 'common/providers/ConfigProvider' import { getStore } from 'common/store' import { getGithubIntegration } from 'common/services/useGithubIntegration' -import AccountStore from 'common/stores/account-store' +import { useCurrentOrganisation } from 'common/hooks/useCurrentOrganisation' import CreateEditIntegration from './modals/CreateEditIntegrationModal' import Project from 'common/project' import { @@ -66,6 +66,7 @@ type IntegrationProps = { } const Integration: FC = (props) => { + const organisation = useCurrentOrganisation() const history = useHistory() const [reFetchgithubId, setReFetchgithubId] = useState('') const [windowInstallationId, setWindowInstallationId] = useState('') @@ -116,10 +117,11 @@ const Integration: FC = (props) => { setWindowInstallationId(event.data.installationId) localStorage.removeItem('githubIntegrationSetupFromFlagsmith') childWindow?.close() + if (!organisation) return getGithubIntegration( getStore(), { - organisation_id: AccountStore.getOrganisation().id, + organisation_id: organisation.id, }, { forceRefetch: true }, ).then((res) => { @@ -164,9 +166,7 @@ const Integration: FC = (props) => { !isOrgPage && !!isOrganisationLevel && !!isProjectLevel // Project-only integration surfaced on the org page (read-only, informational) const isProjectOnlyOnOrgPage = isOrgPage && !isOrganisationLevel - const orgIntegrationsHref = `/organisation/${ - AccountStore.getOrganisation()?.id - }/integrations` + const orgIntegrationsHref = `/organisation/${organisation?.id}/integrations` const isConnectedAtOrg = !!props.githubMeta.hasIntegrationWithGithub const hasActiveConfig = !!activeIntegrations?.length const isEditing = hasActiveConfig && !perEnvironment @@ -371,6 +371,7 @@ interface IntegrationListProps { isOrgAdmin?: boolean } const IntegrationList: FC = (props) => { + const organisation = useCurrentOrganisation() const [githubId, setGithubId] = useState(0) const [hasIntegrationWithGithub, setHasIntegrationWithGithub] = useState(false) @@ -391,10 +392,11 @@ const IntegrationList: FC = (props) => { }, []) const fetchGithubIntegration = () => { + if (!organisation) return getGithubIntegration( getStore(), { - organisation_id: AccountStore.getOrganisation().id, + organisation_id: organisation.id, }, { forceRefetch: true }, ).then((res) => { diff --git a/frontend/web/components/ManagementAPIKeys.js b/frontend/web/components/ManagementAPIKeys.js index 46de59ba5847..0f6131a21a48 100644 --- a/frontend/web/components/ManagementAPIKeys.js +++ b/frontend/web/components/ManagementAPIKeys.js @@ -83,7 +83,7 @@ export class CreateAPIKey extends PureComponent { this.state.roles.map((role) => createRoleMasterApiKey(getStore(), { body: { master_api_key: res.id }, - org_id: AccountStore.getOrganisation().id, + org_id: this.props.organisationId, role_id: role.id, }).then(() => { toast('Role API Key was Created') @@ -103,7 +103,7 @@ export class CreateAPIKey extends PureComponent { name: this.state.name, revoked: false, }, - org_id: AccountStore.getOrganisation().id, + org_id: this.props.organisationId, prefix: prefix, }).then(() => { this.props.onSuccess() @@ -112,7 +112,7 @@ export class CreateAPIKey extends PureComponent { getApiKeyByPrefix = (prefix) => { getMasterAPIKeyWithMasterAPIKeyRoles(getStore(), { - org_id: AccountStore.getOrganisation().id, + org_id: this.props.organisationId, prefix: prefix, }).then((res) => { this.setState({ @@ -121,7 +121,7 @@ export class CreateAPIKey extends PureComponent { name: res.data.name, }) getRolesMasterAPIKeyWithMasterAPIKeyRoles(getStore(), { - org_id: AccountStore.getOrganisation().id, + org_id: this.props.organisationId, prefix: prefix, }).then((rolesData) => { this.setState({ @@ -135,7 +135,7 @@ export class CreateAPIKey extends PureComponent { const roleSelected = this.state.roles.find((item) => item.id === roleId) if (isEdit) { deleteMasterAPIKeyWithMasterAPIKeyRoles(getStore(), { - org_id: AccountStore.getOrganisation().id, + org_id: this.props.organisationId, prefix: this.props.prefix, role_id: roleSelected.id, }).then(() => { @@ -151,7 +151,7 @@ export class CreateAPIKey extends PureComponent { if (isEdit) { createRoleMasterApiKey(getStore(), { body: { master_api_key: this.props.masterAPIKey }, - org_id: AccountStore.getOrganisation().id, + org_id: this.props.organisationId, role_id: role.id, }).then((res) => { toast('Role API Key was added') @@ -250,7 +250,7 @@ export class CreateAPIKey extends PureComponent {
v.id)} onAdd={(role) => this.addRole(role, this.props.isEdit) @@ -386,6 +386,7 @@ export default class ManagementAPIKeys extends PureComponent { `${name} API Key`, { diff --git a/frontend/web/components/MyGroupsSelect.tsx b/frontend/web/components/MyGroupsSelect.tsx index edb35a47d65f..d84bb3603143 100644 --- a/frontend/web/components/MyGroupsSelect.tsx +++ b/frontend/web/components/MyGroupsSelect.tsx @@ -3,7 +3,7 @@ import { useGetMyGroupsQuery } from 'common/services/useMyGroup' import GroupSelect, { GroupSelectType } from './GroupSelect' type MyGroupsSelectType = Omit & { - orgId: string | number + orgId: string | number | undefined } const MyGroupsSelect: FC = ({ orgId, ...props }) => { diff --git a/frontend/web/components/MyRoleSelect.tsx b/frontend/web/components/MyRoleSelect.tsx index 04a5334eb9ed..ec1c6cacfcf8 100644 --- a/frontend/web/components/MyRoleSelect.tsx +++ b/frontend/web/components/MyRoleSelect.tsx @@ -4,7 +4,7 @@ import RolesSelect, { RoleSelectType } from './RolesSelect' import { PermissionLevel } from 'common/types/requests' type MyRoleSelectType = Omit & { - orgId: string | number + orgId: string | number | undefined level?: PermissionLevel } diff --git a/frontend/web/components/ProjectManageWidget.tsx b/frontend/web/components/ProjectManageWidget.tsx index 62821e48f747..44f3bd4b2689 100644 --- a/frontend/web/components/ProjectManageWidget.tsx +++ b/frontend/web/components/ProjectManageWidget.tsx @@ -4,7 +4,7 @@ import { useHistory, useLocation } from 'react-router-dom' import Utils from 'common/utils/utils' import Constants from 'common/constants' -import AccountStore from 'common/stores/account-store' +import { useIsOrganisationAdmin } from 'common/hooks/useCurrentOrganisation' import { useHasPermission } from 'common/providers/Permission' import ConfigProvider from 'common/providers/ConfigProvider' import { useGetOrganisationsQuery } from 'common/services/useOrganisation' @@ -24,7 +24,7 @@ type SegmentsPageType = { const ProjectManageWidget: FC = ({ organisationId }) => { const history = useHistory() const location = useLocation() - const isAdmin = AccountStore.isAdmin() + const isAdmin = useIsOrganisationAdmin() const create = Utils.fromParam()?.create const { data: organisations } = useGetOrganisationsQuery({}) @@ -124,7 +124,7 @@ const ProjectManageWidget: FC = ({ organisationId }) => { canCreateProject, Constants.organisationPermissions( Utils.getCreateProjectPermission( - AccountStore.getOrganisation(), + organisation, ), ),