The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Show the sender and clearer choices on the unsubscribe page (#28135)
Thomas des Francs6a3d3fb33fd6
diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreview.tsx b/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreview.tsxindex b6b68caff60..9faed111566 100644--- a/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreview.tsx+++ b/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreview.tsx@@ -1,19 +1,23 @@import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';+import { isNonEmptyString } from '@sniptt/guards';import { useUnsubscribeTopics } from '@/activities/emails/hooks/useUnsubscribeTopics';-import { Section } from 'twenty-ui/components/layout';-import {- Button,- Checkbox,- Radio,- RadioGroup,-} from 'twenty-ui/primitives/input';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { SettingsUnsubscribePreviewSender } from '@/settings/unsubscribers/components/SettingsUnsubscribePreviewSender';+import { SettingsUnsubscribePreviewTracking } from '@/settings/unsubscribers/components/SettingsUnsubscribePreviewTracking';+import { getUnsubscribePageHeaderDescription } from '@/settings/unsubscribers/utils/getUnsubscribePageHeaderDescription';import { LabeledDivider } from '@/ui/layout/line/components/LabeledDivider';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { MainButton } from 'twenty-ui/components/input';+import { Section } from 'twenty-ui/components/layout';+import { Checkbox } from 'twenty-ui/primitives/input';import { Card } from 'twenty-ui/primitives/surfaces';import { themeCssVariables } from 'twenty-ui/theme';import { UnsubscribeTopicVisibility } from '~/generated-metadata/graphql';+const PREVIEW_RECIPIENT_EMAIL_ADDRESS = '[email protected]';+const StyledViewport = styled.div`align-items: center;background: ${themeCssVariables.background.secondary};@@ -24,59 +28,56 @@ const StyledViewport = styled.div`padding: ${themeCssVariables.spacing[10]} ${themeCssVariables.spacing[6]};`;-const StyledCard = styled(Card.Root)`- display: flex;- flex-direction: column;- gap: ${themeCssVariables.spacing[5]};+const StyledCardContainer = styled.div`max-width: 420px;- padding: ${themeCssVariables.spacing[8]};+ width: 100%;`;-const StyledHeader = styled(Section.Header)`- align-items: center;- text-align: center;+const StyledCardBody = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[6]};+ padding: ${themeCssVariables.spacing[8]};`;const StyledTopics = styled.div`display: flex;flex-direction: column;- gap: ${themeCssVariables.spacing[3]};`;-const StyledTopicRow = styled.div`+const StyledTopicLabel = styled.label`align-items: center;color: ${themeCssVariables.font.color.primary};+ cursor: pointer;display: flex;- font-size: ${themeCssVariables.font.size.md};- gap: ${themeCssVariables.spacing[2]};+ font-size: ${themeCssVariables.font.size.sm};+ gap: ${themeCssVariables.spacing[1]};`;-const StyledTrackingSection = styled.div`+const StyledActions = styled.div`display: flex;flex-direction: column;- gap: ${themeCssVariables.spacing[2]};- text-align: left;-`;--const StyledTrackingTitle = styled.span`- color: ${themeCssVariables.font.color.primary};- font-weight: ${themeCssVariables.font.weight.medium};-`;--const StyledTrackingHint = styled.span`- color: ${themeCssVariables.font.color.secondary};- font-size: ${themeCssVariables.font.size.sm};+ gap: ${themeCssVariables.spacing[3]};`;export const SettingsUnsubscribePreview = () => {const { t } = useLingui();const { unsubscribeTopics, loading } = useUnsubscribeTopics();+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);const publicTopics = unsubscribeTopics.filter((topic) => topic.visibility === UnsubscribeTopicVisibility.PUBLIC,);+ const workspaceName = currentWorkspace?.displayName;+ const isOpenTrackingEnabled =+ currentWorkspace?.isCampaignOpenTrackingEnabled ?? false;+ const isClickTrackingEnabled =+ currentWorkspace?.isCampaignClickTrackingEnabled ?? false;+const hasPublicTopics = publicTopics.length > 0;+ const isTrackingActive = isOpenTrackingEnabled || isClickTrackingEnabled;+ const hasPreferences = hasPublicTopics || isTrackingActive;return (<Section.Root>@@ -86,63 +87,63 @@ export const SettingsUnsubscribePreview = () => {/><StyledViewport>{!loading && (- <StyledCard- fullWidth- backgroundColor={themeCssVariables.background.primary}- >- <StyledHeader- size="xl"- title={t`Do you want to unsubscribe?`}- description={t`Confirm your preferences:`}- />- {hasPublicTopics && (- <StyledTopics>- {publicTopics.map((topic) => (- <StyledTopicRow key={topic.id}>- <Checkbox- checked- onCheckedChange={() => {}}- aria-label={topic.name ?? t`Untitled topic`}- />- {topic.name ?? t`Untitled topic`}- </StyledTopicRow>- ))}- </StyledTopics>- )}- <StyledTrackingSection>- <StyledTrackingTitle>{t`Email tracking`}</StyledTrackingTitle>- <StyledTrackingHint>- {t`This sender records which links you click in its emails. You can opt out for this email address.`}- </StyledTrackingHint>- <RadioGroup- value="TRACKED"- onValueChange={() => {}}- aria-label={t`Email tracking`}- >- <StyledTopicRow>- <Radio- value="TRACKED"- aria-label={t`Keep tracking my clicks`}+ <StyledCardContainer>+ <Card.Root+ fullWidth+ backgroundColor={themeCssVariables.background.primary}+ >+ <StyledCardBody>+ <div>+ <SettingsUnsubscribePreviewSender+ workspaceName={workspaceName}+ workspaceLogo={currentWorkspace?.logo}+ />+ <Section.Header+ level={3}+ size="lg"+ title={t`Do you want to unsubscribe?`}+ description={getUnsubscribePageHeaderDescription({+ recipientEmailAddress: PREVIEW_RECIPIENT_EMAIL_ADDRESS,+ hasPublicTopics,+ isTrackingActive,+ })}/>- {t`Keep tracking my clicks`}- </StyledTopicRow>- <StyledTopicRow>- <Radio- value="OPTED_OUT"- aria-label={t`Opt out of click tracking`}+ {hasPublicTopics && (+ <StyledTopics>+ {publicTopics.map((topic) => (+ <StyledTopicLabel key={topic.id}>+ <Checkbox defaultChecked />+ {topic.name ?? t`Untitled topic`}+ </StyledTopicLabel>+ ))}+ </StyledTopics>+ )}+ </div>+ {isTrackingActive && (+ <SettingsUnsubscribePreviewTracking+ senderName={+ isNonEmptyString(workspaceName)+ ? workspaceName+ : t`This sender`+ }+ isOpenTrackingEnabled={isOpenTrackingEnabled}+ isClickTrackingEnabled={isClickTrackingEnabled}/>- {t`Opt out of click tracking`}- </StyledTopicRow>- </RadioGroup>- </StyledTrackingSection>- <Button fullWidth variant="solid" color="accent">- {t`Update`}- </Button>- <LabeledDivider noMargin>{t`Or`}</LabeledDivider>- <Button fullWidth variant="outline">- {t`Unsubscribe all`}- </Button>- </StyledCard>+ )}+ {hasPreferences ? (+ <StyledActions>+ <MainButton fullWidth>{t`Update`}</MainButton>+ <LabeledDivider noMargin>{t`Or`}</LabeledDivider>+ <MainButton fullWidth variant="outline" elevated={false}>+ {t`Unsubscribe all`}+ </MainButton>+ </StyledActions>+ ) : (+ <MainButton fullWidth>{t`Unsubscribe`}</MainButton>+ )}+ </StyledCardBody>+ </Card.Root>+ </StyledCardContainer>)}</StyledViewport></Section.Root>diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreviewSender.tsx b/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreviewSender.tsxnew file mode 100644index 00000000000..2a976aea477--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreviewSender.tsx@@ -0,0 +1,45 @@+import { styled } from '@linaria/react';+import { isNonEmptyString } from '@sniptt/guards';++import { getWorkspaceAvatarColorSeed } from '@/workspace/utils/getWorkspaceAvatarColorSeed';+import { Avatar } from 'twenty-ui/primitives/data-display';+import { themeCssVariables } from 'twenty-ui/theme';+import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';++const StyledSender = styled.div`+ align-items: center;+ color: ${themeCssVariables.font.color.primary};+ display: flex;+ font-weight: ${themeCssVariables.font.weight.semiBold};+ gap: ${themeCssVariables.spacing[2]};+ margin-bottom: ${themeCssVariables.spacing[4]};+`;++type SettingsUnsubscribePreviewSenderProps = {+ workspaceName: string | null | undefined;+ workspaceLogo: string | null | undefined;+};++export const SettingsUnsubscribePreviewSender = ({+ workspaceName,+ workspaceLogo,+}: SettingsUnsubscribePreviewSenderProps) => {+ if (!isNonEmptyString(workspaceName) && !isNonEmptyString(workspaceLogo)) {+ return null;+ }++ return (+ <StyledSender>+ {isNonEmptyString(workspaceLogo) && (+ <Avatar+ name={workspaceName ?? ''}+ colorSeed={getWorkspaceAvatarColorSeed(workspaceName)}+ src={getAbsoluteImageUrl(workspaceLogo)}+ shape="square"+ size="lg"+ />+ )}+ {workspaceName}+ </StyledSender>+ );+};diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreviewTracking.tsx b/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreviewTracking.tsxnew file mode 100644index 00000000000..f59f4c872bb--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/components/SettingsUnsubscribePreviewTracking.tsx@@ -0,0 +1,47 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';++import { getUnsubscribePageTrackingCopy } from '@/settings/unsubscribers/utils/getUnsubscribePageTrackingCopy';+import { Section } from 'twenty-ui/components/layout';+import { Radio, RadioGroup } from 'twenty-ui/primitives/input';+import { themeCssVariables } from 'twenty-ui/theme';++const StyledTrackingOptions = styled.div`+ padding-top: ${themeCssVariables.spacing[1]};+`;++type SettingsUnsubscribePreviewTrackingProps = {+ senderName: string;+ isOpenTrackingEnabled: boolean;+ isClickTrackingEnabled: boolean;+};++export const SettingsUnsubscribePreviewTracking = ({+ senderName,+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+}: SettingsUnsubscribePreviewTrackingProps) => {+ const { t } = useLingui();++ const { description, keepLabel } = getUnsubscribePageTrackingCopy({+ senderName,+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+ });++ return (+ <div>+ <Section.Header+ level={4}+ title={t`Email tracking`}+ description={description}+ />+ <StyledTrackingOptions>+ <RadioGroup defaultValue="TRACKED" aria-label={t`Email tracking`}>+ <Radio value="TRACKED">{keepLabel}</Radio>+ <Radio value="OPTED_OUT">{t`Opt out of tracking`}</Radio>+ </RadioGroup>+ </StyledTrackingOptions>+ </div>+ );+};diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/components/__stories__/SettingsUnsubscribePreviewSender.stories.tsx b/packages/twenty-front/src/modules/settings/unsubscribers/components/__stories__/SettingsUnsubscribePreviewSender.stories.tsxnew file mode 100644index 00000000000..e248f706ee5--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/components/__stories__/SettingsUnsubscribePreviewSender.stories.tsx@@ -0,0 +1,57 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, within } from 'storybook/test';++import { SettingsUnsubscribePreviewSender } from '@/settings/unsubscribers/components/SettingsUnsubscribePreviewSender';+import { ComponentDecorator } from 'twenty-ui/testing';++const meta: Meta<typeof SettingsUnsubscribePreviewSender> = {+ title: 'Modules/Settings/Unsubscribers/SettingsUnsubscribePreviewSender',+ component: SettingsUnsubscribePreviewSender,+ decorators: [ComponentDecorator],+ args: {+ workspaceName: 'Apple',+ workspaceLogo: 'https://twenty-icons.com/apple.com',+ },+};++export default meta;+type Story = StoryObj<typeof SettingsUnsubscribePreviewSender>;++export const WithLogo: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText('Apple')).toBeVisible();+ await expect(await canvas.findByAltText('')).toBeVisible();+ },+};++export const NameOnly: Story = {+ args: { workspaceLogo: null },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByText('Apple')).toBeVisible();+ await expect(canvas.queryByAltText('')).not.toBeInTheDocument();+ },+};++export const LogoOnly: Story = {+ args: { workspaceName: null },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(await canvas.findByAltText('')).toBeVisible();+ await expect(canvas.queryByText('Apple')).not.toBeInTheDocument();+ },+};++export const UnknownSender: Story = {+ args: { workspaceName: null, workspaceLogo: null },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.queryByText('Apple')).not.toBeInTheDocument();+ await expect(canvas.queryByAltText('')).not.toBeInTheDocument();+ },+};diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/components/__stories__/SettingsUnsubscribePreviewTracking.stories.tsx b/packages/twenty-front/src/modules/settings/unsubscribers/components/__stories__/SettingsUnsubscribePreviewTracking.stories.tsxnew file mode 100644index 00000000000..26ffcfa48d5--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/components/__stories__/SettingsUnsubscribePreviewTracking.stories.tsx@@ -0,0 +1,70 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, userEvent, within } from 'storybook/test';++import { SettingsUnsubscribePreviewTracking } from '@/settings/unsubscribers/components/SettingsUnsubscribePreviewTracking';+import { ComponentDecorator } from 'twenty-ui/testing';++const meta: Meta<typeof SettingsUnsubscribePreviewTracking> = {+ title: 'Modules/Settings/Unsubscribers/SettingsUnsubscribePreviewTracking',+ component: SettingsUnsubscribePreviewTracking,+ decorators: [ComponentDecorator],+ args: {+ senderName: 'Apple',+ isOpenTrackingEnabled: true,+ isClickTrackingEnabled: true,+ },+};++export default meta;+type Story = StoryObj<typeof SettingsUnsubscribePreviewTracking>;++const checkTrackingChoices = async ({+ canvasElement,+ keepLabel,+}: {+ canvasElement: HTMLElement;+ keepLabel: string;+}) => {+ const canvas = within(canvasElement);+ const keepTracking = canvas.getByRole('radio', { name: keepLabel });+ const optOut = canvas.getByRole('radio', { name: 'Opt out of tracking' });++ await expect(keepTracking).toBeChecked();+ await expect(optOut).not.toBeChecked();+ await userEvent.click(optOut);+ await expect(optOut).toBeChecked();+ await expect(keepTracking).not.toBeChecked();+ keepTracking.focus();+ await userEvent.keyboard(' ');+ await expect(keepTracking).toBeChecked();+ await expect(optOut).not.toBeChecked();+};++export const OpensAndClicks: Story = {+ play: async ({ canvasElement }) => {+ await checkTrackingChoices({+ canvasElement,+ keepLabel: 'Keep tracking my opens and clicks',+ });+ },+};++export const OpensOnly: Story = {+ args: { isClickTrackingEnabled: false },+ play: async ({ canvasElement }) => {+ await checkTrackingChoices({+ canvasElement,+ keepLabel: 'Keep tracking my opens',+ });+ },+};++export const ClicksOnly: Story = {+ args: { isOpenTrackingEnabled: false },+ play: async ({ canvasElement }) => {+ await checkTrackingChoices({+ canvasElement,+ keepLabel: 'Keep tracking my clicks',+ });+ },+};diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/utils/__tests__/getUnsubscribePageHeaderDescription.test.ts b/packages/twenty-front/src/modules/settings/unsubscribers/utils/__tests__/getUnsubscribePageHeaderDescription.test.tsnew file mode 100644index 00000000000..dfd3fcbe44e--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/utils/__tests__/getUnsubscribePageHeaderDescription.test.ts@@ -0,0 +1,37 @@+import { getUnsubscribePageHeaderDescription } from '@/settings/unsubscribers/utils/getUnsubscribePageHeaderDescription';++describe('getUnsubscribePageHeaderDescription', () => {+ it.each([+ {+ hasPublicTopics: true,+ isTrackingActive: true,+ description: 'Uncheck the emails you no longer want at [email protected].',+ },+ {+ hasPublicTopics: true,+ isTrackingActive: false,+ description: 'Uncheck the emails you no longer want at [email protected].',+ },+ {+ hasPublicTopics: false,+ isTrackingActive: true,+ description: 'Email preferences for [email protected]',+ },+ {+ hasPublicTopics: false,+ isTrackingActive: false,+ description: 'You will stop receiving these emails at [email protected].',+ },+ ])(+ 'matches the recipient header with topics: $hasPublicTopics, tracking: $isTrackingActive',+ ({ hasPublicTopics, isTrackingActive, description }) => {+ expect(+ getUnsubscribePageHeaderDescription({+ recipientEmailAddress: '[email protected]',+ hasPublicTopics,+ isTrackingActive,+ }),+ ).toBe(description);+ },+ );+});diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/utils/__tests__/getUnsubscribePageTrackingCopy.test.ts b/packages/twenty-front/src/modules/settings/unsubscribers/utils/__tests__/getUnsubscribePageTrackingCopy.test.tsnew file mode 100644index 00000000000..e3e26ab5dfe--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/utils/__tests__/getUnsubscribePageTrackingCopy.test.ts@@ -0,0 +1,43 @@+import { getUnsubscribePageTrackingCopy } from '@/settings/unsubscribers/utils/getUnsubscribePageTrackingCopy';++describe('getUnsubscribePageTrackingCopy', () => {+ it.each([+ {+ isOpenTrackingEnabled: true,+ isClickTrackingEnabled: true,+ description:+ 'Acme may record when you open its emails and which links you click. You can opt out for this email address.',+ keepLabel: 'Keep tracking my opens and clicks',+ },+ {+ isOpenTrackingEnabled: true,+ isClickTrackingEnabled: false,+ description:+ 'Acme may record when you open its emails. You can opt out for this email address.',+ keepLabel: 'Keep tracking my opens',+ },+ {+ isOpenTrackingEnabled: false,+ isClickTrackingEnabled: true,+ description:+ 'Acme may record which links you click in its emails. You can opt out for this email address.',+ keepLabel: 'Keep tracking my clicks',+ },+ ])(+ 'matches the recipient tracking copy with opens: $isOpenTrackingEnabled, clicks: $isClickTrackingEnabled',+ ({+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+ description,+ keepLabel,+ }) => {+ expect(+ getUnsubscribePageTrackingCopy({+ senderName: 'Acme',+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+ }),+ ).toEqual({ description, keepLabel });+ },+ );+});diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/utils/getUnsubscribePageHeaderDescription.ts b/packages/twenty-front/src/modules/settings/unsubscribers/utils/getUnsubscribePageHeaderDescription.tsnew file mode 100644index 00000000000..62cdabb6b64--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/utils/getUnsubscribePageHeaderDescription.ts@@ -0,0 +1,23 @@+import { t } from '@lingui/core/macro';++type GetUnsubscribePageHeaderDescriptionArgs = {+ recipientEmailAddress: string;+ hasPublicTopics: boolean;+ isTrackingActive: boolean;+};++export const getUnsubscribePageHeaderDescription = ({+ recipientEmailAddress,+ hasPublicTopics,+ isTrackingActive,+}: GetUnsubscribePageHeaderDescriptionArgs): string => {+ if (hasPublicTopics) {+ return t`Uncheck the emails you no longer want at ${recipientEmailAddress}.`;+ }++ if (isTrackingActive) {+ return t`Email preferences for ${recipientEmailAddress}`;+ }++ return t`You will stop receiving these emails at ${recipientEmailAddress}.`;+};diff --git a/packages/twenty-front/src/modules/settings/unsubscribers/utils/getUnsubscribePageTrackingCopy.ts b/packages/twenty-front/src/modules/settings/unsubscribers/utils/getUnsubscribePageTrackingCopy.tsnew file mode 100644index 00000000000..0f930a6c024--- /dev/null+++ b/packages/twenty-front/src/modules/settings/unsubscribers/utils/getUnsubscribePageTrackingCopy.ts@@ -0,0 +1,35 @@+import { t } from '@lingui/core/macro';++type GetUnsubscribePageTrackingCopyArgs = {+ senderName: string;+ isOpenTrackingEnabled: boolean;+ isClickTrackingEnabled: boolean;+};++export const getUnsubscribePageTrackingCopy = ({+ senderName,+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+}: GetUnsubscribePageTrackingCopyArgs): {+ description: string;+ keepLabel: string;+} => {+ if (isOpenTrackingEnabled && isClickTrackingEnabled) {+ return {+ description: t`${senderName} may record when you open its emails and which links you click. You can opt out for this email address.`,+ keepLabel: t`Keep tracking my opens and clicks`,+ };+ }++ if (isOpenTrackingEnabled) {+ return {+ description: t`${senderName} may record when you open its emails. You can opt out for this email address.`,+ keepLabel: t`Keep tracking my opens`,+ };+ }++ return {+ description: t`${senderName} may record which links you click in its emails. You can opt out for this email address.`,+ keepLabel: t`Keep tracking my clicks`,+ };+};diff --git a/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceNewUnsubscribeTopic.tsx b/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceNewUnsubscribeTopic.tsxindex 019ce72a82a..6976a8edcbe 100644--- a/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceNewUnsubscribeTopic.tsx+++ b/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceNewUnsubscribeTopic.tsx@@ -141,6 +141,7 @@ export const SettingsWorkspaceNewUnsubscribeTopic = () => {<SettingsTextInputinstanceId="unsubscribe-topic-description"label={t`Description`}+ placeholder={t`Product news and tips, once a month`}value={description}onChange={setDescription}disabled={loading}diff --git a/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceUnsubscribeTopicDetail.tsx b/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceUnsubscribeTopicDetail.tsxindex 43b69a3c0e8..ce147d934f3 100644--- a/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceUnsubscribeTopicDetail.tsx+++ b/packages/twenty-front/src/pages/settings/communications/SettingsWorkspaceUnsubscribeTopicDetail.tsx@@ -164,6 +164,7 @@ export const SettingsWorkspaceUnsubscribeTopicDetail = () => {<SettingsTextInputinstanceId="unsubscribe-topic-name"label={t`Name`}+ placeholder={t`Newsletters`}value={name}onChange={setName}onBlur={handleNameBlur}@@ -178,6 +179,7 @@ export const SettingsWorkspaceUnsubscribeTopicDetail = () => {<SettingsTextInputinstanceId="unsubscribe-topic-description"label={t`Description`}+ placeholder={t`Product news and tips, once a month`}value={description}onChange={setDescription}onBlur={handleDescriptionBlur}diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-page-sender.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-page-sender.type.tsnew file mode 100644index 00000000000..054076fed38--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-page-sender.type.ts@@ -0,0 +1,4 @@+export type UnsubscribePageSender = {+ name: string | null;+ logoUrl: string | null;+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-page-tracking.type.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-page-tracking.type.tsnew file mode 100644index 00000000000..6be198270c5--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/types/unsubscribe-page-tracking.type.ts@@ -0,0 +1,5 @@+export type UnsubscribePageTracking = {+ isOptedOut: boolean;+ isOpenTrackingEnabled: boolean;+ isClickTrackingEnabled: boolean;+};diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/build-unsubscribe-preferences-page.util.spec.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/build-unsubscribe-preferences-page.util.spec.tsindex 568e08d75fb..b9505517a17 100644--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/build-unsubscribe-preferences-page.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/__tests__/build-unsubscribe-preferences-page.util.spec.ts@@ -1,51 +1,110 @@import { type TopicOptOutState } from 'src/engine/core-modules/emailing-domain/types/topic-opt-out-state.type';+import { type UnsubscribePageSender } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-page-sender.type';+import { type UnsubscribePageTracking } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-page-tracking.type';import { buildUnsubscribePreferencesPage } from 'src/engine/core-modules/emailing-domain/utils/build-unsubscribe-preferences-page.util';-const buildPage = (topics: TopicOptOutState[]) =>+const SENDER: UnsubscribePageSender = {+ name: 'Acme',+ logoUrl: 'https://files.example.com/acme-logo.png',+};++const buildPage = ({+ topics = [],+ tracking,+ sender = SENDER,+ token = 'token-1',+}: {+ topics?: TopicOptOutState[];+ tracking?: UnsubscribePageTracking;+ sender?: UnsubscribePageSender;+ token?: string;+}) =>buildUnsubscribePreferencesPage({- token: 'token-1',+ token,+ sender,+ emailAddress: '[email protected]',topics,- isTrackingOptedOut: undefined,+ tracking,updatePath: '/unsubscribe/update',unsubscribeAllPath: '/unsubscribe/all',});+const TOPICS: TopicOptOutState[] = [+ {+ unsubscribeTopicId: 'topic-1',+ topicName: 'Product updates',+ optedOut: false,+ },+ {+ unsubscribeTopicId: 'topic-2',+ topicName: 'Newsletter',+ optedOut: true,+ },+];+describe('buildUnsubscribePreferencesPage', () => {- describe('when there are no topics', () => {- it('renders a single unsubscribe call to action', () => {- const page = buildPage([]);+ describe('sender', () => {+ it('names the sender and shows its logo', () => {+ const page = buildPage({ topics: TOPICS });++ expect(page).toContain('<span>Acme</span>');+ expect(page).toContain(+ '<img class="logo" src="https://files.example.com/acme-logo.png" alt="" />',+ );+ });++ it('leaves the header out when the sender is unknown', () => {+ const page = buildPage({+ topics: TOPICS,+ sender: { name: null, logoUrl: null },+ });++ expect(page).not.toContain('class="sender"');+ });++ it('escapes the sender name', () => {+ const page = buildPage({+ topics: TOPICS,+ sender: { name: '<script>alert(1)</script>', logoUrl: null },+ });+ expect(page).not.toContain('<script>');+ });+ });++ describe('when there is nothing to choose from', () => {+ it('renders a single unsubscribe call to action for the address', () => {+ const page = buildPage({});++ expect(page).toContain(+ 'You will stop receiving these emails at [email protected].',+ );expect(page).toContain('>Unsubscribe</button>');expect(page).toContain('action="/unsubscribe/all"');expect(page.match(/<button/g)).toHaveLength(1);});it('does not render the preferences form', () => {- const page = buildPage([]);+ const page = buildPage({});expect(page).not.toContain('action="/unsubscribe/update"');expect(page).not.toContain('type="checkbox"');- expect(page).not.toContain('Confirm your preferences:');+ expect(page).not.toContain('Uncheck the emails');expect(page).not.toContain('class="divider"');});});describe('when there are topics', () => {- const topics: TopicOptOutState[] = [- {- unsubscribeTopicId: 'topic-1',- topicName: 'Product updates',- optedOut: false,- },- {- unsubscribeTopicId: 'topic-2',- topicName: 'Newsletter',- optedOut: true,- },- ];+ it('asks the address to uncheck the emails it no longer wants', () => {+ const page = buildPage({ topics: TOPICS });++ expect(page).toContain(+ 'Uncheck the emails you no longer want at [email protected].',+ );+ });it('renders both the update and unsubscribe all calls to action', () => {- const page = buildPage(topics);+ const page = buildPage({ topics: TOPICS });expect(page).toContain('action="/unsubscribe/update"');expect(page).toContain('>Update</button>');@@ -54,61 +113,116 @@ describe('buildUnsubscribePreferencesPage', () => {});it('checks only the topics the recipient is still opted into', () => {- const page = buildPage(topics);+ const page = buildPage({ topics: TOPICS });expect(page).toContain('value="topic-1" checked />Product updates');expect(page).toContain('value="topic-2" />Newsletter');});it('falls back to a placeholder for unnamed topics', () => {- const page = buildPage([- { unsubscribeTopicId: 'topic-3', topicName: null, optedOut: false },- ]);+ const page = buildPage({+ topics: [+ { unsubscribeTopicId: 'topic-3', topicName: null, optedOut: false },+ ],+ });expect(page).toContain('Untitled topic');});});it('escapes the token in every form', () => {- const page = buildUnsubscribePreferencesPage({- token: '"><script>alert(1)</script>',+ const page = buildPage({topics: [{ unsubscribeTopicId: 'topic-1', topicName: 'News', optedOut: false },],- isTrackingOptedOut: undefined,- updatePath: '/unsubscribe/update',- unsubscribeAllPath: '/unsubscribe/all',+ token: '"><script>alert(1)</script>',});expect(page).not.toContain('<script>');});- describe('when the workspace tracks clicks', () => {+ describe('when the workspace tracks engagement', () => {it('offers the tracking choice even without topics', () => {- const page = buildUnsubscribePreferencesPage({- token: 'token-1',- topics: [],- isTrackingOptedOut: false,- updatePath: '/unsubscribe/update',- unsubscribeAllPath: '/unsubscribe/all',+ const page = buildPage({+ tracking: {+ isOptedOut: false,+ isOpenTrackingEnabled: false,+ isClickTrackingEnabled: true,+ },});+ expect(page).toContain('Email preferences for [email protected]');expect(page).toContain('action="/unsubscribe/update"');expect(page).toContain('value="TRACKED" checked />');expect(page).toContain('value="OPTED_OUT" />');});it('preselects the refusal the recipient already made', () => {- const page = buildUnsubscribePreferencesPage({- token: 'token-1',- topics: [],- isTrackingOptedOut: true,- updatePath: '/unsubscribe/update',- unsubscribeAllPath: '/unsubscribe/all',+ const page = buildPage({+ tracking: {+ isOptedOut: true,+ isOpenTrackingEnabled: false,+ isClickTrackingEnabled: true,+ },});expect(page).toContain('value="TRACKED" />');expect(page).toContain('value="OPTED_OUT" checked />');});++ it.each([+ {+ isOpenTrackingEnabled: true,+ isClickTrackingEnabled: true,+ description:+ 'Acme may record when you open its emails and which links you click.',+ keepLabel: 'Keep tracking my opens and clicks',+ },+ {+ isOpenTrackingEnabled: true,+ isClickTrackingEnabled: false,+ description: 'Acme may record when you open its emails.',+ keepLabel: 'Keep tracking my opens',+ },+ {+ isOpenTrackingEnabled: false,+ isClickTrackingEnabled: true,+ description: 'Acme may record which links you click in its emails.',+ keepLabel: 'Keep tracking my clicks',+ },+ ])(+ 'describes only what is tracked (opens: $isOpenTrackingEnabled, clicks: $isClickTrackingEnabled)',+ ({+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+ description,+ keepLabel,+ }) => {+ const page = buildPage({+ tracking: {+ isOptedOut: false,+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+ },+ });++ expect(page).toContain(description);+ expect(page).toContain(`${keepLabel}</label>`);+ expect(page).toContain('Opt out of tracking</label>');+ },+ );++ it('falls back to a generic sender when the workspace has no name', () => {+ const page = buildPage({+ sender: { name: null, logoUrl: null },+ tracking: {+ isOptedOut: false,+ isOpenTrackingEnabled: false,+ isClickTrackingEnabled: true,+ },+ });++ expect(page).toContain('This sender may record');+ });});});diff --git a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-preferences-page.util.ts b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-preferences-page.util.tsindex 17b277d446a..9723b24e325 100644--- a/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-preferences-page.util.ts+++ b/packages/twenty-server/src/engine/core-modules/emailing-domain/utils/build-unsubscribe-preferences-page.util.ts@@ -2,17 +2,39 @@ import { isNonEmptyString } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';import { type TopicOptOutState } from 'src/engine/core-modules/emailing-domain/types/topic-opt-out-state.type';+import { type UnsubscribePageSender } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-page-sender.type';+import { type UnsubscribePageTracking } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-page-tracking.type';import { escapeHtml } from 'src/engine/core-modules/emailing-domain/utils/escape-html.util';type BuildUnsubscribePreferencesPageArgs = {token: string;+ sender: UnsubscribePageSender;+ emailAddress: string;topics: TopicOptOutState[];- isTrackingOptedOut: boolean | undefined;+ tracking: UnsubscribePageTracking | undefined;updatePath: string;unsubscribeAllPath: string;};-const PAGE_STYLE = `body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#fafafa;margin:0;padding:48px 16px;color:#1a1a1a}.card{max-width:420px;margin:0 auto;background:#fff;border:1px solid #ededed;border-radius:16px;padding:40px 32px;text-align:center}h1{font-size:28px;font-weight:700;margin:0 0 8px}.subtitle{color:#888;margin:0 0 28px}.topics{text-align:left;margin:0 0 28px}.topic{display:flex;align-items:center;gap:12px;padding:10px 0;font-size:16px}.topic input{width:18px;height:18px;accent-color:#1a1a1a}.section-title{font-weight:600;margin:0 0 4px}.hint{color:#888;font-size:14px;margin:0 0 8px}button{width:100%;border-radius:10px;padding:14px;font-size:16px;font-weight:600;cursor:pointer;border:1px solid transparent}.primary{background:#1a1a1a;color:#fff}.divider{color:#aaa;margin:16px 0}.secondary{background:#fff;color:#1a1a1a;border:1px solid #ddd}`;+const PAGE_STYLE = `body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#fafafa;margin:0;padding:48px 16px;color:#1a1a1a}.card{max-width:420px;margin:0 auto;background:#fff;border:1px solid #ededed;border-radius:16px;padding:40px 32px;text-align:left}.sender{display:flex;align-items:center;gap:8px;margin:0 0 16px;font-weight:600}.logo{width:24px;height:24px;border-radius:4px;object-fit:cover}h1{font-size:28px;font-weight:700;margin:0 0 8px}.subtitle{color:#888;margin:0 0 28px}.topics{text-align:left;margin:0 0 28px}.topic{display:flex;align-items:center;gap:12px;padding:10px 0;font-size:16px}.topic input{width:18px;height:18px;accent-color:color(display-p3 0.276 0.384 0.837)}.section-title{font-weight:600;margin:0 0 4px}.hint{color:#888;font-size:14px;margin:0 0 8px}button{width:100%;border-radius:10px;padding:14px;font-size:16px;font-weight:600;cursor:pointer;border:1px solid transparent}.primary{background:#1a1a1a;color:#fff}.divider{color:#aaa;margin:16px 0;text-align:center}.secondary{background:#fff;color:#1a1a1a;border:1px solid #ddd}`;++const buildSenderHeader = ({+ name,+ logoUrl,+}: UnsubscribePageSender): string => {+ if (!isNonEmptyString(name) && !isNonEmptyString(logoUrl)) {+ return '';+ }++ const logo = isNonEmptyString(logoUrl)+ ? `<img class="logo" src="${escapeHtml(logoUrl)}" alt="" />`+ : '';+ const label = isNonEmptyString(name)+ ? `<span>${escapeHtml(name)}</span>`+ : '';++ return `<div class="sender">${logo}${label}</div>`;+};const buildTopicCheckbox = (topic: TopicOptOutState): string => {const label = escapeHtml(topic.topicName ?? 'Untitled topic');@@ -25,38 +47,84 @@ const buildTopicCheckbox = (topic: TopicOptOutState): string => {const buildTopicsSection = (topics: TopicOptOutState[]): string =>`<div class="topics">${topics.map(buildTopicCheckbox).join('')}</div>`;-const buildTrackingSection = (isTrackingOptedOut: boolean): string => {- const trackedAttribute = isTrackingOptedOut ? '' : ' checked';- const optedOutAttribute = isTrackingOptedOut ? ' checked' : '';+const getTrackingCopy = ({+ isOpenTrackingEnabled,+ isClickTrackingEnabled,+}: UnsubscribePageTracking): {+ trackedActivityPhrase: string;+ keepLabel: string;+} => {+ if (isOpenTrackingEnabled && isClickTrackingEnabled) {+ return {+ trackedActivityPhrase:+ 'when you open its emails and which links you click',+ keepLabel: 'Keep tracking my opens and clicks',+ };+ }++ if (isOpenTrackingEnabled) {+ return {+ trackedActivityPhrase: 'when you open its emails',+ keepLabel: 'Keep tracking my opens',+ };+ }- return `<div class="topics"><p class="section-title">Email tracking</p><p class="hint">This sender may record when you open its emails and which links you click. You can opt out for this email address.</p><label class="topic"><input type="radio" name="tracking" value="TRACKED"${trackedAttribute} />Keep tracking my opens and clicks</label><label class="topic"><input type="radio" name="tracking" value="OPTED_OUT"${optedOutAttribute} />Opt out of tracking</label></div>`;+ return {+ trackedActivityPhrase: 'which links you click in its emails',+ keepLabel: 'Keep tracking my clicks',+ };+};++const buildTrackingSection = ({+ tracking,+ senderName,+}: {+ tracking: UnsubscribePageTracking;+ senderName: string | null;+}): string => {+ const { trackedActivityPhrase, keepLabel } = getTrackingCopy(tracking);+ const senderLabel = isNonEmptyString(senderName)+ ? escapeHtml(senderName)+ : 'This sender';+ const trackedAttribute = tracking.isOptedOut ? '' : ' checked';+ const optedOutAttribute = tracking.isOptedOut ? ' checked' : '';++ return `<div class="topics"><p class="section-title">Email tracking</p><p class="hint">${senderLabel} may record ${trackedActivityPhrase}. You can opt out for this email address.</p><label class="topic"><input type="radio" name="tracking" value="TRACKED"${trackedAttribute} />${keepLabel}</label><label class="topic"><input type="radio" name="tracking" value="OPTED_OUT"${optedOutAttribute} />Opt out of tracking</label></div>`;};export const buildUnsubscribePreferencesPage = ({token,+ sender,+ emailAddress,topics,- isTrackingOptedOut,+ tracking,updatePath,unsubscribeAllPath,}: BuildUnsubscribePreferencesPageArgs): string => {const safeToken = escapeHtml(token);+ const safeEmailAddress = escapeHtml(emailAddress);const tokenField = `<input type="hidden" name="t" value="${safeToken}" />`;const preferenceSections = [topics.length > 0 ? buildTopicsSection(topics) : '',- isDefined(isTrackingOptedOut)- ? buildTrackingSection(isTrackingOptedOut)+ isDefined(tracking)+ ? buildTrackingSection({ tracking, senderName: sender.name }): '',].filter(isNonEmptyString);+ const preferencesSubtitle =+ topics.length > 0+ ? `Uncheck the emails you no longer want at ${safeEmailAddress}.`+ : `Email preferences for ${safeEmailAddress}`;+// Without anything to pick from, the page collapses to a single// confirmation instead of offering an empty preferences form.const body =preferenceSections.length > 0- ? `<p class="subtitle">Confirm your preferences:</p><form method="post" action="${updatePath}">${tokenField}${preferenceSections.join(+ ? `<p class="subtitle">${preferencesSubtitle}</p><form method="post" action="${updatePath}">${tokenField}${preferenceSections.join('',)}<button type="submit" class="primary">Update</button></form><p class="divider">Or</p><form method="post" action="${unsubscribeAllPath}">${tokenField}<button type="submit" class="secondary">Unsubscribe all</button></form>`- : `<p class="subtitle">You will stop receiving these emails.</p><form method="post" action="${unsubscribeAllPath}">${tokenField}<button type="submit" class="primary">Unsubscribe</button></form>`;+ : `<p class="subtitle">You will stop receiving these emails at ${safeEmailAddress}.</p><form method="post" action="${unsubscribeAllPath}">${tokenField}<button type="submit" class="primary">Unsubscribe</button></form>`;- return `<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Email preferences</title><style>${PAGE_STYLE}</style></head><body><div class="card"><h1>Do you want to unsubscribe?</h1>${body}</div></body></html>`;+ return `<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Email preferences</title><style>${PAGE_STYLE}</style></head><body><div class="card">${buildSenderHeader(sender)}<h1>Do you want to unsubscribe?</h1>${body}</div></body></html>`;};diff --git a/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.ts b/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.tsindex bd051d761a0..09066f9865e 100644--- a/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.ts+++ b/packages/twenty-server/src/modules/emailing/controllers/unsubscribe.controller.ts@@ -29,6 +29,7 @@ import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.seimport { throttlerToRestApiExceptionHandler } from 'src/engine/core-modules/throttler/utils/throttler-to-rest-api-exception-handler.util';import { RecipientPageExceptionFilter } from 'src/modules/emailing/filters/recipient-page-exception.filter';import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';+import { UnsubscribePreferencesService } from 'src/modules/emailing/services/unsubscribe-preferences.service';const UNSUBSCRIBE_TOKEN_FORMAT = /^[A-Za-z0-9_-]{1,1024}$/;@@ -59,6 +60,7 @@ export class UnsubscribeController {private readonly unsubscribeTokenService: UnsubscribeTokenService,private readonly messageSuppressionService: MessageSuppressionService,private readonly throttlerService: ThrottlerService,+ private readonly unsubscribePreferencesService: UnsubscribePreferencesService,) {}private async throttleOrThrow(bucketKey: string): Promise<void> {@@ -120,23 +122,27 @@ export class UnsubscribeController {const { payload, isExpired } = this.verifyTokenOrThrow(token);- const [topics, isTrackingOptedOut] = isExpired- ? [[], undefined]- : await Promise.all([- this.messageSuppressionService.getTopicOptOutState({- workspaceId: payload.workspaceId,- emailAddress: payload.emailAddress,- }),- this.messageSuppressionService.isTrackingOptedOut({- workspaceId: payload.workspaceId,- emailAddress: payload.emailAddress,- }),- ]);+ const recipient = {+ workspaceId: payload.workspaceId,+ emailAddress: payload.emailAddress,+ };++ const [sender, topics, tracking] = await Promise.all([+ this.unsubscribePreferencesService.getSender(payload.workspaceId),+ isExpired+ ? []+ : this.messageSuppressionService.getTopicOptOutState(recipient),+ isExpired+ ? undefined+ : this.unsubscribePreferencesService.getTracking(recipient),+ ]);return buildUnsubscribePreferencesPage({token,+ sender,+ emailAddress: payload.emailAddress,topics,- isTrackingOptedOut,+ tracking,updatePath: UPDATE_PREFERENCES_PATH,unsubscribeAllPath: UNSUBSCRIBE_ALL_PATH,});diff --git a/packages/twenty-server/src/modules/emailing/emailing.module.ts b/packages/twenty-server/src/modules/emailing/emailing.module.tsindex 508f832e8be..bc024cfa449 100644--- a/packages/twenty-server/src/modules/emailing/emailing.module.ts+++ b/packages/twenty-server/src/modules/emailing/emailing.module.ts@@ -16,6 +16,7 @@ import { ClickHouseModule } from 'src/database/clickhouse/clickhouse.module';import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';import { UnsubscribeTopicEntity } from 'src/engine/core-modules/emailing-domain/unsubscribe-topic.entity';import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';+import { FileUrlModule } from 'src/engine/core-modules/file/file-url/file-url.module';import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { MessageChannelMetadataModule } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.module';@@ -61,6 +62,7 @@ import { MessageCampaignService } from 'src/modules/emailing/services/message-caimport { MessageListDuplicationService } from 'src/modules/emailing/services/message-list-duplication.service';import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';import { UnsubscribeTopicService } from 'src/modules/emailing/services/unsubscribe-topic.service';+import { UnsubscribePreferencesService } from 'src/modules/emailing/services/unsubscribe-preferences.service';import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool';@Module({@@ -74,6 +76,7 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'ThrottlerModule,MessageChannelMetadataModule,FeatureFlagModule,+ FileUrlModule,PermissionsModule,UserRoleModule,BillingModule,@@ -107,6 +110,7 @@ import { SaveCampaignTool } from 'src/modules/emailing/tools/save-campaign-tool'MessageCampaignRecoveryService,MessageCampaignStatisticsService,MessageSuppressionService,+ UnsubscribePreferencesService,UnsubscribeTopicService,EmailingDomainSenderService,SaveCampaignTool,diff --git a/packages/twenty-server/src/modules/emailing/services/unsubscribe-preferences.service.ts b/packages/twenty-server/src/modules/emailing/services/unsubscribe-preferences.service.tsnew file mode 100644index 00000000000..d3568485acb--- /dev/null+++ b/packages/twenty-server/src/modules/emailing/services/unsubscribe-preferences.service.ts@@ -0,0 +1,65 @@+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';++import { isDefined } from 'twenty-shared/utils';+import { Repository } from 'typeorm';++import { type UnsubscribePageSender } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-page-sender.type';+import { type UnsubscribePageTracking } from 'src/engine/core-modules/emailing-domain/types/unsubscribe-page-tracking.type';+import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';+import { MessageSuppressionService } from 'src/modules/emailing/services/message-suppression.service';++@Injectable()+export class UnsubscribePreferencesService {+ constructor(+ private readonly messageSuppressionService: MessageSuppressionService,+ private readonly fileUrlService: FileUrlService,+ @InjectRepository(WorkspaceEntity)+ private readonly workspaceRepository: Repository<WorkspaceEntity>,+ ) {}++ async getSender(workspaceId: string): Promise<UnsubscribePageSender> {+ const workspace = await this.workspaceRepository.findOneBy({+ id: workspaceId,+ });++ if (!isDefined(workspace)) {+ return { name: null, logoUrl: null };+ }++ return {+ name: workspace.displayName ?? null,+ logoUrl: await this.fileUrlService.signWorkspaceLogoUrl(workspace),+ };+ }++ async getTracking({+ workspaceId,+ emailAddress,+ }: {+ workspaceId: string;+ emailAddress: string;+ }): Promise<UnsubscribePageTracking | undefined> {+ const workspace = await this.workspaceRepository.findOneBy({+ id: workspaceId,+ });++ if (+ !isDefined(workspace) ||+ (!workspace.isCampaignOpenTrackingEnabled &&+ !workspace.isCampaignClickTrackingEnabled)+ ) {+ return undefined;+ }++ return {+ isOptedOut: await this.messageSuppressionService.isTrackingOptedOut({+ workspaceId,+ emailAddress,+ }),+ isOpenTrackingEnabled: workspace.isCampaignOpenTrackingEnabled,+ isClickTrackingEnabled: workspace.isCampaignClickTrackingEnabled,+ };+ }+}