Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: turn off notification via email#14520

New issue

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

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

Already on GitHub?Sign in to your account

Merged
BrunoQuaresma merged 9 commits intocoder:mainfromjoobisb:email-notification-disable
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletionscoderd/database/queries.sql.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

1 change: 1 addition & 0 deletionscoderd/database/queries/notifications.sql
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
-- name: FetchNewMessageMetadata :one
-- This is used to build up the notification_message's JSON payload.
SELECT nt.name AS notification_name,
nt.id AS notification_template_id,
nt.actions AS actions,
nt.method AS custom_method,
u.id AS user_id,
Expand Down
1 change: 1 addition & 0 deletionscoderd/notifications/dispatch/smtp/html.gotmpl
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,6 +26,7 @@
<div style="border-top: 1px solid #e2e8f0; color: #475569; font-size: 12px; margin-top: 64px; padding-top: 24px; line-height: 1.6;">
<p>&copy;&nbsp;{{ current_year }}&nbsp;Coder. All rights reserved&nbsp;-&nbsp;<a href="{{ base_url }}" style="color: #2563eb; text-decoration: none;">{{ base_url }}</a></p>
<p><a href="{{ base_url }}/settings/notifications" style="color: #2563eb; text-decoration: none;">Click here to manage your notification settings</a></p>
<p><a href="{{ base_url }}/settings/notifications?disabled={{ .NotificationTemplateID }}" style="color: #2563eb; text-decoration: none;">Stop receiving emails like this</a></p>
</div>
</div>
</body>
Expand Down
5 changes: 3 additions & 2 deletionscoderd/notifications/enqueuer.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -121,9 +121,10 @@ func (s *StoreEnqueuer) Enqueue(ctx context.Context, userID, templateID uuid.UUI
// actions which can be taken by the recipient.
func (s *StoreEnqueuer) buildPayload(metadata database.FetchNewMessageMetadataRow, labels map[string]string) (*types.MessagePayload, error) {
payload := types.MessagePayload{
Version: "1.0",
Version: "1.1",

NotificationName: metadata.NotificationName,
NotificationName: metadata.NotificationName,
NotificationTemplateID: metadata.NotificationTemplateID.String(),

UserID: metadata.UserID.String(),
UserEmail: metadata.UserEmail,
Expand Down
9 changes: 9 additions & 0 deletionscoderd/notifications/render/gotmpl_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,6 +56,15 @@ func TestGoTemplate(t *testing.T) {
"url": "https://mocked-server-address/@johndoe/my-workspace"
}]`,
},
{
name: "render notification template ID",
in: `{{ .NotificationTemplateID }}`,
payload: types.MessagePayload{
NotificationTemplateID: "4e19c0ac-94e1-4532-9515-d1801aa283b2",
},
expectedOutput: "4e19c0ac-94e1-4532-9515-d1801aa283b2",
expectedErr: nil,
},
}

for _, tc := range tests {
Expand Down
3 changes: 2 additions & 1 deletioncoderd/notifications/types/payload.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,8 @@ package types
type MessagePayload struct {
Version string `json:"_version"`

NotificationName string `json:"notification_name"`
NotificationName string `json:"notification_name"`
NotificationTemplateID string `json:"notification_template_id"`

UserID string `json:"user_id"`
UserEmail string `json:"user_email"`
Expand Down
19 changes: 19 additions & 0 deletionssite/src/api/queries/notifications.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -136,3 +136,22 @@ export const updateNotificationTemplateMethod = (
UpdateNotificationTemplateMethod
>;
};

export const disableNotification = (
userId: string,
queryClient: QueryClient,
) => {
return {
mutationFn: async (templateId: string) => {
const result = await API.putUserNotificationPreferences(userId, {
template_disabled_map: {
[templateId]: true,
},
});
return result;
},
onSuccess: (data) => {
queryClient.setQueryData(userNotificationPreferencesKey(userId), data);
},
} satisfies UseMutationOptions<NotificationPreference[], unknown, string>;
};
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
import type { Meta, StoryObj } from "@storybook/react";
import { spyOn, userEvent, within } from "@storybook/test";
import {expect,spyOn, userEvent, waitFor, within } from "@storybook/test";
import { API } from "api/api";
import {
notificationDispatchMethodsKey,
systemNotificationTemplatesKey,
userNotificationPreferencesKey,
} from "api/queries/notifications";
import { http, HttpResponse } from "msw";
import { reactRouterParameters } from "storybook-addon-remix-react-router";
import {
MockNotificationMethodsResponse,
MockNotificationPreferences,
Expand All@@ -19,7 +21,7 @@ import {
} from "testHelpers/storybook";
import { NotificationsPage } from "./NotificationsPage";

const meta: Meta<typeof NotificationsPage> = {
const meta = {
title: "pages/UserSettingsPage/NotificationsPage",
component: NotificationsPage,
parameters: {
Expand All@@ -42,7 +44,7 @@ const meta: Meta<typeof NotificationsPage> = {
permissions: { viewDeploymentValues: true },
},
decorators: [withGlobalSnackbar, withAuthProvider, withDashboardProvider],
};
} satisfies Meta<typeof NotificationsPage>;

export default meta;
type Story = StoryObj<typeof NotificationsPage>;
Expand DownExpand Up@@ -76,3 +78,78 @@ export const NonAdmin: Story = {
permissions: { viewDeploymentValues: false },
},
};

// Ensure the selected notification template is enabled before attempting to
// disable it.
const enabledPreference = MockNotificationPreferences.find(
(pref) => pref.disabled === false,
);
if (!enabledPreference) {
throw new Error(
"No enabled notification preference available to test the disabling action.",
);
}
const templateToDisable = MockNotificationTemplates.find(
(tpl) => tpl.id === enabledPreference.id,
);
if (!templateToDisable) {
throw new Error("No notification template matches the enabled preference.");
}

export const DisableValidTemplate: Story = {
parameters: {
reactRouter: reactRouterParameters({
location: {
searchParams: { disabled: templateToDisable.id },
},
}),
},
decorators: [
(Story) => {
// Since the action occurs during the initial render, we need to spy on
// the API call before the story is rendered. This is done using a
// decorator to ensure the spy is set up in time.
spyOn(API, "putUserNotificationPreferences").mockResolvedValue(
MockNotificationPreferences.map((pref) => {
if (pref.id === templateToDisable.id) {
return {
...pref,
disabled: true,
};
}
return pref;
}),
);
return <Story />;
},
],
play: async ({ canvasElement }) => {
await within(document.body).findByText("Notification has been disabled");
const switchEl = await within(canvasElement).findByLabelText(
templateToDisable.name,
);
expect(switchEl).not.toBeChecked();
},
};

export const DisableInvalidTemplate: Story = {
parameters: {
reactRouter: reactRouterParameters({
location: {
searchParams: { disabled: "invalid-template-id" },
},
}),
},
decorators: [
(Story) => {
// Since the action occurs during the initial render, we need to spy on
// the API call before the story is rendered. This is done using a
// decorator to ensure the spy is set up in time.
spyOn(API, "putUserNotificationPreferences").mockRejectedValue({});
return <Story />;
},
],
play: async () => {
await within(document.body).findByText("Error disabling notification");
},
};
View file
Open in desktop
Copy link
Collaborator

Choose a reason for hiding this comment

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

I need to remember to check for the following scenarios:

  1. When a valid template ID is disabled and the request is successful, check if the success message is displayed. Also, ensure that the UI is updated correctly. Verify if the request is being sent properly. Additionally, confirm if the error message is displayed when the request fails.

  2. When a not found template ID is disabled, check if an error message is displayed.

You can check how we do that usingStorybook interaction tests on theNotificationsPage.stories.tsx.

joobisb reacted with thumbs up emoji
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

I have verified these scnearios

Copy link
Contributor

Choose a reason for hiding this comment

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

@joobisb can you add a test please? Manual verification is good but it only helps us know if this works currently, and doesn't catch future degradations.

Copy link
Collaborator

Choose a reason for hiding this comment

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

@joobisb we are close, we just need to automate these tests using the way I shared before. Thanks for your hard work! 🙏

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@BrunoQuaresma the tests needed to be added toNotificationsPage.stories.tsx right ?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

@joobisb we are close, we just need to automate these tests using the way I shared before. Thanks for your hard work! 🙏

done, please have a look

Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import ListItemText, { listItemTextClasses } from "@mui/material/ListItemText";
import Switch from "@mui/material/Switch";
import Tooltip from "@mui/material/Tooltip";
import {
disableNotification,
notificationDispatchMethods,
selectTemplatesByGroup,
systemNotificationTemplates,
Expand All@@ -18,7 +19,7 @@ import type {
NotificationPreference,
NotificationTemplate,
} from "api/typesGenerated";
import { displaySuccess } from "components/GlobalSnackbar/utils";
import {displayError,displaySuccess } from "components/GlobalSnackbar/utils";
import { Loader } from "components/Loader/Loader";
import { Stack } from "components/Stack/Stack";
import { useAuthenticated } from "contexts/auth/RequireAuth";
Expand All@@ -28,8 +29,10 @@ import {
methodLabels,
} from "modules/notifications/utils";
import { type FC, Fragment } from "react";
import { useEffect } from "react";
import { Helmet } from "react-helmet-async";
import { useMutation, useQueries, useQueryClient } from "react-query";
import { useSearchParams } from "react-router-dom";
import { pageTitle } from "utils/page";
import { Section } from "../Section";

Expand DownExpand Up@@ -60,6 +63,30 @@ export const NotificationsPage: FC = () => {
const updatePreferences = useMutation(
updateUserNotificationPreferences(user.id, queryClient),
);

// Notification emails contain a link to disable a specific notification
// template. This functionality is achieved using the query string parameter
// "disabled".
const disableMutation = useMutation(
disableNotification(user.id, queryClient),
);
const [searchParams] = useSearchParams();
const disabledId = searchParams.get("disabled");
useEffect(() => {
if (!disabledId) {
return;
}
searchParams.delete("disabled");
disableMutation
.mutateAsync(disabledId)
.then(() => {
displaySuccess("Notification has been disabled");
})
.catch(() => {
displayError("Error disabling notification");
});
}, [searchParams.delete, disabledId, disableMutation]);

const ready =
disabledPreferences.data && templatesByGroup.data && dispatchMethods.data;

Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp