Skip to content

fix(site): only show method warning if some template is using it #14565

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Extract notification events to its own component
  • Loading branch information
BrunoQuaresma committed Sep 4, 2024
commit f58660ef0adc4749bf76278f2887d21311727276
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import type { Meta, StoryObj } from "@storybook/react";
import { spyOn, userEvent, within } from "@storybook/test";
import { API } from "api/api";
import type { DeploymentValues } from "api/typesGenerated";
import { baseMeta } from "./storybookUtils";
import { NotificationEvents } from "./NotificationEvents";

const meta: Meta<typeof NotificationEvents> = {
title: "pages/DeploymentSettings/NotificationsPage/NotificationEvents",
component: NotificationEvents,
...baseMeta,
};

export default meta;

type Story = StoryObj<typeof NotificationEvents>;

export const NoEmailSmarthost: Story = {
parameters: {
deploymentValues: {
notifications: {
webhook: {
endpoint: "https://example.com",
},
email: {
smarthost: "",
},
},
} as DeploymentValues,
},
};

export const NoWebhookEndpoint: Story = {
parameters: {
deploymentValues: {
notifications: {
webhook: {
endpoint: "",
},
email: {
smarthost: "smtp.example.com",
},
},
} as DeploymentValues,
},
};

export const Toggle: Story = {
play: async ({ canvasElement }) => {
spyOn(API, "updateNotificationTemplateMethod").mockResolvedValue();
const user = userEvent.setup();
const canvas = within(canvasElement);
const option = await canvas.findByText("Workspace Marked as Dormant");
Copy link
Contributor

Choose a reason for hiding this comment

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

I wonder if we should include the template ID as a data attribute and select on that? It'll be more stable than the name.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

In this case, it doesn't matter too much since we control the data. I prefer to use the name in UI tests to match the user behavior.

Copy link
Contributor

Choose a reason for hiding this comment

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

We control it, yes, but we may rename this template, which will cause this test to fail mysteriously.
IDs will likely never be changed, so it's more resilient.

Copy link
Collaborator Author

@BrunoQuaresma BrunoQuaresma Sep 5, 2024

Choose a reason for hiding this comment

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

This test won't fail if we rename the template because we're using mocked data. It's not an end-to-end test. I understand that using IDs makes the test more resilient, but this is a UI test in a controlled context, so I think we should test it as the user would. However, if you strongly prefer using IDs, we can switch to that approach and start a discussion with the front-end guild to establish it as a convention, since the community uses a different method. The goal is to test the UI as the user would.

Copy link
Contributor

Choose a reason for hiding this comment

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

Right, but when you implement what we discussed in https://github.com/coder/coder/pull/14565/files#r1745353934 then it will go out of sync, and this is an entirely preventable problem.
I'm not part of the front-end guild so it's up to you.

const li = option.closest("li");
if(!li) {
throw new Error("Could not find li");
}
const toggleButton = within(li).getByRole("button", {
name: "Webhook",
});
await user.click(toggleButton);
},
};

Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
import type { Interpolation, Theme } from "@emotion/react";
import Button from "@mui/material/Button";
import Card from "@mui/material/Card";
import Divider from "@mui/material/Divider";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemText, { listItemTextClasses } from "@mui/material/ListItemText";
import ToggleButton from "@mui/material/ToggleButton";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import Tooltip from "@mui/material/Tooltip";
import {
updateNotificationTemplateMethod,
type selectTemplatesByGroup,
} from "api/queries/notifications";
import type { DeploymentValues } from "api/typesGenerated";
import { Alert } from "components/Alert/Alert";
import { displaySuccess } from "components/GlobalSnackbar/utils";
import { Stack } from "components/Stack/Stack";
import {
type NotificationMethod,
castNotificationMethod,
methodIcons,
methodLabels,
} from "modules/notifications/utils";
import { type FC, Fragment } from "react";
import { useMutation, useQueryClient } from "react-query";
import { docs } from "utils/docs";

