Skip to content
41 changes: 29 additions & 12 deletions frontend/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -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().'
Expand Down Expand Up @@ -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/**'],
Expand Down Expand Up @@ -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',
Expand Down
89 changes: 89 additions & 0 deletions frontend/common/hooks/__tests__/currentAccount.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import AccountStore from 'common/stores/account-store'

Check warning on line 1 in frontend/common/hooks/__tests__/currentAccount.test.ts

View workflow job for this annotation

GitHub Actions / Lint changed files

'common/stores/account-store' import is restricted from being used by a pattern. Read the organisation and user with useCurrentOrganisation, useIsOrganisationAdmin or useCurrentUser (common/hooks)
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)
})
})
32 changes: 32 additions & 0 deletions frontend/common/hooks/useAccountStoreUpdates.ts
Original file line number Diff line number Diff line change
@@ -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
17 changes: 17 additions & 0 deletions frontend/common/hooks/useCurrentOrganisation.ts
Original file line number Diff line number Diff line change
@@ -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())
11 changes: 11 additions & 0 deletions frontend/common/hooks/useCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -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()
}
10 changes: 5 additions & 5 deletions frontend/common/hooks/useHasGithubIntegration.ts
Original file line number Diff line number Diff line change
@@ -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
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const { currentData: data } = useGetGithubIntegrationQuery(
organisationId ? { organisation_id: organisationId } : skipToken,
)

return {
Expand Down
20 changes: 20 additions & 0 deletions frontend/common/hooks/withCurrentOrganisation.tsx
Original file line number Diff line number Diff line change
@@ -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 = <P extends object>(
Component: ComponentType<P & CurrentOrganisationProps>,
) => {
const WithCurrentOrganisation = (props: P) => {
const organisation = useCurrentOrganisation()
return <Component {...props} organisation={organisation} />
}
return WithCurrentOrganisation
}

export default withCurrentOrganisation
6 changes: 3 additions & 3 deletions frontend/common/loadChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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<HubspotChatToken | undefined> {
const user = AccountStore.getUser() as AccountModel | undefined
const user = getCurrentUser()
if (!user?.id) return
try {
const { data, error } = await getHubspotChatToken(
Expand Down
4 changes: 3 additions & 1 deletion frontend/common/providers/OrganisationProvider.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -39,6 +40,7 @@ const OrganisationProvider: FC<OrganisationProviderType> = ({
onRemoveProject,
onSave,
}) => {
const organisation = useCurrentOrganisation()
const [_, setUpdate] = useState(Date.now())
const { data: groups } = useGetGroupsQuery(
{ orgId: id!, page: 1 },
Expand Down Expand Up @@ -84,7 +86,7 @@ const OrganisationProvider: FC<OrganisationProviderType> = ({
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(),
Expand Down
17 changes: 8 additions & 9 deletions frontend/common/providers/Permission.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -78,6 +78,7 @@ export const useHasPermission = ({
permission,
tags,
}: UseHasPermissionParams) => {
const isAdmin = useIsOrganisationAdmin()
const {
data: permissionsData,
isLoading,
Expand All @@ -103,7 +104,7 @@ export const useHasPermission = ({
return {
isLoading,
isSuccess,
permission: !!hasPermission || !!AccountStore.isAdmin(),
permission: hasPermission || isAdmin,
}
}

Expand Down Expand Up @@ -178,8 +179,6 @@ const Permission: FC<PermissionType> = ({
tags,
})

const finalPermission = hasPermission || AccountStore.isAdmin()

const getPermissionDescription = (): string => {
switch (level) {
case 'environment':
Expand All @@ -200,26 +199,26 @@ const Permission: FC<PermissionType> = ({
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}</>
Expand Down
7 changes: 5 additions & 2 deletions frontend/common/stores/organisation-store.js
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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 ``
}
Expand Down Expand Up @@ -202,7 +204,8 @@ const controller = {
}
},
invalidateInviteLink: (link) => {
const id = AccountStore.getOrganisation().id
const id = getCurrentOrganisation()?.id
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
if (!id) return
const role = link.role
data
.delete(`${Project.api}organisations/${id}/invite-links/${link.id}/`)
Expand Down
Loading
Loading