The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GDGT-1668: Migrate notifications to TypeScript (#69104)
Stas Gavrylov9529117f1ed1
diff --git a/CLAUDE.md b/CLAUDE.mdindex 479ab0046ee..11defa25357 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -23,6 +23,8 @@ For detailed guidance on writing and reviewing code and documentation, see the s- **[analytics-events](.claude/skills/analytics-events/SKILL.md)** - Add product analytics events to track user interactions+**Important**: When working with frontend code, read [frontend/CLAUDE.md](frontend/CLAUDE.md) for project-specific guidelines on component preferences, styling, TypeScript migration, testing requirements, and available scripts.+## Tool PreferencesIf `clojure-mcp` tools are available, prefer them over shell-based alternatives for Clojure development.diff --git a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsx b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsxindex 53cb175c606..8d9bfd7f43b 100644--- a/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/advanced_permissions/components/ImpersonationModal/ImpersonationModal.tsx@@ -1,3 +1,4 @@+import type { Location } from "history";import { useCallback } from "react";import { withRouter } from "react-router";import { push } from "react-router-redux";@@ -30,6 +31,7 @@ import { ImpersonationModalView } from "./ImpersonationModalView";interface ImpersonationModalProps {params: ImpersonationModalParams;+ location: Location;route: {path: string;};@@ -48,6 +50,7 @@ const parseParams = (params: ImpersonationModalParams): ImpersonationParams => {const ImpersonationModalInner = ({route,params,+ location,}: ImpersonationModalProps) => {const [{@@ -90,7 +93,7 @@ const ImpersonationModalInner = ({const close = useCallback(() => {dispatch(push(getParentPath(route, location)));- }, [dispatch, route]);+ }, [dispatch, route, location]);const handleSave = useCallback((attribute: UserAttributeKey) => {@@ -123,7 +126,7 @@ const ImpersonationModalInner = ({const handleCancel = useCallback(() => {dispatch(push(getParentPath(route, location)));- }, [dispatch, route]);+ }, [dispatch, route, location]);useMount(() => {dispatch(fetchUserAttributes());diff --git a/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionModal.tsx b/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionModal.tsxindex 1ea65794c39..dac2dbb1463 100644--- a/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/clean_up/CleanupCollectionModal/CleanupCollectionModal.tsx@@ -1,5 +1,5 @@+import type { Location } from "history";import { useEffect, useMemo, useState } from "react";-import { withRouter } from "react-router";import { t } from "ttag";import { skipToken } from "metabase/api";@@ -36,15 +36,16 @@ import {interface CleanupCollectionModalProps {onClose: () => void;- params: { slug: string };+ params: { slug?: string };+ location: Location;}-const CleanupCollectionModalInner = ({+export const CleanupCollectionModal = ({onClose: handleClose,- params: { slug },+ params,}: CleanupCollectionModalProps) => {const dispatch = useDispatch();- const collectionId = Urls.extractCollectionId(slug);+ const collectionId = Urls.extractCollectionId(params.slug ?? "");// selectionconst selection = useListSelect(itemKeyFn);@@ -223,5 +224,3 @@ const CleanupCollectionModalInner = ({</Modal.Root>);};--export const CleanupCollectionModal = withRouter(CleanupCollectionModalInner);diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsxindex 7d6d01acf7b..4fe65742647 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/containers/EditSandboxingModal.tsx@@ -1,3 +1,4 @@+import type { Location } from "history";import { useEffect } from "react";import { withRouter } from "react-router";import { push } from "react-router-redux";@@ -31,6 +32,7 @@ interface EditSandboxingModalContainerProps {attributes: UserAttributeKey[];push: (path: string) => void;params: GroupTableAccessPolicyParams;+ location: Location;route: any;policyRequestState: any;fetchPolicy: (params: GroupTableAccessPolicyParams) => void;@@ -45,6 +47,7 @@ const EditSandboxingModalContainer = ({policy,push,params,+ location,route,fetchPolicy,fetchUserAttributes,diff --git a/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsx b/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsxindex 1f4b5c33807..fb2b94c2a82 100644--- a/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsx@@ -14,12 +14,8 @@ import {PULSE_PARAM_USE_DEFAULT,getDefaultValuePopulatedParameters,} from "metabase-lib/v1/parameters/utils/parameter-values";-import type {- Dashboard,- DashboardSubscription,- Parameter,- ParameterId,-} from "metabase-types/api";+import type { Dashboard, Parameter, ParameterId } from "metabase-types/api";+import type { DraftDashboardSubscription } from "metabase-types/store";import { getSortedParameters } from "./utils";@@ -27,7 +23,7 @@ export type MutableParametersSectionProps = {className?: string;parameters: UiParameter[];dashboard: Dashboard;- pulse: DashboardSubscription;+ pulse: DraftDashboardSubscription;setPulseParameters: (parameters: UiParameter[]) => void;hiddenParameters?: string;};diff --git a/frontend/CLAUDE.md b/frontend/CLAUDE.mdindex 3b1efd4fe10..e9cfc9f7c9c 100644--- a/frontend/CLAUDE.md+++ b/frontend/CLAUDE.md@@ -47,3 +47,8 @@ All PRs should include tests. Prefer Unit tests over E2E tests.### LocalizationAll user-facing strings MUST be localized using the ttag library. Localized strings should be complete phrases, do not concatenate a few separately localized strings. You should add context to strings where the meaning of the string might not be obvious in isolation: e.g. "Home" might have different words in some languages depending on whether you're talking about a dwelling or the landing page for a website.++### Scripts++- Use `yarn type-check-pure` to run project-wide type checking.+- Use `yarn lint-eslint-pure` to run project-wide linting.diff --git a/frontend/src/metabase-types/store/pulse.ts b/frontend/src/metabase-types/store/pulse.tsindex dd3844a640e..b144b2d5513 100644--- a/frontend/src/metabase-types/store/pulse.ts+++ b/frontend/src/metabase-types/store/pulse.ts@@ -3,8 +3,45 @@ import type {DashboardSubscription,} from "metabase-types/api";+/**+ * Represents the draft state during pulse editing.+ * Contains all fields that can be set by the user, with optional fields for server-generated data.+ */+export type DraftDashboardSubscription = Pick<+ DashboardSubscription,+ "cards" | "channels"+> &+ Partial<+ Pick<+ DashboardSubscription,+ | "id"+ | "name"+ | "dashboard_id"+ | "parameters"+ | "skip_if_empty"+ | "archived"+ | "can_write"+ | "collection_id"+ | "collection_position"+ | "created_at"+ | "creator"+ | "creator_id"+ | "disable_links"+ | "entity_id"+ | "updated_at"+ >+ >;++/**+ * Union type for pulse that can be either a complete DashboardSubscription+ * or a draft during editing.+ */+export type DashboardSubscriptionData =+ | DashboardSubscription+ | DraftDashboardSubscription;+export interface PulseState {- editingPulse: DashboardSubscription;+ editingPulse: DraftDashboardSubscription;formInput: ChannelApiResponse;cardPreviews: Record<number, { id: number }>;pulseList: DashboardSubscription[];diff --git a/frontend/src/metabase/account/notifications/actions.js b/frontend/src/metabase/account/notifications/actions.tssimilarity index 54%rename from frontend/src/metabase/account/notifications/actions.jsrename to frontend/src/metabase/account/notifications/actions.tsindex 647e70c3b18..097269b1244 100644--- a/frontend/src/metabase/account/notifications/actions.js+++ b/frontend/src/metabase/account/notifications/actions.ts@@ -1,17 +1,28 @@import { push } from "react-router-redux";+import type { NotificationListItem } from "./types";+const PREFIX = `/account/notifications`;-const TYPE_MAP = {+type ListItemType = NotificationListItem["type"];++const TYPE_MAP: Record<ListItemType, string> = {"question-notification": "alert",pulse: "pulse",};-export const navigateToUnsubscribe = (item, type) => {+export const navigateToUnsubscribe = (+ item: { id: number },+ type: ListItemType,+) => {return push(`${PREFIX}/${TYPE_MAP[type]}/${item.id}/unsubscribe`);};-export const navigateToArchive = (item, type, hasUnsubscribed) => {+export const navigateToArchive = (+ item: { id: number },+ type: ListItemType,+ hasUnsubscribed?: boolean,+) => {const query = hasUnsubscribed ? "?unsubscribed=true" : "";return push(`${PREFIX}/${TYPE_MAP[type]}/${item.id}/archive${query}`);};diff --git a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.jsx b/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.tsxsimilarity index 59%rename from frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.jsxrename to frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.tsxindex 8e1ce91d0bc..955244a5a78 100644--- a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.jsx+++ b/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.tsx@@ -1,4 +1,3 @@-import PropTypes from "prop-types";import { useCallback, useState } from "react";import { t } from "ttag";@@ -8,34 +7,40 @@ import { FormMessage } from "metabase/forms";import { formatDateTimeWithUnit } from "metabase/lib/formatting";import { formatChannelRecipients } from "metabase/lib/pulse";import Settings from "metabase/lib/settings";+import type { Alert, DashboardSubscription, User } from "metabase-types/api";++import type { NotificationType } from "../../types";import { ModalMessage } from "./ArchiveModal.styled";-const propTypes = {- item: PropTypes.object.isRequired,- type: PropTypes.oneOf(["alert", "pulse"]).isRequired,- user: PropTypes.object,- hasUnsubscribed: PropTypes.bool,- onArchive: PropTypes.func,- onClose: PropTypes.func,+type ArchiveModalProps = {+ item: Alert | DashboardSubscription;+ type: NotificationType;+ user: User;+ hasUnsubscribed: boolean;+ onArchive: (+ item: Alert | DashboardSubscription,+ archived: boolean,+ ) => Promise<void>;+ onClose: () => void;};-const ArchiveModal = ({+function ArchiveNotificationModal({item,type,user,hasUnsubscribed,onArchive,onClose,-}) => {- const [error, setError] = useState();+}: ArchiveModalProps): JSX.Element {+ const [error, setError] = useState<unknown>();const handleArchiveClick = useCallback(async () => {try {await onArchive(item, true);onClose();- } catch (error) {- setError(error);+ } catch (err) {+ setError(err);}}, [item, onArchive, onClose]);@@ -56,7 +61,7 @@ const ArchiveModal = ({{isCreator(item, user) && hasUnsubscribed && (<ModalMessage data-server-date>{getCreatorMessage(type, user)}- {t`As the creator you can also choose to delete this if it’s no longer relevant to others as well.`}+ {t`As the creator you can also choose to delete this if it's no longer relevant to others as well.`}</ModalMessage>)}<ModalMessage>@@ -65,28 +70,35 @@ const ArchiveModal = ({</ModalMessage></ModalContent>);-};--ArchiveModal.propTypes = propTypes;+}-const isCreator = (item, user) => {- return user != null && user.id === item.creator?.id;+const isCreator = (+ item: Alert | DashboardSubscription,+ user: User,+): boolean => {+ return user.id === item.creator?.id;};-const getTitleMessage = (type, hasUnsubscribed) => {+const getTitleMessage = (+ type: NotificationType,+ hasUnsubscribed: boolean,+): string => {switch (type) {case "alert":return hasUnsubscribed- ? t`You’re unsubscribed. Delete this alert as well?`+ ? t`You're unsubscribed. Delete this alert as well?`: t`Delete this alert?`;case "pulse":return hasUnsubscribed- ? t`You’re unsubscribed. Delete this subscription as well?`+ ? t`You're unsubscribed. Delete this subscription as well?`: t`Delete this subscription?`;}};-const getSubmitMessage = (type, hasUnsubscribed) => {+const getSubmitMessage = (+ type: NotificationType,+ hasUnsubscribed: boolean,+): string => {switch (type) {case "alert":return hasUnsubscribed ? t`Delete this alert` : t`Yes, delete this alert`;@@ -97,20 +109,23 @@ const getSubmitMessage = (type, hasUnsubscribed) => {}};-const getCancelMessage = (hasUnsubscribed) => {+const getCancelMessage = (hasUnsubscribed: boolean): string => {return hasUnsubscribed ? t`Keep it around` : t`I changed my mind`;};-const getCreatorMessage = (type, user) => {+const getCreatorMessage = (type: NotificationType, user: User): string => {switch (type) {case "alert":- return t`You won’t receive this alert at ${user.email} any more. `;+ return t`You won't receive this alert at ${user.email} any more. `;case "pulse":- return t`You won’t receive this subscription at ${user.email} any more. `;+ return t`You won't receive this subscription at ${user.email} any more. `;}};-const getDateMessage = (item, type) => {+const getDateMessage = (+ item: Alert | DashboardSubscription,+ type: NotificationType,+): string => {const options = Settings.formattingOptions();const createdAt = formatDateTimeWithUnit(item.created_at, "day", options);@@ -122,9 +137,8 @@ const getDateMessage = (item, type) => {}};-const getRecipientsMessage = (item) => {- return t`It’s currently being sent to ${formatChannelRecipients(item)}.`;+const getRecipientsMessage = (item: Alert | DashboardSubscription): string => {+ return t`It's currently being sent to ${formatChannelRecipients(item)}.`;};-// eslint-disable-next-line import/no-default-export -- deprecated usage-export default ArchiveModal;+export { ArchiveNotificationModal };diff --git a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.js b/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.jsdeleted file mode 100644index 191ca47e327..00000000000--- a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.js+++ /dev/null@@ -1,157 +0,0 @@-import { render, screen, waitFor } from "__support__/ui";--import ArchiveModal from "./ArchiveModal";--const getAlert = ({ creator = getUser(), channels = [getChannel()] } = {}) => ({- creator,- channels,- created_at: "2021-05-08T02:02:07.441Z",-});--const getPulse = ({ creator = getUser(), channels = [getChannel()] } = {}) => ({- creator,- channels,- created_at: "2021-05-08T02:02:07.441Z",-});--const getUser = ({ id = 1 } = {}) => ({- id,- common_name: "John Doe",-});--const getChannel = ({- channel_type = "email",- schedule_type = "hourly",- recipients = [getUser()],-} = {}) => {- return {- channel_type,- schedule_type,- recipients,- schedule_hour: 8,- schedule_day: "mon",- schedule_frame: "first",- };-};--describe("ArchiveModal", () => {- it("should render an email alert", () => {- const alert = getAlert();-- render(<ArchiveModal item={alert} type="alert" />);-- expect(screen.getByText("Delete this alert?")).toBeInTheDocument();- expect(screen.getByText("Yes, delete this alert")).toBeInTheDocument();- expect(- screen.getByText("You created this alert on May 8, 2021", {- exact: false,- }),- ).toBeInTheDocument();- expect(- screen.getByText("It’s currently being sent to 1 email.", {- exact: false,- }),- ).toBeInTheDocument();- });-- it("should render an email pulse", () => {- const pulse = getPulse();-- render(<ArchiveModal item={pulse} type="pulse" />);-- expect(screen.getByText("Delete this subscription?")).toBeInTheDocument();- expect(- screen.getByText("Yes, delete this subscription"),- ).toBeInTheDocument();- expect(- screen.getByText("May 8, 2021", { exact: false }),- ).toBeInTheDocument();- expect(- screen.getByText("It’s currently being sent to 1 email.", {- exact: false,- }),- ).toBeInTheDocument();- });-- it("should render a slack pulse", () => {- const pulse = getPulse({- channels: [getChannel({ channel_type: "slack" })],- });-- render(<ArchiveModal item={pulse} type="pulse" />);-- expect(- screen.getByText("1 Slack channel", { exact: false }),- ).toBeInTheDocument();- });-- it("should render an alert with both email and slack channels", () => {- const alert = getAlert({- channels: [- getChannel({- channel_type: "email",- recipients: [getUser(), getUser()],- }),- getChannel({- channel_type: "slack",- recipients: [getUser(), getUser(), getUser()],- }),- ],- });-- render(<ArchiveModal item={alert} type="alert" />);-- expect(- screen.getByText("2 emails and 3 Slack channels", { exact: false }),- ).toBeInTheDocument();- });-- it("should close on submit", async () => {- const alert = getAlert();- const onArchive = jest.fn();- const onClose = jest.fn();-- onArchive.mockResolvedValue();-- render(- <ArchiveModal- item={alert}- type="alert"- onArchive={onArchive}- onClose={onClose}- />,- );-- screen.getByText("Yes, delete this alert").click();-- await waitFor(() => {- expect(onArchive).toHaveBeenCalledWith(alert, true);- });- expect(onClose).toHaveBeenCalled();- });-- it("should not close on a submit error", async () => {- const alert = getAlert();- const onArchive = jest.fn();- const onClose = jest.fn();-- onArchive.mockRejectedValue({ data: { message: "An error occurred" } });-- render(- <ArchiveModal- item={alert}- type="alert"- onArchive={onArchive}- onClose={onClose}- />,- );-- screen.getByText("Yes, delete this alert").click();-- await waitFor(() => {- expect(screen.getByText("An error occurred")).toBeInTheDocument();- });- expect(onArchive).toHaveBeenCalledWith(alert, true);- expect(onClose).not.toHaveBeenCalled();- });-});diff --git a/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.tsx b/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.tsxnew file mode 100644index 00000000000..1617b61acc9--- /dev/null+++ b/frontend/src/metabase/account/notifications/components/ArchiveModal/ArchiveModal.unit.spec.tsx@@ -0,0 +1,212 @@+import { render, screen, waitFor } from "__support__/ui";+import { getNextId } from "__support__/utils";+import {+ createMockAlert,+ createMockChannel,+} from "metabase-types/api/mocks/alert";+import { createMockDashboardSubscription } from "metabase-types/api/mocks/pulse";+import { createMockUser } from "metabase-types/api/mocks/user";++import { ArchiveNotificationModal } from "./ArchiveModal";++describe("ArchiveNotificationModal", () => {+ it("should render an email alert", () => {+ const alert = createMockAlert({+ id: getNextId(),+ created_at: "2021-05-08T02:02:07.441Z",+ channels: [+ createMockChannel({+ channel_id: getNextId(),+ channel_type: "email",+ recipients: [createMockUser({ id: getNextId() })],+ }),+ ],+ });++ render(+ <ArchiveNotificationModal+ item={alert}+ type="alert"+ user={createMockUser({ id: getNextId() })}+ hasUnsubscribed={false}+ onArchive={jest.fn()}+ onClose={jest.fn()}+ />,+ );++ expect(screen.getByText("Delete this alert?")).toBeInTheDocument();+ expect(screen.getByText("Yes, delete this alert")).toBeInTheDocument();+ expect(+ screen.getByText("You created this alert on May 8, 2021", {+ exact: false,+ }),+ ).toBeInTheDocument();+ expect(+ screen.getByText("It's currently being sent to 1 email.", {+ exact: false,+ }),+ ).toBeInTheDocument();+ });++ it("should render an email pulse", () => {+ const pulse = createMockDashboardSubscription({+ id: getNextId(),+ created_at: "2021-05-08T02:02:07.441Z",+ channels: [+ createMockChannel({+ channel_id: getNextId(),+ channel_type: "email",+ recipients: [createMockUser({ id: getNextId() })],+ }),+ ],+ });++ render(+ <ArchiveNotificationModal+ item={pulse}+ type="pulse"+ user={createMockUser({ id: getNextId() })}+ hasUnsubscribed={false}+ onArchive={jest.fn()}+ onClose={jest.fn()}+ />,+ );++ expect(screen.getByText("Delete this subscription?")).toBeInTheDocument();+ expect(+ screen.getByText("Yes, delete this subscription"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("May 8, 2021", { exact: false }),+ ).toBeInTheDocument();+ expect(+ screen.getByText("It's currently being sent to 1 email.", {+ exact: false,+ }),+ ).toBeInTheDocument();+ });++ it("should render a slack pulse", () => {+ const pulse = createMockDashboardSubscription({+ id: getNextId(),+ channels: [+ createMockChannel({+ channel_id: getNextId(),+ channel_type: "slack",+ recipients: [createMockUser({ id: getNextId() })],+ }),+ ],+ });++ render(+ <ArchiveNotificationModal+ item={pulse}+ type="pulse"+ user={createMockUser({ id: getNextId() })}+ hasUnsubscribed={false}+ onArchive={jest.fn()}+ onClose={jest.fn()}+ />,+ );++ expect(+ screen.getByText("1 Slack channel", { exact: false }),+ ).toBeInTheDocument();+ });++ it("should render an alert with both email and slack channels", () => {+ const alert = createMockAlert({+ id: getNextId(),+ channels: [+ createMockChannel({+ channel_id: getNextId(),+ channel_type: "email",+ recipients: [+ createMockUser({ id: getNextId() }),+ createMockUser({ id: getNextId() }),+ ],+ }),+ createMockChannel({+ channel_id: getNextId(),+ channel_type: "slack",+ recipients: [+ createMockUser({ id: getNextId() }),+ createMockUser({ id: getNextId() }),+ createMockUser({ id: getNextId() }),+ ],+ }),+ ],+ });++ render(+ <ArchiveNotificationModal+ item={alert}+ type="alert"+ user={createMockUser({ id: getNextId() })}+ hasUnsubscribed={false}+ onArchive={jest.fn()}+ onClose={jest.fn()}+ />,+ );++ expect(+ screen.getByText("2 emails and 3 Slack channels", { exact: false }),+ ).toBeInTheDocument();+ });++ it("should close on submit", async () => {+ const alert = createMockAlert({ id: getNextId() });+ const onArchive = jest.fn();+ const onClose = jest.fn();++ onArchive.mockResolvedValue(undefined);++ render(+ <ArchiveNotificationModal+ item={alert}+ type="alert"+ user={createMockUser({ id: getNextId() })}+ hasUnsubscribed={false}+ onArchive={onArchive}+ onClose={onClose}+ />,+ );++ screen.getByText("Yes, delete this alert").click();++ await waitFor(() => {+ expect(onArchive).toHaveBeenCalledWith(alert, true);+ });+ expect(onClose).toHaveBeenCalled();+ });++ it("should not close on a submit error", async () => {+ const alert = createMockAlert({ id: getNextId() });+ const onArchive = jest.fn();+ const onClose = jest.fn();++ onArchive.mockRejectedValue({+ status: 500,+ data: { message: "An error occurred" },+ });++ render(+ <ArchiveNotificationModal+ item={alert}+ type="alert"+ user={createMockUser({ id: getNextId() })}+ hasUnsubscribed={false}+ onArchive={onArchive}+ onClose={onClose}+ />,+ );++ screen.getByText("Yes, delete this alert").click();++ await waitFor(() => {+ expect(screen.getByText("An error occurred")).toBeInTheDocument();+ });+ expect(onArchive).toHaveBeenCalledWith(alert, true);+ expect(onClose).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/metabase/account/notifications/components/ArchiveModal/index.ts b/frontend/src/metabase/account/notifications/components/ArchiveModal/index.tsindex 20d6362dcb0..522f174ae9e 100644--- a/frontend/src/metabase/account/notifications/components/ArchiveModal/index.ts+++ b/frontend/src/metabase/account/notifications/components/ArchiveModal/index.ts@@ -1,2 +1 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./ArchiveModal";+export { ArchiveNotificationModal } from "./ArchiveModal";diff --git a/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.jsx b/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.jsxdeleted file mode 100644index 3e571a7c1c2..00000000000--- a/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.jsx+++ /dev/null@@ -1,63 +0,0 @@-import PropTypes from "prop-types";-import { jt, t } from "ttag";--import { Button } from "metabase/common/components/Button";-import { Link } from "metabase/common/components/Link";-import { ModalContent } from "metabase/common/components/ModalContent";-import { useSelector } from "metabase/lib/redux";-import Settings from "metabase/lib/settings";-import { getApplicationName } from "metabase/selectors/whitelabel";--import { ModalMessage } from "./HelpModal.styled";--const propTypes = {- onClose: PropTypes.func,-};--const HelpModal = ({ onClose }) => {- const email = Settings.get("admin-email");-- const handleClose = () => onClose(true);-- const applicationName = useSelector(getApplicationName);-- return (- <ModalContent- title={t`Not seeing something listed here?`}- footer={- <Button key="close" onClick={handleClose}>- {t`Got it`}- </Button>- }- onClose={handleClose}- >- <ModalMessage>- {t`It’s possible you may also receive emails from ${applicationName} if you’re a member of an email distribution list, like “[email protected]” and that list is used as the recipient for an alert or dashboard subscription instead of your individual email.`}- </ModalMessage>- <ModalMessage>- {getAdminMessage(email, applicationName)}- {t`Hopefully they’ll be able to help you out!`}- </ModalMessage>- </ModalContent>- );-};--HelpModal.propTypes = propTypes;--const getAdminLink = (email, text) => {- return email ? (- <Link variant="brand" key="admin-link" href={`mailto:${email}`}>- {text}- </Link>- ) : (- text- );-};--const getAdminMessage = (email, applicationName) => {- const adminLink = getAdminLink(email, t`your instance administrator`);- return jt`${applicationName} doesn’t manage those lists, so we’d recommend contacting ${adminLink}. `;-};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default HelpModal;diff --git a/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.tsx b/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.tsxnew file mode 100644index 00000000000..3e0ed4bf10c--- /dev/null+++ b/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.tsx@@ -0,0 +1,76 @@+import { jt, t } from "ttag";++import { Button } from "metabase/common/components/Button";+import { ExternalLink } from "metabase/common/components/ExternalLink";+import { ModalContent } from "metabase/common/components/ModalContent";+import { useSelector } from "metabase/lib/redux";+import Settings from "metabase/lib/settings";+import { getApplicationName } from "metabase/selectors/whitelabel";++import { ModalMessage } from "./HelpModal.styled";++type HelpModalProps = {+ onClose: (confirmed: boolean) => void;+};++function HelpModal({ onClose }: HelpModalProps): JSX.Element {+ const email = Settings.get("admin-email");+ const applicationName = useSelector(getApplicationName);++ const handleClose = () => onClose?.(true);++ return (+ <ModalContent+ title={t`Not seeing something listed here?`}+ footer={+ <Button key="close" onClick={handleClose}>+ {t`Got it`}+ </Button>+ }+ onClose={handleClose}+ >+ <ModalMessage>+ {t`It's possible you may also receive emails from ${applicationName} if you're a member of an email distribution list, like "[email protected]" and that list is used as the recipient for an alert or dashboard subscription instead of your individual email.`}+ </ModalMessage>+ <ModalMessage>+ <AdminMessage email={email} applicationName={applicationName} />+ {t`Hopefully they'll be able to help you out!`}+ </ModalMessage>+ </ModalContent>+ );+}++function AdminLink({+ email,+ text,+}: {+ email: string | null | undefined;+ text: string;+}) {+ return email ? (+ <ExternalLink key="admin-link" href={`mailto:${email}`}>+ {text}+ </ExternalLink>+ ) : (+ <>{text}</>+ );+}++function AdminMessage({+ email,+ applicationName,+}: {+ email: string | null | undefined;+ applicationName: string;+}) {+ const adminLink = (+ <AdminLink+ key="admin-link"+ email={email}+ text={t`your instance administrator`}+ />+ );+ return jt`${applicationName} doesn't manage those lists, so we'd recommend contacting ${adminLink}. `;+}++export { HelpModal };diff --git a/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.unit.spec.js b/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.unit.spec.tsxsimilarity index 77%rename from frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.unit.spec.jsrename to frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.unit.spec.tsxindex 16779eb328a..318cde58550 100644--- a/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.unit.spec.js+++ b/frontend/src/metabase/account/notifications/components/HelpModal/HelpModal.unit.spec.tsx@@ -1,17 +1,21 @@import { mockSettings } from "__support__/settings";import { renderWithProviders, screen } from "__support__/ui";-import HelpModal from "./HelpModal";+import { HelpModal } from "./HelpModal";-function setup({ adminEmail, onClose } = {}) {- renderWithProviders(<HelpModal adminEmail={adminEmail} onClose={onClose} />);+type SetupOpts = {+ onClose?: (confirmed: boolean) => void;+};++function setup({ onClose = jest.fn() }: SetupOpts = {}) {+ renderWithProviders(<HelpModal onClose={onClose} />);}describe("HelpModal", () => {it("should render with admin email", () => {mockSettings({ "admin-email": "[email protected]" });- setup({ adminEmail: "[email protected]" });+ setup();const link = screen.getByRole("link");expect(link).toHaveProperty("href", "mailto:[email protected]");diff --git a/frontend/src/metabase/account/notifications/components/HelpModal/index.ts b/frontend/src/metabase/account/notifications/components/HelpModal/index.tsindex b4f4edd473f..ada238e49a8 100644--- a/frontend/src/metabase/account/notifications/components/HelpModal/index.ts+++ b/frontend/src/metabase/account/notifications/components/HelpModal/index.ts@@ -1,2 +1 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./HelpModal";+export { HelpModal } from "./HelpModal";diff --git a/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsx b/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsxindex d147b072eb1..6b67869e802 100644--- a/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsx+++ b/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsx@@ -3,7 +3,7 @@ import { useCallback } from "react";import { t } from "ttag";import { formatCreatorMessage } from "metabase/account/notifications/components/NotificationCard/utils";-import type { DashboardAlertListItem } from "metabase/account/notifications/types";+import type { DashboardSubscriptionListItem } from "metabase/account/notifications/types";import { Link } from "metabase/common/components/Link";import { formatTitle } from "metabase/lib/notifications";import { canArchiveLegacyAlert, formatChannel } from "metabase/lib/pulse";@@ -19,10 +19,10 @@ import {} from "./DashboardNotificationCard.styled";type Props = {- listItem: DashboardAlertListItem;+ listItem: DashboardSubscriptionListItem;user: User;- onUnsubscribe: (listItem: DashboardAlertListItem) => void;- onArchive: (listItem: DashboardAlertListItem) => void;+ onUnsubscribe: (listItem: DashboardSubscriptionListItem) => void;+ onArchive: (listItem: DashboardSubscriptionListItem) => void;isEditable: boolean;};diff --git a/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.unit.spec.tsx b/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.unit.spec.tsxindex 7f4979eb384..abdb2d1d479 100644--- a/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.unit.spec.tsx+++ b/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.unit.spec.tsx@@ -1,9 +1,9 @@import { fireEvent, render, screen } from "__support__/ui";-import type { DashboardAlertListItem } from "metabase/account/notifications/types";+import type { DashboardSubscriptionListItem } from "metabase/account/notifications/types";import type { Channel } from "metabase-types/api";import {- createMockAlert,createMockChannel,+ createMockDashboardSubscription,createMockUser,} from "metabase-types/api/mocks";@@ -12,8 +12,8 @@ import { DashboardNotificationCard } from "./DashboardNotificationCard";const getPulseItem = ({creator = getUser(),channels = [getChannel()],-} = {}): DashboardAlertListItem => ({- item: createMockAlert({+} = {}): DashboardSubscriptionListItem => ({+ item: createMockDashboardSubscription({creator,channels,created_at: "2021-05-08T02:02:07.441Z",diff --git a/frontend/src/metabase/account/notifications/components/NotificationList/NotificationList.unit.spec.tsx b/frontend/src/metabase/account/notifications/components/NotificationList/NotificationList.unit.spec.tsxindex e75ac341b86..22777054b26 100644--- a/frontend/src/metabase/account/notifications/components/NotificationList/NotificationList.unit.spec.tsx+++ b/frontend/src/metabase/account/notifications/components/NotificationList/NotificationList.unit.spec.tsx@@ -1,7 +1,10 @@import { screen } from "@testing-library/react";import { renderWithTheme } from "__support__/ui";-import { createMockAlert, createMockUser } from "metabase-types/api/mocks";+import {+ createMockDashboardSubscription,+ createMockUser,+} from "metabase-types/api/mocks";import { NotificationList } from "./NotificationList";@@ -9,7 +12,7 @@ const mockUser = createMockUser({ common_name: "John Doe" });describe("NotificationList", () => {it("should render items", () => {- const pulse = createMockAlert();+ const pulse = createMockDashboardSubscription();renderWithTheme(<NotificationListdiff --git a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.jsx b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.tsxsimilarity index 51%rename from frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.jsxrename to frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.tsxindex eaa1d3fa232..0cf13e6b715 100644--- a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.jsx+++ b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.tsx@@ -1,29 +1,35 @@-import PropTypes from "prop-types";import { useCallback, useState } from "react";import { t } from "ttag";import { Button } from "metabase/common/components/Button";import { ModalContent } from "metabase/common/components/ModalContent";import { FormMessage } from "metabase/forms";+import type { Alert, DashboardSubscription, User } from "metabase-types/api";-const propTypes = {- item: PropTypes.object.isRequired,- type: PropTypes.oneOf(["alert", "pulse"]).isRequired,- user: PropTypes.object,- onUnsubscribe: PropTypes.func,- onArchive: PropTypes.func,- onClose: PropTypes.func,+import type { NotificationType } from "../../types";++type UnsubscribeModalProps = {+ item: Alert | DashboardSubscription;+ type: NotificationType;+ user: User;+ onUnsubscribe: (item: Alert | DashboardSubscription) => Promise<void>;+ onArchive: (+ item: Alert | DashboardSubscription,+ type: NotificationType,+ hasUnsubscribed: boolean,+ ) => void;+ onClose: () => void;};-const UnsubscribeModal = ({+function UnsubscribeModal({item,type,user,onUnsubscribe,onArchive,onClose,-}) => {- const [error, setError] = useState();+}: UnsubscribeModalProps): JSX.Element {+ const [error, setError] = useState<unknown>();const handleUnsubscribeClick = useCallback(async () => {try {@@ -34,8 +40,8 @@ const UnsubscribeModal = ({} else {onClose();}- } catch (error) {- setError(error);+ } catch (err) {+ setError(err);}}, [item, type, user, onUnsubscribe, onArchive, onClose]);@@ -55,26 +61,26 @@ const UnsubscribeModal = ({><p>{getUnsubscribeMessage(type)}- {t`Depending on your organization’s permissions you might need to ask a moderator to be re-added in the future.`}+ {t`Depending on your organization's permissions you might need to ask a moderator to be re-added in the future.`}</p></ModalContent>);-};--UnsubscribeModal.propTypes = propTypes;+}-const isCreator = (item, user) => {- return user != null && user.id === item.creator?.id;+const isCreator = (+ item: Alert | DashboardSubscription,+ user: User,+): boolean => {+ return user.id === item.creator?.id;};-const getUnsubscribeMessage = (type) => {+const getUnsubscribeMessage = (type: NotificationType): string => {switch (type) {case "alert":- return t`You’ll stop receiving this alert from now on. `;+ return t`You'll stop receiving this alert from now on. `;case "pulse":- return t`You’ll stop receiving this subscription from now on. `;+ return t`You'll stop receiving this subscription from now on. `;}};-// eslint-disable-next-line import/no-default-export -- deprecated usage-export default UnsubscribeModal;+export { UnsubscribeModal };diff --git a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.js b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.tsxsimilarity index 61%rename from frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.jsrename to frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.tsxindex ba061d1b0c2..7508cf73931 100644--- a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.js+++ b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/UnsubscribeModal.unit.spec.tsx@@ -1,26 +1,25 @@import { render, screen, waitFor } from "__support__/ui";+import { getNextId } from "__support__/utils";+import { createMockAlert } from "metabase-types/api/mocks/alert";+import { createMockDashboardSubscription } from "metabase-types/api/mocks/pulse";+import { createMockUser } from "metabase-types/api/mocks/user";-import UnsubscribeModal from "./UnsubscribeModal";--const getAlert = ({ creator = getUser({ id: 1 }) } = {}) => ({- name: "Alert",- creator: creator,-});--const getPulse = ({ creator = getUser({ id: 1 }) } = {}) => ({- name: "Pulse",- creator: creator,-});--const getUser = ({ id = 2 } = {}) => ({- id,-});+import { UnsubscribeModal } from "./UnsubscribeModal";describe("UnsubscribeModal", () => {it("should render an alert", () => {- const alert = getAlert();+ const alert = createMockAlert();- render(<UnsubscribeModal item={alert} type="alert" />);+ render(+ <UnsubscribeModal+ item={alert}+ type="alert"+ user={createMockUser()}+ onUnsubscribe={jest.fn()}+ onArchive={jest.fn()}+ onClose={jest.fn()}+ />,+ );expect(screen.getByText("this alert", { exact: false }),@@ -28,9 +27,18 @@ describe("UnsubscribeModal", () => {});it("should render a pulse", () => {- const pulse = getPulse();+ const pulse = createMockDashboardSubscription();- render(<UnsubscribeModal item={pulse} type="pulse" />);+ render(+ <UnsubscribeModal+ item={pulse}+ type="pulse"+ user={createMockUser()}+ onUnsubscribe={jest.fn()}+ onArchive={jest.fn()}+ onClose={jest.fn()}+ />,+ );expect(screen.getByText("this subscription", { exact: false }),@@ -38,17 +46,19 @@ describe("UnsubscribeModal", () => {});it("should close if unsubscribed successfully", async () => {- const alert = getAlert();+ const alert = createMockAlert({ creator_id: getNextId() });+ const user = createMockUser({ id: getNextId() });const onUnsubscribe = jest.fn();const onArchive = jest.fn();const onClose = jest.fn();- onUnsubscribe.mockResolvedValue();+ onUnsubscribe.mockResolvedValue(undefined);render(<UnsubscribeModalitem={alert}type="alert"+ user={user}onUnsubscribe={onUnsubscribe}onArchive={onArchive}onClose={onClose}@@ -65,13 +75,13 @@ describe("UnsubscribeModal", () => {});it("should proceed with archiving if the notification is created by the user", async () => {- const user = getUser();- const alert = getAlert({ creator: user });+ const user = createMockUser({ id: getNextId() });+ const alert = createMockAlert({ creator_id: user.id, creator: user });const onUnsubscribe = jest.fn();const onArchive = jest.fn();const onClose = jest.fn();- onUnsubscribe.mockResolvedValue();+ onUnsubscribe.mockResolvedValue(undefined);render(<UnsubscribeModal@@ -94,13 +104,16 @@ describe("UnsubscribeModal", () => {});it("should not close on a submit error", async () => {- const user = getUser();- const alert = getAlert();+ const user = createMockUser({ id: getNextId() });+ const alert = createMockAlert({ creator_id: user.id, creator: user });const onUnsubscribe = jest.fn();const onArchive = jest.fn();const onClose = jest.fn();- onUnsubscribe.mockRejectedValue({ data: { message: "An error occurred" } });+ onUnsubscribe.mockRejectedValue({+ status: 500,+ data: { message: "An error occurred" },+ });render(<UnsubscribeModaldiff --git a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/index.ts b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/index.tsindex 2aca4558a65..21704527ebd 100644--- a/frontend/src/metabase/account/notifications/components/UnsubscribeModal/index.ts+++ b/frontend/src/metabase/account/notifications/components/UnsubscribeModal/index.ts@@ -1,2 +1 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./UnsubscribeModal";+export { UnsubscribeModal } from "./UnsubscribeModal";diff --git a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.jsx b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.jsxdeleted file mode 100644index 8477e4ebf2d..00000000000--- a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.jsx+++ /dev/null@@ -1,27 +0,0 @@-import _ from "underscore";--import { Pulses } from "metabase/entities/pulses";-import { connect } from "metabase/lib/redux";-import { getUser } from "metabase/selectors/user";--import ArchiveModal from "../../components/ArchiveModal";-import { getPulseId } from "../../selectors";--const mapStateToProps = (state, { pulse, location }) => ({- item: pulse,- type: "pulse",- user: getUser(state),- hasUnsubscribed: location.query.unsubscribed,-});--const mapDispatchToProps = {- onArchive: Pulses.actions.setArchived,-};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default _.compose(- Pulses.load({- id: (state, props) => getPulseId(props),- }),- connect(mapStateToProps, mapDispatchToProps),-)(ArchiveModal);diff --git a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsxnew file mode 100644index 00000000000..9e946a9ff3e--- /dev/null+++ b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/ArchivePulseModal.tsx@@ -0,0 +1,58 @@+import { skipToken } from "@reduxjs/toolkit/query/react";+import type { Location } from "history";++import {+ useGetSubscriptionQuery,+ useUpdateSubscriptionMutation,+} from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useSelector } from "metabase/lib/redux";+import { getUser } from "metabase/selectors/user";++import { ArchiveNotificationModal } from "../../components/ArchiveModal";+import { getPulseId } from "../../selectors";++type ArchivePulseModalProps = {+ params: { pulseId?: string };+ location: Location;+ onClose: () => void;+};++export function ArchivePulseModal({+ params,+ location,+ onClose,+}: ArchivePulseModalProps) {+ const pulseId = getPulseId({ params });+ const user = useSelector(getUser);++ const {+ data: pulse,+ isLoading,+ error,+ } = useGetSubscriptionQuery(pulseId ?? skipToken);++ const [updateSubscription] = useUpdateSubscriptionMutation();++ const handleArchive = async (+ item: { id: number },+ archived: boolean,+ ): Promise<void> => {+ await updateSubscription({ id: item.id, archived });+ };++ if (isLoading || error) {+ return <LoadingAndErrorWrapper loading={isLoading} error={error} />;+ }++ return pulse && user ? (+ <ArchiveNotificationModal+ item={pulse}+ type="pulse"+ user={user}+ hasUnsubscribed={Boolean(location.query?.unsubscribed)}+ onArchive={handleArchive}+ onClose={onClose}+ />+ ) : null;+}diff --git a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/index.ts b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/index.tsindex 918d3659b2c..f5ef9cef742 100644--- a/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/index.ts+++ b/frontend/src/metabase/account/notifications/containers/ArchivePulseModal/index.ts@@ -1,2 +1 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./ArchivePulseModal";+export { ArchivePulseModal } from "./ArchivePulseModal";diff --git a/frontend/src/metabase/account/notifications/containers/NotificationsApp/NotificationsApp.tsx b/frontend/src/metabase/account/notifications/containers/NotificationsApp/NotificationsApp.tsxindex 17444a93bc5..b155b403fe8 100644--- a/frontend/src/metabase/account/notifications/containers/NotificationsApp/NotificationsApp.tsx+++ b/frontend/src/metabase/account/notifications/containers/NotificationsApp/NotificationsApp.tsx@@ -10,7 +10,7 @@ import {canManageSubscriptions as canManageSubscriptionsSelector,getUser,} from "metabase/selectors/user";-import type { Alert } from "metabase-types/api";+import type { DashboardSubscription } from "metabase-types/api";import {navigateToArchive,@@ -20,7 +20,7 @@ import {import { NotificationList } from "../../components/NotificationList";interface NotificationsAppProps {- pulses: Alert[];+ pulses: DashboardSubscription[];children?: ReactNode;}diff --git a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.jsx b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.jsxdeleted file mode 100644index 6ff1a4d2240..00000000000--- a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.jsx+++ /dev/null@@ -1,28 +0,0 @@-import _ from "underscore";--import { Pulses } from "metabase/entities/pulses";-import { connect } from "metabase/lib/redux";-import { getUser } from "metabase/selectors/user";--import { navigateToArchive } from "../../actions";-import UnsubscribeModal from "../../components/UnsubscribeModal";-import { getPulseId } from "../../selectors";--const mapStateToProps = (state, { pulse }) => ({- item: pulse,- type: "pulse",- user: getUser(state),-});--const mapDispatchToProps = {- onUnsubscribe: Pulses.actions.unsubscribe,- onArchive: navigateToArchive,-};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default _.compose(- Pulses.load({- id: (state, props) => getPulseId(props),- }),- connect(mapStateToProps, mapDispatchToProps),-)(UnsubscribeModal);diff --git a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.tsx b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.tsxnew file mode 100644index 00000000000..8f8d22ed700--- /dev/null+++ b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/UnsubscribePulseModal.tsx@@ -0,0 +1,59 @@+import { skipToken } from "@reduxjs/toolkit/query/react";++import { useGetSubscriptionQuery, useUnsubscribeMutation } from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useDispatch, useSelector } from "metabase/lib/redux";+import { getUser } from "metabase/selectors/user";++import { navigateToArchive } from "../../actions";+import { UnsubscribeModal } from "../../components/UnsubscribeModal";+import { getPulseId } from "../../selectors";++type UnsubscribePulseModalProps = {+ params: { pulseId?: string };+ onClose: () => void;+};++export function UnsubscribePulseModal({+ params,+ onClose,+}: UnsubscribePulseModalProps) {+ const dispatch = useDispatch();+ const pulseId = getPulseId({ params });+ const user = useSelector(getUser);++ const {+ data: pulse,+ isLoading,+ error,+ } = useGetSubscriptionQuery(pulseId ?? skipToken);++ const [unsubscribe] = useUnsubscribeMutation();++ const handleUnsubscribe = async (item: { id: number }): Promise<void> => {+ await unsubscribe(item.id);+ };++ const handleArchive = (+ item: { id: number },+ _type: "alert" | "pulse",+ hasUnsubscribed: boolean,+ ): void => {+ dispatch(navigateToArchive(item, "pulse", hasUnsubscribed));+ };++ if (isLoading || error) {+ return <LoadingAndErrorWrapper loading={isLoading} error={error} />;+ }++ return pulse && user ? (+ <UnsubscribeModal+ item={pulse}+ type="pulse"+ user={user}+ onUnsubscribe={handleUnsubscribe}+ onArchive={handleArchive}+ onClose={onClose}+ />+ ) : null;+}diff --git a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/index.ts b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/index.tsindex 911cbef3bd7..8c1b47c9da6 100644--- a/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/index.ts+++ b/frontend/src/metabase/account/notifications/containers/UnsubscribePulseModal/index.ts@@ -1,2 +1 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./UnsubscribePulseModal";+export { UnsubscribePulseModal } from "./UnsubscribePulseModal";diff --git a/frontend/src/metabase/account/notifications/routes.jsx b/frontend/src/metabase/account/notifications/routes.jsxdeleted file mode 100644index 7d5ed3815ed..00000000000--- a/frontend/src/metabase/account/notifications/routes.jsx+++ /dev/null@@ -1,30 +0,0 @@-import { Route } from "react-router";--import { ModalRoute } from "metabase/hoc/ModalRoute";--import HelpModal from "./components/HelpModal";-import { DeleteAlertModal } from "./containers/ArchiveAlertModal";-import ArchivePulseModal from "./containers/ArchivePulseModal";-import { NotificationsApp } from "./containers/NotificationsApp";-import { UnsubscribeAlertModal } from "./containers/UnsubscribeAlertModal";-import UnsubscribePulseModal from "./containers/UnsubscribePulseModal";--const getRoutes = () => (- <Route path="notifications" component={NotificationsApp}>- <ModalRoute path="help" modal={HelpModal} />- <ModalRoute path="alert/:alertId/archive" modal={DeleteAlertModal} noWrap />- <ModalRoute path="pulse/:pulseId/archive" modal={ArchivePulseModal} />- <ModalRoute- path="alert/:alertId/unsubscribe"- modal={UnsubscribeAlertModal}- noWrap- />- <ModalRoute- path="pulse/:pulseId/unsubscribe"- modal={UnsubscribePulseModal}- />- </Route>-);--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default getRoutes;diff --git a/frontend/src/metabase/account/notifications/routes.tsx b/frontend/src/metabase/account/notifications/routes.tsxnew file mode 100644index 00000000000..7e4abd6d39c--- /dev/null+++ b/frontend/src/metabase/account/notifications/routes.tsx@@ -0,0 +1,33 @@+import { Route } from "react-router";++import { ModalRoute } from "metabase/hoc/ModalRoute";++import { HelpModal } from "./components/HelpModal";+import { DeleteAlertModal } from "./containers/ArchiveAlertModal";+import { ArchivePulseModal } from "./containers/ArchivePulseModal";+import { NotificationsApp } from "./containers/NotificationsApp";+import { UnsubscribeAlertModal } from "./containers/UnsubscribeAlertModal";+import { UnsubscribePulseModal } from "./containers/UnsubscribePulseModal";++export function getNotificationRoutes() {+ return (+ <Route path="notifications" component={NotificationsApp}>+ <ModalRoute path="help" modal={HelpModal} />+ <ModalRoute+ path="alert/:alertId/archive"+ modal={DeleteAlertModal}+ noWrap+ />+ <ModalRoute path="pulse/:pulseId/archive" modal={ArchivePulseModal} />+ <ModalRoute+ path="alert/:alertId/unsubscribe"+ modal={UnsubscribeAlertModal}+ noWrap+ />+ <ModalRoute+ path="pulse/:pulseId/unsubscribe"+ modal={UnsubscribePulseModal}+ />+ </Route>+ );+}diff --git a/frontend/src/metabase/account/notifications/types.ts b/frontend/src/metabase/account/notifications/types.tsindex 94b21ce62e7..59770f81fda 100644--- a/frontend/src/metabase/account/notifications/types.ts+++ b/frontend/src/metabase/account/notifications/types.ts@@ -1,7 +1,9 @@-import type { Alert, Notification } from "metabase-types/api";+import type { DashboardSubscription, Notification } from "metabase-types/api";-export type DashboardAlertListItem = {- item: Alert;+export type NotificationType = "alert" | "pulse";++export type DashboardSubscriptionListItem = {+ item: DashboardSubscription;type: "pulse";};@@ -11,5 +13,5 @@ export type QuestionNotificationListItem = {};export type NotificationListItem =- | DashboardAlertListItem+ | DashboardSubscriptionListItem| QuestionNotificationListItem;diff --git a/frontend/src/metabase/account/routes.jsx b/frontend/src/metabase/account/routes.tsxsimilarity index 70%rename from frontend/src/metabase/account/routes.jsxrename to frontend/src/metabase/account/routes.tsxindex a1034ede938..2f3381d4718 100644--- a/frontend/src/metabase/account/routes.jsx+++ b/frontend/src/metabase/account/routes.tsx@@ -1,12 +1,19 @@+import type { Store } from "@reduxjs/toolkit";+import type { ComponentType } from "react";import { IndexRedirect, Route } from "react-router";+import type { State } from "metabase-types/store";+import AccountApp from "./app/containers/AccountApp";import LoginHistoryApp from "./login-history/containers/LoginHistoryApp";-import getNotificationRoutes from "./notifications/routes";+import { getNotificationRoutes } from "./notifications/routes";import UserPasswordApp from "./password/containers/UserPasswordApp";import UserProfileApp from "./profile/containers/UserProfileApp";-const getRoutes = (store, IsAuthenticated) => {+export const getAccountRoutes = (+ _store: Store<State>,+ IsAuthenticated: ComponentType,+) => {return (<Route path="/account" component={IsAuthenticated}><Route component={AccountApp}>@@ -19,6 +26,3 @@ const getRoutes = (store, IsAuthenticated) => {</Route>);};--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default getRoutes;diff --git a/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.jsx b/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.jsxdeleted file mode 100644index ed3bb42934b..00000000000--- a/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.jsx+++ /dev/null@@ -1,42 +0,0 @@-import PropTypes from "prop-types";-import { Component } from "react";-import { t } from "ttag";--import { ActionButton } from "metabase/common/components/ActionButton";-import { cleanPulse } from "metabase/lib/pulse";--export class SendTestPulse extends Component {- static propTypes = {- channel: PropTypes.object.isRequired,- channelSpecs: PropTypes.object.isRequired,- pulse: PropTypes.object.isRequired,- testPulse: PropTypes.func.isRequired,- disabled: PropTypes.bool.isRequired,- normalText: PropTypes.string.isRequired,- successText: PropTypes.string.isRequired,- };- static defaultProps = {};-- onTestPulseChannel = () => {- const { pulse, channel, channelSpecs, testPulse } = this.props;- const channelPulse = { ...pulse, channels: [channel] };- const cleanedPulse = cleanPulse(channelPulse, channelSpecs);-- return testPulse(cleanedPulse);- };-- render() {- const { disabled, normalText, successText } = this.props;-- return (- <ActionButton- actionFn={this.onTestPulseChannel}- disabled={disabled}- normalText={normalText}- activeText={t`Sending…`}- failedText={t`Sending failed`}- successText={successText}- />- );- }-}diff --git a/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.tsx b/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.tsxnew file mode 100644index 00000000000..6fb318a5bd5--- /dev/null+++ b/frontend/src/metabase/common/components/SendTestPulse/SendTestPulse.tsx@@ -0,0 +1,45 @@+import { useCallback } from "react";+import { t } from "ttag";++import { ActionButton } from "metabase/common/components/ActionButton";+import { cleanPulse } from "metabase/lib/pulse";+import type { Channel, ChannelSpecs } from "metabase-types/api";+import type { DashboardSubscriptionData } from "metabase-types/store";++type SendTestPulseProps<T extends DashboardSubscriptionData> = {+ channel: Channel;+ channelSpecs: Partial<ChannelSpecs>;+ pulse: T;+ testPulse: (pulse: T) => Promise<unknown>;+ disabled: boolean;+ normalText: string;+ successText: string;+};++export function SendTestPulse<T extends DashboardSubscriptionData>({+ channel,+ channelSpecs,+ pulse,+ testPulse,+ disabled,+ normalText,+ successText,+}: SendTestPulseProps<T>): JSX.Element {+ const onTestPulseChannel = useCallback(() => {+ const channelPulse = { ...pulse, channels: [channel] };+ const cleanedPulse = cleanPulse(channelPulse, channelSpecs);++ return testPulse(cleanedPulse);+ }, [pulse, channel, channelSpecs, testPulse]);++ return (+ <ActionButton+ actionFn={onTestPulseChannel}+ disabled={disabled}+ normalText={normalText}+ activeText={t`Sending…`}+ failedText={t`Sending failed`}+ successText={successText}+ />+ );+}diff --git a/frontend/src/metabase/entities/pulses.js b/frontend/src/metabase/entities/pulses.jsindex 26ebe4ca6b3..05367fa986b 100644--- a/frontend/src/metabase/entities/pulses.js+++ b/frontend/src/metabase/entities/pulses.js@@ -12,10 +12,6 @@ import {entityCompatibleQuery,undo,} from "metabase/lib/entities";-import { addUndo } from "metabase/redux/undo";--export const UNSUBSCRIBE = "metabase/entities/pulses/unsubscribe";-/*** @deprecated use "metabase/api" instead*/@@ -24,10 +20,6 @@ export const Pulses = createEntity({nameOne: "pulse",path: "/api/pulse",- actionTypes: {- UNSUBSCRIBE,- },-rtk: {getUseGetQuery: () => ({useGetQuery,@@ -73,19 +65,6 @@ export const Pulses = createEntity({undo(opts, t`subscription`, archived ? t`deleted` : t`restored`),);},-- unsubscribe:- ({ id }) =>- async (dispatch) => {- await entityCompatibleQuery(- id,- dispatch,- subscriptionApi.endpoints.unsubscribe,- );- dispatch(addUndo({ message: t`Successfully unsubscribed` }));- dispatch({ type: UNSUBSCRIBE, payload: { id } });- dispatch({ type: Pulses.actionTypes.INVALIDATE_LISTS_ACTION });- },},objectSelectors: {diff --git a/frontend/src/metabase/forms/components/FormMessage/FormMessage.tsx b/frontend/src/metabase/forms/components/FormMessage/FormMessage.tsxindex 45ca5b54f25..3fcbcb5fb01 100644--- a/frontend/src/metabase/forms/components/FormMessage/FormMessage.tsx+++ b/frontend/src/metabase/forms/components/FormMessage/FormMessage.tsx@@ -1,20 +1,32 @@import { t } from "ttag";+import { isObject } from "metabase-types/guards";+import { FormMessageStyled } from "./FormMessage.styled";-type Response = {+export type Response = {status: number;data?: {message?: string;};};+function isResponse(value: unknown): value is Response {+ return (+ isObject(value) &&+ "status" in value &&+ typeof value.status === "number" &&+ (value.data === undefined ||+ (isObject(value.data) && typeof value.data.message === "string"))+ );+}+interface FormMessageProps {className?: string;message?: string;noPadding?: boolean;formSuccess?: Response;- formError?: Response;+ formError?: unknown;}const getMessage = ({@@ -34,16 +46,17 @@ const getMessage = ({/*** @deprecated*/-export const getErrorMessage = (formError?: Response) => {- if (formError) {- if (formError.data && formError.data.message) {+export const getErrorMessage = (formError?: unknown) => {+ if (isResponse(formError)) {+ if (formError.data?.message) {return formError.data.message;} else if (formError.status >= 400) {return t`Server error encountered`;- } else {- return t`Unknown error encountered`;}}+ if (formError) {+ return t`Unknown error encountered`;+ }};/**diff --git a/frontend/src/metabase/hoc/ModalRoute.tsx b/frontend/src/metabase/hoc/ModalRoute.tsxindex 0b87d373edb..3af0598f7f3 100644--- a/frontend/src/metabase/hoc/ModalRoute.tsx+++ b/frontend/src/metabase/hoc/ModalRoute.tsx@@ -1,4 +1,4 @@-import type { LocationDescriptor } from "history";+import type { Location, LocationDescriptor } from "history";import { Component } from "react";import * as React from "react";import { Route } from "react-router";@@ -8,6 +8,8 @@ import { Modal } from "metabase/common/components/Modal";import { connect } from "metabase/lib/redux";import MetabaseSettings from "metabase/lib/settings";+type RouteParams = Record<string, string | undefined>;+type IRoute = {path: string;};@@ -37,12 +39,18 @@ export const getParentPath = (route: IRoute, location: Location) => {return fullPathSegments.join("/");};-type ComposedModalProps = {+export type ComposedModalProps<+ P extends RouteParams = RouteParams,+ Q = unknown,+> = {+ params: P;+ location: Location<Q>;onClose: () => void;};interface WrappedModalRouteProps {route: IRoute;+ params: RouteParams;location: Location;onChangeLocation: (nextLocation: LocationDescriptor) => void;}@@ -80,9 +88,18 @@ const ModalWithRoute = (return connect(null, { onChangeLocation: push })(ModalRouteComponent);};+// Base props that any modal rendered by ModalRoute must accept.+// Modal components typically narrow `params` to specific keys (e.g., { alertId?: string }),+// but they must accept the full ComposedModalProps shape.+type ModalComponentProps = {+ params: RouteParams;+ location: Location;+ onClose: () => void;+};+interface ModalRouteProps {path: string;- modal: React.ComponentType<ComposedModalProps>;+ modal: React.ComponentType<ModalComponentProps>;modalProps?: unknown;noWrap?: boolean;}diff --git a/frontend/src/metabase/lib/pulse.ts b/frontend/src/metabase/lib/pulse.tsindex c4182de4a0c..56f09e588a4 100644--- a/frontend/src/metabase/lib/pulse.ts+++ b/frontend/src/metabase/lib/pulse.ts@@ -21,6 +21,7 @@ import type {ScheduleSettings,User,} from "metabase-types/api";+import type { DashboardSubscriptionData } from "metabase-types/store";export const NEW_PULSE_TEMPLATE = {name: null,@@ -95,7 +96,7 @@ export function fieldsAreValid(channel: Channel, channelSpec?: ChannelSpec) {}function pulseChannelsAreValid(- pulse: DashboardSubscription,+ pulse: DashboardSubscriptionData,channelSpecs: Partial<ChannelSpecs>,) {return (@@ -124,7 +125,7 @@ export function recipientIsValid(recipient: RecipientPickerValue) {}export function pulseIsValid(- pulse: DashboardSubscription,+ pulse: DashboardSubscriptionData,channelSpecs: ChannelSpecs,) {return (@@ -136,13 +137,13 @@ export function pulseIsValid(}export function dashboardPulseIsValid(- pulse: DashboardSubscription,+ pulse: DashboardSubscriptionData,channelSpecs: Partial<ChannelSpecs>,) {return pulseChannelsAreValid(pulse, channelSpecs);}-export function emailIsEnabled(pulse: DashboardSubscription) {+export function emailIsEnabled(pulse: DashboardSubscriptionData) {return (pulse.channels.filter((channel) => channel.channel_type === "email" && channel.enabled,@@ -150,18 +151,21 @@ export function emailIsEnabled(pulse: DashboardSubscription) {);}-export function cleanPulse(- pulse: DashboardSubscription,- channelSpecs: ChannelSpecs,-) {+export function cleanPulse<T extends DashboardSubscriptionData>(+ pulse: T,+ channelSpecs: Partial<ChannelSpecs>,+): T {return {...pulse,channels: cleanPulseChannels(pulse.channels, channelSpecs),parameters: cleanPulseParameters(getPulseParameters(pulse)),- };+ } as T;}-function cleanPulseChannels(channels: Channel[], channelSpecs: ChannelSpecs) {+function cleanPulseChannels(+ channels: Channel[],+ channelSpecs: Partial<ChannelSpecs>,+) {return channels.filter((channel) =>channelIsValid(channel, channelSpecs?.[channel.channel_type]),);@@ -212,14 +216,14 @@ export function createChannel(};}-export function getPulseParameters(pulse: DashboardSubscription) {+export function getPulseParameters(pulse: DashboardSubscriptionData) {return pulse?.parameters || [];}// pulse parameters list cannot be trusted for existence/up-to-date defaults// rely on given parameters list but take pulse parameter values if they are not nullexport function getActivePulseParameters(- pulse: DashboardSubscription,+ pulse: DashboardSubscriptionData,parameters: Parameter[],) {const parameterValues = getPulseParameters(pulse).reduce<@@ -310,7 +314,9 @@ export const formatChannelDetails = ({ channel_type, details }: Channel) => {}};-export const formatChannelRecipients = (item: Alert) => {+export const formatChannelRecipients = (+ item: Alert | DashboardSubscription,+) => {const emailCount = getRecipientsCount(item, "email");const slackCount = getRecipientsCount(item, "slack");@@ -336,7 +342,7 @@ export const formatChannelRecipients = (item: Alert) => {};export const getRecipientsCount = (- item: Alert,+ item: Alert | DashboardSubscription,channelType: "email" | "slack",) => {return item.channels@@ -344,7 +350,10 @@ export const getRecipientsCount = (.reduce((total, channel) => total + (channel.recipients?.length || 0), 0);};-export const canArchiveLegacyAlert = (item: Alert, user: User): boolean => {+export const canArchiveLegacyAlert = (+ item: Alert | DashboardSubscription,+ user: User,+): boolean => {const recipients = item.channels.flatMap((channel) => {if (channel.recipients) {return channel.recipients.map((recipient) => recipient.id);diff --git a/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsx b/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsxindex de40970f1a6..5be60962bef 100644--- a/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsx+++ b/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsx@@ -27,10 +27,10 @@ import type {ChannelApiResponse,ChannelSpec,Dashboard,- DashboardSubscription,ScheduleSettings,User,} from "metabase-types/api";+import type { DraftDashboardSubscription } from "metabase-types/store";import { CaveatMessage } from "./CaveatMessage";import DefaultParametersSection from "./DefaultParametersSection";@@ -39,7 +39,7 @@ import Heading from "./Heading";import { CHANNEL_NOUN_PLURAL } from "./constants";interface AddEditEmailSidebarProps {- pulse: DashboardSubscription;+ pulse: DraftDashboardSubscription;formInput: ChannelApiResponse;channel: Channel;channelSpec: ChannelSpec;@@ -54,9 +54,9 @@ interface AddEditEmailSidebarProps {schedule: ScheduleSettings,changedProp: ScheduleChangeProp,) => void;- testPulse: () => void;+ testPulse: (pulse: DraftDashboardSubscription) => Promise<unknown>;toggleSkipIfEmpty: () => void;- setPulse: (pulse: DashboardSubscription) => void;+ setPulse: (pulse: DraftDashboardSubscription) => void;handleArchive: () => void;setPulseParameters: (parameters: UiParameter[]) => void;}diff --git a/frontend/src/metabase/notifications/AddEditSidebar/AddEditSlackSidebar.tsx b/frontend/src/metabase/notifications/AddEditSidebar/AddEditSlackSidebar.tsxindex 342cf3d76a9..914d5034fc8 100644--- a/frontend/src/metabase/notifications/AddEditSidebar/AddEditSlackSidebar.tsx+++ b/frontend/src/metabase/notifications/AddEditSidebar/AddEditSlackSidebar.tsx@@ -21,9 +21,9 @@ import type {ChannelSpec,ChannelSpecs,Dashboard,- DashboardSubscription,ScheduleSettings,} from "metabase-types/api";+import type { DraftDashboardSubscription } from "metabase-types/store";import { CaveatMessage } from "./CaveatMessage";import DefaultParametersSection from "./DefaultParametersSection";@@ -32,7 +32,7 @@ import Heading from "./Heading";import { CHANNEL_NOUN_PLURAL } from "./constants";interface AddEditSlackSidebarProps {- pulse: DashboardSubscription;+ pulse: DraftDashboardSubscription;formInput: ChannelApiResponse;channel: Channel;channelSpec: ChannelSpec;@@ -46,7 +46,7 @@ interface AddEditSlackSidebarProps {schedule: ScheduleSettings,changedProp: ScheduleChangeProp,) => void;- testPulse: () => void;+ testPulse: (pulse: DraftDashboardSubscription) => Promise<unknown>;toggleSkipIfEmpty: () => void;handleArchive: () => void;setPulseParameters: (parameters: UiParameter[]) => void;diff --git a/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsx b/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsxindex cfdcc3185f4..dbce7a4f675 100644--- a/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsx+++ b/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsx@@ -6,9 +6,10 @@ import { jt, msgid, ngettext, t } from "ttag";import CS from "metabase/css/core/index.css";import { Button, Checkbox, Flex, Modal } from "metabase/ui";-import type { Channel, DashboardSubscription } from "metabase-types/api";+import type { Channel } from "metabase-types/api";+import type { DraftDashboardSubscription } from "metabase-types/store";-function getConfirmItems(pulse: DashboardSubscription): ReactNode[] {+function getConfirmItems(pulse: DraftDashboardSubscription): ReactNode[] {return pulse.channels.map((c: Channel, index: number) =>c.channel_type === "email" ? (<span key={index}>@@ -44,7 +45,7 @@ function getConfirmItems(pulse: DashboardSubscription): ReactNode[] {}interface DeleteSubscriptionActionProps {- pulse: DashboardSubscription;+ pulse: DraftDashboardSubscription;handleArchive: () => void;}diff --git a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsxindex 49b158addff..796ec83f859 100644--- a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx+++ b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx@@ -45,7 +45,7 @@ import type {SubscriptionSupportingCard,User,} from "metabase-types/api";-import type { State } from "metabase-types/store";+import type { DraftDashboardSubscription, State } from "metabase-types/store";import { getSupportedCardsForSubscriptions } from "./get-supported-cards-for-subscriptions";@@ -92,23 +92,32 @@ const cardsToPulseCards = (const getEditingPulseWithDefaults = (state: State,props: { dashboard: Dashboard },-): DashboardSubscription => {- const pulse: DashboardSubscription = getEditingPulse(state);+): DraftDashboardSubscription => {+ const pulse = getEditingPulse(state);const dashboardWrapper = state.dashboard;- if (!pulse.name) {- pulse.name =- dashboardWrapper.dashboards[dashboardWrapper.dashboardId!].name;- }- if (!pulse.dashboard_id) {- pulse.dashboard_id =- dashboardWrapper.dashboards[dashboardWrapper.dashboardId!].id;+ const dashboardId = dashboardWrapper.dashboardId;++ if (dashboardId == null) {+ return {+ ...pulse,+ cards: cardsToPulseCards(+ getSupportedCardsForSubscriptions(props.dashboard),+ pulse.cards,+ ),+ };}- pulse.cards = cardsToPulseCards(- getSupportedCardsForSubscriptions(props.dashboard),- pulse.cards,- );- return pulse;+ const currentDashboard = dashboardWrapper.dashboards[dashboardId];++ return {+ ...pulse,+ name: pulse.name ?? currentDashboard.name,+ dashboard_id: pulse.dashboard_id ?? currentDashboard.id,+ cards: cardsToPulseCards(+ getSupportedCardsForSubscriptions(props.dashboard),+ pulse.cards,+ ),+ };};const mapStateToProps = (state: State, props: { dashboard: Dashboard }) => ({@@ -151,15 +160,15 @@ interface DashboardSubscriptionsSidebarInnerProps {formInput: ChannelApiResponse;initialCollectionId?: number;isAdmin?: boolean;- pulse: DashboardSubscription;+ pulse: DraftDashboardSubscription;saveEditingPulse: () => Promise<DashboardSubscription>;- testPulse: () => void;- updateEditingPulse: (pulse: Partial<DashboardSubscription>) => void;+ testPulse: (pulse: DraftDashboardSubscription) => Promise<unknown>;+ updateEditingPulse: (pulse: DraftDashboardSubscription) => void;cancelEditingPulse: () => void;pulses?: DashboardSubscription[];onCancel: () => void;setPulseArchived: (- pulse: DashboardSubscription,+ pulse: DraftDashboardSubscription,archived: boolean,) => Promise<void>;params?: Record<string, string>;@@ -193,7 +202,7 @@ function DashboardSubscriptionsSidebarInner({pulseRef.current = pulse;const setPulse = useCallback(- (p: Partial<DashboardSubscription>) => {+ (p: DraftDashboardSubscription) => {updateEditing(p);},[updateEditing],@@ -208,11 +217,11 @@ function DashboardSubscriptionsSidebarInner({const channel = createChannel(channelSpec);- const newPulse = {+ const newPulse: DraftDashboardSubscription = {...NEW_PULSE_TEMPLATE,channels: [channel],cards: getSupportedCardsForSubscriptions(dashboard),- } satisfies Partial<DashboardSubscription>;+ };setPulse(newPulse);},[dashboard, formInput, setPulse],@@ -532,7 +541,7 @@ function DashboardSubscriptionsSidebarInner({interface AddEditEmailSidebarWithHooksProps {index: number;- pulse: DashboardSubscription;+ pulse: DraftDashboardSubscription;formInput: ChannelApiResponse;channel: Channel;channelSpec: ChannelSpec | undefined;@@ -548,9 +557,9 @@ interface AddEditEmailSidebarWithHooksProps {schedule: ScheduleSettings,changedProp: ScheduleChangeProp,) => void;- testPulse: () => void;+ testPulse: (pulse: DraftDashboardSubscription) => Promise<unknown>;toggleSkipIfEmpty: () => void;- setPulse: (pulse: DashboardSubscription) => void;+ setPulse: (pulse: DraftDashboardSubscription) => void;users: User[];handleArchive: () => void;dashboard: Dashboard;@@ -583,7 +592,10 @@ function AddEditEmailSidebarWithHooks({[index, onChannelPropertyChange],);- const handleChannelScheduleChange = _.partial(onChannelScheduleChange, index);+ const handleChannelScheduleChange = useMemo(+ () => _.partial(onChannelScheduleChange, index),+ [index, onChannelScheduleChange],+ );return (<AddEditEmailSidebardiff --git a/frontend/src/metabase/notifications/EmailAttachmentPicker.tsx b/frontend/src/metabase/notifications/EmailAttachmentPicker.tsxindex 55a86917236..d1d58f276bf 100644--- a/frontend/src/metabase/notifications/EmailAttachmentPicker.tsx+++ b/frontend/src/metabase/notifications/EmailAttachmentPicker.tsx@@ -1,5 +1,12 @@import cx from "classnames";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ useCallback,+ useEffect,+ useMemo,+ useReducer,+ useRef,+ useState,+} from "react";import { t } from "ttag";import _ from "underscore";@@ -8,10 +15,8 @@ import { Toggle } from "metabase/common/components/Toggle";import type { ExportFormat } from "metabase/common/types/export";import CS from "metabase/css/core/index.css";import { Box, Checkbox, Group, Icon, Text, Tooltip } from "metabase/ui";-import type {- DashboardSubscription,- SubscriptionSupportingCard,-} from "metabase-types/api";+import type { SubscriptionSupportingCard } from "metabase-types/api";+import type { DraftDashboardSubscription } from "metabase-types/store";const DEFAULT_ATTACHMENT_TYPE: AttachmentType = "csv";@@ -48,7 +53,9 @@ function getInitialPivotingState(cards: SubscriptionSupportingCard[]): boolean {return false;}-function getInitialAttachmentOnlyState(pulse: DashboardSubscription): boolean {+function getInitialAttachmentOnlyState(+ pulse: DraftDashboardSubscription,+): boolean {if (pulse?.channels?.length > 0) {return pulse.channels.some((channel) => !!channel.details?.attachment_only);}@@ -57,7 +64,7 @@ function getInitialAttachmentOnlyState(pulse: DashboardSubscription): boolean {function calculateStateFromCards(cards: SubscriptionSupportingCard[],- pulse: DashboardSubscription,+ pulse: DraftDashboardSubscription,) {const selectedCards = cards.filter((card) => card.include_csv || card.include_xls,@@ -73,9 +80,48 @@ function calculateStateFromCards(};}+type ExportOptionsState = {+ isFormattingEnabled: boolean;+ isPivotingEnabled: boolean;+ isAttachmentOnly: boolean;+};++type ExportOptionsAction =+ | { type: "TOGGLE_FORMATTING" }+ | { type: "TOGGLE_PIVOTING" }+ | { type: "TOGGLE_ATTACHMENT_ONLY" }+ | { type: "DISABLE_ATTACHMENT_ONLY" }+ | { type: "SET_ALL"; payload: ExportOptionsState };++function exportOptionsReducer(+ state: ExportOptionsState,+ action: ExportOptionsAction,+): ExportOptionsState {+ switch (action.type) {+ case "TOGGLE_FORMATTING":+ return { ...state, isFormattingEnabled: !state.isFormattingEnabled };+ case "TOGGLE_PIVOTING":+ return { ...state, isPivotingEnabled: !state.isPivotingEnabled };+ case "TOGGLE_ATTACHMENT_ONLY":+ return { ...state, isAttachmentOnly: !state.isAttachmentOnly };+ case "DISABLE_ATTACHMENT_ONLY":+ return { ...state, isAttachmentOnly: false };+ case "SET_ALL":+ return action.payload;+ default:+ return state;+ }+}++const INITIAL_EXPORT_OPTIONS: ExportOptionsState = {+ isFormattingEnabled: true,+ isPivotingEnabled: false,+ isAttachmentOnly: false,+};+type EmailAttachmentPickerProps = {- pulse: DashboardSubscription;- setPulse: (pulse: DashboardSubscription) => void;+ pulse: DraftDashboardSubscription;+ setPulse: (pulse: DraftDashboardSubscription) => void;cards: SubscriptionSupportingCard[];allowDownload: boolean | undefined;};@@ -87,14 +133,18 @@ export function EmailAttachmentPicker({allowDownload,}: EmailAttachmentPickerProps) {const [isEnabled, setIsEnabled] = useState(false);- const [isFormattingEnabled, setIsFormattingEnabled] = useState(true);- const [isPivotingEnabled, setIsPivotingEnabled] = useState(false);- const [isAttachmentOnly, setIsAttachmentOnly] = useState(false);const [selectedAttachmentType, setSelectedAttachmentType] =useState<AttachmentType>(DEFAULT_ATTACHMENT_TYPE);const [selectedCardIds, setSelectedCardIds] = useState<Set<string>>(new Set(),);+ const [exportOptions, dispatchExportOptions] = useReducer(+ exportOptionsReducer,+ INITIAL_EXPORT_OPTIONS,+ );++ const { isFormattingEnabled, isPivotingEnabled, isAttachmentOnly } =+ exportOptions;const updatePulseCards = useCallback(/*@@ -104,11 +154,7 @@ export function EmailAttachmentPicker({(attachmentType: AttachmentType,cardIds: Set<string>,- options: {- isFormattingEnabled: boolean;- isPivotingEnabled: boolean;- isAttachmentOnly: boolean;- },+ options: ExportOptionsState,) => {const isXls = attachmentType === "xlsx";const isCsv = attachmentType === "csv";@@ -144,49 +190,62 @@ export function EmailAttachmentPicker({useEffect(() => {const newState = calculateStateFromCards(cards, pulse);+ const prev = prevComputedStateRef.current;++ const applyState = (isInitial: boolean) => {+ prevComputedStateRef.current = newState;++ if (isInitial) {+ setIsEnabled(newState.isEnabled);+ setSelectedAttachmentType(newState.selectedAttachmentType);+ setSelectedCardIds(newState.selectedCardIds);+ } else {+ // Preserve enabled state if it was already enabled+ setIsEnabled((prevEnabled) => newState.isEnabled || prevEnabled);+ // Only update attachment type if there are selected cards+ setSelectedAttachmentType((prevType) =>+ newState.selectedCardIds.size === 0+ ? prevType+ : newState.selectedAttachmentType,+ );+ setSelectedCardIds((prevIds) =>+ _.isEqual(newState.selectedCardIds, prevIds)+ ? prevIds+ : newState.selectedCardIds,+ );+ }++ dispatchExportOptions({+ type: "SET_ALL",+ payload: {+ isFormattingEnabled: newState.isFormattingEnabled,+ isPivotingEnabled: newState.isPivotingEnabled,+ isAttachmentOnly: newState.isAttachmentOnly,+ },+ });+ };if (isInitialMount.current) {isInitialMount.current = false;- prevComputedStateRef.current = newState;- setIsEnabled(newState.isEnabled);- setSelectedAttachmentType(newState.selectedAttachmentType);- setSelectedCardIds(newState.selectedCardIds);- setIsFormattingEnabled(newState.isFormattingEnabled);- setIsPivotingEnabled(newState.isPivotingEnabled);- setIsAttachmentOnly(newState.isAttachmentOnly);+ applyState(true);return;}- const prev = prevComputedStateRef.current;- // Match class component's shouldUpdateState: skip if nothing meaningful changed- if (+ // Skip if nothing meaningful changed+ const hasNoMeaningfulChanges =prev &&(prev.isEnabled || !newState.isEnabled) &&prev.selectedAttachmentType === newState.selectedAttachmentType &&_.isEqual(prev.selectedCardIds, newState.selectedCardIds) &&prev.isFormattingEnabled === newState.isFormattingEnabled &&prev.isPivotingEnabled === newState.isPivotingEnabled &&- prev.isAttachmentOnly === newState.isAttachmentOnly- ) {+ prev.isAttachmentOnly === newState.isAttachmentOnly;++ if (hasNoMeaningfulChanges) {return;}- prevComputedStateRef.current = newState;-- setIsEnabled((prev) => newState.isEnabled || prev);- setSelectedAttachmentType((prev) =>- newState.selectedCardIds.size === 0- ? prev- : newState.selectedAttachmentType,- );- setSelectedCardIds((prev) => {- if (_.isEqual(newState.selectedCardIds, prev)) {- return prev;- }- return newState.selectedCardIds;- });- setIsFormattingEnabled(newState.isFormattingEnabled);- setIsPivotingEnabled(newState.isPivotingEnabled);- setIsAttachmentOnly(newState.isAttachmentOnly);++ applyState(false);}, [cards, pulse]);const canAttachFiles = !!allowDownload;@@ -216,21 +275,17 @@ export function EmailAttachmentPicker({const emptySet = new Set<string>();setSelectedCardIds(emptySet);updatePulseCards(selectedAttachmentType, emptySet, {- isFormattingEnabled,- isPivotingEnabled,+ ...exportOptions,isAttachmentOnly: false,});}setIsEnabled(includeAttachment);- setIsAttachmentOnly((prev) => (includeAttachment ? prev : false));+ if (!includeAttachment) {+ dispatchExportOptions({ type: "DISABLE_ATTACHMENT_ONLY" });+ }},- [- selectedAttachmentType,- updatePulseCards,- isFormattingEnabled,- isPivotingEnabled,- ],+ [selectedAttachmentType, updatePulseCards, exportOptions],);const setAttachmentType = useCallback(@@ -239,20 +294,10 @@ export function EmailAttachmentPicker({*/(format: ExportFormat) => {if (format === "csv" || format === "xlsx") {- updatePulseCards(format, selectedCardIds, {- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,- });+ updatePulseCards(format, selectedCardIds, exportOptions);}},- [- selectedCardIds,- updatePulseCards,- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,- ],+ [selectedCardIds, updatePulseCards, exportOptions],);const onToggleCard = useCallback(@@ -270,20 +315,14 @@ export function EmailAttachmentPicker({}setSelectedCardIds(next);- updatePulseCards(attachmentType, next, {- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,- });+ updatePulseCards(attachmentType, next, exportOptions);},[cardIdsToCards,selectedCardIds,selectedAttachmentType,updatePulseCards,- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,+ exportOptions,],);@@ -298,11 +337,7 @@ export function EmailAttachmentPicker({cards.length === selectedCardIds.size ? new Set<string>() : allCardIds;setSelectedCardIds(newSelectedCardIds);- updatePulseCards(attachmentType, newSelectedCardIds, {- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,- });+ updatePulseCards(attachmentType, newSelectedCardIds, exportOptions);}, [allCardIds,cardIdsToCards,@@ -310,59 +345,51 @@ export function EmailAttachmentPicker({selectedCardIds,selectedAttachmentType,updatePulseCards,- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,+ exportOptions,]);const onToggleFormatting = useCallback(() => {- const newValue = !isFormattingEnabled;- setIsFormattingEnabled(newValue);- updatePulseCards(selectedAttachmentType, selectedCardIds, {- isFormattingEnabled: newValue,- isPivotingEnabled,- isAttachmentOnly,- });+ const newOptions = {+ ...exportOptions,+ isFormattingEnabled: !isFormattingEnabled,+ };+ dispatchExportOptions({ type: "TOGGLE_FORMATTING" });+ updatePulseCards(selectedAttachmentType, selectedCardIds, newOptions);}, [selectedAttachmentType,selectedCardIds,updatePulseCards,+ exportOptions,isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,]);const onTogglePivoting = useCallback(() => {- const newValue = !isPivotingEnabled;- setIsPivotingEnabled(newValue);- updatePulseCards(selectedAttachmentType, selectedCardIds, {- isFormattingEnabled,- isPivotingEnabled: newValue,- isAttachmentOnly,- });+ const newOptions = {+ ...exportOptions,+ isPivotingEnabled: !isPivotingEnabled,+ };+ dispatchExportOptions({ type: "TOGGLE_PIVOTING" });+ updatePulseCards(selectedAttachmentType, selectedCardIds, newOptions);}, [selectedAttachmentType,selectedCardIds,updatePulseCards,- isFormattingEnabled,+ exportOptions,isPivotingEnabled,- isAttachmentOnly,]);const onToggleAttachmentOnly = useCallback(() => {- const newValue = !isAttachmentOnly;- setIsAttachmentOnly(newValue);- updatePulseCards(selectedAttachmentType, selectedCardIds, {- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly: newValue,- });+ const newOptions = {+ ...exportOptions,+ isAttachmentOnly: !isAttachmentOnly,+ };+ dispatchExportOptions({ type: "TOGGLE_ATTACHMENT_ONLY" });+ updatePulseCards(selectedAttachmentType, selectedCardIds, newOptions);}, [selectedAttachmentType,selectedCardIds,updatePulseCards,- isFormattingEnabled,- isPivotingEnabled,+ exportOptions,isAttachmentOnly,]);diff --git a/frontend/src/metabase/notifications/PulsesListSidebar.tsx b/frontend/src/metabase/notifications/PulsesListSidebar.tsxindex 801336a951c..a366fa9b212 100644--- a/frontend/src/metabase/notifications/PulsesListSidebar.tsx+++ b/frontend/src/metabase/notifications/PulsesListSidebar.tsx@@ -170,11 +170,11 @@ function buildRecipientText(pulse: DashboardSubscription): string {const { channel_type, recipients } = firstChannel;- if (channel_type !== "email" || _.isEmpty(recipients)) {+ if (channel_type !== "email" || !recipients || recipients.length === 0) {return "";}- const [firstRecipient, ...otherRecipients] = recipients!;+ const [firstRecipient, ...otherRecipients] = recipients;const firstRecipientText = firstRecipient.common_name || firstRecipient.email;return _.isEmpty(otherRecipients)? firstRecipientTextdiff --git a/frontend/src/metabase/notifications/pulse/reducers.ts b/frontend/src/metabase/notifications/pulse/reducers.tsindex a109ac32fb6..3b47fb24b86 100644--- a/frontend/src/metabase/notifications/pulse/reducers.ts+++ b/frontend/src/metabase/notifications/pulse/reducers.ts@@ -4,6 +4,7 @@ import type {ChannelApiResponse,DashboardSubscription,} from "metabase-types/api";+import type { DraftDashboardSubscription } from "metabase-types/store";import {CANCEL_EDITING_PULSE,@@ -15,32 +16,24 @@ import {UPDATE_EDITING_PULSE,} from "./actions";-const DEFAULT_EDITING_PULSE = {- name: null,+const DEFAULT_EDITING_PULSE: DraftDashboardSubscription = {cards: [],channels: [],- // Required casting because we can't fully instantiate DashboardSubscription on the client.-} as unknown as DashboardSubscription;+};-export const editingPulse = handleActions(+export const editingPulse = handleActions<+ DraftDashboardSubscription,+ DraftDashboardSubscription+>({[SET_EDITING_PULSE]: {- next: (- _state: DashboardSubscription,- { payload }: { payload: DashboardSubscription },- ) => payload,+ next: (_state, { payload }) => payload,},[UPDATE_EDITING_PULSE]: {- next: (- _state: DashboardSubscription,- { payload }: { payload: DashboardSubscription },- ) => payload,+ next: (_state, { payload }) => payload,},[SAVE_EDITING_PULSE]: {- next: (- _state: DashboardSubscription,- { payload }: { payload: DashboardSubscription },- ) => payload,+ next: (_state, { payload }) => payload,},[CANCEL_EDITING_PULSE]: {next: () => DEFAULT_EDITING_PULSE,diff --git a/frontend/src/metabase/notifications/pulse/selectors.ts b/frontend/src/metabase/notifications/pulse/selectors.tsindex f69133b2144..28a82d8199a 100644--- a/frontend/src/metabase/notifications/pulse/selectors.ts+++ b/frontend/src/metabase/notifications/pulse/selectors.ts@@ -1,10 +1,7 @@-import type {- ChannelApiResponse,- DashboardSubscription,-} from "metabase-types/api";-import type { State } from "metabase-types/store";+import type { ChannelApiResponse } from "metabase-types/api";+import type { DraftDashboardSubscription, State } from "metabase-types/store";-export const getEditingPulse = (state: State): DashboardSubscription =>+export const getEditingPulse = (state: State): DraftDashboardSubscription =>state.pulse.editingPulse;export const getPulseFormInput = (diff --git a/frontend/src/metabase/plugins/oss/core.ts b/frontend/src/metabase/plugins/oss/core.tsindex 8ec340c848a..97a35a14698 100644--- a/frontend/src/metabase/plugins/oss/core.ts+++ b/frontend/src/metabase/plugins/oss/core.ts@@ -5,8 +5,12 @@ import { t } from "ttag";import noResultsSource from "assets/img/no_results.svg";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";import type { UiParameter } from "metabase-lib/v1/parameters/types";-import type { Dashboard, DashboardSubscription } from "metabase-types/api";-import type { AdminPathKey, State } from "metabase-types/store";+import type { Dashboard } from "metabase-types/api";+import type {+ AdminPathKey,+ DraftDashboardSubscription,+ State,+} from "metabase-types/store";// Typesexport type IllustrationValue = {@@ -20,7 +24,7 @@ interface PluginDashboardSubscriptionParametersSectionOverride {parameters: UiParameter[];hiddenParameters?: string;dashboard: Dashboard;- pulse: DashboardSubscription;+ pulse: DraftDashboardSubscription;setPulseParameters: (parameters: UiParameter[]) => void;}>;}diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsxindex e88cd5b168f..3c2c4582564 100644--- a/frontend/src/metabase/routes.jsx+++ b/frontend/src/metabase/routes.jsx@@ -1,7 +1,7 @@import { IndexRedirect, IndexRoute, Redirect, Route } from "react-router";import App from "metabase/App.tsx";-import getAccountRoutes from "metabase/account/routes";+import { getAccountRoutes } from "metabase/account/routes";import CollectionPermissionsModal from "metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal";import { getRoutes as getAdminRoutes } from "metabase/admin/routes";import { ForgotPassword } from "metabase/auth/components/ForgotPassword";