type NotificationEventsProps = {
defaultMethod: NotificationMethod;
availableMethods: NotificationMethod[];
templatesByGroup: ReturnType<typeof selectTemplatesByGroup>;
deploymentValues: DeploymentValues;
};

export const NotificationEvents: FC<NotificationEventsProps> = ({
defaultMethod,
availableMethods,
templatesByGroup,
deploymentValues,
}) => {
return (
<Stack spacing={4}>
{availableMethods.includes("smtp") &&
deploymentValues.notifications?.webhook.endpoint === "" && (
<Alert
severity="warning"
actions={
<Button
variant="text"
size="small"
component="a"
target="_blank"
rel="noreferrer"
href={docs("/cli/server#--notifications-webhook-endpoint")}
>
Read the docs
</Button>
}
>
Webhook notifications are enabled, but no endpoint has been
configured.
</Alert>
)}

{availableMethods.includes("smtp") &&
deploymentValues.notifications?.email.smarthost === "" && (
<Alert
severity="warning"
actions={
<Button
variant="text"
size="small"
component="a"
target="_blank"
rel="noreferrer"
href={docs("/cli/server#--notifications-email-smarthost")}
>
Read the docs
</Button>
}
>
SMTP notifications are enabled, but no smarthost has been
configured.
</Alert>
)}

{Object.entries(templatesByGroup).map(([group, templates]) => (
<Card
key={group}
variant="outlined"
css={{ background: "transparent", width: "100%" }}
>
<List>
<ListItem css={styles.listHeader}>
<ListItemText css={styles.listItemText} primary={group} />
</ListItem>

{templates.map((tpl, i) => {
const value = castNotificationMethod(tpl.method || defaultMethod);
const isLastItem = i === templates.length - 1;

return (
<Fragment key={tpl.id}>
<ListItem>
<ListItemText
css={styles.listItemText}
primary={tpl.name}
/>
<MethodToggleGroup
templateId={tpl.id}
options={availableMethods}
value={value}
/>
</ListItem>
{!isLastItem && <Divider />}
</Fragment>
);
})}
</List>
</Card>
))}
</Stack>
);
};

type MethodToggleGroupProps = {
templateId: string;
options: NotificationMethod[];
value: NotificationMethod;
};

const MethodToggleGroup: FC<MethodToggleGroupProps> = ({
value,
options,
templateId,
}) => {
const queryClient = useQueryClient();
const updateMethodMutation = useMutation(
updateNotificationTemplateMethod(templateId, queryClient),
);

return (
<ToggleButtonGroup
exclusive
value={value}
size="small"
aria-label="Notification method"
css={styles.toggleGroup}
onChange={async (_, method) => {
await updateMethodMutation.mutateAsync({
method,
});
displaySuccess("Notification method updated");
}}
>
{options.map((method) => {
const Icon = methodIcons[method];
const label = methodLabels[method];
return (
<Tooltip key={method} title={label}>
<ToggleButton
value={method}
css={styles.toggleButton}
onClick={(e) => {
// Retain the value if the user clicks the same button, ensuring
// at least one value remains selected.
if (method === value) {
e.preventDefault();
e.stopPropagation();
return;
}
}}
>
<Icon aria-label={label} />
</ToggleButton>
</Tooltip>
);
})}
</ToggleButtonGroup>
);
};

const styles = {
listHeader: (theme) => ({
background: theme.palette.background.paper,
borderBottom: `1px solid ${theme.palette.divider}`,
}),
listItemText: {
[`& .${listItemTextClasses.primary}`]: {
fontSize: 14,
fontWeight: 500,
},
[`& .${listItemTextClasses.secondary}`]: {
fontSize: 14,
},
},
toggleGroup: (theme) => ({
border: `1px solid ${theme.palette.divider}`,
borderRadius: 4,
}),
toggleButton: (theme) => ({
border: 0,
borderRadius: 4,
fontSize: 16,
padding: "4px 8px",
color: theme.palette.text.disabled,

"&:hover": {
color: theme.palette.text.primary,
},

"& svg": {
fontSize: "inherit",
},
}),
} as Record<string, Interpolation<Theme>>;
Loading