Skip to content

The open alternative to Salesforce, designed for AI.

Align the Granola settings with Twenty's native settings design (#26172)

nitin10f00f3c0b49
diff --git a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts
index 5ca52c8f241..f53e049d110 100644
--- a/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/granola/src/constants/universal-identifiers.ts
@@ -37,5 +37,7 @@ export const GRANOLA_FOLDERS_UNIVERSAL_IDENTIFIER =
'e054fa37-78c9-4f6a-a064-f887b87f1fc5';
export const GRANOLA_UPDATE_WEBHOOK_FOLDERS_UNIVERSAL_IDENTIFIER =
'5092d8b4-b10d-4fcb-b029-c4e93d5234c5';
+export const GRANOLA_FOLDER_SELECTION_UNIVERSAL_IDENTIFIER =
+ '97f2a79b-cb0f-419f-a7d7-580e56078224';
export const GRANOLA_API_KEY_VARIABLE_UNIVERSAL_IDENTIFIER =
'cbc0f310-d0e9-4033-ae07-0271405195e7';
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaApiKeyForm.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaApiKeyForm.tsx
new file mode 100644
index 00000000000..5d2039f3874
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaApiKeyForm.tsx
@@ -0,0 +1,71 @@
+import styled from '@emotion/styled';
+import { isNonEmptyString } from '@sniptt/guards';
+import { useId, useState } from 'react';
+import { t } from 'twenty-sdk/front-component';
+import { Button } from 'twenty-ui/input';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+import { LabelledSettingsField } from 'src/front-components/components/LabelledSettingsField';
+import { StyledSettingsTextInput } from 'src/front-components/components/StyledSettingsTextInput';
+
+const StyledKeyRow = styled.div`
+ align-items: center;
+ display: flex;
+ gap: ${() => themeCssVariables.spacing[2]};
+`;
+
+type GranolaApiKeyFormProps = {
+ errorMessage: string | undefined;
+ isConnectDisabled: boolean;
+ onConnect: (apiKey: string) => void;
+};
+
+export const GranolaApiKeyForm = ({
+ errorMessage,
+ isConnectDisabled,
+ onConnect,
+}: GranolaApiKeyFormProps) => {
+ const inputId = useId();
+ const [apiKeyDraft, setApiKeyDraft] = useState('');
+
+ const trimmedApiKeyDraft = apiKeyDraft.trim();
+
+ const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+
+ if (isConnectDisabled || !isNonEmptyString(trimmedApiKeyDraft)) {
+ return;
+ }
+
+ onConnect(trimmedApiKeyDraft);
+ };
+
+ return (
+ <form onSubmit={handleSubmit}>
+ <LabelledSettingsField
+ label={t('API key')}
+ inputId={inputId}
+ errorMessage={errorMessage}
+ >
+ <StyledKeyRow>
+ <StyledSettingsTextInput
+ id={inputId}
+ type="password"
+ autoComplete="off"
+ placeholder="grn_…"
+ value={apiKeyDraft}
+ onChange={(event) => setApiKeyDraft(event.target.value)}
+ />
+ <Button
+ type="submit"
+ title={t('Connect')}
+ accent="blue"
+ disabled={
+ isConnectDisabled || !isNonEmptyString(trimmedApiKeyDraft)
+ }
+ />
+ </StyledKeyRow>
+ </LabelledSettingsField>
+ </form>
+ );
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionCard.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionCard.tsx
new file mode 100644
index 00000000000..0ac2f4c98b3
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionCard.tsx
@@ -0,0 +1,127 @@
+import { t } from 'twenty-sdk/front-component';
+import { Status } from 'twenty-ui/data-display';
+import { Info } from 'twenty-ui/feedback';
+import { IconKey } from 'twenty-ui/icon';
+import { type ThemeColor } from 'twenty-ui/theme';
+
+import { SettingsControlLoader } from 'src/front-components/components/SettingsControlLoader';
+import { SettingsOptionCardContent } from 'src/front-components/components/SettingsOptionCardContent';
+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';
+import { type GranolaConnectionState } from 'src/front-components/types/granola-connection-state.type';
+
+type GranolaKnownConnectionState = Exclude<GranolaConnectionState, 'CHECKING'>;
+
+const STATUS_COLOR_BY_CONNECTION_STATE: Record<
+ GranolaKnownConnectionState,
+ ThemeColor
+> = {
+ CONNECTING: 'turquoise',
+ CONNECTED: 'green',
+ INVALID_KEY: 'red',
+ UNREACHABLE: 'orange',
+ PAUSED: 'orange',
+ SETUP_INCOMPLETE: 'orange',
+};
+
+const getStatusText = (connectionState: GranolaKnownConnectionState) =>
+ ({
+ CONNECTING: t('Connecting'),
+ CONNECTED: t('Connected'),
+ INVALID_KEY: t('Invalid key'),
+ UNREACHABLE: t('Unreachable'),
+ PAUSED: t('Paused'),
+ SETUP_INCOMPLETE: t('Setup incomplete'),
+ })[connectionState];
+
+const getDescription = ({
+ connectionState,
+ isWorkspaceKey,
+}: {
+ connectionState: GranolaConnectionState;
+ isWorkspaceKey: boolean;
+}) => {
+ if (connectionState === 'CHECKING') {
+ return t('Checking the connection with Granola.');
+ }
+
+ if (connectionState === 'CONNECTING') {
+ return t('Setting up live sync. This may take a few seconds.');
+ }
+
+ if (connectionState !== 'CONNECTED') {
+ return t('Live sync is not running.');
+ }
+
+ return isWorkspaceKey
+ ? t("Workspace key. Your team's shared notes sync live.")
+ : t("Personal key. Only the key owner's notes sync live.");
+};
+
+type GranolaConnectionCardProps = {
+ connectionState: GranolaConnectionState;
+ isWorkspaceKey: boolean;
+ onRetry: () => void;
+ onReplaceKey: () => void;
+};
+
+export const GranolaConnectionCard = ({
+ connectionState,
+ isWorkspaceKey,
+ onRetry,
+ onReplaceKey,
+}: GranolaConnectionCardProps) => (
+ <>
+ <StyledSettingsCard>
+ <SettingsOptionCardContent
+ Icon={IconKey}
+ title={t('API key')}
+ description={getDescription({ connectionState, isWorkspaceKey })}
+ >
+ {connectionState === 'CHECKING' ? (
+ <SettingsControlLoader />
+ ) : (
+ <Status
+ color={STATUS_COLOR_BY_CONNECTION_STATE[connectionState]}
+ text={getStatusText(connectionState)}
+ isLoaderVisible={connectionState === 'CONNECTING'}
+ weight="medium"
+ />
+ )}
+ </SettingsOptionCardContent>
+ </StyledSettingsCard>
+ {connectionState === 'INVALID_KEY' && (
+ <Info
+ accent="danger"
+ text={t('Granola rejected this API key.')}
+ buttonTitle={t('Use another key')}
+ onClick={onReplaceKey}
+ />
+ )}
+ {connectionState === 'UNREACHABLE' && (
+ <Info
+ accent="danger"
+ text={t('Could not reach Granola. Try again in a moment.')}
+ buttonTitle={t('Retry')}
+ onClick={onRetry}
+ />
+ )}
+ {connectionState === 'SETUP_INCOMPLETE' && (
+ <Info
+ accent="danger"
+ text={t('Could not set up live sync with Granola.')}
+ buttonTitle={t('Retry')}
+ onClick={onRetry}
+ />
+ )}
+ {connectionState === 'PAUSED' && (
+ <Info
+ accent="blue"
+ text={t(
+ 'Live sync is paused in Granola, so new notes are not arriving.',
+ )}
+ buttonTitle={t('Resume')}
+ onClick={onRetry}
+ />
+ )}
+ </>
+);
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx
index 4c6455bbc71..1eba51bb942 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaConnectionSection.tsx
@@ -1,198 +1,24 @@
-import styled from '@emotion/styled';
-import { isNonEmptyString } from '@sniptt/guards';
-import { useId, useState } from 'react';
+import { type ReactNode } from 'react';
import { t } from 'twenty-sdk/front-component';
-import { isDefined } from 'twenty-sdk/utils';
-import { Status } from 'twenty-ui/data-display';
-import { Loader } from 'twenty-ui/feedback';
-import { IconKey, IconTrash } from 'twenty-ui/icon';
-import { Button, IconButton, LightButton } from 'twenty-ui/input';
import { Section } from 'twenty-ui/layout';
-import { themeCssVariables } from 'twenty-ui/theme-constants';
import { H2Title } from 'twenty-ui/typography';
-import { LabelledSettingsField } from 'src/front-components/components/LabelledSettingsField';
-import { SettingsOptionCardContent } from 'src/front-components/components/SettingsOptionCardContent';
-import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';
-import { StyledSettingsError } from 'src/front-components/components/StyledSettingsError';
import { StyledSettingsSectionStack } from 'src/front-components/components/StyledSettingsSectionStack';
-import { StyledSettingsTextInput } from 'src/front-components/components/StyledSettingsTextInput';
-import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';
-import { isGranolaConnectionReady } from 'src/front-components/utils/is-granola-connection-ready.util';
-
-const StyledKeyForm = styled.form`
- display: flex;
- flex-direction: column;
- gap: ${() => themeCssVariables.spacing[3]};
-`;
-
-const StyledActions = styled.div`
- display: flex;
- gap: ${() => themeCssVariables.spacing[2]};
- justify-content: flex-start;
-`;
-
-const StyledConnectButtonContainer = styled.div`
- button {
- gap: ${() => themeCssVariables.spacing[2]};
- min-width: ${() => themeCssVariables.spacing[32]};
- padding-inline: ${() => themeCssVariables.spacing[4]};
- }
-`;
-
-const StyledConnectionHint = styled.div`
- color: ${() => themeCssVariables.font.color.secondary};
- font-family: ${() => themeCssVariables.font.family};
- font-size: ${() => themeCssVariables.font.size.sm};
-`;
-
-// Button's isLoading animation clips the title; keep the loader in its icon slot.
-const ConnectionLoader = () => <Loader />;
type GranolaConnectionSectionProps = {
- status: GranolaConnectionStatus;
- isConnecting: boolean;
- isRemoving: boolean;
- connectError: string | undefined;
- removeError: string | undefined;
- onConnect: (apiKey: string) => Promise<boolean>;
- onRemove: () => Promise<void>;
- onRetry: () => void;
+ children: ReactNode;
};
export const GranolaConnectionSection = ({
- status,
- isConnecting,
- isRemoving,
- connectError,
- removeError,
- onConnect,
- onRemove,
- onRetry,
-}: GranolaConnectionSectionProps) => {
- const inputId = useId();
- const [apiKeyDraft, setApiKeyDraft] = useState('');
-
- const trimmedApiKeyDraft = apiKeyDraft.trim();
- const isConnected =
- !isConnecting &&
- isGranolaConnectionReady(status) &&
- !isDefined(connectError);
- const connectionError = isConnecting
- ? undefined
- : (connectError ??
- (status.isApiKeySet && !isConnected
- ? t('Could not connect to Granola. Try again.')
- : undefined));
-
- const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
- event.preventDefault();
-
- if (isConnecting || isRemoving) {
- return;
- }
-
- if (status.isApiKeySet) {
- onRetry();
-
- return;
- }
-
- if (!isNonEmptyString(trimmedApiKeyDraft)) {
- return;
- }
-
- const isSaved = await onConnect(trimmedApiKeyDraft);
-
- if (isSaved) {
- setApiKeyDraft('');
- }
- };
-
- return (
- <Section>
- <H2Title
- title={t('Granola account')}
- description={t(
- 'Requires Granola Business or Enterprise. Create a key in Granola under Settings → Connectors → API keys.',
- )}
- />
- <StyledSettingsSectionStack>
- {isConnected && (
- <StyledSettingsCard>
- <SettingsOptionCardContent
- Icon={IconKey}
- title={t('API key')}
- description={t(
- 'New and updated notes appear in Call Recordings automatically.',
- )}
- >
- <Status color="green" text={t('Connected')} />
- <IconButton
- Icon={IconTrash}
- variant="tertiary"
- accent="danger"
- ariaLabel={
- isRemoving ? t('Removing API key') : t('Remove API key')
- }
- disabled={isRemoving}
- onClick={() => onRemove()}
- />
- </SettingsOptionCardContent>
- </StyledSettingsCard>
- )}
- {isDefined(removeError) && (
- <StyledSettingsError>{removeError}</StyledSettingsError>
- )}
- {!isConnected && (
- <StyledKeyForm onSubmit={handleSubmit}>
- <LabelledSettingsField
- label={t('API key')}
- inputId={inputId}
- errorMessage={connectionError}
- >
- <StyledSettingsTextInput
- id={inputId}
- type="password"
- autoComplete="off"
- placeholder={status.isApiKeySet ? '••••••••' : 'grn_…'}
- value={apiKeyDraft}
- disabled={isConnecting || isRemoving || status.isApiKeySet}
- onChange={(event) => setApiKeyDraft(event.target.value)}
- />
- </LabelledSettingsField>
- <StyledActions>
- {status.isApiKeySet && isDefined(connectionError) && (
- <LightButton
- title={t('Cancel')}
- disabled={isRemoving}
- onClick={() => onRemove()}
- />
- )}
- <StyledConnectButtonContainer>
- <Button
- type="submit"
- title={isConnecting ? t('Connecting') : t('Connect')}
- accent="blue"
- justify="center"
- Icon={isConnecting ? ConnectionLoader : undefined}
- disabled={
- isConnecting ||
- isRemoving ||
- (!status.isApiKeySet &&
- !isNonEmptyString(trimmedApiKeyDraft))
- }
- />
- </StyledConnectButtonContainer>
- </StyledActions>
- {isConnecting && (
- <StyledConnectionHint role="status">
- {t('Configuring your connection. This may take a few seconds.')}
- </StyledConnectionHint>
- )}
- </StyledKeyForm>
- )}
- </StyledSettingsSectionStack>
- </Section>
- );
-};
+ children,
+}: GranolaConnectionSectionProps) => (
+ <Section>
+ <H2Title
+ title={t('Granola account')}
+ description={t(
+ 'Requires Granola Business or Enterprise. Create a key in Granola under Settings → Connectors → API keys.',
+ )}
+ />
+ <StyledSettingsSectionStack>{children}</StyledSettingsSectionStack>
+ </Section>
+);
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaDangerZoneSection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaDangerZoneSection.tsx
new file mode 100644
index 00000000000..4a31bc14a0b
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaDangerZoneSection.tsx
@@ -0,0 +1,49 @@
+import { openCommandConfirmationModal, t } from 'twenty-sdk/front-component';
+import { IconTrash } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/input';
+import { Section } from 'twenty-ui/layout';
+import { H2Title } from 'twenty-ui/typography';
+
+type GranolaDangerZoneSectionProps = {
+ isDisabled: boolean;
+ onDisconnect: () => void;
+};
+
+export const GranolaDangerZoneSection = ({
+ isDisabled,
+ onDisconnect,
+}: GranolaDangerZoneSectionProps) => {
+ const handleDisconnectClick = async () => {
+ const confirmationResult = await openCommandConfirmationModal({
+ title: t('Disconnect Granola'),
+ subtitle: t(
+ 'This removes the API key and stops live sync. Recordings already in Twenty are kept.',
+ ),
+ confirmButtonText: t('Disconnect'),
+ confirmButtonAccent: 'danger',
+ });
+
+ if (confirmationResult !== 'confirm') {
+ return;
+ }
+
+ onDisconnect();
+ };
+
+ return (
+ <Section>
+ <H2Title
+ title={t('Danger zone')}
+ description={t('Remove the API key and stop syncing notes')}
+ />
+ <Button
+ Icon={IconTrash}
+ title={t('Disconnect')}
+ variant="secondary"
+ accent="danger"
+ disabled={isDisabled}
+ onClick={handleDisconnectClick}
+ />
+ </Section>
+ );
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPicker.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPicker.tsx
new file mode 100644
index 00000000000..7087da4d8bc
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPicker.tsx
@@ -0,0 +1,222 @@
+import { useState } from 'react';
+import { enqueueSnackbar, t } from 'twenty-sdk/front-component';
+import { isDefined } from 'twenty-sdk/utils';
+import { Info } from 'twenty-ui/feedback';
+
+import { GRANOLA_FOLDER_SELECTION_LIMIT } from 'src/constants/granola-api.constant';
+import { GranolaFolderEmptyState } from 'src/front-components/components/GranolaFolderEmptyState';
+import { GranolaFolderPolicyRadioCard } from 'src/front-components/components/GranolaFolderPolicyRadioCard';
+import { GranolaFolderTree } from 'src/front-components/components/GranolaFolderTree';
+import { GranolaFolderTreeSkeleton } from 'src/front-components/components/GranolaFolderTreeSkeleton';
+import { OnMountEffect } from 'src/front-components/components/OnMountEffect';
+import { useAutosaveGranolaFolderSelection } from 'src/front-components/hooks/use-autosave-granola-folder-selection';
+import { type GranolaFolderPolicy } from 'src/front-components/types/granola-folder-policy.type';
+import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';
+import { type GranolaStoredFolderSelection } from 'src/front-components/types/granola-stored-folder-selection.type';
+import { computeGranolaFolderSelection } from 'src/front-components/utils/compute-granola-folder-selection.util';
+import { dropInaccessibleGranolaFolders } from 'src/front-components/utils/drop-inaccessible-granola-folders.util';
+import { fetchGranolaFoldersOrThrow } from 'src/front-components/utils/fetch-granola-folders-or-throw.util';
+
+const getSelectionHint = (selectedFolderCount: number) => {
+ if (selectedFolderCount === 0) {
+ return t('Nothing is picked yet, so every folder still syncs.');
+ }
+
+ if (selectedFolderCount === 1) {
+ return t('Switch to Everything to stop filtering by folder.');
+ }
+
+ if (selectedFolderCount >= GRANOLA_FOLDER_SELECTION_LIMIT) {
+ return t('You can pick up to {limit} folders.', {
+ limit: GRANOLA_FOLDER_SELECTION_LIMIT,
+ });
+ }
+
+ return undefined;
+};
+
+type GranolaFolderListState =
+ | { step: 'NOT_LOADED' }
+ | { step: 'LOADING' }
+ | { step: 'FAILED' }
+ | { step: 'LOADED'; folders: GranolaSettingsFolder[] };
+
+type GranolaFolderPickerProps = GranolaStoredFolderSelection;
+
+export const GranolaFolderPicker = ({
+ selectedFolderIds,
+ pendingFolderIds,
+}: GranolaFolderPickerProps) => {
+ const [selection, setSelection] = useState(() =>
+ computeGranolaFolderSelection({ selectedFolderIds, pendingFolderIds }),
+ );
+ const [folderList, setFolderList] = useState<GranolaFolderListState>({
+ step: 'NOT_LOADED',
+ });
+ const [isLocked, setIsLocked] = useState(false);
+
+ const loadFolderList = async ({
+ isSelectionStale,
+ }: {
+ isSelectionStale: boolean;
+ }) => {
+ if (isSelectionStale) {
+ setIsLocked(true);
+ }
+ setFolderList({ step: 'LOADING' });
+
+ const foldersResult = await fetchGranolaFoldersOrThrow().catch(
+ () => undefined,
+ );
+
+ if (!isDefined(foldersResult)) {
+ setFolderList({ step: 'FAILED' });
+
+ return;
+ }
+
+ setSelection((current) =>
+ dropInaccessibleGranolaFolders({
+ selection: isSelectionStale
+ ? computeGranolaFolderSelection(foldersResult)
+ : current,
+ folders: foldersResult.folders,
+ }),
+ );
+ setFolderList({ step: 'LOADED', folders: foldersResult.folders });
+
+ if (isSelectionStale) {
+ setIsLocked(false);
+ }
+ };
+
+ const loadFolderListIfSelected = () => {
+ if (selection.policy === 'SELECTED_FOLDERS') {
+ loadFolderList({ isSelectionStale: false });
+ }
+ };
+
+ const { save } = useAutosaveGranolaFolderSelection({
+ onSaveSuccess: (folderIds) =>
+ setSelection((current) => ({
+ ...current,
+ selectedFolderIds: folderIds,
+ isSelectionPending: false,
+ })),
+ onSaveError: () => {
+ enqueueSnackbar({
+ message: t('Could not save the folder selection. Try again.'),
+ variant: 'error',
+ });
+ loadFolderList({ isSelectionStale: true });
+ },
+ });
+
+ const handleReplaceSelection = (nextSelectedFolderIds: string[]) => {
+ setSelection((current) => ({
+ ...current,
+ selectedFolderIds: nextSelectedFolderIds,
+ hasInaccessibleSelection: false,
+ }));
+ save(nextSelectedFolderIds);
+ };
+
+ const handlePolicyChange = (nextPolicy: GranolaFolderPolicy) => {
+ setSelection((current) => ({ ...current, policy: nextPolicy }));
+
+ if (
+ nextPolicy === 'SELECTED_FOLDERS' &&
+ (folderList.step === 'NOT_LOADED' || folderList.step === 'FAILED')
+ ) {
+ loadFolderList({ isSelectionStale: false });
+ }
+
+ if (
+ nextPolicy === 'ALL_FOLDERS' &&
+ (selection.selectedFolderIds.length > 0 ||
+ selection.hasInaccessibleSelection)
+ ) {
+ handleReplaceSelection([]);
+ }
+ };
+
+ const handleToggleFolder = (folderId: string, checked: boolean) => {
+ handleReplaceSelection(
+ checked
+ ? [...selection.selectedFolderIds, folderId]
+ : selection.selectedFolderIds.filter((id) => id !== folderId),
+ );
+ };
+
+ const getSelectedFoldersContent = () => {
+ if (folderList.step === 'FAILED') {
+ return undefined;
+ }
+
+ if (folderList.step !== 'LOADED') {
+ return <GranolaFolderTreeSkeleton />;
+ }
+
+ if (folderList.folders.length === 0) {
+ return <GranolaFolderEmptyState />;
+ }
+
+ return (
+ <GranolaFolderTree
+ folders={folderList.folders}
+ selectedFolderIds={selection.selectedFolderIds}
+ selectionLimit={GRANOLA_FOLDER_SELECTION_LIMIT}
+ hint={
+ selection.hasInaccessibleSelection
+ ? undefined
+ : getSelectionHint(selection.selectedFolderIds.length)
+ }
+ onToggleFolder={handleToggleFolder}
+ onReplaceSelection={handleReplaceSelection}
+ />
+ );
+ };
+
+ const showsFolderListError =
+ folderList.step === 'FAILED' &&
+ (isLocked || selection.policy === 'SELECTED_FOLDERS');
+
+ return (
+ <>
+ <OnMountEffect onMount={loadFolderListIfSelected} />
+ <GranolaFolderPolicyRadioCard
+ policy={isLocked ? undefined : selection.policy}
+ selectedFoldersContent={getSelectedFoldersContent()}
+ onChange={handlePolicyChange}
+ />
+ {showsFolderListError && (
+ <Info
+ accent="danger"
+ text={t('Could not load your Granola folders.')}
+ buttonTitle={t('Retry')}
+ onClick={() => loadFolderList({ isSelectionStale: isLocked })}
+ />
+ )}
+ {!isLocked && selection.hasInaccessibleSelection && (
+ <Info
+ accent="danger"
+ text={t(
+ 'The folders you picked are no longer available. Pick folders again, or switch to Everything.',
+ )}
+ />
+ )}
+ {!isLocked &&
+ selection.isSelectionPending &&
+ !selection.hasInaccessibleSelection && (
+ <Info
+ accent="blue"
+ text={t(
+ 'This selection is not applied in Granola yet. It is retried at the next daily catch-up.',
+ )}
+ buttonTitle={t('Retry now')}
+ onClick={() => save(selection.selectedFolderIds)}
+ />
+ )}
+ </>
+ );
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPolicyRadioCard.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPolicyRadioCard.tsx
new file mode 100644
index 00000000000..2581540d10b
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderPolicyRadioCard.tsx
@@ -0,0 +1,39 @@
+import { t } from 'twenty-sdk/front-component';
+
+import { GranolaFolderPolicyIcon } from 'src/front-components/components/GranolaFolderPolicyIcon';
+import { SettingsRadioCard } from 'src/front-components/components/SettingsRadioCard';
+import { type GranolaFolderPolicy } from 'src/front-components/types/granola-folder-policy.type';
+
+type GranolaFolderPolicyRadioCardProps = {
+ policy: GranolaFolderPolicy | undefined;
+ selectedFoldersContent?: React.ReactNode;
+ onChange?: (policy: GranolaFolderPolicy) => void;
+};
+
+export const GranolaFolderPolicyRadioCard = ({
+ policy,
+ selectedFoldersContent,
+ onChange = () => undefined,
+}: GranolaFolderPolicyRadioCardProps) => (
+ <SettingsRadioCard
+ value={policy}
+ onChange={onChange}
+ options={[
+ {
+ value: 'ALL_FOLDERS',
+ cardMedia: <GranolaFolderPolicyIcon policy="ALL_FOLDERS" />,
+ title: t('Everything'),
+ description: t('Sync notes from every folder you can access'),
+ },
+ {
+ value: 'SELECTED_FOLDERS',
+ cardMedia: <GranolaFolderPolicyIcon policy="SELECTED_FOLDERS" />,
+ title: t('Some folders'),
+ description: t(
+ 'Sync only the folders you pick, including their subfolders',
+ ),
+ expandedContent: selectedFoldersContent,
+ },
+ ]}
+ />
+);
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderSection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderSection.tsx
index 9a10d4160d8..cdaa8a4a6cd 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderSection.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderSection.tsx
@@ -1,111 +1,43 @@
import { useState } from 'react';
import { t } from 'twenty-sdk/front-component';
import { isDefined } from 'twenty-sdk/utils';
+import { Info } from 'twenty-ui/feedback';
import { Section } from 'twenty-ui/layout';
import { H2Title } from 'twenty-ui/typography';
-import { GRANOLA_FOLDER_SELECTION_LIMIT } from 'src/constants/granola-api.constant';
-import { GranolaFolderEmptyState } from 'src/front-components/components/GranolaFolderEmptyState';
-import { GranolaFolderPolicyIcon } from 'src/front-components/components/GranolaFolderPolicyIcon';
-import { GranolaFolderTree } from 'src/front-components/components/GranolaFolderTree';
+import { GranolaFolderPicker } from 'src/front-components/components/GranolaFolderPicker';
+import { GranolaFolderPolicyRadioCard } from 'src/front-components/components/GranolaFolderPolicyRadioCard';
import { OnMountEffect } from 'src/front-components/components/OnMountEffect';
-import { SettingsRadioCard } from 'src/front-components/components/SettingsRadioCard';
-import { StyledSettingsError } from 'src/front-components/components/StyledSettingsError';
-import { StyledSettingsHint } from 'src/front-components/components/StyledSettingsHint';
import { StyledSettingsSectionStack } from 'src/front-components/components/StyledSettingsSectionStack';
-import { useAutosaveGranolaFolderSelection } from 'src/front-components/hooks/use-autosave-granola-folder-selection';
-import { type GranolaFolderPolicy } from 'src/front-components/types/granola-folder-policy.type';
-import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';
-import { fetchGranolaFoldersOrThrow } from 'src/front-components/utils/fetch-granola-folders-or-throw.util';
+import { type GranolaStoredFolderSelection } from 'src/front-components/types/granola-stored-folder-selection.type';
+import { fetchGranolaFolderSelectionOrThrow } from 'src/front-components/utils/fetch-granola-folder-selection-or-throw.util';
-type FolderSaveState =
- | { kind: 'idle' }
- | { kind: 'saving' }
- | { kind: 'saved' }
- | { kind: 'pending' }
- | { kind: 'error'; message: string };
+type GranolaStoredSelectionState =
+ | { step: 'LOADING' }
+ | { step: 'FAILED' }
+ | { step: 'LOADED'; storedSelection: GranolaStoredFolderSelection };
export const GranolaFolderSection = () => {
- const [folders, setFolders] = useState<GranolaSettingsFolder[] | undefined>(
- undefined,
- );
- const [loadError, setLoadError] = useState<string | undefined>(undefined);
- const [selectedFolderIds, setSelectedFolderIds] = useState<string[]>([]);
- const [policy, setPolicy] = useState<GranolaFolderPolicy>('ALL_FOLDERS');
- const [hasInaccessibleSelection, setHasInaccessibleSelection] =
- useState(false);
- const [saveState, setSaveState] = useState<FolderSaveState>({ kind: 'idle' });
-
- const { save } = useAutosaveGranolaFolderSelection({
- onSaveStart: () => setSaveState({ kind: 'saving' }),
- onSaveSuccess: (folderIds) => {
- setSaveState({ kind: 'saved' });
- setSelectedFolderIds(folderIds);
- },
- onSaveError: (message) => setSaveState({ kind: 'error', message }),
- });
-
- const loadFolders = async () => {
- try {
- const result = await fetchGranolaFoldersOrThrow();
- const accessibleIds = new Set(result.folders.map((folder) => folder.id));
- const storedFolderIds =
- result.pendingFolderIds ?? result.selectedFolderIds;
- const accessibleSelectedIds = storedFolderIds.filter((id) =>
- accessibleIds.has(id),
- );
+ const [storedSelectionState, setStoredSelectionState] =
+ useState<GranolaStoredSelectionState>({ step: 'LOADING' });
- setFolders(result.folders);
- setSelectedFolderIds(accessibleSelectedIds);
- setPolicy(
- storedFolderIds.length > 0 ? 'SELECTED_FOLDERS' : 'ALL_FOLDERS',
- );
- setHasInaccessibleSelection(
- storedFolderIds.length > 0 && accessibleSelectedIds.length === 0,
- );
-
- if (isDefined(result.pendingFolderIds)) {
- setSaveState({ kind: 'pending' });
- }
- } catch {
- setLoadError(t('Could not load your Granola folders. Reload to retry.'));
- }
- };
+ const loadStoredSelection = async () => {
+ setStoredSelectionState({ step: 'LOADING' });
- const handlePolicyChange = (nextPolicy: GranolaFolderPolicy) => {
- setPolicy(nextPolicy);
-
- if (
- nextPolicy === 'ALL_FOLDERS' &&
- (selectedFolderIds.length > 0 || hasInaccessibleSelection)
- ) {
- setHasInaccessibleSelection(false);
- setSelectedFolderIds([]);
- save([]);
- }
- };
-
- const handleReplaceSelection = (nextSelectedFolderIds: string[]) => {
- setHasInaccessibleSelection(false);
- setSelectedFolderIds(nextSelectedFolderIds);
- save(nextSelectedFolderIds);
- };
+ const storedSelection = await fetchGranolaFolderSelectionOrThrow().catch(
+ () => undefined,
+ );
- const handleToggleFolder = (folderId: string, checked: boolean) => {
- handleReplaceSelection(
- checked
- ? [...selectedFolderIds, folderId]
- : selectedFolderIds.filter((id) => id !== folderId),
+ setStoredSelectionState(
+ isDefined(storedSelection)
+ ? { step: 'LOADED', storedSelection }
+ : { step: 'FAILED' },
);
};
- const isSelectionFull =
- selectedFolderIds.length >= GRANOLA_FOLDER_SELECTION_LIMIT;
- const hasFolders = isDefined(folders) && folders.length > 0;
-
return (
<Section>
- <OnMountEffect onMount={loadFolders} />
+ <OnMountEffect onMount={loadStoredSelection} />
<H2Title
title={t('Folders')}
description={t(
@@ -113,88 +45,19 @@ export const GranolaFolderSection = () => {
)}
/>
<StyledSettingsSectionStack>
- <SettingsRadioCard
- value={policy}
- disabled={!isDefined(folders)}
- onChange={handlePolicyChange}
- options={[
- {
- value: 'ALL_FOLDERS',
- cardMedia: <GranolaFolderPolicyIcon policy="ALL_FOLDERS" />,
- title: t('Everything'),
- description: t('Sync notes from every folder you can access'),
- },
- {
- value: 'SELECTED_FOLDERS',
- cardMedia: <GranolaFolderPolicyIcon policy="SELECTED_FOLDERS" />,
- title: t('Some folders'),
- description: t(
- 'Sync only the folders you pick, including their subfolders',
- ),
- expandedContent: hasFolders ? (
- <GranolaFolderTree
- folders={folders}
- selectedFolderIds={selectedFolderIds}
- selectionLimit={GRANOLA_FOLDER_SELECTION_LIMIT}
- onToggleFolder={handleToggleFolder}
- onReplaceSelection={handleReplaceSelection}
- />
- ) : (
- <GranolaFolderEmptyState />
- ),
- },
- ]}
- />
- {!isDefined(folders) && !isDefined(loadError) && (
- <StyledSettingsHint>{t('Loading folders…')}</StyledSettingsHint>
- )}
- {isDefined(loadError) && (
- <StyledSettingsError>{loadError}</StyledSettingsError>
- )}
- {hasInaccessibleSelection && (
- <StyledSettingsError>
- {t(
- 'The folders you picked are no longer available. Pick folders again, or switch to Everything.',
- )}
- </StyledSettingsError>
- )}
- {policy === 'SELECTED_FOLDERS' &&
- !hasInaccessibleSelection &&
- hasFolders &&
- selectedFolderIds.length === 0 && (
- <StyledSettingsHint>
- {t('Nothing is picked yet, so every folder still syncs.')}
- </StyledSettingsHint>
- )}
- {policy === 'SELECTED_FOLDERS' && selectedFolderIds.length === 1 && (
- <StyledSettingsHint>
- {t('Switch to Everything to stop filtering by folder.')}
- </StyledSettingsHint>
- )}
- {isSelectionFull && (
- <StyledSettingsHint>
- {t('You can pick up to {limit} folders.', {
- limit: GRANOLA_FOLDER_SELECTION_LIMIT,
- })}
- </StyledSettingsHint>
- )}
- {saveState.kind === 'saving' && (
- <StyledSettingsHint>{t('Saving…')}</StyledSettingsHint>
- )}
- {saveState.kind === 'saved' && (
- <StyledSettingsHint>
- {t('Saved. Live sync and imports now follow this selection.')}
- </StyledSettingsHint>
+ {storedSelectionState.step === 'LOADING' && (
+ <GranolaFolderPolicyRadioCard policy={undefined} />
)}
- {saveState.kind === 'pending' && (
- <StyledSettingsHint>
- {t(
- 'This selection is not applied in Granola yet. It is retried at the next daily catch-up, or change it again to retry now.',
- )}
- </StyledSettingsHint>
+ {storedSelectionState.step === 'LOADED' && (
+ <GranolaFolderPicker {...storedSelectionState.storedSelection} />
)}
- {saveState.kind === 'error' && (
- <StyledSettingsError>{saveState.message}</StyledSettingsError>
+ {storedSelectionState.step === 'FAILED' && (
+ <Info
+ accent="danger"
+ text={t('Could not load your Granola folders.')}
+ buttonTitle={t('Retry')}
+ onClick={loadStoredSelection}
+ />
)}
</StyledSettingsSectionStack>
</Section>
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTree.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTree.tsx
index c5889601cb0..ea7f63c076d 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTree.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTree.tsx
@@ -1,6 +1,7 @@
import styled from '@emotion/styled';
import { useState } from 'react';
import { t } from 'twenty-sdk/front-component';
+import { isDefined } from 'twenty-sdk/utils';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { Label } from 'twenty-ui/typography';
@@ -25,6 +26,7 @@ const StyledLabelContainer = styled.span`
align-items: center;
color: ${() => themeCssVariables.font.color.tertiary};
display: flex;
+ justify-content: space-between;
margin-bottom: ${() => themeCssVariables.spacing[2]};
margin-top: ${() => themeCssVariables.spacing[2]};
`;
@@ -51,6 +53,7 @@ type GranolaFolderTreeProps = {
folders: GranolaSettingsFolder[];
selectedFolderIds: string[];
selectionLimit: number;
+ hint: string | undefined;
onToggleFolder: (folderId: string, checked: boolean) => void;
onReplaceSelection: (folderIds: string[]) => void;
};
@@ -59,6 +62,7 @@ export const GranolaFolderTree = ({
folders,
selectedFolderIds,
selectionLimit,
+ hint,
onToggleFolder,
onReplaceSelection,
}: GranolaFolderTreeProps) => {
@@ -107,6 +111,9 @@ export const GranolaFolderTree = ({
</StyledSearchInputContainer>
<StyledLabelContainer>
<Label>{t('Folders')}</Label>
+ <Label>
+ {selectedFolderIds.length}/{selectionLimit}
+ </Label>
</StyledLabelContainer>
<StyledSectionHeader>
<Label>{t('Toggle all folders')}</Label>
@@ -136,6 +143,7 @@ export const GranolaFolderTree = ({
/>
))}
</StyledTreeList>
+ {isDefined(hint) && <StyledSettingsHint>{hint}</StyledSettingsHint>}
</StyledContainer>
);
};
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeSkeleton.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeSkeleton.tsx
new file mode 100644
index 00000000000..0e005b6b35a
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaFolderTreeSkeleton.tsx
@@ -0,0 +1,39 @@
+import styled from '@emotion/styled';
+import { t } from 'twenty-sdk/front-component';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+import { StyledSkeletonBlock } from 'src/front-components/components/StyledSkeletonBlock';
+
+const FOLDER_ROW_NAME_WIDTHS_PIXELS = [140, 96, 180];
+const CHECKBOX_SKELETON_SIZE_PIXELS = 16;
+
+const StyledList = styled.div`
+ display: flex;
+ flex-direction: column;
+ padding: ${() => themeCssVariables.spacing[2]} 0;
+`;
+
+const StyledRow = styled.div`
+ align-items: center;
+ display: flex;
+ gap: ${() => themeCssVariables.spacing[2]};
+ height: 28px;
+`;
+
+const StyledCheckboxSkeleton = styled(StyledSkeletonBlock)`
+ margin: 5px;
+`;
+
+export const GranolaFolderTreeSkeleton = () => (
+ <StyledList role="status" aria-label={t('Loading')}>
+ {FOLDER_ROW_NAME_WIDTHS_PIXELS.map((nameWidthPixels) => (
+ <StyledRow key={nameWidthPixels}>
+ <StyledCheckboxSkeleton
+ $width={CHECKBOX_SKELETON_SIZE_PIXELS}
+ $height={CHECKBOX_SKELETON_SIZE_PIXELS}
+ />
+ <StyledSkeletonBlock $width={nameWidthPixels} $height={13} />
+ </StyledRow>
+ ))}
+ </StyledList>
+);
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaImportHistorySection.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaImportHistorySection.tsx
index 69c899e4374..92b972b6a53 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaImportHistorySection.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaImportHistorySection.tsx
@@ -1,82 +1,72 @@
import styled from '@emotion/styled';
import { useId, useState } from 'react';
-import { t } from 'twenty-sdk/front-component';
+import { enqueueSnackbar, t } from 'twenty-sdk/front-component';
import { isDefined } from 'twenty-sdk/utils';
+import { IconFileImport } from 'twenty-ui/icon';
import { Button } from 'twenty-ui/input';
import { Section } from 'twenty-ui/layout';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { H2Title } from 'twenty-ui/typography';
import { GRANOLA_BACKFILL_ROUTE_PATH } from 'src/constants/granola-backfill-route-path';
-import { GRANOLA_HISTORY_MAX_IMPORT_DAYS } from 'src/constants/granola-history.constant';
+import {
+ GRANOLA_HISTORY_MAX_IMPORT_DAYS,
+ GRANOLA_INITIAL_IMPORT_DAYS,
+} from 'src/constants/granola-history.constant';
+import { SettingsOptionCardContent } from 'src/front-components/components/SettingsOptionCardContent';
+import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';
import { StyledSettingsError } from 'src/front-components/components/StyledSettingsError';
-import { StyledSettingsHint } from 'src/front-components/components/StyledSettingsHint';
import { StyledSettingsSectionStack } from 'src/front-components/components/StyledSettingsSectionStack';
import { StyledSettingsTextInput } from 'src/front-components/components/StyledSettingsTextInput';
import { DEFAULT_GRANOLA_HISTORY_IMPORT_DAYS } from 'src/front-components/constants/default-granola-history-import-days.constant';
import { parseHistoryImportDays } from 'src/front-components/utils/parse-history-import-days.util';
import { postGranolaSettingsRouteOrThrow } from 'src/front-components/utils/post-granola-settings-route-or-throw.util';
-const StyledRow = styled.form`
- align-items: center;
- display: flex;
- gap: ${() => themeCssVariables.spacing[2]};
-`;
-
const StyledDaysInputContainer = styled.div`
display: flex;
- width: ${() => themeCssVariables.spacing[20]};
+ width: ${() => themeCssVariables.spacing[16]};
`;
-const StyledRowLabel = styled.label`
+const StyledDaysLabel = styled.label`
color: ${() => themeCssVariables.font.color.secondary};
font-family: ${() => themeCssVariables.font.family};
font-size: ${() => themeCssVariables.font.size.md};
`;
-type ImportFeedback = { kind: 'success' | 'error'; message: string };
-
export const GranolaImportHistorySection = () => {
const inputId = useId();
const [daysDraft, setDaysDraft] = useState(
String(DEFAULT_GRANOLA_HISTORY_IMPORT_DAYS),
);
const [isImporting, setIsImporting] = useState(false);
- const [feedback, setFeedback] = useState<ImportFeedback | undefined>(
- undefined,
- );
const days = parseHistoryImportDays(daysDraft);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
- if (!isDefined(days)) {
+ if (!isDefined(days) || isImporting) {
return;
}
setIsImporting(true);
- setFeedback(undefined);
try {
await postGranolaSettingsRouteOrThrow({
routePath: GRANOLA_BACKFILL_ROUTE_PATH,
body: { days },
});
- setFeedback({
- kind: 'success',
+ enqueueSnackbar({
message: t(
'Import started. Notes from the last {days} days will appear in Call Recordings over the next few hours.',
{ days },
),
+ variant: 'success',
});
- } catch (error) {
- setFeedback({
- kind: 'error',
- message:
- error instanceof Error
- ? error.message
- : t('Could not start the import. Try again.'),
+ } catch {
+ enqueueSnackbar({
+ message: t('Could not start the import. Try again.'),
+ variant: 'error',
});
} finally {
setIsImporting(false);
@@ -92,30 +82,38 @@ export const GranolaImportHistorySection = () => {
)}
/>
<StyledSettingsSectionStack>
- <StyledRow onSubmit={handleSubmit}>
- <StyledRowLabel htmlFor={inputId}>
- {t('Import the last')}
- </StyledRowLabel>
- <StyledDaysInputContainer>
- <StyledSettingsTextInput
- id={inputId}
- type="number"
- min={1}
- max={GRANOLA_HISTORY_MAX_IMPORT_DAYS}
- step={1}
- value={daysDraft}
- disabled={isImporting}
- onChange={(event) => setDaysDraft(event.target.value)}
- />
- </StyledDaysInputContainer>
- <StyledRowLabel htmlFor={inputId}>{t('days')}</StyledRowLabel>
- <Button
- type="submit"
- title={t('Import')}
- isLoading={isImporting}
- disabled={isImporting || !isDefined(days)}
- />
- </StyledRow>
+ <form onSubmit={handleSubmit}>
+ <StyledSettingsCard>
+ <SettingsOptionCardContent
+ Icon={IconFileImport}
+ title={t('Import past notes')}
+ description={t('The last {days} days import on connect.', {
+ days: GRANOLA_INITIAL_IMPORT_DAYS,
+ })}
+ >
+ <StyledDaysInputContainer>
+ <StyledSettingsTextInput
+ id={inputId}
+ type="number"
+ min={1}
+ max={GRANOLA_HISTORY_MAX_IMPORT_DAYS}
+ step={1}
+ aria-label={t('Days to import')}
+ value={daysDraft}
+ disabled={isImporting}
+ onChange={(event) => setDaysDraft(event.target.value)}
+ />
+ </StyledDaysInputContainer>
+ <StyledDaysLabel htmlFor={inputId}>{t('days')}</StyledDaysLabel>
+ <Button
+ type="submit"
+ title={t('Import')}
+ isLoading={isImporting}
+ disabled={isImporting || !isDefined(days)}
+ />
+ </SettingsOptionCardContent>
+ </StyledSettingsCard>
+ </form>
{!isDefined(days) && (
<StyledSettingsError>
{t('Enter a whole number of days between 1 and {max}.', {
@@ -123,12 +121,6 @@ export const GranolaImportHistorySection = () => {
})}
</StyledSettingsError>
)}
- {feedback?.kind === 'success' && (
- <StyledSettingsHint>{feedback.message}</StyledSettingsHint>
- )}
- {feedback?.kind === 'error' && (
- <StyledSettingsError>{feedback.message}</StyledSettingsError>
- )}
</StyledSettingsSectionStack>
</Section>
);
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
index 2a0a61d5963..ed60e7b5b4e 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/GranolaSettings.tsx
@@ -3,11 +3,13 @@ import 'twenty-ui/style.css';
import styled from '@emotion/styled';
import { useState } from 'react';
import {
+ enqueueSnackbar,
t,
useColorScheme,
useFrontComponentId,
} from 'twenty-sdk/front-component';
import { isDefined } from 'twenty-sdk/utils';
+import { Info } from 'twenty-ui/feedback';
import { THEME_DARK, THEME_LIGHT } from 'twenty-ui/theme';
import {
ThemeContext,
@@ -15,17 +17,22 @@ import {
type ThemeType,
} from 'twenty-ui/theme-constants';
-import { GranolaFolderSection } from 'src/front-components/components/GranolaFolderSection';
-import { GranolaImportHistorySection } from 'src/front-components/components/GranolaImportHistorySection';
import { GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH } from 'src/constants/granola-webhook-registration-route-path';
import { GRANOLA_WEBHOOK_REMOVAL_ROUTE_PATH } from 'src/constants/granola-webhook-removal-route-path';
+import { GranolaApiKeyForm } from 'src/front-components/components/GranolaApiKeyForm';
+import { GranolaConnectionCard } from 'src/front-components/components/GranolaConnectionCard';
import { GranolaConnectionSection } from 'src/front-components/components/GranolaConnectionSection';
+import { GranolaDangerZoneSection } from 'src/front-components/components/GranolaDangerZoneSection';
+import { GranolaFolderSection } from 'src/front-components/components/GranolaFolderSection';
+import { GranolaImportHistorySection } from 'src/front-components/components/GranolaImportHistorySection';
import { OnMountEffect } from 'src/front-components/components/OnMountEffect';
import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';
+import { computeGranolaConnectionState } from 'src/front-components/utils/compute-granola-connection-state.util';
import { fetchGranolaConnectionStatusOrThrow } from 'src/front-components/utils/fetch-granola-connection-status-or-throw.util';
-import { isGranolaConnectionReady } from 'src/front-components/utils/is-granola-connection-ready.util';
import { postGranolaSettingsRouteOrThrow } from 'src/front-components/utils/post-granola-settings-route-or-throw.util';
+import { readStoredGranolaApiKeyHint } from 'src/front-components/utils/read-stored-granola-api-key-hint.util';
import { setGranolaApiKeyOrThrow } from 'src/front-components/utils/set-granola-api-key-or-throw.util';
+import { storeGranolaApiKeyHint } from 'src/front-components/utils/store-granola-api-key-hint.util';
const StyledContainer = styled.div`
box-sizing: border-box;
@@ -39,13 +46,6 @@ const StyledContainer = styled.div`
}
`;
-const StyledNotice = styled.div`
- color: ${() => themeCssVariables.font.color.tertiary};
- font-family: ${() => themeCssVariables.font.family};
- font-size: ${() => themeCssVariables.font.size.md};
- line-height: ${() => themeCssVariables.text.lineHeight.md};
-`;
-
type GranolaSettingsState =
| { step: 'loading' }
| { step: 'unavailable' }
@@ -53,92 +53,114 @@ type GranolaSettingsState =
const shouldSetUpLiveSync = (status: GranolaConnectionStatus) =>
status.isConnected &&
- status.canManage &&
status.needsRegistration &&
!isDefined(status.registration);
+const fetchGranolaConnectionStatusOrUndefined = async () => {
+ try {
+ return await fetchGranolaConnectionStatusOrThrow();
+ } catch {
+ return undefined;
+ }
+};
+
+const registerGranolaLiveSync = async (): Promise<boolean> => {
+ try {
+ await postGranolaSettingsRouteOrThrow({
+ routePath: GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH,
+ body: {},
+ });
+
+ return true;
+ } catch {
+ return false;
+ }
+};
+
export const GranolaSettings = () => {
const colorScheme = useColorScheme();
const frontComponentId = useFrontComponentId();
const [state, setState] = useState<GranolaSettingsState>({ step: 'loading' });
- const [isConnecting, setIsConnecting] = useState(false);
+ const [isSettingUpConnection, setIsSettingUpConnection] = useState(true);
+ const [hasSetupFailed, setHasSetupFailed] = useState(false);
const [connectError, setConnectError] = useState<string | undefined>();
const [isRemoving, setIsRemoving] = useState(false);
- const [removeError, setRemoveError] = useState<string | undefined>();
- const [isRegistering, setIsRegistering] = useState(false);
- const [registrationError, setRegistrationError] = useState<
- string | undefined
- >();
+ const [isApiKeyExpected] = useState(readStoredGranolaApiKeyHint);
- const refreshConnectionStatus = async () => {
- try {
- const status = await fetchGranolaConnectionStatusOrThrow();
-
- setState({ step: 'ready', status });
+ const showConnectionStatus = (status: GranolaConnectionStatus) => {
+ storeGranolaApiKeyHint(status.isApiKeySet);
+ setState({ step: 'ready', status });
+ };
- return status;
- } catch {
- setRegistrationError(t('Could not connect to Granola. Try again.'));
+ const finishConnectionSetup = ({
+ status,
+ hasRegistrationFailed,
+ }: {
+ status: GranolaConnectionStatus | undefined;
+ hasRegistrationFailed: boolean;
+ }) => {
+ if (isDefined(status)) {
+ showConnectionStatus(status);
+ } else {
setState((current) =>
current.step === 'ready' ? current : { step: 'unavailable' },
);
-
- return undefined;
}
+ setHasSetupFailed(hasRegistrationFailed || !isDefined(status));
+ setIsSettingUpConnection(false);
};
const registerLiveSync = async () => {
- setIsRegistering(true);
- setRegistrationError(undefined);
+ setIsSettingUpConnection(true);
- try {
- await postGranolaSettingsRouteOrThrow({
- routePath: GRANOLA_WEBHOOK_REGISTRATION_ROUTE_PATH,
- body: {},
- });
- } catch {
- setRegistrationError(t('Could not connect to Granola. Try again.'));
- }
+ const isRegistered = await registerGranolaLiveSync();
+ const status = await fetchGranolaConnectionStatusOrUndefined();
- await refreshConnectionStatus();
- setIsRegistering(false);
+ finishConnectionSetup({ status, hasRegistrationFailed: !isRegistered });
};
const loadConnectionStatus = async () => {
- setIsRegistering(true);
- setRegistrationError(undefined);
- const status = await refreshConnectionStatus();
+ setIsSettingUpConnection(true);
+ setState((current) =>
+ current.step === 'ready' ? current : { step: 'loading' },
+ );
+
+ const status = await fetchGranolaConnectionStatusOrUndefined();
if (isDefined(status) && shouldSetUpLiveSync(status)) {
+ showConnectionStatus(status);
await registerLiveSync();
+
+ return;
}
- setIsRegistering(false);
+
+ finishConnectionSetup({ status, hasRegistrationFailed: false });
};
- const handleConnect = async (apiKey: string): Promise<boolean> => {
- setIsConnecting(true);
+ const handleConnect = async (apiKey: string) => {
+ setIsSettingUpConnection(true);
setConnectError(undefined);
try {
await setGranolaApiKeyOrThrow({ frontComponentId, apiKey });
} catch {
setConnectError(t('Could not save the API key. Try again.'));
- setIsConnecting(false);
+ setIsSettingUpConnection(false);
- return false;
+ return;
}
await loadConnectionStatus();
- setIsConnecting(false);
-
- return true;
};
// Deleting the endpoint needs the key that created it, so the webhook goes
// before the variable is cleared.
- const handleRemove = async () => {
+ const handleRemoveApiKey = async () => {
+ if (isRemoving) {
+ return;
+ }
+
setIsRemoving(true);
- setRemoveError(undefined);
try {
await postGranolaSettingsRouteOrThrow({
@@ -147,15 +169,40 @@ export const GranolaSettings = () => {
});
await setGranolaApiKeyOrThrow({ frontComponentId, apiKey: '' });
setConnectError(undefined);
- setRegistrationError(undefined);
+ setHasSetupFailed(false);
} catch {
- setRemoveError(t('Could not remove the API key. Try again.'));
+ enqueueSnackbar({
+ message: t('Could not remove the API key. Try again.'),
+ variant: 'error',
+ });
}
- await refreshConnectionStatus();
+ const status = await fetchGranolaConnectionStatusOrUndefined();
+
+ if (isDefined(status)) {
+ showConnectionStatus(status);
+ }
setIsRemoving(false);
};
+ const status = state.step === 'ready' ? state.status : undefined;
+ const connectionState = isDefined(status)
+ ? computeGranolaConnectionState({
+ status,
+ isConnecting: isSettingUpConnection,
+ hasSetupFailed,
+ })
+ : 'CHECKING';
+ const isConnectionExpected = state.step === 'loading' && isApiKeyExpected;
+ const showsConnectionCard =
+ isConnectionExpected ||
+ (isDefined(status) && (status.isApiKeySet || isSettingUpConnection));
+ const showsLiveSyncSections =
+ isConnectionExpected || connectionState === 'CONNECTED';
+ const showsDangerZone =
+ isConnectionExpected ||
+ (isDefined(status) && status.isApiKeySet && !isSettingUpConnection);
+
// twenty-ui components read icon sizes off ThemeContext, and the context
// default resolves them to var() strings an SVG size attribute cannot use.
return (
@@ -169,44 +216,47 @@ export const GranolaSettings = () => {
>
<StyledContainer>
<OnMountEffect onMount={loadConnectionStatus} />
- {state.step === 'loading' && (
- <StyledNotice>{t('Checking your Granola connection…')}</StyledNotice>
- )}
- {state.step === 'unavailable' && (
- <StyledNotice>
- {t(
- 'Could not load Granola settings. Reload the page to try again.',
- )}
- </StyledNotice>
- )}
- {state.step === 'ready' && (
- <>
- <GranolaConnectionSection
- status={state.status}
- isConnecting={isConnecting || isRegistering}
- isRemoving={isRemoving}
- connectError={connectError ?? registrationError}
- removeError={removeError}
+ <GranolaConnectionSection>
+ {state.step === 'unavailable' && (
+ <Info
+ accent="danger"
+ text={t('Could not load Granola settings.')}
+ buttonTitle={t('Retry')}
+ onClick={loadConnectionStatus}
+ />
+ )}
+ {state.step !== 'unavailable' && !showsConnectionCard && (
+ <GranolaApiKeyForm
+ errorMessage={connectError}
+ isConnectDisabled={!isDefined(status)}
onConnect={handleConnect}
- onRemove={handleRemove}
+ />
+ )}
+ {showsConnectionCard && (
+ <GranolaConnectionCard
+ connectionState={connectionState}
+ isWorkspaceKey={
+ status?.registration?.scopes.includes('workspace') ?? false
+ }
onRetry={
- state.status.isConnected && state.status.canManage
- ? registerLiveSync
- : loadConnectionStatus
+ status?.isConnected ? registerLiveSync : loadConnectionStatus
}
+ onReplaceKey={handleRemoveApiKey}
/>
- {state.status.canManage &&
- isGranolaConnectionReady(state.status) &&
- !isConnecting &&
- !isRegistering &&
- !isDefined(registrationError) && (
- <>
- <GranolaFolderSection />
- <GranolaImportHistorySection />
- </>
- )}
+ )}
+ </GranolaConnectionSection>
+ {showsLiveSyncSections && (
+ <>
+ <GranolaFolderSection />
+ <GranolaImportHistorySection />
</>
)}
+ {showsDangerZone && (
+ <GranolaDangerZoneSection
+ isDisabled={isRemoving || !isDefined(status)}
+ onDisconnect={handleRemoveApiKey}
+ />
+ )}
</StyledContainer>
</ThemeContext.Provider>
);
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/SettingsControlLoader.tsx b/packages/twenty-apps/public/granola/src/front-components/components/SettingsControlLoader.tsx
new file mode 100644
index 00000000000..10aa192ecd2
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/SettingsControlLoader.tsx
@@ -0,0 +1,13 @@
+import { CircularProgressBar } from 'twenty-ui/feedback';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+const CONTROL_LOADER_SIZE_PIXELS = 16;
+const CONTROL_LOADER_BAR_WIDTH_PIXELS = 2;
+
+export const SettingsControlLoader = () => (
+ <CircularProgressBar
+ size={CONTROL_LOADER_SIZE_PIXELS}
+ barWidth={CONTROL_LOADER_BAR_WIDTH_PIXELS}
+ barColor={themeCssVariables.font.color.tertiary}
+ />
+);
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/SettingsRadioCard.tsx b/packages/twenty-apps/public/granola/src/front-components/components/SettingsRadioCard.tsx
index 80387435bf8..12e2008f93e 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/SettingsRadioCard.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/SettingsRadioCard.tsx
@@ -1,30 +1,43 @@
+import { css } from '@emotion/react';
import styled from '@emotion/styled';
import { Fragment, useId } from 'react';
+import { t } from 'twenty-sdk/front-component';
import { isDefined } from 'twenty-sdk/utils';
-import { OverflowingTextWithTooltip } from 'twenty-ui/surfaces';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { Radio } from 'src/front-components/components/Radio';
import { Separator } from 'src/front-components/components/Separator';
-import {
- StyledSettingsCardDescription,
- StyledSettingsCardTextContainer,
- StyledSettingsCardTitle,
-} from 'src/front-components/components/SettingsCardContentBase';
+import { StyledSettingsCardTextContainer } from 'src/front-components/components/SettingsCardContentBase';
+import { SettingsControlLoader } from 'src/front-components/components/SettingsControlLoader';
import { StyledSettingsCard } from 'src/front-components/components/StyledSettingsCard';
-const StyledOptionRow = styled.div<{ $disabled: boolean }>`
+const StyledOptionRow = styled.div<{ $isClickable: boolean }>`
align-items: center;
background-color: ${() => themeCssVariables.background.secondary};
- cursor: ${({ $disabled }) => ($disabled ? 'default' : 'pointer')};
display: flex;
gap: ${() => themeCssVariables.spacing[4]};
padding: ${() => themeCssVariables.spacing[4]};
- pointer-events: ${({ $disabled }) => ($disabled ? 'none' : 'auto')};
- &:hover {
- background: ${() => themeCssVariables.background.transparent.lighter};
- }
+ ${({ $isClickable }) =>
+ $isClickable &&
+ css`
+ cursor: pointer;
+
+ &:hover {
+ background: ${themeCssVariables.background.transparent.lighter};
+ }
+ `}
+`;
+
+const StyledOptionTitle = styled.div`
+ color: ${() => themeCssVariables.font.color.primary};
+ font-weight: ${() => themeCssVariables.font.weight.medium};
+ margin-bottom: ${() => themeCssVariables.spacing[2]};
+`;
+
+const StyledOptionDescription = styled.div`
+ color: ${() => themeCssVariables.font.color.tertiary};
+ font-size: ${() => themeCssVariables.font.size.sm};
`;
const StyledRadioContainer = styled.span`
@@ -34,6 +47,11 @@ const StyledRadioContainer = styled.span`
margin-left: auto;
`;
+const StyledRadioLoaderContainer = styled.span`
+ display: flex;
+ padding: 3px;
+`;
+
const StyledExpandedContent = styled.div`
background-color: ${() => themeCssVariables.background.secondary};
padding: 0 ${() => themeCssVariables.spacing[4]}
@@ -50,21 +68,24 @@ export type SettingsRadioCardOption<TValue extends string> = {
type SettingsRadioCardProps<TValue extends string> = {
options: SettingsRadioCardOption<TValue>[];
- value: TValue;
- disabled?: boolean;
+ value: TValue | undefined;
onChange: (value: TValue) => void;
};
export const SettingsRadioCard = <TValue extends string>({
options,
value,
- disabled = false,
onChange,
}: SettingsRadioCardProps<TValue>) => {
const groupId = useId();
+ const isValueKnown = isDefined(value);
return (
- <StyledSettingsCard role="radiogroup">
+ <StyledSettingsCard
+ role="radiogroup"
+ aria-busy={!isValueKnown}
+ aria-label={isValueKnown ? undefined : t('Loading')}
+ >
{options.map((option, index) => {
const isSelected = option.value === value;
const titleId = `${groupId}-${index}-title`;
@@ -73,26 +94,31 @@ export const SettingsRadioCard = <TValue extends string>({
return (
<Fragment key={option.value}>
<StyledOptionRow
- $disabled={disabled}
- onClick={() => onChange(option.value)}
+ $isClickable={isValueKnown}
+ onClick={isValueKnown ? () => onChange(option.value) : undefined}
>
{option.cardMedia}
<StyledSettingsCardTextContainer>
- <StyledSettingsCardTitle id={titleId}>
+ <StyledOptionTitle id={titleId}>
{option.title}
- </StyledSettingsCardTitle>
- <StyledSettingsCardDescription id={descriptionId}>
- <OverflowingTextWithTooltip text={option.description} />
- </StyledSettingsCardDescription>
+ </StyledOptionTitle>
+ <StyledOptionDescription id={descriptionId}>
+ {option.description}
+ </StyledOptionDescription>
</StyledSettingsCardTextContainer>
<StyledRadioContainer>
- <Radio
- checked={isSelected}
- disabled={disabled}
- aria-labelledby={titleId}
- aria-describedby={descriptionId}
- onSelect={() => onChange(option.value)}
- />
+ {isValueKnown ? (
+ <Radio
+ checked={isSelected}
+ aria-labelledby={titleId}
+ aria-describedby={descriptionId}
+ onSelect={() => onChange(option.value)}
+ />
+ ) : (
+ <StyledRadioLoaderContainer>
+ <SettingsControlLoader />
+ </StyledRadioLoaderContainer>
+ )}
</StyledRadioContainer>
</StyledOptionRow>
{isSelected && isDefined(option.expandedContent) && (
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsTextInput.tsx b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsTextInput.tsx
index 77e5812a237..259ed67f1be 100644
--- a/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsTextInput.tsx
+++ b/packages/twenty-apps/public/granola/src/front-components/components/StyledSettingsTextInput.tsx
@@ -8,4 +8,14 @@ export const StyledSettingsTextInput = styled.input`
height: 32px;
text-overflow: ellipsis;
${getSettingsControlStyles}
+
+ &[type='number']::-webkit-outer-spin-button,
+ &[type='number']::-webkit-inner-spin-button {
+ -webkit-appearance: none;
+ margin: 0;
+ }
+
+ &[type='number'] {
+ -moz-appearance: textfield;
+ }
`;
diff --git a/packages/twenty-apps/public/granola/src/front-components/components/StyledSkeletonBlock.tsx b/packages/twenty-apps/public/granola/src/front-components/components/StyledSkeletonBlock.tsx
new file mode 100644
index 00000000000..3f43929cdf5
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/components/StyledSkeletonBlock.tsx
@@ -0,0 +1,39 @@
+import { keyframes } from '@emotion/react';
+import styled from '@emotion/styled';
+import { isDefined } from 'twenty-sdk/utils';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+const shimmer = keyframes`
+ 100% {
+ transform: translateX(100%);
+ }
+`;
+
+export const StyledSkeletonBlock = styled.div<{
+ $width?: number;
+ $height: number;
+ $isCircle?: boolean;
+}>`
+ background-color: ${() => themeCssVariables.background.tertiary};
+ border-radius: ${({ $isCircle }) =>
+ $isCircle ? '50%' : themeCssVariables.border.radius.sm};
+ flex: ${({ $width }) => (isDefined($width) ? '0 0 auto' : '1')};
+ height: ${({ $height }) => $height}px;
+ overflow: hidden;
+ position: relative;
+ width: ${({ $width }) => (isDefined($width) ? `${$width}px` : 'auto')};
+
+ &::after {
+ animation: ${shimmer} 1.5s ease-in-out infinite;
+ background-image: linear-gradient(
+ 90deg,
+ transparent,
+ ${() => themeCssVariables.background.transparent.lighter},
+ transparent
+ );
+ content: '';
+ inset: 0;
+ position: absolute;
+ transform: translateX(-100%);
+ }
+`;
diff --git a/packages/twenty-apps/public/granola/src/front-components/constants/granola-api-key-hint-storage-key.constant.ts b/packages/twenty-apps/public/granola/src/front-components/constants/granola-api-key-hint-storage-key.constant.ts
new file mode 100644
index 00000000000..94b30123561
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/constants/granola-api-key-hint-storage-key.constant.ts
@@ -0,0 +1 @@
+export const GRANOLA_API_KEY_HINT_STORAGE_KEY = 'granola-is-api-key-set';
diff --git a/packages/twenty-apps/public/granola/src/front-components/hooks/use-autosave-granola-folder-selection.ts b/packages/twenty-apps/public/granola/src/front-components/hooks/use-autosave-granola-folder-selection.ts
index 8827976a29a..62c4ae8eab1 100644
--- a/packages/twenty-apps/public/granola/src/front-components/hooks/use-autosave-granola-folder-selection.ts
+++ b/packages/twenty-apps/public/granola/src/front-components/hooks/use-autosave-granola-folder-selection.ts
@@ -1,25 +1,20 @@
import { useState } from 'react';
-import { t } from 'twenty-sdk/front-component';
import { createSaveQueue } from 'src/front-components/utils/create-save-queue.util';
import { saveGranolaFolderSelectionOrThrow } from 'src/front-components/utils/save-granola-folder-selection-or-throw.util';
type UseAutosaveGranolaFolderSelectionParams = {
- onSaveStart: () => void;
onSaveSuccess: (folderIds: string[]) => void;
- onSaveError: (message: string) => void;
+ onSaveError: () => void;
};
export const useAutosaveGranolaFolderSelection = ({
- onSaveStart,
onSaveSuccess,
onSaveError,
}: UseAutosaveGranolaFolderSelectionParams) => {
const [saveQueue] = useState(() =>
createSaveQueue<string[]>({
saveValue: async (folderIds, isSupersededValue) => {
- onSaveStart();
-
try {
const savedFolderIds =
await saveGranolaFolderSelectionOrThrow(folderIds);
@@ -27,13 +22,9 @@ export const useAutosaveGranolaFolderSelection = ({
if (!isSupersededValue()) {
onSaveSuccess(savedFolderIds);
}
- } catch (error) {
+ } catch {
if (!isSupersededValue()) {
- onSaveError(
- error instanceof Error
- ? error.message
- : t('Could not save the folder selection. Try again.'),
- );
+ onSaveError();
}
}
},
diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-state.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-state.type.ts
new file mode 100644
index 00000000000..6507b06f02b
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-state.type.ts
@@ -0,0 +1,8 @@
+export type GranolaConnectionState =
+ | 'CHECKING'
+ | 'CONNECTING'
+ | 'CONNECTED'
+ | 'INVALID_KEY'
+ | 'UNREACHABLE'
+ | 'PAUSED'
+ | 'SETUP_INCOMPLETE';
diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts
index b647a9408df..27f38239b4f 100644
--- a/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts
+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-connection-status.type.ts
@@ -6,7 +6,6 @@ export const GRANOLA_CONNECTION_STATUS_SCHEMA = z.object({
isConnected: z.boolean(),
isApiKeySet: z.boolean(),
isGranolaReachable: z.boolean().default(true),
- canManage: z.boolean().default(false),
needsRegistration: z.boolean().default(false),
error: z.string().optional(),
registration: z
diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-folder-selection.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-folder-selection.type.ts
new file mode 100644
index 00000000000..b5a99aceea8
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-folder-selection.type.ts
@@ -0,0 +1,8 @@
+import { type GranolaFolderPolicy } from 'src/front-components/types/granola-folder-policy.type';
+
+export type GranolaFolderSelection = {
+ selectedFolderIds: string[];
+ policy: GranolaFolderPolicy;
+ hasInaccessibleSelection: boolean;
+ isSelectionPending: boolean;
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-folders-result.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-folders-result.type.ts
new file mode 100644
index 00000000000..e821dd9042d
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-folders-result.type.ts
@@ -0,0 +1,6 @@
+import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';
+import { type GranolaStoredFolderSelection } from 'src/front-components/types/granola-stored-folder-selection.type';
+
+export type GranolaFoldersResult = GranolaStoredFolderSelection & {
+ folders: GranolaSettingsFolder[];
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/types/granola-stored-folder-selection.type.ts b/packages/twenty-apps/public/granola/src/front-components/types/granola-stored-folder-selection.type.ts
new file mode 100644
index 00000000000..8fd3a33da33
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/types/granola-stored-folder-selection.type.ts
@@ -0,0 +1,4 @@
+export type GranolaStoredFolderSelection = {
+ selectedFolderIds: string[];
+ pendingFolderIds: string[] | undefined;
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-connection-state.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-connection-state.test.ts
new file mode 100644
index 00000000000..258c2f546e7
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-connection-state.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+
+import { GRANOLA_CONNECTION_STATUS_SCHEMA } from 'src/front-components/types/granola-connection-status.type';
+import { computeGranolaConnectionState } from 'src/front-components/utils/compute-granola-connection-state.util';
+
+const READY_STATUS = {
+ isConnected: true,
+ isApiKeySet: true,
+ registration: { scopes: ['workspace'], isActive: true },
+};
+
+describe('computeGranolaConnectionState', () => {
+ it('shows connected for an accepted key with an active registration', () => {
+ expect(
+ computeGranolaConnectionState({
+ status: GRANOLA_CONNECTION_STATUS_SCHEMA.parse(READY_STATUS),
+ isConnecting: false,
+ hasSetupFailed: false,
+ }),
+ ).toBe('CONNECTED');
+ });
+
+ it('shows connecting while the connection is being set up', () => {
+ expect(
+ computeGranolaConnectionState({
+ status: GRANOLA_CONNECTION_STATUS_SCHEMA.parse({
+ isConnected: false,
+ isApiKeySet: false,
+ }),
+ isConnecting: true,
+ hasSetupFailed: true,
+ }),
+ ).toBe('CONNECTING');
+ });
+
+ it.each([
+ {
+ overrides: { isConnected: false, isGranolaReachable: false },
+ expected: 'UNREACHABLE',
+ },
+ { overrides: { isConnected: false }, expected: 'INVALID_KEY' },
+ {
+ overrides: { registration: { scopes: ['workspace'], isActive: false } },
+ expected: 'PAUSED',
+ },
+ {
+ overrides: { registration: undefined, needsRegistration: true },
+ expected: 'SETUP_INCOMPLETE',
+ },
+ { overrides: { error: 'Granola failed' }, expected: 'SETUP_INCOMPLETE' },
+ ])('tells $expected apart from the status', ({ overrides, expected }) => {
+ expect(
+ computeGranolaConnectionState({
+ status: GRANOLA_CONNECTION_STATUS_SCHEMA.parse({
+ ...READY_STATUS,
+ ...overrides,
+ }),
+ isConnecting: false,
+ hasSetupFailed: false,
+ }),
+ ).toBe(expected);
+ });
+
+ it('shows an incomplete setup when the setup request failed', () => {
+ expect(
+ computeGranolaConnectionState({
+ status: GRANOLA_CONNECTION_STATUS_SCHEMA.parse(READY_STATUS),
+ isConnecting: false,
+ hasSetupFailed: true,
+ }),
+ ).toBe('SETUP_INCOMPLETE');
+ });
+});
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-selection.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-selection.test.ts
new file mode 100644
index 00000000000..8017c1ba9e9
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/compute-granola-folder-selection.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import { computeGranolaFolderSelection } from 'src/front-components/utils/compute-granola-folder-selection.util';
+
+describe('computeGranolaFolderSelection', () => {
+ it('syncs everything when no folder is stored', () => {
+ expect(
+ computeGranolaFolderSelection({
+ selectedFolderIds: [],
+ pendingFolderIds: undefined,
+ }),
+ ).toEqual({
+ selectedFolderIds: [],
+ policy: 'ALL_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: false,
+ });
+ });
+
+ it('restores the stored folders', () => {
+ expect(
+ computeGranolaFolderSelection({
+ selectedFolderIds: ['fol_sales', 'fol_support'],
+ pendingFolderIds: undefined,
+ }),
+ ).toEqual({
+ selectedFolderIds: ['fol_sales', 'fol_support'],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: false,
+ });
+ });
+
+ it('prefers a selection that is not applied in Granola yet', () => {
+ expect(
+ computeGranolaFolderSelection({
+ selectedFolderIds: ['fol_sales'],
+ pendingFolderIds: ['fol_support'],
+ }),
+ ).toEqual({
+ selectedFolderIds: ['fol_support'],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: true,
+ });
+ });
+
+ it('marks a pending switch back to everything', () => {
+ expect(
+ computeGranolaFolderSelection({
+ selectedFolderIds: ['fol_sales'],
+ pendingFolderIds: [],
+ }),
+ ).toEqual({
+ selectedFolderIds: [],
+ policy: 'ALL_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: true,
+ });
+ });
+});
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/drop-inaccessible-granola-folders.test.ts b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/drop-inaccessible-granola-folders.test.ts
new file mode 100644
index 00000000000..52c15c53eed
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/__tests__/drop-inaccessible-granola-folders.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+
+import { dropInaccessibleGranolaFolders } from 'src/front-components/utils/drop-inaccessible-granola-folders.util';
+
+const FOLDERS = [{ id: 'fol_sales' }, { id: 'fol_support' }];
+
+describe('dropInaccessibleGranolaFolders', () => {
+ it('keeps the stored folders that are still accessible', () => {
+ expect(
+ dropInaccessibleGranolaFolders({
+ selection: {
+ selectedFolderIds: ['fol_sales', 'fol_removed'],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: false,
+ },
+ folders: FOLDERS,
+ }),
+ ).toEqual({
+ selectedFolderIds: ['fol_sales'],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: false,
+ });
+ });
+
+ it('flags a stored selection whose folders are all gone', () => {
+ expect(
+ dropInaccessibleGranolaFolders({
+ selection: {
+ selectedFolderIds: ['fol_removed'],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: true,
+ },
+ folders: FOLDERS,
+ }),
+ ).toEqual({
+ selectedFolderIds: [],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: true,
+ isSelectionPending: true,
+ });
+ });
+
+ it('leaves an empty selection alone', () => {
+ expect(
+ dropInaccessibleGranolaFolders({
+ selection: {
+ selectedFolderIds: [],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: false,
+ },
+ folders: [],
+ }),
+ ).toEqual({
+ selectedFolderIds: [],
+ policy: 'SELECTED_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: false,
+ });
+ });
+});
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-connection-state.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-connection-state.util.ts
new file mode 100644
index 00000000000..a3c0a2097b2
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-connection-state.util.ts
@@ -0,0 +1,48 @@
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type GranolaConnectionState } from 'src/front-components/types/granola-connection-state.type';
+import { type GranolaConnectionStatus } from 'src/front-components/types/granola-connection-status.type';
+import { isGranolaConnectionReady } from 'src/front-components/utils/is-granola-connection-ready.util';
+
+export const computeGranolaConnectionState = ({
+ status,
+ isConnecting,
+ hasSetupFailed,
+}: {
+ status: Pick<
+ GranolaConnectionStatus,
+ | 'isConnected'
+ | 'isGranolaReachable'
+ | 'needsRegistration'
+ | 'registration'
+ | 'error'
+ >;
+ isConnecting: boolean;
+ hasSetupFailed: boolean;
+}): GranolaConnectionState => {
+ if (isConnecting) {
+ return 'CONNECTING';
+ }
+
+ if (!status.isGranolaReachable) {
+ return 'UNREACHABLE';
+ }
+
+ if (!status.isConnected) {
+ return 'INVALID_KEY';
+ }
+
+ if (hasSetupFailed) {
+ return 'SETUP_INCOMPLETE';
+ }
+
+ if (isGranolaConnectionReady(status)) {
+ return 'CONNECTED';
+ }
+
+ if (isDefined(status.registration) && !status.registration.isActive) {
+ return 'PAUSED';
+ }
+
+ return 'SETUP_INCOMPLETE';
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-selection.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-selection.util.ts
new file mode 100644
index 00000000000..6a995a0f9cd
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/compute-granola-folder-selection.util.ts
@@ -0,0 +1,18 @@
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type GranolaFolderSelection } from 'src/front-components/types/granola-folder-selection.type';
+import { type GranolaStoredFolderSelection } from 'src/front-components/types/granola-stored-folder-selection.type';
+
+export const computeGranolaFolderSelection = ({
+ selectedFolderIds,
+ pendingFolderIds,
+}: GranolaStoredFolderSelection): GranolaFolderSelection => {
+ const storedFolderIds = pendingFolderIds ?? selectedFolderIds;
+
+ return {
+ selectedFolderIds: storedFolderIds,
+ policy: storedFolderIds.length > 0 ? 'SELECTED_FOLDERS' : 'ALL_FOLDERS',
+ hasInaccessibleSelection: false,
+ isSelectionPending: isDefined(pendingFolderIds),
+ };
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/drop-inaccessible-granola-folders.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/drop-inaccessible-granola-folders.util.ts
new file mode 100644
index 00000000000..fcf47e50a0b
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/drop-inaccessible-granola-folders.util.ts
@@ -0,0 +1,23 @@
+import { type GranolaFolderSelection } from 'src/front-components/types/granola-folder-selection.type';
+import { type GranolaSettingsFolder } from 'src/front-components/types/granola-settings-folder.type';
+
+export const dropInaccessibleGranolaFolders = ({
+ selection,
+ folders,
+}: {
+ selection: GranolaFolderSelection;
+ folders: Pick<GranolaSettingsFolder, 'id'>[];
+}): GranolaFolderSelection => {
+ const accessibleFolderIds = new Set(folders.map((folder) => folder.id));
+ const accessibleSelectedFolderIds = selection.selectedFolderIds.filter(
+ (folderId) => accessibleFolderIds.has(folderId),
+ );
+
+ return {
+ ...selection,
+ selectedFolderIds: accessibleSelectedFolderIds,
+ hasInaccessibleSelection:
+ selection.selectedFolderIds.length > 0 &&
+ accessibleSelectedFolderIds.length === 0,
+ };
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folder-selection-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folder-selection-or-throw.util.ts
new file mode 100644
index 00000000000..04aac95d29a
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folder-selection-or-throw.util.ts
@@ -0,0 +1,30 @@
+import { RestApiClient } from 'twenty-client-sdk/rest';
+import { z } from 'zod';
+
+import { GRANOLA_FOLDER_SELECTION_ROUTE_PATH } from 'src/constants/granola-folder-selection-route-path';
+import { type GranolaStoredFolderSelection } from 'src/front-components/types/granola-stored-folder-selection.type';
+
+const FOLDER_SELECTION_RESULT_SCHEMA = z.discriminatedUnion('success', [
+ z.object({
+ success: z.literal(true),
+ folderIds: z.array(z.string()),
+ pendingFolderIds: z.array(z.string()).optional(),
+ }),
+ z.object({ success: z.literal(false), error: z.string() }),
+]);
+
+export const fetchGranolaFolderSelectionOrThrow =
+ async (): Promise<GranolaStoredFolderSelection> => {
+ const result = FOLDER_SELECTION_RESULT_SCHEMA.parse(
+ await new RestApiClient().get(`/s${GRANOLA_FOLDER_SELECTION_ROUTE_PATH}`),
+ );
+
+ if (!result.success) {
+ throw new Error(result.error);
+ }
+
+ return {
+ selectedFolderIds: result.folderIds,
+ pendingFolderIds: result.pendingFolderIds,
+ };
+ };
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folders-or-throw.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folders-or-throw.util.ts
index d37e4ceb5f5..f8dc27269a3 100644
--- a/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folders-or-throw.util.ts
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/fetch-granola-folders-or-throw.util.ts
@@ -2,6 +2,7 @@ import { RestApiClient } from 'twenty-client-sdk/rest';
import { z } from 'zod';
import { GRANOLA_FOLDERS_ROUTE_PATH } from 'src/constants/granola-folders-route-path';
+import { type GranolaFoldersResult } from 'src/front-components/types/granola-folders-result.type';
import { GRANOLA_SETTINGS_FOLDER_SCHEMA } from 'src/front-components/types/granola-settings-folder.type';
const FOLDERS_RESULT_SCHEMA = z.discriminatedUnion('success', [
@@ -14,18 +15,19 @@ const FOLDERS_RESULT_SCHEMA = z.discriminatedUnion('success', [
z.object({ success: z.literal(false), error: z.string() }),
]);
-export const fetchGranolaFoldersOrThrow = async () => {
- const result = FOLDERS_RESULT_SCHEMA.parse(
- await new RestApiClient().get(`/s${GRANOLA_FOLDERS_ROUTE_PATH}`),
- );
+export const fetchGranolaFoldersOrThrow =
+ async (): Promise<GranolaFoldersResult> => {
+ const result = FOLDERS_RESULT_SCHEMA.parse(
+ await new RestApiClient().get(`/s${GRANOLA_FOLDERS_ROUTE_PATH}`),
+ );
- if (!result.success) {
- throw new Error(result.error);
- }
+ if (!result.success) {
+ throw new Error(result.error);
+ }
- return {
- folders: result.folders,
- selectedFolderIds: result.folderIds,
- pendingFolderIds: result.pendingFolderIds,
+ return {
+ folders: result.folders,
+ selectedFolderIds: result.folderIds,
+ pendingFolderIds: result.pendingFolderIds,
+ };
};
-};
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/read-stored-granola-api-key-hint.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/read-stored-granola-api-key-hint.util.ts
new file mode 100644
index 00000000000..ff1ccf40640
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/read-stored-granola-api-key-hint.util.ts
@@ -0,0 +1,9 @@
+import { GRANOLA_API_KEY_HINT_STORAGE_KEY } from 'src/front-components/constants/granola-api-key-hint-storage-key.constant';
+
+export const readStoredGranolaApiKeyHint = (): boolean => {
+ try {
+ return localStorage.getItem(GRANOLA_API_KEY_HINT_STORAGE_KEY) === 'true';
+ } catch {
+ return false;
+ }
+};
diff --git a/packages/twenty-apps/public/granola/src/front-components/utils/store-granola-api-key-hint.util.ts b/packages/twenty-apps/public/granola/src/front-components/utils/store-granola-api-key-hint.util.ts
new file mode 100644
index 00000000000..c1e5ec15a58
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/front-components/utils/store-granola-api-key-hint.util.ts
@@ -0,0 +1,12 @@
+import { GRANOLA_API_KEY_HINT_STORAGE_KEY } from 'src/front-components/constants/granola-api-key-hint-storage-key.constant';
+
+export const storeGranolaApiKeyHint = (isApiKeySet: boolean): void => {
+ try {
+ localStorage.setItem(
+ GRANOLA_API_KEY_HINT_STORAGE_KEY,
+ isApiKeySet ? 'true' : 'false',
+ );
+ } catch {
+ return;
+ }
+};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts
index d649bb31ece..a57866b51d7 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-connection-status.ts
@@ -6,7 +6,6 @@ import { GRANOLA_CONNECTION_STATUS_ROUTE_PATH } from 'src/constants/granola-conn
import { GRANOLA_CONNECTION_STATUS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
import { GranolaApiError } from 'src/logic-functions/types/granola-api-error';
import { createGranolaClientOrThrow } from 'src/logic-functions/utils/create-granola-client-or-throw.util';
-import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';
import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';
import { isGranolaApiKeySet } from 'src/logic-functions/utils/is-granola-api-key-set.util';
@@ -31,7 +30,6 @@ export const granolaConnectionStatusHandler = async () => {
}
throw error;
}
- const canManage = await currentUserCanManageGranolaOrThrow();
try {
const { webhook_endpoints: endpoints } =
await client.listWebhookEndpoints();
@@ -43,14 +41,12 @@ export const granolaConnectionStatusHandler = async () => {
return {
isConnected: true,
isApiKeySet: true,
- canManage,
needsRegistration: true,
};
}
return {
isConnected: true,
isApiKeySet: true,
- canManage,
registration: { scopes: endpoint.scopes, isActive: endpoint.enabled },
};
} catch (error) {
@@ -58,7 +54,6 @@ export const granolaConnectionStatusHandler = async () => {
return {
isConnected: true,
isApiKeySet: true,
- canManage,
needsRegistration: true,
error: error.message,
};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-folder-selection.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-folder-selection.ts
new file mode 100644
index 00000000000..4ea244684cf
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-folder-selection.ts
@@ -0,0 +1,31 @@
+import { defineLogicFunction } from 'twenty-sdk/define';
+
+import { GRANOLA_FOLDER_SELECTION_ROUTE_PATH } from 'src/constants/granola-folder-selection-route-path';
+import { GRANOLA_FOLDER_SELECTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';
+import { readGranolaFolderSelection } from 'src/logic-functions/utils/read-granola-folder-selection.util';
+
+export const granolaFolderSelectionHandler = async () => {
+ if (!(await currentUserCanManageGranolaOrThrow())) {
+ return {
+ success: false,
+ error: 'Application settings permission is required.',
+ };
+ }
+
+ return { success: true, ...(await readGranolaFolderSelection()) };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: GRANOLA_FOLDER_SELECTION_UNIVERSAL_IDENTIFIER,
+ name: 'granola-folder-selection',
+ description:
+ 'Reads the stored Granola folder selection for the settings picker.',
+ timeoutSeconds: 30,
+ handler: granolaFolderSelectionHandler,
+ httpRouteTriggerSettings: {
+ path: GRANOLA_FOLDER_SELECTION_ROUTE_PATH,
+ httpMethod: 'GET',
+ isAuthRequired: true,
+ },
+});
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/granola-folders.ts b/packages/twenty-apps/public/granola/src/logic-functions/granola-folders.ts
index e5097764332..4ba784c87fc 100644
--- a/packages/twenty-apps/public/granola/src/logic-functions/granola-folders.ts
+++ b/packages/twenty-apps/public/granola/src/logic-functions/granola-folders.ts
@@ -1,13 +1,10 @@
import { defineLogicFunction } from 'twenty-sdk/define';
-import { kv } from 'twenty-sdk/logic-function';
import { GRANOLA_FOLDERS_ROUTE_PATH } from 'src/constants/granola-folders-route-path';
-import { GRANOLA_PENDING_FOLDER_SELECTION_KEY } from 'src/constants/granola.constant';
import { GRANOLA_FOLDERS_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
-import { type GranolaPendingFolderSelection } from 'src/logic-functions/types/granola-pending-folder-selection.type';
import { currentUserCanManageGranolaOrThrow } from 'src/logic-functions/utils/current-user-can-manage-granola-or-throw.util';
-import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';
import { listAllGranolaFoldersOrThrow } from 'src/logic-functions/utils/list-all-granola-folders-or-throw.util';
+import { readGranolaFolderSelection } from 'src/logic-functions/utils/read-granola-folder-selection.util';
export const granolaFoldersHandler = async () => {
if (!(await currentUserCanManageGranolaOrThrow())) {
@@ -17,16 +14,10 @@ export const granolaFoldersHandler = async () => {
};
}
- const registration = await findGranolaRegistrationForCurrentKey();
- const pending = await kv.get<GranolaPendingFolderSelection>(
- GRANOLA_PENDING_FOLDER_SELECTION_KEY,
- );
-
return {
success: true,
folders: await listAllGranolaFoldersOrThrow(),
- folderIds: registration?.folderIds ?? [],
- pendingFolderIds: pending?.folderIds,
+ ...(await readGranolaFolderSelection()),
};
};
diff --git a/packages/twenty-apps/public/granola/src/logic-functions/utils/read-granola-folder-selection.util.ts b/packages/twenty-apps/public/granola/src/logic-functions/utils/read-granola-folder-selection.util.ts
new file mode 100644
index 00000000000..b5a0c886924
--- /dev/null
+++ b/packages/twenty-apps/public/granola/src/logic-functions/utils/read-granola-folder-selection.util.ts
@@ -0,0 +1,20 @@
+import { kv } from 'twenty-sdk/logic-function';
+
+import { GRANOLA_PENDING_FOLDER_SELECTION_KEY } from 'src/constants/granola.constant';
+import { type GranolaPendingFolderSelection } from 'src/logic-functions/types/granola-pending-folder-selection.type';
+import { findGranolaRegistrationForCurrentKey } from 'src/logic-functions/utils/find-granola-registration-for-current-key.util';
+
+export const readGranolaFolderSelection = async (): Promise<{
+ folderIds: string[];
+ pendingFolderIds: string[] | undefined;
+}> => {
+ const registration = await findGranolaRegistrationForCurrentKey();
+ const pending = await kv.get<GranolaPendingFolderSelection>(
+ GRANOLA_PENDING_FOLDER_SELECTION_KEY,
+ );
+
+ return {
+ folderIds: registration?.folderIds ?? [],
+ pendingFolderIds: pending?.folderIds,
+ };
+};