diff --git a/frontend/common/hooks/__tests__/useFeatureStates.test.ts b/frontend/common/hooks/__tests__/useFeatureStates.test.ts new file mode 100644 index 000000000000..5667e4aa1379 --- /dev/null +++ b/frontend/common/hooks/__tests__/useFeatureStates.test.ts @@ -0,0 +1,83 @@ +jest.mock('common/services/useProjectFlag', () => ({ + useGetProjectFlagsQuery: jest.fn(), +})) + +jest.mock('common/hooks/useProjectEnvironments', () => ({ + useProjectEnvironments: jest.fn(), +})) + +import { useFeatureStates } from 'common/hooks/useFeatureStates' +import { useGetProjectFlagsQuery } from 'common/services/useProjectFlag' +import { useProjectEnvironments } from 'common/hooks/useProjectEnvironments' +import { ProjectFlag } from 'common/types/responses' + +const mockUseGetProjectFlagsQuery = + useGetProjectFlagsQuery as jest.MockedFunction +const mockUseProjectEnvironments = + useProjectEnvironments as jest.MockedFunction + +const enabledFeature = { + environment_feature_state: { enabled: true }, + id: 1, +} as unknown as ProjectFlag + +describe('useFeatureStates', () => { + beforeEach(() => { + mockUseProjectEnvironments.mockReturnValue({ + error: undefined, + getEnvironmentIdFromKey: () => 2, + isLoading: false, + } as any) + }) + + it("ignores another environment's list while this one's loads", () => { + // Given + mockUseGetProjectFlagsQuery.mockReturnValue({ + currentData: undefined, + data: { results: [enabledFeature] }, + isError: false, + isLoading: false, + } as any) + + // When + const states = useFeatureStates({ environmentId: 'key', projectId: 1 }) + + // Then + expect(states.isLoading).toBe(true) + expect(states.features).toEqual([]) + }) + + it('requests project flags for the resolved environment', () => { + // Given + mockUseGetProjectFlagsQuery.mockReturnValue({ + currentData: { results: [] }, + isError: false, + isLoading: false, + } as any) + + // When + useFeatureStates({ environmentId: 'key', projectId: 1 }) + + // Then + expect(mockUseGetProjectFlagsQuery).toHaveBeenCalledWith( + { environment: 2, project: '1' }, + { skip: false }, + ) + }) + + it("reads this environment's list once loaded", () => { + // Given + mockUseGetProjectFlagsQuery.mockReturnValue({ + currentData: { results: [enabledFeature] }, + isError: false, + isLoading: false, + } as any) + + // When + const states = useFeatureStates({ environmentId: 'key', projectId: 1 }) + + // Then + expect(states.isLoading).toBe(false) + expect(states.isEnabled(1)).toBe(true) + }) +}) diff --git a/frontend/common/hooks/useFeatureStates.ts b/frontend/common/hooks/useFeatureStates.ts index 5d1a6a593775..d7ce97378827 100644 --- a/frontend/common/hooks/useFeatureStates.ts +++ b/frontend/common/hooks/useFeatureStates.ts @@ -1,4 +1,4 @@ -import { useGetFeatureListQuery } from 'common/services/useProjectFlag' +import { useGetProjectFlagsQuery } from 'common/services/useProjectFlag' import { useProjectEnvironments } from './useProjectEnvironments' import { ProjectFlag } from 'common/types/responses' @@ -12,8 +12,9 @@ type UseFeatureStatesArgs = { skip?: boolean } -// Whether each of a project's features is on in one environment, from the -// feature list. getFeatureList takes the numeric environment id, not the key. +// Whether each of a project's features is on in one environment, from every +// page of the feature list, as a feature missing from it reads as off. +// getProjectFlags takes the numeric environment id, not the key. export const useFeatureStates = ({ environmentId, projectId, @@ -25,22 +26,19 @@ export const useFeatureStates = ({ isLoading: isLoadingEnvironments, } = useProjectEnvironments(projectId) const numericEnvId = getEnvironmentIdFromKey(environmentId) + const shouldSkip = skip || !numericEnvId + // currentData, not data, which keeps another environment's list while this + // one's loads. const { - data, + currentData, isError: isFeatureListError, isLoading: isLoadingFeatureList, - } = useGetFeatureListQuery( - { - environmentId: String(numericEnvId ?? ''), - page: 1, - // One page has to cover every feature, or one outside it reads as off. - page_size: 999, - projectId, - }, - { skip: skip || !numericEnvId }, + } = useGetProjectFlagsQuery( + { environment: numericEnvId, project: String(projectId) }, + { skip: shouldSkip }, ) - const features = data?.results ?? NO_FEATURES + const features = currentData?.results ?? NO_FEATURES return { features, isEnabled: (featureId: number) => @@ -52,6 +50,9 @@ export const useFeatureStates = ({ // The lookup finished without finding the environment, so the feature // list will never run and nothing is coming. (!isLoadingEnvironments && !numericEnvId), - isLoading: isLoadingEnvironments || isLoadingFeatureList, + isLoading: + isLoadingEnvironments || + isLoadingFeatureList || + (!shouldSkip && !currentData && !isFeatureListError), } } diff --git a/frontend/common/services/useProjectFlag.ts b/frontend/common/services/useProjectFlag.ts index b1b7e41ef959..a934236bc570 100644 --- a/frontend/common/services/useProjectFlag.ts +++ b/frontend/common/services/useProjectFlag.ts @@ -149,6 +149,12 @@ export const projectFlagService = service .join('-'), type: 'ProjectFlag', }, + // Refreshed with the feature list, as it carries the same states. + { + id: `${req?.project}-${req?.environment}`, + type: 'FeatureList', + }, + { id: 'LIST', type: 'FeatureList' }, ], queryFn: async (args, _, _2, baseQuery) => { return await recursivePageGet( diff --git a/frontend/common/utils/__tests__/recursivePageGet.test.ts b/frontend/common/utils/__tests__/recursivePageGet.test.ts new file mode 100644 index 000000000000..ec49f6371e45 --- /dev/null +++ b/frontend/common/utils/__tests__/recursivePageGet.test.ts @@ -0,0 +1,47 @@ +import { recursivePageGet } from 'common/utils/recursivePageGet' + +describe('recursivePageGet', () => { + it('follows next links, concatenating the pages', async () => { + // Given + const baseQuery = jest + .fn() + .mockResolvedValueOnce({ + data: { + count: 3, + next: 'items/?page=2', + previous: null, + results: [1, 2], + }, + }) + .mockResolvedValueOnce({ + data: { count: 3, next: null, previous: 'items/?page=1', results: [3] }, + }) + + // When + const res = await recursivePageGet('items/?page=1', null, baseQuery) + + // Then + expect(baseQuery.mock.calls.map(([arg]) => arg)).toEqual([ + { method: 'GET', url: 'items/?page=1' }, + { method: 'GET', url: 'items/?page=2' }, + ]) + expect(res.data?.results).toEqual([1, 2, 3]) + }) + + it('returns the error of a failing page', async () => { + // Given + const error = { status: 500 } + const baseQuery = jest + .fn() + .mockResolvedValueOnce({ + data: { count: 3, next: 'items/?page=2', previous: null, results: [1] }, + }) + .mockResolvedValueOnce({ error }) + + // When + const res = await recursivePageGet('items/?page=1', null, baseQuery) + + // Then + expect(res).toEqual({ error }) + }) +}) diff --git a/frontend/e2e/tests/flag-dependencies-test.pw.ts b/frontend/e2e/tests/flag-dependencies-test.pw.ts index 0e26be9072fc..1f50d151e12e 100644 --- a/frontend/e2e/tests/flag-dependencies-test.pw.ts +++ b/frontend/e2e/tests/flag-dependencies-test.pw.ts @@ -38,7 +38,8 @@ test.describe('Flag Dependencies', () => { const openDependencies = async (feature: string) => { await gotoFeature(feature) - await page.getByRole('button', { name: 'Dependencies' }).click() + // The tab's name goes on to count the prerequisites met. + await page.getByRole('button', { name: /^Dependencies/ }).click() } log('The dependent has no prerequisites yet') @@ -66,9 +67,27 @@ test.describe('Flag Dependencies', () => { log('The prerequisite is off, so the flag is held off') await expect(row.getByRole('img', { name: 'Off' })).toBeVisible() await expect(row.getByText('No', { exact: true })).toBeVisible() - await expect(page.getByText(/Serving off in/)).toBeVisible() + // The Value tab's banner stays in the page behind the open tab, and the + // role skips hidden elements, so this only matches the open tab's. + const servingOff = page + .getByRole('status') + .filter({ hasText: /Serving off in/ }) + await expect(servingOff).toBeVisible() await visualSnapshot(page, 'dependencies-blocked', testInfo) + log('The tab counts the prerequisites met, and the Value tab says why') + await expect( + page.getByRole('button', { name: /0 of 1 prerequisites met/ }), + ).toBeVisible() + await page.getByRole('button', { exact: true, name: 'Value' }).click() + await expect(servingOff).toBeVisible() + await visualSnapshot(page, 'dependencies-blocked-value', testInfo) + await page + .getByRole('button', { exact: true, name: 'View dependencies' }) + .click() + await expect(page).toHaveURL(/tab=dependencies/) + await expect(row).toBeVisible() + log('Turning the prerequisite on satisfies it') await closeModal() await waitForModalToClose() @@ -76,7 +95,10 @@ test.describe('Flag Dependencies', () => { await openDependencies(DEPENDENT) await expect(row.getByRole('img', { name: 'On' })).toBeVisible() await expect(row.getByText('Yes', { exact: true })).toBeVisible() - await expect(page.getByText(/Serving off in/)).toBeHidden() + await expect(servingOff).toBeHidden() + await expect( + page.getByRole('button', { name: /1 of 1 prerequisites met/ }), + ).toBeVisible() await visualSnapshot(page, 'dependencies-satisfied', testInfo) log('The dependency manages its segment override') diff --git a/frontend/web/components/modals/create-feature/index.tsx b/frontend/web/components/modals/create-feature/index.tsx index d617330f51b8..8950d0bdd27f 100644 --- a/frontend/web/components/modals/create-feature/index.tsx +++ b/frontend/web/components/modals/create-feature/index.tsx @@ -46,7 +46,10 @@ import SegmentOverridesTab, { SegmentOverrideValue, } from './tabs/SegmentOverridesTab' import UsageTab from './tabs/UsageTab' -import FeatureDependenciesTab from './tabs/FeatureDependenciesTab' +import FeatureDependenciesTab, { + DependenciesTabLabel, + usePrerequisiteStatus, +} from './tabs/FeatureDependenciesTab' import { useStagedPrerequisites } from './tabs/FeatureDependenciesTab/hooks/useStagedPrerequisites' import FeatureLimitAlert from './components/FeatureLimitAlert' import FeatureUpdateSummary from './components/FeatureUpdateSummary' @@ -461,6 +464,16 @@ const CreateFeatureModal: FC = (props) => { setSkipSaveProjectFeature(!createFeaturePermission) }, [createFeaturePermission]) + // Shown on the Value tab and the Dependencies tab's label, as + // prerequisites that are off serve the flag off. Dependencies don't apply + // to identity overrides, nor show for change requests. + const prerequisites = usePrerequisiteStatus({ + environmentId, + featureId: projectFlag.id, + projectId, + skip: !isEdit || !!identity || !!existingChangeRequest, + }) + if (!environment || !project) { return (
@@ -479,6 +492,15 @@ const CreateFeatureModal: FC = (props) => { const isVersionedChangeRequest = existingChangeRequest && isVersioned const hideIdentityOverridesTab = Utils.getShouldHideIdentityOverridesTab() const isDependenciesTabEnabled = !existingChangeRequest + const onTabChange = () => { + setTabKey((k) => k + 1) + // A save error belongs to the tab it occurred on — the + // other tabs cannot render its shape meaningfully. + if (FeatureListStore.error) { + FeatureListStore.error = null + FeatureListStore.trigger('change') + } + } // Shows the Dependencies tab, as `Tabs` does when it's clicked. const showDependencies = @@ -490,7 +512,7 @@ const CreateFeatureModal: FC = (props) => { pathname: window.location.pathname, search: searchParams.toString(), }) - setTabKey((k) => k + 1) + onTabChange() } : undefined @@ -812,15 +834,7 @@ const CreateFeatureModal: FC = (props) => { { - setTabKey((k) => k + 1) - // A save error belongs to the tab it occurred on — the - // other tabs cannot render its shape meaningfully. - if (FeatureListStore.error) { - FeatureListStore.error = null - FeatureListStore.trigger('change') - } - }} + onChange={onTabChange} overflowX > = (props) => { > = (props) => { {isDependenciesTabEnabled && ( + } isDirty={dependenciesChanged} > = ({ environmentName, rows }) => +const BlockedBanner: FC = ({ + action, + environmentName, + rows, +}) => isBlocked(rows) ? ( {describeOffCount(rows)} diff --git a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/DependenciesTabLabel.tsx b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/DependenciesTabLabel.tsx new file mode 100644 index 000000000000..9408daf446ad --- /dev/null +++ b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/DependenciesTabLabel.tsx @@ -0,0 +1,36 @@ +import { FC } from 'react' +import Chip from 'components/base/Chip' +import { PrerequisiteRow, countMet } from './prerequisiteState' + +type DependenciesTabLabelProps = { + // Undefined while loading, when there's nothing to count yet. + prerequisites?: PrerequisiteRow[] +} + +// Counts the prerequisites met, as the flag is served off while any isn't. +const DependenciesTabLabel: FC = ({ + prerequisites, +}) => { + const { met, total } = countMet(prerequisites ?? []) + return ( + <> + Dependencies + {!!total && ( + <> + {/* Read out in full instead, as part of the tab's name. The body's + line height stops the chip taking the tab's, which is its height. */} + + + {met}/{total} + + + + {met} of {total} prerequisites met + + + )} + + ) +} + +export default DependenciesTabLabel diff --git a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/__tests__/prerequisiteState.test.ts b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/__tests__/prerequisiteState.test.ts index 3cf2f26a09ce..4e633ec994d7 100644 --- a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/__tests__/prerequisiteState.test.ts +++ b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/__tests__/prerequisiteState.test.ts @@ -1,5 +1,6 @@ import { DependencyEdge, ProjectFlag } from 'common/types/responses' import { + countMet, describeOffCount, isBlocked, toPrerequisiteRow, @@ -108,6 +109,26 @@ describe('isBlocked', () => { }) }) +describe('countMet', () => { + it('counts the prerequisites met', () => { + expect(countMet([row(true, true), row(false, false)])).toEqual({ + met: 1, + total: 2, + }) + }) + + it('leaves out those that cannot be judged', () => { + expect(countMet([row(true, true), row(false, undefined)])).toEqual({ + met: 1, + total: 1, + }) + }) + + it('counts nothing with no prerequisites', () => { + expect(countMet([])).toEqual({ met: 0, total: 0 }) + }) +}) + describe('describeOffCount', () => { it('names a single prerequisite rather than counting it', () => { expect(describeOffCount([row(false, false)])).toBe( diff --git a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/hooks/usePrerequisiteStatus.ts b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/hooks/usePrerequisiteStatus.ts new file mode 100644 index 000000000000..a6abe2038221 --- /dev/null +++ b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/hooks/usePrerequisiteStatus.ts @@ -0,0 +1,50 @@ +import { useMemo } from 'react' +import { useGetFeatureDependenciesQuery } from 'common/services/useFeatureDependency' +import { useFeatureStates } from 'common/hooks/useFeatureStates' +import { + PrerequisiteRow, + toPrerequisiteRows, +} from 'components/modals/create-feature/tabs/FeatureDependenciesTab/prerequisiteState' + +type UsePrerequisiteStatusArgs = { + environmentId: string + featureId: number + projectId: number + skip?: boolean +} + +/** + * Whether each of a flag's prerequisites is on, for showing outside the + * Dependencies tab. Shares its requests with useDependencies. + * + * Undefined until both the dependencies and the feature list are in, as every + * prerequisite reads as off without the latter. + */ +export const usePrerequisiteStatus = ({ + environmentId, + featureId, + projectId, + skip, +}: UsePrerequisiteStatusArgs): PrerequisiteRow[] | undefined => { + // currentData, not data, which keeps another flag's or environment's + // dependencies while these load. + const { + currentData: dependencies, + isError, + isLoading, + } = useGetFeatureDependenciesQuery({ environmentId, featureId }, { skip }) + const featureStates = useFeatureStates({ environmentId, projectId, skip }) + const rows = useMemo( + () => + toPrerequisiteRows(dependencies?.results ?? [], featureStates.features), + [dependencies, featureStates.features], + ) + const isReady = + !skip && + !!dependencies && + !isLoading && + !isError && + !featureStates.isLoading && + !featureStates.isError + return isReady ? rows : undefined +} diff --git a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/index.ts b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/index.ts index f15752e6820f..db52e3ac7e02 100644 --- a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/index.ts +++ b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/index.ts @@ -1,5 +1,6 @@ export { default } from './FeatureDependenciesTab' export { default as BlockedBanner } from './BlockedBanner' +export { default as DependenciesTabLabel } from './DependenciesTabLabel' export { default as DependenciesPanel } from './DependenciesPanel' export { default as DependentFeatures } from './DependentFeatures' export { default as FeatureDependenciesSkeleton } from './FeatureDependenciesSkeleton' @@ -9,4 +10,5 @@ export { PrerequisitesEmptyState, } from './DependenciesEmptyStates' export { toPrerequisiteRow } from './prerequisiteState' +export { usePrerequisiteStatus } from './hooks/usePrerequisiteStatus' export type { PrerequisiteRow } from './prerequisiteState' diff --git a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/prerequisiteState.ts b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/prerequisiteState.ts index 4545aaf77d67..e5ba1c9217db 100644 --- a/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/prerequisiteState.ts +++ b/frontend/web/components/modals/create-feature/tabs/FeatureDependenciesTab/prerequisiteState.ts @@ -75,6 +75,17 @@ export const withStagedChanges = ( export const isBlocked = (rows: PrerequisiteRow[]): boolean => rows.some((row) => row.isMet === false) +// How many prerequisites are met, of those whose rule can be read. +export const countMet = ( + rows: PrerequisiteRow[], +): { met: number; total: number } => { + const judged = rows.filter((row) => row.isMet !== undefined) + return { + met: judged.filter((row) => row.isMet).length, + total: judged.length, + } +} + export const describeOffCount = (rows: PrerequisiteRow[]): string => { const total = rows.length const offCount = rows.filter((row) => !row.isEnabled).length diff --git a/frontend/web/components/modals/create-feature/tabs/FeatureValueTab.tsx b/frontend/web/components/modals/create-feature/tabs/FeatureValueTab.tsx index 71fc35401d52..4ad432712699 100644 --- a/frontend/web/components/modals/create-feature/tabs/FeatureValueTab.tsx +++ b/frontend/web/components/modals/create-feature/tabs/FeatureValueTab.tsx @@ -34,6 +34,7 @@ import { import { FeatureExperimentFreeze } from 'common/hooks/useFeatureExperimentFreeze' import { useExperimentationEnabled } from 'common/hooks/useExperimentationEnabled' import ExperimentFreezeNotice from 'components/modals/create-feature/components/ExperimentFreezeNotice' +import { BlockedBanner, PrerequisiteRow } from './FeatureDependenciesTab' import { useHasPermission } from 'common/providers/Permission' import { ProjectPermission } from 'common/types/permissions.types' @@ -50,6 +51,11 @@ function isNegativeNumberString(str: any) { type FeatureValueTabProps = { error: any + // The flag's prerequisites in the environment, which serve it off while any + // is off. Undefined where they don't apply, e.g. to identity overrides. + prerequisites?: PrerequisiteRow[] + // Shows the flag's dependencies, where they can be changed. + onViewDependencies?: () => void projectId: number | string identity?: string noPermissions: boolean @@ -106,7 +112,9 @@ const FeatureValueTab: FC = ({ onRemoveMultivariateOption, onSaveFeatureValue, onSaveVariationValues, + onViewDependencies, originalMultivariateOptions, + prerequisites, preventFlagDefaults, projectFlag, projectId, @@ -368,6 +376,19 @@ const FeatureValueTab: FC = ({ return (
+ {prerequisites && environmentName && ( + + View dependencies + + ) + } + /> + )} {freeze?.isFrozen && freeze.experiment && environmentId && (