Skip to content

The open alternative to Salesforce, designed for AI.

7.8 KB
Raw Blame
import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';
import { SettingsTabBar } from '@/settings/components/layout/SettingsTabBar';
import { DEFAULT_SETTINGS_DRAFT_ROLE } from '@/settings/roles/constants/DefaultSettingsDraftRole';
import { SettingsRoleAssignment } from '@/settings/roles/role-assignment/components/SettingsRoleAssignment';
import { useIsRoleAgentChatChannelAccessDirty } from '@/settings/roles/role-permissions/agent-chat-channels/hooks/useIsRoleAgentChatChannelAccessDirty';
import { useResetRoleAgentChatChannelAccess } from '@/settings/roles/role-permissions/agent-chat-channels/hooks/useResetRoleAgentChatChannelAccess';
import { useSaveRoleAgentChatChannelAccess } from '@/settings/roles/role-permissions/agent-chat-channels/hooks/useSaveRoleAgentChatChannelAccess';
import { SettingsRolePermissions } from '@/settings/roles/role-permissions/components/SettingsRolePermissions';
import { SettingsRoleSettings } from '@/settings/roles/role-settings/components/SettingsRoleSettings';
import { SettingsRoleLabelContainer } from '@/settings/roles/role/components/SettingsRoleLabelContainer';
import { SETTINGS_ROLE_DETAIL_TABS } from '@/settings/roles/role/constants/SettingsRoleDetailTabs';
import { useSaveDraftRoleToDB } from '@/settings/roles/role/hooks/useSaveDraftRoleToDB';
import { settingsDraftRoleFamilyState } from '@/settings/roles/states/settingsDraftRoleFamilyState';
import { settingsPersistedRoleFamilyState } from '@/settings/roles/states/settingsPersistedRoleFamilyState';
import { useWorkspaceSurfaceScopedComponentInstanceId } from '@/ui/layout/hooks/useWorkspaceSurfaceScopedComponentInstanceId';
import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';
import { useSetAtomFamilyState } from '@/ui/utilities/state/jotai/hooks/useSetAtomFamilyState';
import { useLoadCurrentUser } from '@/users/hooks/useLoadCurrentUser';
import { useRefreshAgentChatChannels } from '@/ai/hooks/useRefreshAgentChatChannels';
import { useState } from 'react';
import { SettingsPath } from 'twenty-shared/types';
import { getSettingsPath, isDefined } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import { IconLock, IconSettings, IconUserPlus } from 'twenty-ui/icon';

import { useNavigateSettings } from '~/hooks/useNavigateSettings';
import { getRoleDirtyFields } from '@/settings/roles/role/utils/getRoleDirtyFields';
import { useLingui } from '@lingui/react/macro';

type SettingsRoleProps = {
  roleId: string;
  isCreateMode: boolean;
};

