Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Reduce `metabase/utils` violations by moving notifications helpers into shared (#72510)

Romeo Van Snicke0acf707bd4a
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
index 2b22927e580..a0cbba417bc 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts
@@ -68,11 +68,6 @@ export async function runQuestionQuerySdk(
question = question.maybeResetDisplay(data, sensibleDisplays, undefined);
}
- // FIXME: this removes "You can also get an alert when there are some results." feature for question
- if (question) {
- question.alertType = () => null;
- }
-
return { question, queryResults };
}
diff --git a/frontend/src/metabase-lib/v1/Alert/constants.ts b/frontend/src/metabase-lib/v1/Alert/constants.ts
deleted file mode 100644
index 9322290d77f..00000000000
--- a/frontend/src/metabase-lib/v1/Alert/constants.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-export const ALERT_TYPE_ROWS = "alert-type-rows";
-export const ALERT_TYPE_TIMESERIES_GOAL = "alert-type-timeseries-goal";
-export const ALERT_TYPE_PROGRESS_BAR_GOAL = "alert-type-progress-bar-goal";
-
-// eslint-disable-next-line @typescript-eslint/no-unused-vars -- used for types
-const AlertTypes = [
- ALERT_TYPE_ROWS,
- ALERT_TYPE_TIMESERIES_GOAL,
- ALERT_TYPE_PROGRESS_BAR_GOAL,
-] as const;
-
-export type NotificationTriggerType = (typeof AlertTypes)[number];
diff --git a/frontend/src/metabase-lib/v1/Alert/index.ts b/frontend/src/metabase-lib/v1/Alert/index.ts
deleted file mode 100644
index 6abcd8bd9f9..00000000000
--- a/frontend/src/metabase-lib/v1/Alert/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export {
- ALERT_TYPE_ROWS,
- ALERT_TYPE_TIMESERIES_GOAL,
- ALERT_TYPE_PROGRESS_BAR_GOAL,
-} from "./constants";
diff --git a/frontend/src/metabase-lib/v1/Question.ts b/frontend/src/metabase-lib/v1/Question.ts
index 8174a3935a8..52c78e66170 100644
--- a/frontend/src/metabase-lib/v1/Question.ts
+++ b/frontend/src/metabase-lib/v1/Question.ts
@@ -11,12 +11,6 @@ import {
serializeCardForUrl,
} from "metabase/utils/card";
import * as Lib from "metabase-lib";
-import {
- ALERT_TYPE_PROGRESS_BAR_GOAL,
- ALERT_TYPE_ROWS,
- ALERT_TYPE_TIMESERIES_GOAL,
-} from "metabase-lib/v1/Alert";
-import type { NotificationTriggerType } from "metabase-lib/v1/Alert/constants";
import type Database from "metabase-lib/v1/metadata/Database";
import Metadata from "metabase-lib/v1/metadata/Metadata";
import { getQuestionVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";
@@ -397,45 +391,6 @@ class Question {
return (db && db.auto_run_queries) || false;
}
- /**
- * Returns the type of alert that current question supports
- *
- * The `visualization_settings` in card object doesn't contain default settings,
- * so you can provide the complete visualization settings object to `alertType`
- * for taking those into account
- */
- alertType(visualizationSettings): NotificationTriggerType | null {
- const display = this.display();
-
- if (!this.canRun()) {
- return null;
- }
-
- const isLineAreaBar =
- display === "line" || display === "area" || display === "bar";
-
- if (display === "progress") {
- return ALERT_TYPE_PROGRESS_BAR_GOAL;
- } else if (isLineAreaBar) {
- const vizSettings = visualizationSettings
- ? visualizationSettings
- : this.card().visualization_settings;
- const goalEnabled = vizSettings["graph.show_goal"];
- const hasSingleYAxisColumn =
- vizSettings["graph.metrics"] &&
- vizSettings["graph.metrics"].length === 1;
-
- // We don't currently support goal alerts for multiseries question
- if (goalEnabled && hasSingleYAxisColumn) {
- return ALERT_TYPE_TIMESERIES_GOAL;
- } else {
- return ALERT_TYPE_ROWS;
- }
- } else {
- return ALERT_TYPE_ROWS;
- }
- }
-
/**
* Visualization drill-through and action widget actions
*
diff --git a/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsx b/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsx
index 7336c0c3370..f1aac3ea73b 100644
--- a/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsx
+++ b/frontend/src/metabase/account/notifications/components/NotificationCard/DashboardNotificationCard.tsx
@@ -5,7 +5,7 @@ import { t } from "ttag";
import { formatCreatorMessage } from "metabase/account/notifications/components/NotificationCard/utils";
import type { DashboardSubscriptionListItem } from "metabase/account/notifications/types";
import { Link } from "metabase/common/components/Link";
-import { formatTitle } from "metabase/utils/notifications";
+import { formatTitle } from "metabase/notifications/utils";
import { canArchiveLegacyAlert, formatChannel } from "metabase/utils/pulse";
import * as Urls from "metabase/utils/urls";
import type { Channel, User } from "metabase-types/api";
diff --git a/frontend/src/metabase/account/notifications/components/NotificationCard/NotificationCard.tsx b/frontend/src/metabase/account/notifications/components/NotificationCard/NotificationCard.tsx
index 8eda3357fcc..a6bca2cb662 100644
--- a/frontend/src/metabase/account/notifications/components/NotificationCard/NotificationCard.tsx
+++ b/frontend/src/metabase/account/notifications/components/NotificationCard/NotificationCard.tsx
@@ -11,13 +11,13 @@ import {
import { formatCreatorMessage } from "metabase/account/notifications/components/NotificationCard/utils";
import type { QuestionNotificationListItem } from "metabase/account/notifications/types";
import { Link } from "metabase/common/components/Link/Link";
-import { Group, Icon } from "metabase/ui";
import {
canArchive,
formatNotificationSchedule,
formatTitle,
getNotificationEnabledChannelsMap,
-} from "metabase/utils/notifications";
+} from "metabase/notifications/utils";
+import { Group, Icon } from "metabase/ui";
import * as Urls from "metabase/utils/urls";
import type { User } from "metabase-types/api";
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
index 30301f70fc7..d26ff8d8ab1 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx
@@ -12,7 +12,11 @@ import {
} from "metabase/api";
import CS from "metabase/css/core/index.css";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
-import { getDefaultQuestionAlertRequest } from "metabase/notifications/utils";
+import {
+ alertIsValid,
+ getAlertTriggerOptions,
+ getDefaultQuestionAlertRequest,
+} from "metabase/notifications/utils";
import { updateUrl } from "metabase/query_builder/actions/url";
import {
getQuestion,
@@ -32,10 +36,6 @@ import {
rem,
} from "metabase/ui";
import { getResponseErrorMessage } from "metabase/utils/errors";
-import {
- alertIsValid,
- getAlertTriggerOptions,
-} from "metabase/utils/notifications";
import {
getHasConfiguredAnyChannel,
getHasConfiguredEmailOrSlackChannel,
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
index 54960a19d15..259075bd843 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationSchedule/NotificationSchedule.tsx
@@ -10,12 +10,12 @@ import {
import {
DEFAULT_ALERT_CRON_SCHEDULE,
DEFAULT_ALERT_SCHEDULE,
+ formatNotificationScheduleDescription,
} from "metabase/notifications/utils";
import { getSetting } from "metabase/selectors/settings";
import { getApplicationName } from "metabase/selectors/whitelabel";
import { Box, type BoxProps, Flex, Text } from "metabase/ui";
import { getScheduleExplanation } from "metabase/utils/cron";
-import { formatNotificationScheduleDescription } from "metabase/utils/notifications";
import { useSelector } from "metabase/utils/redux";
import type {
NotificationCronSubscription,
diff --git a/frontend/src/metabase/notifications/modals/QuestionAlertListModal/AlertListItem.tsx b/frontend/src/metabase/notifications/modals/QuestionAlertListModal/AlertListItem.tsx
index 8e63c912cdf..2907936205d 100644
--- a/frontend/src/metabase/notifications/modals/QuestionAlertListModal/AlertListItem.tsx
+++ b/frontend/src/metabase/notifications/modals/QuestionAlertListModal/AlertListItem.tsx
@@ -4,12 +4,12 @@ import { msgid, ngettext, t } from "ttag";
import _ from "underscore";
import { formatCreatorMessage } from "metabase/account/notifications/components/NotificationCard/utils";
-import { getUser } from "metabase/selectors/user";
-import { Box, FixedSizeIcon, Group, Stack, Text } from "metabase/ui";
import {
formatNotificationSchedule,
getNotificationHandlersGroupedByTypes,
-} from "metabase/utils/notifications";
+} from "metabase/notifications/utils";
+import { getUser } from "metabase/selectors/user";
+import { Box, FixedSizeIcon, Group, Stack, Text } from "metabase/ui";
import { useSelector } from "metabase/utils/redux";
import { isNotFalsy } from "metabase/utils/types";
import type {
diff --git a/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx b/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx
index b3de116a66f..34e29f90b89 100644
--- a/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx
+++ b/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx
@@ -4,8 +4,8 @@ import { t } from "ttag";
import { Link } from "metabase/common/components/Link/Link";
import CS from "metabase/css/core/index.css";
+import { getNotificationHandlersGroupedByTypes } from "metabase/notifications/utils";
import { Button, Menu, Text } from "metabase/ui";
-import { getNotificationHandlersGroupedByTypes } from "metabase/utils/notifications";
import type {
ChannelApiResponse,
NotificationChannel,
diff --git a/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx b/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx
index c73599dc52c..9c3b5cace9a 100644
--- a/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx
+++ b/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx
@@ -8,9 +8,9 @@ import {
type ChannelToAddOption,
NotificationChannelsAddMenu,
} from "metabase/notifications/modals/components/NotificationChannelsAddMenu";
+import { getNotificationHandlersGroupedByTypes } from "metabase/notifications/utils";
import { canAccessSettings, getUser } from "metabase/selectors/user";
import { Stack } from "metabase/ui";
-import { getNotificationHandlersGroupedByTypes } from "metabase/utils/notifications";
import { useSelector } from "metabase/utils/redux";
import type {
ChannelApiResponse,
diff --git a/frontend/src/metabase/notifications/utils.ts b/frontend/src/metabase/notifications/utils.ts
index 40658c27ba6..241ff2af54a 100644
--- a/frontend/src/metabase/notifications/utils.ts
+++ b/frontend/src/metabase/notifications/utils.ts
@@ -1,11 +1,36 @@
+import { c, msgid, ngettext, t } from "ttag";
+import _ from "underscore";
+
+import type { NotificationListItem } from "metabase/account/notifications/types";
+import { cronToScheduleSettings } from "metabase/common/components/Schedule/cron";
+import { getScheduleExplanation } from "metabase/utils/cron";
+import { getEmailDomain, isEmail } from "metabase/utils/email";
+import { formatDateTimeWithUnit } from "metabase/utils/formatting/date";
+import { formatTimeWithUnit } from "metabase/utils/formatting/time";
+import MetabaseSettings from "metabase/utils/settings";
+import { formatFrame } from "metabase/utils/time-dayjs";
+import type Question from "metabase-lib/v1/Question";
import type {
CardId,
ChannelApiResponse,
+ ChannelType,
CreateAlertNotificationRequest,
+ Notification,
+ NotificationCardSendCondition,
NotificationChannel,
+ NotificationChannelType,
+ NotificationCronSubscription,
NotificationHandler,
+ NotificationHandlerEmail,
+ NotificationHandlerHttp,
+ NotificationHandlerSlack,
+ NotificationRecipient,
+ NotificationRecipientRawValue,
ScheduleSettings,
+ UpdateAlertNotificationRequest,
+ User,
UserId,
+ VisualizationSettings,
} from "metabase-types/api";
import type { NotificationTriggerOption } from "./modals/CreateOrEditQuestionAlertModal/types";
@@ -118,3 +143,348 @@ export const getDefaultQuestionAlertRequest = ({
],
};
};
+
+export const formatTitle = ({ item, type }: NotificationListItem) => {
+ switch (type) {
+ case "pulse":
+ return item.name;
+ case "question-notification":
+ return item.payload.card?.name || t`Alert`;
+ }
+};
+
+const getRecipientIdentity = (recipient: NotificationRecipient) => {
+ if (recipient.type === "notification-recipient/user") {
+ return recipient.user_id;
+ }
+
+ if (recipient.type === "notification-recipient/raw-value") {
+ return recipient.details.value; // email
+ }
+};
+
+export const canArchive = (item: Notification, user: User) => {
+ const recipients = item.handlers.flatMap((channel) => {
+ if (channel.recipients) {
+ return channel.recipients.map(getRecipientIdentity);
+ } else {
+ return [];
+ }
+ });
+
+ const isCreator = item.creator?.id === user.id;
+ const isSubscribed = recipients.includes(user.id);
+ const isOnlyRecipient = recipients.length === 1;
+
+ return isCreator && (!isSubscribed || isOnlyRecipient);
+};
+
+export function emailHandlerRecipientIsValid(recipient: NotificationRecipient) {
+ if (recipient.type === "notification-recipient/user") {
+ return !!recipient.user_id;
+ }
+
+ if (recipient.type === "notification-recipient/raw-value") {
+ const email = recipient.details.value;
+
+ const recipientDomain = getEmailDomain(email);
+ const allowedDomains = MetabaseSettings.subscriptionAllowedDomains();
+ return (
+ !!email &&
+ isEmail(email) &&
+ (_.isEmpty(allowedDomains) ||
+ !!(recipientDomain && allowedDomains.includes(recipientDomain)))
+ );
+ }
+}
+
+export function slackHandlerRecipientIsValid(
+ recipient: NotificationRecipientRawValue,
+) {
+ return !!recipient.details.value;
+}
+
+export function channelIsValid(handlers: NotificationHandler) {
+ switch (handlers.channel_type) {
+ case "channel/email":
+ return (
+ handlers.recipients &&
+ handlers.recipients.length > 0 &&
+ handlers.recipients.every(emailHandlerRecipientIsValid)
+ );
+ case "channel/slack":
+ return (
+ handlers.recipients &&
+ handlers.recipients.length > 0 &&
+ handlers.recipients.every(slackHandlerRecipientIsValid)
+ );
+ case "channel/http":
+ return handlers.channel_id;
+ default:
+ return false;
+ }
+}
+
+const notificationHandlerTypeToChannelMap: Record<
+ NotificationChannelType,
+ ChannelType
+> = {
+ ["channel/email"]: "email",
+ ["channel/slack"]: "slack",
+ ["channel/http"]: "http",
+};
+
+export function alertIsValid(
+ notification: CreateAlertNotificationRequest | UpdateAlertNotificationRequest,
+ channelSpec: ChannelApiResponse | undefined,
+) {
+ const handlers = notification.handlers;
+
+ return (
+ channelSpec?.channels &&
+ handlers.length > 0 &&
+ handlers.every((handlers) => channelIsValid(handlers)) &&
+ handlers.every((c) => {
+ const handlerChannelType =
+ notificationHandlerTypeToChannelMap[c.channel_type];
+
+ return channelSpec?.channels[handlerChannelType]?.configured;
+ })
+ );
+}
+
+function hasProperGoalForAlert({
+ question,
+ visualizationSettings,
+}: {
+ question: Question | undefined;
+ visualizationSettings: VisualizationSettings;
+}): boolean {
+ if (!question) {
+ return false;
+ }
+
+ const alertType = getAlertType(question, visualizationSettings);
+
+ if (!alertType) {
+ return false;
+ }
+
+ return (
+ alertType === ALERT_TYPE_TIMESERIES_GOAL ||
+ alertType === ALERT_TYPE_PROGRESS_BAR_GOAL
+ );
+}
+
+export function getAlertTriggerOptions({
+ question,
+ visualizationSettings,
+}: {
+ question: Question | undefined;
+ visualizationSettings: VisualizationSettings;
+}): NotificationCardSendCondition[] {
+ const hasValidGoal = hasProperGoalForAlert({
+ question,
+ visualizationSettings,
+ });
+
+ if (hasValidGoal) {
+ return ["has_result", "goal_above", "goal_below"];
+ }
+
+ return ["has_result"];
+}
+
+type NotificationEnabledChannelsMap = {
+ [key in NotificationChannelType]?: true;
+};
+export const getNotificationEnabledChannelsMap = (
+ notification: Notification,
+): NotificationEnabledChannelsMap => {
+ const result: NotificationEnabledChannelsMap = {};
+
+ notification.handlers.forEach((handler) => {
+ result[handler.channel_type] = true;
+ });
+
+ return result;
+};
+
+export const getNotificationHandlersGroupedByTypes = (
+ notificationHandlers: NotificationHandler[],
+) => {
+ let emailHandler: NotificationHandlerEmail | undefined;
+ let slackHandler: NotificationHandlerSlack | undefined;
+ let hookHandlers: NotificationHandlerHttp[] | undefined;
+
+ notificationHandlers.forEach((handler) => {
+ if (handler.channel_type === "channel/email") {
+ emailHandler = handler;
+ return;
+ }
+
+ if (handler.channel_type === "channel/slack") {
+ slackHandler = handler;
+ return;
+ }
+
+ if (handler.channel_type === "channel/http") {
+ if (!hookHandlers) {
+ hookHandlers = [];
+ }
+
+ hookHandlers.push(handler);
+ return;
+ }
+ });
+
+ return { emailHandler, slackHandler, hookHandlers };
+};
+
+export const formatNotificationSchedule = (
+ subscription: NotificationCronSubscription,
+): string | null => {
+ const schedule = cronToScheduleSettings(
+ subscription.cron_schedule,
+ subscription.ui_display_type === "cron/raw",
+ );
+
+ return (
+ (schedule &&
+ formatNotificationCheckSchedule(schedule, subscription.cron_schedule)) ||
+ null
+ );
+};
+
+export const formatNotificationCheckSchedule = (
+ {
+ schedule_type,
+ schedule_minute,
+ schedule_hour,
+ schedule_day,
+ schedule_frame,
+ }: ScheduleSettings,
+ cronSchedule: string,
+) => {
+ const options = MetabaseSettings.formattingOptions();
+
+ switch (schedule_type) {
+ case "every_n_minutes":
+ // Converting to lowercase here, because 'minute` is used without pluralization on the backend.
+ // and it's impossible to have both pluralized and single form for the same string.
+ return t`Check every ${ngettext(msgid`Minute`, `${schedule_minute} Minutes`, schedule_minute || 0).toLocaleLowerCase()}`;
+ case "hourly":
+ return t`Check hourly`;
+ case "daily": {
+ if (schedule_hour != null) {
+ const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day", options);
+ return t`Check daily at ${ampm}`;
+ }
+ break;
+ }
+ case "weekly": {
+ if (schedule_hour != null && schedule_day != null) {
+ const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day", options);
+ const day = formatDateTimeWithUnit(
+ schedule_day,
+ "day-of-week",
+ options,
+ );
+ return t`Check on ${day} at ${ampm}`;
+ }
+ break;
+ }
+ case "monthly": {
+ if (schedule_hour != null && schedule_frame != null) {
+ const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day", options);
+ const day = schedule_day
+ ? formatDateTimeWithUnit(schedule_day, "day-of-week", options)
+ : t`day`;
+ const frame = formatFrame(schedule_frame);
+ return t`Check monthly on the ${frame} ${day} at ${ampm}`;
+ }
+ break;
+ }
+ case "cron":
+ try {
+ return t`Check ${getScheduleExplanation(cronSchedule)}`;
+ } catch {
+ return null;
+ }
+ }
+
+ return null;
+};
+
+export const formatNotificationScheduleDescription = ({
+ schedule_type,
+ schedule_hour,
+}: ScheduleSettings) => {
+ switch (schedule_type) {
+ case "daily":
+ case "weekly":
+ case "monthly": {
+ if (schedule_hour != null) {
+ const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day");
+ return c("time with AM/PM label").t`at ${ampm}`;
+ }
+ break;
+ }
+ default:
+ return "";
+ }
+};
+
+export const ALERT_TYPE_ROWS = "alert-type-rows";
+export const ALERT_TYPE_TIMESERIES_GOAL = "alert-type-timeseries-goal";
+export const ALERT_TYPE_PROGRESS_BAR_GOAL = "alert-type-progress-bar-goal";
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars -- used for types
+const AlertTypes = [
+ ALERT_TYPE_ROWS,
+ ALERT_TYPE_TIMESERIES_GOAL,
+ ALERT_TYPE_PROGRESS_BAR_GOAL,
+] as const;
+
+export type NotificationTriggerType = (typeof AlertTypes)[number];
+
+/**
+ * Returns the type of alert that the question supports
+ *
+ * The `visualization_settings` in card object doesn't contain default settings,
+ * so you can provide the complete visualization settings object to `alertType`
+ * for taking those into account
+ */
+export function getAlertType(
+ question: Question,
+ visualizationSettings?: VisualizationSettings,
+) {
+ const display = question.display();
+
+ if (!question.canRun()) {
+ return null;
+ }
+
+ const isLineAreaBar =
+ display === "line" || display === "area" || display === "bar";
+
+ if (display === "progress") {
+ return ALERT_TYPE_PROGRESS_BAR_GOAL;
+ } else if (isLineAreaBar) {
+ const vizSettings = visualizationSettings
+ ? visualizationSettings
+ : question.card().visualization_settings;
+ const goalEnabled = vizSettings["graph.show_goal"];
+ const hasSingleYAxisColumn =
+ vizSettings["graph.metrics"] && vizSettings["graph.metrics"].length === 1;
+
+ // We don't currently support goal alerts for multiseries question
+ if (goalEnabled && hasSingleYAxisColumn) {
+ return ALERT_TYPE_TIMESERIES_GOAL;
+ } else {
+ return ALERT_TYPE_ROWS;
+ }
+ } else {
+ return ALERT_TYPE_ROWS;
+ }
+}
diff --git a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.jsx b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.jsx
index af21eee8441..84fce8ab092 100644
--- a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.jsx
+++ b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.jsx
@@ -9,10 +9,10 @@ import ButtonsS from "metabase/css/components/buttons.module.css";
import CS from "metabase/css/core/index.css";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { CreateOrEditQuestionAlertModalWithQuestion } from "metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal";
+import { ALERT_TYPE_ROWS, getAlertType } from "metabase/notifications/utils";
import { zoomInRow } from "metabase/query_builder/actions";
import Visualization from "metabase/visualizations/components/Visualization";
import * as Lib from "metabase-lib";
-import { ALERT_TYPE_ROWS } from "metabase-lib/v1/Alert";
import { datasetContainsNoResults } from "metabase-lib/v1/queries/utils/dataset";
const ALLOWED_VISUALIZATION_PROPS = [
@@ -74,7 +74,8 @@ export class VisualizationResult extends Component {
const noResults = datasetContainsNoResults(result.data);
if (noResults && !isRunning && !renderEmptyMessage) {
- const supportsRowsPresentAlert = question.alertType() === ALERT_TYPE_ROWS;
+ const supportsRowsPresentAlert =
+ !isEmbeddingSdk() && getAlertType(question) === ALERT_TYPE_ROWS;
const supportsBackToPreviousResult =
!isEmbeddingSdk() || !!onNavigateBack;
diff --git a/frontend/src/metabase/utils/notifications.ts b/frontend/src/metabase/utils/notifications.ts
deleted file mode 100644
index bc7fc8fb94c..00000000000
--- a/frontend/src/metabase/utils/notifications.ts
+++ /dev/null
@@ -1,323 +0,0 @@
-import { c, msgid, ngettext, t } from "ttag";
-import _ from "underscore";
-
-import type { NotificationListItem } from "metabase/account/notifications/types";
-import { cronToScheduleSettings } from "metabase/common/components/Schedule/cron";
-import { getEmailDomain, isEmail } from "metabase/utils/email";
-import { formatDateTimeWithUnit } from "metabase/utils/formatting/date";
-import { formatTimeWithUnit } from "metabase/utils/formatting/time";
-import MetabaseSettings from "metabase/utils/settings";
-import { formatFrame } from "metabase/utils/time-dayjs";
-import {
- ALERT_TYPE_PROGRESS_BAR_GOAL,
- ALERT_TYPE_TIMESERIES_GOAL,
-} from "metabase-lib/v1/Alert";
-import type Question from "metabase-lib/v1/Question";
-import type {
- ChannelApiResponse,
- ChannelType,
- CreateAlertNotificationRequest,
- Notification,
- NotificationCardSendCondition,
- NotificationChannelType,
- NotificationCronSubscription,
- NotificationHandler,
- NotificationHandlerEmail,
- NotificationHandlerHttp,
- NotificationHandlerSlack,
- NotificationRecipient,
- NotificationRecipientRawValue,
- ScheduleSettings,
- UpdateAlertNotificationRequest,
- User,
- VisualizationSettings,
-} from "metabase-types/api";
-
-import { getScheduleExplanation } from "./cron";
-
-export const formatTitle = ({ item, type }: NotificationListItem) => {
- switch (type) {
- case "pulse":
- return item.name;
- case "question-notification":
- return item.payload.card?.name || t`Alert`;
- }
-};
-
-const getRecipientIdentity = (recipient: NotificationRecipient) => {
- if (recipient.type === "notification-recipient/user") {
- return recipient.user_id;
- }
-
- if (recipient.type === "notification-recipient/raw-value") {
- return recipient.details.value; // email
- }
-};
-
-export const canArchive = (item: Notification, user: User) => {
- const recipients = item.handlers.flatMap((channel) => {
- if (channel.recipients) {
- return channel.recipients.map(getRecipientIdentity);
- } else {
- return [];
- }
- });
-
- const isCreator = item.creator?.id === user.id;
- const isSubscribed = recipients.includes(user.id);
- const isOnlyRecipient = recipients.length === 1;
-
- return isCreator && (!isSubscribed || isOnlyRecipient);
-};
-
-export function emailHandlerRecipientIsValid(recipient: NotificationRecipient) {
- if (recipient.type === "notification-recipient/user") {
- return !!recipient.user_id;
- }
-
- if (recipient.type === "notification-recipient/raw-value") {
- const email = recipient.details.value;
-
- const recipientDomain = getEmailDomain(email);
- const allowedDomains = MetabaseSettings.subscriptionAllowedDomains();
- return (
- !!email &&
- isEmail(email) &&
- (_.isEmpty(allowedDomains) ||
- !!(recipientDomain && allowedDomains.includes(recipientDomain)))
- );
- }
-}
-
-export function slackHandlerRecipientIsValid(
- recipient: NotificationRecipientRawValue,
-) {
- return !!recipient.details.value;
-}
-
-export function channelIsValid(handlers: NotificationHandler) {
- switch (handlers.channel_type) {
- case "channel/email":
- return (
- handlers.recipients &&
- handlers.recipients.length > 0 &&
- handlers.recipients.every(emailHandlerRecipientIsValid)
- );
- case "channel/slack":
- return (
- handlers.recipients &&
- handlers.recipients.length > 0 &&
- handlers.recipients.every(slackHandlerRecipientIsValid)
- );
- case "channel/http":
- return handlers.channel_id;
- default:
- return false;
- }
-}
-
-const notificationHandlerTypeToChannelMap: Record<
- NotificationChannelType,
- ChannelType
-> = {
- ["channel/email"]: "email",
- ["channel/slack"]: "slack",
- ["channel/http"]: "http",
-};
-
-export function alertIsValid(
- notification: CreateAlertNotificationRequest | UpdateAlertNotificationRequest,
- channelSpec: ChannelApiResponse | undefined,
-) {
- const handlers = notification.handlers;
-
- return (
- channelSpec?.channels &&
- handlers.length > 0 &&
- handlers.every((handlers) => channelIsValid(handlers)) &&
- handlers.every((c) => {
- const handlerChannelType =
- notificationHandlerTypeToChannelMap[c.channel_type];
-
- return channelSpec?.channels[handlerChannelType]?.configured;
- })
- );
-}
-
-function hasProperGoalForAlert({
- question,
- visualizationSettings,
-}: {
- question: Question | undefined;
- visualizationSettings: VisualizationSettings;
-}): boolean {
- const alertType = question?.alertType(visualizationSettings);
-
- if (!alertType) {
- return false;
- }
-
- return (
- alertType === ALERT_TYPE_TIMESERIES_GOAL ||
- alertType === ALERT_TYPE_PROGRESS_BAR_GOAL
- );
-}
-
-export function getAlertTriggerOptions({
- question,
- visualizationSettings,
-}: {
- question: Question | undefined;
- visualizationSettings: VisualizationSettings;
-}): NotificationCardSendCondition[] {
- const hasValidGoal = hasProperGoalForAlert({
- question,
- visualizationSettings,
- });
-
- if (hasValidGoal) {
- return ["has_result", "goal_above", "goal_below"];
- }
-
- return ["has_result"];
-}
-
-type NotificationEnabledChannelsMap = {
- [key in NotificationChannelType]?: true;
-};
-export const getNotificationEnabledChannelsMap = (
- notification: Notification,
-): NotificationEnabledChannelsMap => {
- const result: NotificationEnabledChannelsMap = {};
-
- notification.handlers.forEach((handler) => {
- result[handler.channel_type] = true;
- });
-
- return result;
-};
-
-export const getNotificationHandlersGroupedByTypes = (
- notificationHandlers: NotificationHandler[],
-) => {
- let emailHandler: NotificationHandlerEmail | undefined;
- let slackHandler: NotificationHandlerSlack | undefined;
- let hookHandlers: NotificationHandlerHttp[] | undefined;
-
- notificationHandlers.forEach((handler) => {
- if (handler.channel_type === "channel/email") {
- emailHandler = handler;
- return;
- }
-
- if (handler.channel_type === "channel/slack") {
- slackHandler = handler;
- return;
- }
-
- if (handler.channel_type === "channel/http") {
- if (!hookHandlers) {
- hookHandlers = [];
- }
-
- hookHandlers.push(handler);
- return;
- }
- });
-
- return { emailHandler, slackHandler, hookHandlers };
-};
-
-export const formatNotificationSchedule = (
- subscription: NotificationCronSubscription,
-): string | null => {
- const schedule = cronToScheduleSettings(
- subscription.cron_schedule,
- subscription.ui_display_type === "cron/raw",
- );
-
- return (
- (schedule &&
- formatNotificationCheckSchedule(schedule, subscription.cron_schedule)) ||
- null
- );
-};
-
-export const formatNotificationCheckSchedule = (
- {
- schedule_type,
- schedule_minute,
- schedule_hour,
- schedule_day,
- schedule_frame,
- }: ScheduleSettings,
- cronSchedule: string,
-) => {
- const options = MetabaseSettings.formattingOptions();
-
- switch (schedule_type) {
- case "every_n_minutes":
- // Converting to lowercase here, because 'minute` is used without pluralization on the backend.
- // and it's impossible to have both pluralized and single form for the same string.
- return t`Check every ${ngettext(msgid`Minute`, `${schedule_minute} Minutes`, schedule_minute || 0).toLocaleLowerCase()}`;
- case "hourly":
- return t`Check hourly`;
- case "daily": {
- if (schedule_hour != null) {
- const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day", options);
- return t`Check daily at ${ampm}`;
- }
- break;
- }
- case "weekly": {
- if (schedule_hour != null && schedule_day != null) {
- const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day", options);
- const day = formatDateTimeWithUnit(
- schedule_day,
- "day-of-week",
- options,
- );
- return t`Check on ${day} at ${ampm}`;
- }
- break;
- }
- case "monthly": {
- if (schedule_hour != null && schedule_frame != null) {
- const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day", options);
- const day = schedule_day
- ? formatDateTimeWithUnit(schedule_day, "day-of-week", options)
- : t`day`;
- const frame = formatFrame(schedule_frame);
- return t`Check monthly on the ${frame} ${day} at ${ampm}`;
- }
- break;
- }
- case "cron":
- try {
- return t`Check ${getScheduleExplanation(cronSchedule)}`;
- } catch {
- return null;
- }
- }
-
- return null;
-};
-
-export const formatNotificationScheduleDescription = ({
- schedule_type,
- schedule_hour,
-}: ScheduleSettings) => {
- switch (schedule_type) {
- case "daily":
- case "weekly":
- case "monthly": {
- if (schedule_hour != null) {
- const ampm = formatTimeWithUnit(schedule_hour, "hour-of-day");
- return c("time with AM/PM label").t`at ${ampm}`;
- }
- break;
- }
- default:
- return "";
- }
-};