Skip to content

The open alternative to Salesforce, designed for AI.

7.2 KB
Raw Blame
import { useUnsubscribeTopics } from '@/activities/emails/hooks/useUnsubscribeTopics';
import { SettingsOptionCardContentSwitch } from '@/settings/components/SettingsOptions/SettingsOptionCardContentSwitch';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { SettingsSkeletonLoader } from '@/settings/components/SettingsSkeletonLoader';
import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';
import { useDeleteUnsubscribeTopic } from '@/settings/unsubscribe-topics/hooks/useDeleteUnsubscribeTopic';
import { useUpdateUnsubscribeTopic } from '@/settings/unsubscribe-topics/hooks/useUpdateUnsubscribeTopic';
import { SETTINGS_UNSUBSCRIBE_TAB_IDS } from '@/settings/unsubscribers/constants/SettingsUnsubscribeTabIds';
import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
import { ConfirmationDialog } from '@/ui/layout/dialog/components/ConfirmationDialog';
import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';
import { useLingui } from '@lingui/react/macro';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { SettingsPath } from 'twenty-shared/types';
import { getSettingsPath, isDefined } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import { Section } from 'twenty-ui/components/layout';
import { IconEye, IconTrash } from 'twenty-ui/icon';
import { Button } from 'twenty-ui/primitives/input';
import { Card } from 'twenty-ui/primitives/surfaces';
import { UnsubscribeTopicVisibility } from '~/generated-metadata/graphql';
import { useNavigateSettings } from '~/hooks/useNavigateSettings';
import { NotFound } from '~/pages/not-found/NotFound';

const DELETE_UNSUBSCRIBE_TOPIC_MODAL_ID = 'delete-unsubscribe-topic-modal';

export const SettingsWorkspaceUnsubscribeTopicDetail = () => {
  const { t } = useLingui();
  const navigateSettings = useNavigateSettings();
  const { unsubscribeTopicId } = useParams<{ unsubscribeTopicId: string }>();
  const { unsubscribeTopics, loading } = useUnsubscribeTopics();
  const { openDialog } = useDialog();
  const { enqueueToast } = useToast();
  const { updateUnsubscribeTopic } = useUpdateUnsubscribeTopic();
  const { deleteUnsubscribeTopic, loading: deleting } =
    useDeleteUnsubscribeTopic();

  const unsubscribeTopic = unsubscribeTopics.find(
    (topic) => topic.id === unsubscribeTopicId,
  );

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [seededTopicId, setSeededTopicId] = useState<string | null>(null);

  useEffect(() => {
    if (isDefined(unsubscribeTopic) && seededTopicId !== unsubscribeTopic.id) {
      setSeededTopicId(unsubscribeTopic.id);
      setName(unsubscribeTopic.name ?? '');
      setDescription(unsubscribeTopic.description ?? '');
    }
  }, [unsubscribeTopic, seededTopicId]);

  if (loading) {
    return <SettingsSkeletonLoader />;
  }

  if (!isDefined(unsubscribeTopic)) {
    return <NotFound />;
  }

  const isPublic =
    unsubscribeTopic.visibility === UnsubscribeTopicVisibility.PUBLIC;

  const persist = async (
    input: Parameters<typeof updateUnsubscribeTopic>[0],
  ) => {
    try {
      await updateUnsubscribeTopic(input);
    } catch {
      enqueueToast({
        status: 'error',
        children: t`Failed to update unsubscribe topic.`,
      });
    }
  };

  const handleNameBlur = () => {
    if (name !== (unsubscribeTopic.name ?? '')) {
      persist({ id: unsubscribeTopic.id, name });
    }
  };

  const handleDescriptionBlur = () => {
    if (description !== (unsubscribeTopic.description ?? '')) {
      persist({ id: unsubscribeTopic.id, description: description || null });
    }
  };

  const handleVisibilityChange = (checked: boolean) => {
    persist({
      id: unsubscribeTopic.id,
      visibility: checked
        ? UnsubscribeTopicVisibility.PUBLIC
        : UnsubscribeTopicVisibility.PRIVATE,
    });
  };

  const handleDelete = async () => {
    try {
      await deleteUnsubscribeTopic(unsubscribeTopic.id);
      navigateSettings(
        SettingsPath.Unsubscribe,
        undefined,
        undefined,
        undefined,
        SETTINGS_UNSUBSCRIBE_TAB_IDS.TOPICS,
      );
    } catch {
      enqueueToast({
        status: 'error',
        children: t`Failed to delete unsubscribe topic.`,
      });
    }
  };

  const topicName = unsubscribeTopic.name ?? t`Untitled topic`;

  return (
    <SettingsPageLayout
      title={topicName}
      links={[
        {
          children: t`Workspace`,
          href: getSettingsPath(SettingsPath.General),
        },
        {
          children: t`Communication`,
          href: getSettingsPath(SettingsPath.WorkspaceCommunications),
        },
        {
          children: t`Unsubscribe`,
          href: getSettingsPath(
            SettingsPath.Unsubscribe,
            undefined,
            undefined,
            SETTINGS_UNSUBSCRIBE_TAB_IDS.TOPICS,
          ),
        },
        { children: topicName },
      ]}
      actionButton={
        <Button
          startIcon={<IconTrash />}
          size="sm"
          disabled={deleting}
          onClick={() => openDialog(DELETE_UNSUBSCRIBE_TOPIC_MODAL_ID)}
          variant="outline"
          color="danger"
        >{t`Delete`}</Button>
      }
    >
      <SettingsPageContainer>
        <Section.Root>
          <Section.Header
            title={t`Name`}
            description={t`The name recipients see for this topic.`}
          />
          <SettingsTextInput
            instanceId="unsubscribe-topic-name"
            label={t`Name`}
            placeholder={t`Newsletters`}
            value={name}
            onChange={setName}
            onBlur={handleNameBlur}
            fullWidth
          />
        </Section.Root>
        <Section.Root>
          <Section.Header
            title={t`Description`}
            description={t`Optional context shown to recipients on the preferences page.`}
          />
          <SettingsTextInput
            instanceId="unsubscribe-topic-description"
            label={t`Description`}
            placeholder={t`Product news and tips, once a month`}
            value={description}
            onChange={setDescription}
            onBlur={handleDescriptionBlur}
            fullWidth
          />
        </Section.Root>
        <Section.Root>
          <Section.Header
            title={t`Visibility`}
            description={t`Control whether recipients can find and manage this topic.`}
          />
          <Card.Root>
            <SettingsOptionCardContentSwitch
              Icon={IconEye}
              title={t`Listed on the unsubscribe page`}
              description={t`Public topics appear on the recipient preferences page.`}
              checked={isPublic}
              onChange={handleVisibilityChange}
            />
          </Card.Root>
        </Section.Root>
      </SettingsPageContainer>
      <ConfirmationDialog
        dialogId={DELETE_UNSUBSCRIBE_TOPIC_MODAL_ID}
        title={t`Delete unsubscribe topic`}
        subtitle={t`Are you sure you want to delete ${topicName}? Recipients will no longer be able to opt out of this category.`}
        onConfirmClick={handleDelete}
        confirmButtonText={t`Delete`}
        confirmButtonColor="danger"
        loading={deleting}
      />
    </SettingsPageLayout>
  );
};