Skip to content

feat: Generalize user preferences as per resource kind #793

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 29 additions & 10 deletions src/Shared/Hooks/useUserPreferences/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ import { getUserPreferenceResourcesMetadata } from './utils'
* @description This function fetches the user preferences from the server. It uses the `get` method to make a request to the server and retrieves the user preferences based on the `USER_PREFERENCES_ATTRIBUTE_KEY`. The result is parsed and returned as a `UserPreferencesType` object.
* @throws Will throw an error if the request fails or if the result is not in the expected format.
*/
export const getUserPreferences = async (): Promise<UserPreferencesType> => {
export const getUserPreferences = async ({
resourceKindType,
}: {
resourceKindType?: ResourceKindType
}): Promise<UserPreferencesType> => {
const queryParamsPayload: Pick<GetUserPreferencesQueryParamsType, 'key'> = {
key: USER_PREFERENCES_ATTRIBUTE_KEY,
}
Expand All @@ -58,23 +62,34 @@ export const getUserPreferences = async (): Promise<UserPreferencesType> => {
? ViewIsPipelineRBACConfiguredRadioTabs.ACCESS_ONLY
: ViewIsPipelineRBACConfiguredRadioTabs.ALL_ENVIRONMENTS

const getPreferredResourcesData = () => {
let resources
switch (resourceKindType) {
case ResourceKindType.devtronApplication:
resources = {
[UserPreferenceResourceActions.RECENTLY_VISITED]:
parsedResult.resources?.[ResourceKindType.devtronApplication]?.[
UserPreferenceResourceActions.RECENTLY_VISITED
] || ([] as BaseAppMetaData[]),
}
break
default:
resources = {}
}
return resources
}

return {
pipelineRBACViewSelectedTab,
themePreference:
parsedResult.computedAppTheme === 'system-dark' || parsedResult.computedAppTheme === 'system-light'
? THEME_PREFERENCE_MAP.auto
: parsedResult.computedAppTheme,
resources: {
[ResourceKindType.devtronApplication]: {
[UserPreferenceResourceActions.RECENTLY_VISITED]:
parsedResult.resources?.[ResourceKindType.devtronApplication]?.[
UserPreferenceResourceActions.RECENTLY_VISITED
] || ([] as BaseAppMetaData[]),
},
[resourceKindType]: resourceKindType ? getPreferredResourcesData() : {},
},
}
}

/**
* @description This function updates the user preferences in the server. It constructs a payload with the updated user preferences and sends a PATCH request to the server. If the request is successful, it returns true. If an error occurs, it shows an error message and returns false.
* @param updatedUserPreferences - The updated user preferences to be sent to the server.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pls fix the comment

Expand All @@ -87,6 +102,7 @@ export const getUserPreferences = async (): Promise<UserPreferencesType> => {
const getUserPreferencePayload = async ({
path,
value,
resourceKind,
}: UserPathValueMapType): Promise<Partial<UserPreferencesPayloadValueType>> => {
switch (path) {
case 'themePreference':
Expand All @@ -102,7 +118,7 @@ const getUserPreferencePayload = async ({

case 'resources':
return {
resources: getUserPreferenceResourcesMetadata(value as BaseAppMetaData[]),
resources: getUserPreferenceResourcesMetadata(value as BaseAppMetaData[], resourceKind),
}
default:
return {}
Expand All @@ -112,12 +128,15 @@ const getUserPreferencePayload = async ({
export const updateUserPreferences = async ({
path,
value,
resourceKind,
shouldThrowError = false,
}: UserPreferenceResourceProps): Promise<boolean> => {
try {
const payload: UpdateUserPreferencesPayloadType = {
key: USER_PREFERENCES_ATTRIBUTE_KEY,
value: JSON.stringify(await getUserPreferencePayload({ path, value } as UserPathValueMapType)),
value: JSON.stringify(
await getUserPreferencePayload({ path, value, resourceKind } as UserPathValueMapType),
),
}

await patch(`${ROUTES.ATTRIBUTES_USER}/${ROUTES.PATCH}`, payload)
Expand Down
20 changes: 13 additions & 7 deletions src/Shared/Hooks/useUserPreferences/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,19 @@ export enum ViewIsPipelineRBACConfiguredRadioTabs {
export enum UserPreferenceResourceActions {
RECENTLY_VISITED = 'recently-visited',
}
export type PreferredResourceKindType = ResourceKindType.devtronApplication

export interface UserPreferenceRecentlyVisitedAppsTypes {
appId: number
appName: string
resourceKind: PreferredResourceKindType
}

export interface UserResourceKindActionType {
[UserPreferenceResourceActions.RECENTLY_VISITED]: BaseAppMetaData[]
}
export interface UserPreferenceResourceType {
[ResourceKindType.devtronApplication]: UserResourceKindActionType
export type UserPreferenceResourceType = {
[key in ResourceKindType]?: UserResourceKindActionType
}
export interface GetUserPreferencesParsedDTO {
viewPermittedEnvOnly?: boolean
Expand Down Expand Up @@ -83,25 +91,23 @@ export type UserPathValueMapType =
| {
path: 'themePreference'
value: Required<Pick<UpdatedUserPreferencesType, 'themePreference' | 'appTheme'>>
resourceKind?: never
}
| {
path: 'pipelineRBACViewSelectedTab'
value: Required<Pick<UserPreferencesType, 'pipelineRBACViewSelectedTab'>>
resourceKind?: never
}
| {
path: 'resources'
value: Required<BaseAppMetaData[]>
resourceKind: PreferredResourceKindType
}

export type UserPreferenceResourceProps = UserPathValueMapType & {
shouldThrowError?: boolean
}

export interface UserPreferenceRecentlyVisitedAppsTypes {
appId: number
appName: string
}

export interface UserPreferenceFilteredListTypes extends UserPreferenceRecentlyVisitedAppsTypes {
userPreferencesResponse: UserPreferencesType
}
18 changes: 11 additions & 7 deletions src/Shared/Hooks/useUserPreferences/useUserPrefrences.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { useState } from 'react'

import { ServerErrors } from '@Common/ServerError'
import { useTheme } from '@Shared/Providers'
import { ResourceKindType } from '@Shared/types'

import { getUserPreferences, updateUserPreferences } from './service'
import {
Expand All @@ -36,26 +35,31 @@ export const useUserPreferences = ({ migrateUserPreferences }: UseUserPreference

const { handleThemeSwitcherDialogVisibilityChange, handleThemePreferenceChange } = useTheme()

const fetchRecentlyVisitedParsedApps = async ({ appId, appName }: UserPreferenceRecentlyVisitedAppsTypes) => {
const userPreferencesResponse = await getUserPreferences()
const fetchRecentlyVisitedParsedApps = async ({
appId,
appName,
resourceKind,
}: UserPreferenceRecentlyVisitedAppsTypes) => {
const userPreferencesResponse = await getUserPreferences({ resourceKindType: resourceKind })

const uniqueFilteredApps = getFilteredUniqueAppList({
userPreferencesResponse,
appId,
appName,
resourceKind,
})

setUserPreferences((prev) => ({
...prev,
resources: {
...prev?.resources,
[ResourceKindType.devtronApplication]: {
...prev?.resources?.[ResourceKindType.devtronApplication],
[resourceKind]: {
...prev?.resources?.[resourceKind],
[UserPreferenceResourceActions.RECENTLY_VISITED]: uniqueFilteredApps,
},
},
}))
await updateUserPreferences({ path: 'resources', value: uniqueFilteredApps })
await updateUserPreferences({ path: 'resources', value: uniqueFilteredApps, resourceKind })
}

const handleInitializeUserPreferencesFromResponse = (userPreferencesResponse: UserPreferencesType) => {
Expand All @@ -70,7 +74,7 @@ export const useUserPreferences = ({ migrateUserPreferences }: UseUserPreference
const handleFetchUserPreferences = async () => {
try {
setUserPreferencesError(null)
const userPreferencesResponse = await getUserPreferences()
const userPreferencesResponse = await getUserPreferences({})
if (migrateUserPreferences) {
const migratedUserPreferences = await migrateUserPreferences(userPreferencesResponse)
handleInitializeUserPreferencesFromResponse(migratedUserPreferences)
Expand Down
12 changes: 7 additions & 5 deletions src/Shared/Hooks/useUserPreferences/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ import { ResourceKindType } from '@Shared/types'

import { UserPreferenceFilteredListTypes, UserPreferenceResourceActions, UserPreferenceResourceType } from './types'

export const getUserPreferenceResourcesMetadata = (recentlyVisited: BaseAppMetaData[]): UserPreferenceResourceType => ({
[ResourceKindType.devtronApplication]: {
export const getUserPreferenceResourcesMetadata = (
recentlyVisited: BaseAppMetaData[],
resourceKind: ResourceKindType,
): UserPreferenceResourceType => ({
[resourceKind]: {
[UserPreferenceResourceActions.RECENTLY_VISITED]: recentlyVisited.map(({ appId, appName }) => ({
appId,
appName,
Expand All @@ -16,11 +19,10 @@ export const getFilteredUniqueAppList = ({
userPreferencesResponse,
appId,
appName,
resourceKind,
}: UserPreferenceFilteredListTypes) => {
const _recentApps =
userPreferencesResponse?.resources?.[ResourceKindType.devtronApplication]?.[
UserPreferenceResourceActions.RECENTLY_VISITED
] || []
userPreferencesResponse?.resources?.[resourceKind]?.[UserPreferenceResourceActions.RECENTLY_VISITED] || []

const isInvalidApp = appId && !appName

Expand Down