export const SettingsRole = ({ roleId, isCreateMode }: SettingsRoleProps) => {
  const { t } = useLingui();
  const tabsComponentInstanceId = useWorkspaceSurfaceScopedComponentInstanceId(
    SETTINGS_ROLE_DETAIL_TABS.COMPONENT_INSTANCE_ID + '-' + roleId,
  );

  const activeTabId = useAtomComponentStateValue(
    activeTabIdComponentState,
    tabsComponentInstanceId,
  );

  const navigateSettings = useNavigateSettings();

  const [isSaving, setIsSaving] = useState(false);

  const settingsDraftRole = useAtomFamilyStateValue(
    settingsDraftRoleFamilyState,
    roleId,
  );
  const setSettingsDraftRole = useSetAtomFamilyState(
    settingsDraftRoleFamilyState,
    roleId,
  );

  const settingsPersistedRole = useAtomFamilyStateValue(
    settingsPersistedRoleFamilyState,
    roleId,
  );

  const { loadCurrentUser } = useLoadCurrentUser();
  const { refreshAgentChatChannels } = useRefreshAgentChatChannels();
  const isRoleAgentChatChannelAccessDirty =
    useIsRoleAgentChatChannelAccessDirty(roleId);
  const { saveRoleAgentChatChannelAccess } =
    useSaveRoleAgentChatChannelAccess(roleId);
  const { resetRoleAgentChatChannelAccess } =
    useResetRoleAgentChatChannelAccess(roleId);

  const { enqueueToast } = useToast();

  const { saveDraftRoleToDB } = useSaveDraftRoleToDB({
    isCreateMode,
    roleId,
    onSuccess: async (savedRoleId) => {
      if (isCreateMode) {
        navigateSettings(SettingsPath.RoleDetail, { roleId: savedRoleId });
      }
    },
  });

  const isRoleEditable = settingsDraftRole.isEditable;

  const tabs = [
    {
      id: SETTINGS_ROLE_DETAIL_TABS.TABS_IDS.PERMISSIONS,
      title: t`Permissions`,
      Icon: IconLock,
    },
    {
      id: SETTINGS_ROLE_DETAIL_TABS.TABS_IDS.ASSIGNMENT,
      title: t`Assignment`,
      Icon: IconUserPlus,
    },
    {
      id: SETTINGS_ROLE_DETAIL_TABS.TABS_IDS.SETTINGS,
      title: t`Settings`,
      Icon: IconSettings,
    },
  ];

  const dirtyFields = getRoleDirtyFields(
    settingsDraftRole,
    settingsPersistedRole,
  );
  const isRoleDirty = Object.keys(dirtyFields).length > 0;
  const isDirty = isRoleDirty || isRoleAgentChatChannelAccessDirty;

  const handleCancel = () => {
    resetRoleAgentChatChannelAccess();

    if (isCreateMode) {
      setSettingsDraftRole(DEFAULT_SETTINGS_DRAFT_ROLE);
      navigateSettings(SettingsPath.Roles);
      return;
    }

    if (isDefined(settingsPersistedRole)) {
      setSettingsDraftRole(settingsPersistedRole);
    }
  };

  const handleSave = async () => {
    if (isDefined(dirtyFields.label) && dirtyFields.label === '') {
      enqueueToast({
        status: 'error',
        children: t`Role name cannot be empty`,
      });
      return;
    }

    setIsSaving(true);

    try {
      if (isCreateMode || isRoleDirty) {
        await saveDraftRoleToDB();
        await loadCurrentUser();
      }
      if (isRoleAgentChatChannelAccessDirty) {
        await saveRoleAgentChatChannelAccess();
      } else if (isDefined(dirtyFields.canAccessAllAgentChatChannels)) {
        await refreshAgentChatChannels();
      }
    } catch (error) {
      enqueueToast(getToastOptionsFromError({ error }));
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <SettingsPageLayout
      title={<SettingsRoleLabelContainer roleId={roleId} />}
      pageTitle={settingsDraftRole.label}
      secondaryBar={
        <SettingsTabBar
          aria-label={t`Role settings`}
          tabs={tabs}
          componentInstanceId={tabsComponentInstanceId}
        />
      }
      links={[
        {
          children: t`Workspace`,
          href: getSettingsPath(SettingsPath.General),
        },
        {
          children: t`Members`,
          href: getSettingsPath(SettingsPath.WorkspaceMembersPage),
        },
        {
          children: t`Roles`,
          href: getSettingsPath(SettingsPath.Roles),
        },
        {
          children: settingsDraftRole.label,
        },
      ]}
      actionButton={
        isRoleEditable &&
        isDirty && (
          <SaveAndCancelButtons
            onSave={handleSave}
            onCancel={handleCancel}
            isLoading={isSaving}
          />
        )
      }
    >
      <SettingsPageContainer>
        {activeTabId === SETTINGS_ROLE_DETAIL_TABS.TABS_IDS.ASSIGNMENT && (
          <SettingsRoleAssignment roleId={roleId} isCreateMode={isCreateMode} />
        )}
        {activeTabId === SETTINGS_ROLE_DETAIL_TABS.TABS_IDS.PERMISSIONS && (
          <SettingsRolePermissions
            roleId={roleId}
            isEditable={isRoleEditable}
          />
        )}
        {activeTabId === SETTINGS_ROLE_DETAIL_TABS.TABS_IDS.SETTINGS && (
          <SettingsRoleSettings
            roleId={roleId}
            isEditable={isRoleEditable}
            isCreateMode={isCreateMode}
          />
        )}
      </SettingsPageContainer>
    </SettingsPageLayout>
  );
};