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
Chore: Migrate pulse code to TS (#68908)
Stas Gavrylov8db69364e82b
diff --git a/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsx b/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsxindex d5a81488d08..1f4b5c33807 100644--- a/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.tsx@@ -14,7 +14,12 @@ import {PULSE_PARAM_USE_DEFAULT,getDefaultValuePopulatedParameters,} from "metabase-lib/v1/parameters/utils/parameter-values";-import type { Dashboard, ParameterId, Pulse } from "metabase-types/api";+import type {+ Dashboard,+ DashboardSubscription,+ Parameter,+ ParameterId,+} from "metabase-types/api";import { getSortedParameters } from "./utils";@@ -22,7 +27,7 @@ export type MutableParametersSectionProps = {className?: string;parameters: UiParameter[];dashboard: Dashboard;- pulse: Pulse;+ pulse: DashboardSubscription;setPulseParameters: (parameters: UiParameter[]) => void;hiddenParameters?: string;};@@ -40,7 +45,9 @@ export const MutableParametersSection = ({}, [parameters, dashboard]);const pulseParameters = getPulseParameters(pulse);- const pulseParamValuesById = pulseParameters.reduce((map, parameter) => {+ const pulseParamValuesById = pulseParameters.reduce<+ Record<string, Parameter["value"]>+ >((map, parameter) => {map[parameter.id] = parameter.value;return map;}, {});@@ -50,20 +57,24 @@ export const MutableParametersSection = ({pulseParamValuesById,);- const setParameterValue = (id: ParameterId, value: any) => {+ const setParameterValue = (id: ParameterId, value: Parameter["value"]) => {const parameter = sortedParameters.find((parameter) => parameter.id === id);- const operator = parameter && deriveFieldOperatorFromParameter(parameter);+ if (!parameter) {+ return;+ }+ const operator = deriveFieldOperatorFromParameter(parameter);const filteredParameters = pulseParameters.filter((parameter) => parameter.id !== id,);+ const newParameter: Parameter = {+ ...parameter,+ value: value,+ options: operator?.optionsDefaults,+ };const newParameters =value === PULSE_PARAM_USE_DEFAULT? filteredParameters- : filteredParameters.concat({- ...parameter,- value,- options: operator?.optionsDefaults,- });+ : filteredParameters.concat(newParameter);setPulseParameters(newParameters);};diff --git a/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.unit.spec.tsxindex 4c13e1c89df..30861179d0a 100644--- a/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sharing/components/MutableParametersSection.unit.spec.tsx@@ -3,12 +3,12 @@ import userEvent from "@testing-library/user-event";import { renderWithProviders, screen } from "__support__/ui";import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";import type { UiParameter } from "metabase-lib/v1/parameters/types";-import type { Dashboard, Pulse } from "metabase-types/api";+import type { Dashboard, DashboardSubscription } from "metabase-types/api";import {createMockActionDashboardCard,createMockDashboard,createMockDashboardCard,- createMockPulse,+ createMockDashboardSubscription,} from "metabase-types/api/mocks";import { MutableParametersSection } from "./MutableParametersSection";@@ -16,7 +16,7 @@ import { MutableParametersSection } from "./MutableParametersSection";type SetupOpts = {parameters: UiParameter[];dashboard: Dashboard;- pulse: Pulse;+ pulse: DashboardSubscription;};function setup({ parameters, dashboard, pulse }: SetupOpts) {@@ -50,7 +50,7 @@ describe("MutableParametersSection", () => {const { setPulseParameters } = setup({parameters: [parameter],dashboard: createMockDashboard(),- pulse: createMockPulse({+ pulse: createMockDashboardSubscription({parameters: [parameter],}),});@@ -76,7 +76,7 @@ describe("MutableParametersSection", () => {const { setPulseParameters } = setup({parameters: [parameter],dashboard: createMockDashboard(),- pulse: createMockPulse({+ pulse: createMockDashboardSubscription({parameters: [parameter],}),});@@ -115,7 +115,7 @@ describe("MutableParametersSection", () => {setup({parameters: [inlineParam, dashboardParam], // Pass inline firstdashboard,- pulse: createMockPulse(),+ pulse: createMockDashboardSubscription(),});const parameterWidgets = screen.getAllByTestId("parameter-widget");@@ -178,7 +178,7 @@ describe("MutableParametersSection", () => {setup({parameters: [param3, param2, param4, param1], // Pass in random orderdashboard,- pulse: createMockPulse(),+ pulse: createMockDashboardSubscription(),});const parameterWidgets = screen.getAllByTestId("parameter-widget");@@ -231,7 +231,7 @@ describe("MutableParametersSection", () => {setup({parameters: [inlineParam2, dashboardParam, inlineParam1],dashboard,- pulse: createMockPulse(),+ pulse: createMockDashboardSubscription(),});const parameterWidgets = screen.getAllByTestId("parameter-widget");@@ -277,7 +277,7 @@ describe("MutableParametersSection", () => {setup({parameters: [param2, param3, param1], // Pass param2 first to test orderingdashboard,- pulse: createMockPulse(),+ pulse: createMockDashboardSubscription(),});const parameterWidgets = screen.getAllByTestId("parameter-widget");@@ -310,7 +310,7 @@ describe("MutableParametersSection", () => {setup({parameters: [dashboardParam],dashboard,- pulse: createMockPulse(),+ pulse: createMockDashboardSubscription(),});const parameterWidgets = screen.getAllByTestId("parameter-widget");diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex 8c8d3733f92..b86262a0b62 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -37,7 +37,6 @@ export * from "./parameters";export * from "./performance";export * from "./permissions";export * from "./persist";-export * from "./pulse";export * from "./query";export * from "./document";export * from "./remote-sync";diff --git a/frontend/src/metabase-types/api/mocks/pulse.ts b/frontend/src/metabase-types/api/mocks/pulse.tsindex a02a07008ae..a8b0947b8f6 100644--- a/frontend/src/metabase-types/api/mocks/pulse.ts+++ b/frontend/src/metabase-types/api/mocks/pulse.ts@@ -1,9 +1,26 @@-import type { Pulse } from "metabase-types/api";+import type { BaseEntityId, DashboardSubscription } from "metabase-types/api";-export const createMockPulse = (opts?: Partial<Pulse>): Pulse => ({+import { createMockUser } from "./user";++export const createMockDashboardSubscription = (+ opts?: Partial<DashboardSubscription>,+): DashboardSubscription => ({name: "Pulse",cards: [],channels: [],parameters: [],+ archived: false,+ can_write: true,+ collection_id: null,+ collection_position: null,+ created_at: "2022-01-01T00:00:00Z",+ creator: createMockUser(),+ creator_id: createMockUser().id,+ dashboard_id: 1,+ disable_links: false,+ entity_id: "" as BaseEntityId,+ skip_if_empty: false,+ id: 1,+ updated_at: "2022-01-01T00:00:00Z",...opts,});diff --git a/frontend/src/metabase-types/api/notification-channels.ts b/frontend/src/metabase-types/api/notification-channels.tsindex c32dd7dd427..c6678f40002 100644--- a/frontend/src/metabase-types/api/notification-channels.ts+++ b/frontend/src/metabase-types/api/notification-channels.ts@@ -26,6 +26,8 @@ export type ChannelSpec = {error?: any;};+export type ChannelSpecs = Record<ChannelType, ChannelSpec>;+export type ChannelDetails = {url: string;"auth-method": NotificationAuthMethods;@@ -91,8 +93,8 @@ export interface ChannelApiResponse {export type ChannelType = keyof ChannelApiResponse["channels"];export type Channel = {- channel_type: string;- details?: Record<string, string>;+ channel_type: ChannelType;+ details?: Record<string, string | boolean>;enabled?: boolean;recipients?: User[];channel_id?: number;diff --git a/frontend/src/metabase-types/api/pulse.ts b/frontend/src/metabase-types/api/pulse.tsdeleted file mode 100644index 8fc1b59ff65..00000000000--- a/frontend/src/metabase-types/api/pulse.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { Card } from "./card";-import type { Channel } from "./notification-channels";--export type Pulse = {- cards: Card[];- channels: Channel[];- name?: string;- parameters?: any[];-};--export type PulseParameter = {- default: boolean;- id: number;- name?: string;- slug?: string;- type?: string;- value?: string;-};diff --git a/frontend/src/metabase-types/api/subscription.ts b/frontend/src/metabase-types/api/subscription.tsindex 4e61be475e1..e553c3ae992 100644--- a/frontend/src/metabase-types/api/subscription.ts+++ b/frontend/src/metabase-types/api/subscription.ts@@ -1,6 +1,6 @@import type { Card } from "./card";import type { RegularCollectionId } from "./collection";-import type { DashboardId } from "./dashboard";+import type { DashCardId, DashboardCard, DashboardId } from "./dashboard";import type { BaseEntityId } from "./entity-id";import type { Channel } from "./notification-channels";import type { Parameter } from "./parameters";@@ -14,7 +14,8 @@ export interface ListSubscriptionsRequest {export interface DashboardSubscription {archived: boolean;- cards: Card[];+ can_write: boolean;+ cards: SubscriptionSupportingCard[];channels: Channel[];collection_id: RegularCollectionId | null;collection_position: number | null;@@ -22,9 +23,10 @@ export interface DashboardSubscription {creator: User;creator_id: number;dashboard_id: DashboardId;+ disable_links: boolean;entity_id: BaseEntityId;id: number;- name: string;+ name: string | null;parameters: Parameter[];skip_if_empty: boolean;updated_at: string;@@ -54,3 +56,16 @@ export interface UpdateSubscriptionRequest {archived?: boolean;can_write?: boolean;}++export type SubscriptionSupportingCard = Pick<+ DashboardCard["card"],+ "id" | "collection_id" | "description" | "display" | "name" | "download_perms"+> & {+ include_csv: boolean;+ include_xls: boolean;+ dashboard_card_id: DashCardId;+ dashboard_id: DashboardId;+ parameter_mappings: DashboardCard["parameter_mappings"];+ format_rows?: boolean;+ pivot_results?: boolean;+};diff --git a/frontend/src/metabase-types/store/index.ts b/frontend/src/metabase-types/store/index.tsindex 841ba9337df..5ac06fade95 100644--- a/frontend/src/metabase-types/store/index.ts+++ b/frontend/src/metabase-types/store/index.ts@@ -6,6 +6,7 @@ export * from "./collection";export * from "./dashboard";export * from "./embed";export * from "./entities";+export * from "./pulse";export * from "./qb";export * from "./requests";export * from "./settings";diff --git a/frontend/src/metabase-types/store/pulse.ts b/frontend/src/metabase-types/store/pulse.tsnew file mode 100644index 00000000000..dd3844a640e--- /dev/null+++ b/frontend/src/metabase-types/store/pulse.ts@@ -0,0 +1,11 @@+import type {+ ChannelApiResponse,+ DashboardSubscription,+} from "metabase-types/api";++export interface PulseState {+ editingPulse: DashboardSubscription;+ formInput: ChannelApiResponse;+ cardPreviews: Record<number, { id: number }>;+ pulseList: DashboardSubscription[];+}diff --git a/frontend/src/metabase-types/store/state.ts b/frontend/src/metabase-types/store/state.tsindex cf8b512fe1b..0e715396b0b 100644--- a/frontend/src/metabase-types/store/state.ts+++ b/frontend/src/metabase-types/store/state.ts@@ -15,6 +15,7 @@ import type { EmbeddingDataPickerState } from "./embedding-data-picker";import type { EntitiesState } from "./entities";import type { ModalState } from "./modal";import type { ParametersState } from "./parameters";+import type { PulseState } from "./pulse";import type { QueryBuilderState } from "./qb";import type { RequestsState } from "./requests";import type { SettingsState } from "./settings";@@ -36,6 +37,7 @@ export interface State {embeddingDataPicker: EmbeddingDataPickerState;entities: EntitiesState;parameters: ParametersState;+ pulse: PulseState;qb: QueryBuilderState;requests: RequestsState;routing: RouterState;diff --git a/frontend/src/metabase/lib/pulse.ts b/frontend/src/metabase/lib/pulse.tsindex 6e8fb5426fb..c4182de4a0c 100644--- a/frontend/src/metabase/lib/pulse.ts+++ b/frontend/src/metabase/lib/pulse.ts@@ -15,8 +15,9 @@ import type {Channel,ChannelApiResponse,ChannelSpec,- Pulse,- PulseParameter,+ ChannelSpecs,+ DashboardSubscription,+ Parameter,ScheduleSettings,User,} from "metabase-types/api";@@ -28,9 +29,9 @@ export const NEW_PULSE_TEMPLATE = {skip_if_empty: false,collection_id: null,parameters: [],-};+} satisfies Partial<DashboardSubscription>;-export function channelIsValid(channel: Channel, channelSpec: ChannelSpec) {+export function channelIsValid(channel: Channel, channelSpec?: ChannelSpec) {switch (channel.channel_type) {case "email":return (@@ -79,7 +80,7 @@ export function scheduleIsValid(channel: Channel) {return true;}-export function fieldsAreValid(channel: Channel, channelSpec: ChannelSpec) {+export function fieldsAreValid(channel: Channel, channelSpec?: ChannelSpec) {if (!channelSpec) {return false;}@@ -93,7 +94,10 @@ export function fieldsAreValid(channel: Channel, channelSpec: ChannelSpec) {.every((field) => Boolean(channel.details?.[field.name]));}-function pulseChannelsAreValid(pulse: Pulse, channelSpecs: any) {+function pulseChannelsAreValid(+ pulse: DashboardSubscription,+ channelSpecs: Partial<ChannelSpecs>,+) {return (pulse.channels.filter((channel) =>channelIsValid(channel, channelSpecs?.[channel.channel_type]),@@ -119,7 +123,10 @@ export function recipientIsValid(recipient: RecipientPickerValue) {);}-export function pulseIsValid(pulse: Pulse, channelSpecs: ChannelSpecs) {+export function pulseIsValid(+ pulse: DashboardSubscription,+ channelSpecs: ChannelSpecs,+) {return ((pulse.name &&pulse.cards.length > 0 &&@@ -129,13 +136,13 @@ export function pulseIsValid(pulse: Pulse, channelSpecs: ChannelSpecs) {}export function dashboardPulseIsValid(- pulse: Pulse,- channelSpecs: ChannelSpecs,+ pulse: DashboardSubscription,+ channelSpecs: Partial<ChannelSpecs>,) {return pulseChannelsAreValid(pulse, channelSpecs);}-export function emailIsEnabled(pulse: Pulse) {+export function emailIsEnabled(pulse: DashboardSubscription) {return (pulse.channels.filter((channel) => channel.channel_type === "email" && channel.enabled,@@ -143,7 +150,10 @@ export function emailIsEnabled(pulse: Pulse) {);}-export function cleanPulse(pulse: Pulse, channelSpecs: any) {+export function cleanPulse(+ pulse: DashboardSubscription,+ channelSpecs: ChannelSpecs,+) {return {...pulse,channels: cleanPulseChannels(pulse.channels, channelSpecs),@@ -151,13 +161,13 @@ export function cleanPulse(pulse: Pulse, channelSpecs: any) {};}-function cleanPulseChannels(channels: Channel[], channelSpecs: any) {+function cleanPulseChannels(channels: Channel[], channelSpecs: ChannelSpecs) {return channels.filter((channel) =>channelIsValid(channel, channelSpecs?.[channel.channel_type]),);}-function cleanPulseParameters(parameters: PulseParameter[]) {+function cleanPulseParameters(parameters: Parameter[]) {return parameters.map((parameter) => {const { default: defaultValue, name, slug, type, value, id } = parameter;const normalizedValue = normalizeParameterValue(type, value);@@ -173,12 +183,6 @@ function cleanPulseParameters(parameters: PulseParameter[]) {});}-type ChannelSpecs = {- email?: {- configured: boolean;- };-};-export function getDefaultChannel(channelSpecs: ChannelSpecs) {// email is the first choiceif (channelSpecs.email?.configured) {@@ -208,22 +212,24 @@ export function createChannel(};}-export function getPulseParameters(pulse: Pulse) {+export function getPulseParameters(pulse: DashboardSubscription) {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: Pulse,- parameters: PulseParameter[],+ pulse: DashboardSubscription,+ parameters: Parameter[],) {- const parameterValues = getPulseParameters(pulse).reduce((map, parameter) => {+ const parameterValues = getPulseParameters(pulse).reduce<+ Record<string, Parameter["value"]>+ >((map, parameter) => {map[parameter.id] = parameter.value;return map;}, {});return getDefaultValuePopulatedParameters(parameters, parameterValues).filter(- (parameter: any) => parameter.value != null,+ (parameter: Parameter) => parameter.value != null,);}diff --git a/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsx b/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsxindex 89c508a74df..de40970f1a6 100644--- a/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsx+++ b/frontend/src/metabase/notifications/AddEditSidebar/AddEditEmailSidebar.tsx@@ -16,7 +16,7 @@ import { Sidebar } from "metabase/dashboard/components/Sidebar";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { dashboardPulseIsValid } from "metabase/lib/pulse";import { useSelector } from "metabase/lib/redux";-import EmailAttachmentPicker from "metabase/notifications/EmailAttachmentPicker";+import { EmailAttachmentPicker } from "metabase/notifications/EmailAttachmentPicker";import { RecipientPicker } from "metabase/notifications/channels/RecipientPicker";import { PLUGIN_DASHBOARD_SUBSCRIPTION_PARAMETERS_SECTION_OVERRIDE } from "metabase/plugins";import { canAccessSettings } from "metabase/selectors/user";@@ -28,7 +28,6 @@ import type {ChannelSpec,Dashboard,DashboardSubscription,- Pulse,ScheduleSettings,User,} from "metabase-types/api";@@ -57,7 +56,7 @@ interface AddEditEmailSidebarProps {) => void;testPulse: () => void;toggleSkipIfEmpty: () => void;- setPulse: (pulse: Pulse) => void;+ setPulse: (pulse: DashboardSubscription) => 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 1d800c88196..342cf3d76a9 100644--- a/frontend/src/metabase/notifications/AddEditSidebar/AddEditSlackSidebar.tsx+++ b/frontend/src/metabase/notifications/AddEditSidebar/AddEditSlackSidebar.tsx@@ -19,6 +19,7 @@ import type {Channel,ChannelApiResponse,ChannelSpec,+ ChannelSpecs,Dashboard,DashboardSubscription,ScheduleSettings,@@ -69,7 +70,10 @@ export const AddEditSlackSidebar = ({handleArchive,setPulseParameters,}: AddEditSlackSidebarProps) => {- const isValid = dashboardPulseIsValid(pulse, formInput.channels);+ const isValid = dashboardPulseIsValid(+ pulse,+ formInput.channels as ChannelSpecs,+ );return (<Sidebardiff --git a/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsx b/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsxindex 894305ad1fd..cfdcc3185f4 100644--- a/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsx+++ b/frontend/src/metabase/notifications/AddEditSidebar/DeleteSubscriptionAction.tsx@@ -6,15 +6,9 @@ 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, Pulse } from "metabase-types/api";+import type { Channel, DashboardSubscription } from "metabase-types/api";-interface PulseWithMetadata extends Pulse {- id?: number | null;- archived?: boolean;- name?: string;-}--function getConfirmItems(pulse: PulseWithMetadata): ReactNode[] {+function getConfirmItems(pulse: DashboardSubscription): ReactNode[] {return pulse.channels.map((c: Channel, index: number) =>c.channel_type === "email" ? (<span key={index}>@@ -50,7 +44,7 @@ function getConfirmItems(pulse: PulseWithMetadata): ReactNode[] {}interface DeleteSubscriptionActionProps {- pulse: PulseWithMetadata;+ pulse: DashboardSubscription;handleArchive: () => void;}diff --git a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.jsx b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.jsxdeleted file mode 100644index ba539d6a317..00000000000--- a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.jsx+++ /dev/null@@ -1,612 +0,0 @@-/* eslint "react/prop-types": "error" */--import PropTypes from "prop-types";-import { Component, useMemo } from "react";-import _ from "underscore";--import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { Sidebar } from "metabase/dashboard/components/Sidebar";-import { useDashboardContext } from "metabase/dashboard/context";-import { isEmbeddingSdk } from "metabase/embedding-sdk/config";-import { Pulses } from "metabase/entities/pulses";-import {- NEW_PULSE_TEMPLATE,- cleanPulse,- createChannel,-} from "metabase/lib/pulse";-import { connect } from "metabase/lib/redux";-import {- AddEditEmailSidebar,- AddEditSlackSidebar,-} from "metabase/notifications/AddEditSidebar/AddEditSidebar";-import { NewPulseSidebar } from "metabase/notifications/NewPulseSidebar";-import { PulsesListSidebar } from "metabase/notifications/PulsesListSidebar";-import {- cancelEditingPulse,- fetchPulseFormInput,- saveEditingPulse,- testPulse,- updateEditingPulse,-} from "metabase/notifications/pulse/actions";-import {- getEditingPulse,- getPulseFormInput,-} from "metabase/notifications/pulse/selectors";-import { getUser, getUserIsAdmin } from "metabase/selectors/user";-import { UserApi } from "metabase/services";--import { getSupportedCardsForSubscriptions } from "./get-supported-cards-for-subscriptions";--export const CHANNEL_ICONS = {- email: "mail",- slack: "slack",-};--const EDITING_MODES = {- ADD_EMAIL: "add-edit-email",- ADD_SLACK: "add-edit-slack",- NEW_PULSE: "new-pulse",- LIST_PULSES_OR_NEW_PULSE: "list-pulses-or-new-pulse",-};--const CHANNEL_TYPES = {- EMAIL: "email",- SLACK: "slack",-};--const cardsToPulseCards = (cards, pulseCards) => {- return cards.map((card) => {- const pulseCard =- pulseCards.find(- (pc) =>- pc.id === card.id && pc.dashboard_card_id === card.dashboard_card_id,- ) || card;- return {- ...card,- format_rows: pulseCard.format_rows,- pivot_results: pulseCard.pivot_results,- include_csv: pulseCard.include_csv,- include_xls: pulseCard.include_xls,- download_perms: pulseCard.download_perms,- };- });-};--const getEditingPulseWithDefaults = (state, props) => {- const pulse = getEditingPulse(state, props);- 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;- }- pulse.cards = cardsToPulseCards(- getSupportedCardsForSubscriptions(props.dashboard),- pulse.cards,- );-- return pulse;-};--const mapStateToProps = (state, props) => ({- isAdmin: getUserIsAdmin(state),- pulse: getEditingPulseWithDefaults(state, props),- formInput: getPulseFormInput(state, props),- user: getUser(state),-});--const mapDispatchToProps = {- updateEditingPulse,- saveEditingPulse,- cancelEditingPulse,- fetchPulseFormInput,- setPulseArchived: Pulses.actions.setArchived,- testPulse,-};--class DashboardSubscriptionsSidebarInner extends Component {- state = {- editingMode: EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,- // use this to know where to go "back" to- returnMode: [],- isSaving: false,- users: undefined,- };-- static propTypes = {- dashboard: PropTypes.object.isRequired,- fetchPulseFormInput: PropTypes.func.isRequired,- formInput: PropTypes.object.isRequired,- initialCollectionId: PropTypes.number,- isAdmin: PropTypes.bool,- pulse: PropTypes.object.isRequired,- saveEditingPulse: PropTypes.func.isRequired,- testPulse: PropTypes.func.isRequired,- updateEditingPulse: PropTypes.func.isRequired,- cancelEditingPulse: PropTypes.func.isRequired,- pulses: PropTypes.array,- onCancel: PropTypes.func.isRequired,- setPulseArchived: PropTypes.func.isRequired,- params: PropTypes.object,- // From Pulses.loadList HOC- loading: PropTypes.bool,- };-- componentDidMount() {- this.props.fetchPulseFormInput();- this.fetchUsers();- }-- componentDidUpdate(prevProps) {- const { editingMode } = this.state;- const { isAdmin, pulses, loading: isSubscriptionListLoading } = this.props;-- /**- * (EMB-976): In modular embedding/modular embedding SDK context we need to avoid showing the NEW_PULSE view (the view that lets users select- * between Email and Slack options) because we only allow email subscriptions there.- *- * And it's guaranteed that email would already be set up in modular embedding/SDK context.- * Otherwise, we won't show the subscription button to open this sidebar- * in the first place.- */- if (- isEmbeddingSdk() &&- shouldDisplayNewPulse(editingMode, pulses) &&- /**- * Ensure we don't prematurely switch to ADD_EMAIL while the pulse list is loading.- * When loading completes, shouldDisplayNewPulse() will correctly return false if the list is empty.- */- !isSubscriptionListLoading- ) {- this.setState({- editingMode: EDITING_MODES.ADD_EMAIL,- });- this.setPulseWithChannel(CHANNEL_TYPES.EMAIL);- }-- if (!isAdmin) {- this.forwardNonAdmins({ prevProps });- }- }-- fetchUsers = async () => {- if (isEmbeddingSdk()) {- // We don't need the the list of users in modular embedding/SDK context because we will hard code the recipient to the logged in user.- this.setState({ users: [] });- } else {- this.setState({ users: (await UserApi.list()).data });- }- };-- forwardNonAdmins = ({ prevProps }) => {- const { editingMode } = this.state;- const { formInput, pulses: newPulses } = this.props;- const { pulses: prevPulses } = prevProps;-- // prevent forwarding to add-pulse editingMode after creating a new pulse- // when none existed previously- if (newPulses?.length > 0 && prevPulses?.length === 0) {- this.setState(() => {- return {- editingMode: EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,- returnMode: [],- };- });-- return;- }-- const isEditingModeForwardable = shouldDisplayNewPulse(- editingMode,- newPulses,- );-- if (isEditingModeForwardable) {- const emailConfigured = formInput?.channels?.email?.configured || false;- const slackConfigured = formInput?.channels?.slack?.configured || false;-- const shouldForwardToAddEmail = emailConfigured && !slackConfigured;- const shouldForwardToAddSlack = slackConfigured && !emailConfigured;-- if (shouldForwardToAddEmail) {- this.setState(() => {- return {- editingMode: EDITING_MODES.ADD_EMAIL,- };- });- this.setPulseWithChannel(CHANNEL_TYPES.EMAIL);-- return;- }-- if (shouldForwardToAddSlack) {- this.setState(() => {- return {- editingMode: EDITING_MODES.ADD_SLACK,- };- });- this.setPulseWithChannel(CHANNEL_TYPES.SLACK);-- return;- }- }- };-- setPulse = (pulse) => {- this.props.updateEditingPulse(pulse);- };-- setPulseWithChannel = (type) => {- const { dashboard, formInput } = this.props;-- const channelSpec = formInput.channels[type];- if (!channelSpec) {- return;- }-- const channel = createChannel(channelSpec);-- const newPulse = {- ...NEW_PULSE_TEMPLATE,- channels: [channel],- cards: getSupportedCardsForSubscriptions(dashboard),- };- this.setPulse(newPulse);- };-- onChannelPropertyChange = (index, name, value) => {- const { pulse } = this.props;- const channels = [...pulse.channels];-- channels[index] = { ...channels[index], [name]: value };-- this.setPulse({ ...pulse, channels });- };-- // changedProp contains the schedule property that user just changed- // newSchedule may contain also other changed properties as some property changes reset other properties- onChannelScheduleChange = (index, newSchedule, changedProp) => {- const { pulse } = this.props;- const channels = [...pulse.channels];-- channels[index] = { ...channels[index], ...newSchedule };- this.setPulse({ ...pulse, channels });- };-- toggleSkipIfEmpty = () => {- const { pulse } = this.props;- this.setPulse({ ...pulse, skip_if_empty: !pulse.skip_if_empty });- };-- setPulseParameters = (parameters) => {- const { pulse } = this.props;-- this.setPulse({- ...pulse,- parameters,- });- };-- handleSave = async () => {- const { pulse, dashboard, formInput } = this.props;- const { isSaving } = this.state;-- if (isSaving) {- return;- }-- const cleanedPulse = cleanPulse(pulse, formInput.channels);- cleanedPulse.name = dashboard.name;-- try {- this.setState({ isSaving: true });- await this.props.updateEditingPulse(cleanedPulse);- await this.props.saveEditingPulse();- this.setState({- editingMode: EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,- returnMode: [],- });- } finally {- this.setState({ isSaving: false });- }- };-- createSubscription = () => {- this.setState(({ editingMode, returnMode }) => {- return {- editingMode: EDITING_MODES.NEW_PULSE,- returnMode: returnMode.concat([editingMode]),- };- });- };-- editPulse = (pulse, channelType) => {- this.setPulse(pulse);- this.setState(({ editingMode, returnMode }) => {- const editingModeMap = {- [CHANNEL_TYPES.EMAIL]: EDITING_MODES.ADD_EMAIL,- [CHANNEL_TYPES.SLACK]: EDITING_MODES.ADD_SLACK,- };- return {- editingMode: editingModeMap[channelType],- returnMode: returnMode.concat([- editingMode || EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,- ]),- };- });- };-- handleArchive = async () => {- const { pulse, pulses, setPulseArchived, onCancel } = this.props;-- await setPulseArchived(pulse, true);-- if (isEmbeddingSdk() && pulses.length === 1) {- onCancel();- } else {- this.setState({- editingMode: EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,- returnMode: [],- });- }- };-- // Because you can navigate down the sidebar, we need to wrap- // onCancel from props and either call that or reset back a screen- onCancel = () => {- const { cancelEditingPulse, onCancel } = this.props;- const { returnMode } = this.state;- if (returnMode.length) {- // set the current mode back to what it should be- this.setState({- editingMode: returnMode[returnMode.length - 1],- returnMode: returnMode.slice(0, -1),- });- } else {- onCancel();- }- cancelEditingPulse();- };-- render() {- const { editingMode, users } = this.state;- const { dashboard, formInput, pulse, pulses, testPulse } = this.props;-- const isLoading = !pulses || !users || !pulse || !formInput?.channels;-- if (isLoading) {- return (- <Sidebar>- <LoadingAndErrorWrapper loading />- </Sidebar>- );- }-- if (- editingMode === EDITING_MODES.LIST_PULSES_OR_NEW_PULSE &&- pulses.length > 0- ) {- return (- <PulsesListSidebar- pulses={pulses}- formInput={formInput}- createSubscription={this.createSubscription}- onCancel={this.onCancel}- editPulse={this.editPulse}- />- );- }-- if (- editingMode === EDITING_MODES.ADD_EMAIL &&- pulse.channels &&- pulse.channels.length > 0- ) {- const channelDetails = pulse.channels- .map((c, i) => [c, i])- .filter(- ([c, i]) => c.enabled && c.channel_type === CHANNEL_TYPES.EMAIL,- );- // protection from a failure where the channels aren't loaded yet- if (channelDetails.length === 0) {- return <Sidebar />;- }-- const [channel, index] = channelDetails[0];- const channelSpec = formInput.channels.email;-- return (- <AddEditEmailSidebarWithHooks- index={index}- pulse={pulse}- formInput={formInput}- channel={channel}- channelSpec={channelSpec}- handleSave={this.handleSave}- onCancel={this.onCancel}- onChannelPropertyChange={this.onChannelPropertyChange}- onChannelScheduleChange={this.onChannelScheduleChange}- testPulse={testPulse}- toggleSkipIfEmpty={this.toggleSkipIfEmpty}- setPulse={this.setPulse}- users={users}- handleArchive={this.handleArchive}- dashboard={dashboard}- setPulseParameters={this.setPulseParameters}- />- );- }-- if (- editingMode === EDITING_MODES.ADD_SLACK &&- pulse.channels &&- pulse.channels.length > 0- ) {- const channelDetails = pulse.channels- .map((c, i) => [c, i])- .filter(- ([c, i]) => c.enabled && c.channel_type === CHANNEL_TYPES.SLACK,- );-- // protection from a failure where the channels aren't loaded yet- if (channelDetails.length === 0) {- return <Sidebar />;- }-- const [channel, index] = channelDetails[0];- const channelSpec = formInput.channels.slack;- return (- <AddEditSlackSidebar- pulse={pulse}- formInput={formInput}- channel={channel}- channelSpec={channelSpec}- handleSave={this.handleSave}- onCancel={this.onCancel}- onChannelPropertyChange={_.partial(- this.onChannelPropertyChange,- index,- )}- onChannelScheduleChange={_.partial(- this.onChannelScheduleChange,- index,- )}- testPulse={testPulse}- toggleSkipIfEmpty={this.toggleSkipIfEmpty}- handleArchive={this.handleArchive}- dashboard={dashboard}- setPulseParameters={this.setPulseParameters}- />- );- }-- if (shouldDisplayNewPulse(editingMode, pulses) && !isEmbeddingSdk()) {- const emailConfigured = formInput?.channels?.email?.configured || false;- const slackConfigured = formInput?.channels?.slack?.configured || false;-- return (- <NewPulseSidebar- onCancel={this.onCancel}- emailConfigured={emailConfigured}- slackConfigured={slackConfigured}- onNewEmailPulse={() => {- if (emailConfigured) {- this.setState(({ returnMode }) => {- return {- editingMode: EDITING_MODES.ADD_EMAIL,- returnMode: returnMode.concat([editingMode]),- };- });- this.setPulseWithChannel(CHANNEL_TYPES.EMAIL);- }- }}- onNewSlackPulse={() => {- if (slackConfigured) {- this.setState(({ returnMode }) => {- return {- editingMode: EDITING_MODES.ADD_SLACK,- returnMode: returnMode.concat([editingMode]),- };- });- this.setPulseWithChannel(CHANNEL_TYPES.SLACK);- }- }}- />- );- }-- return <Sidebar />;- }-}--function AddEditEmailSidebarWithHooks({- /* eslint-disable react/prop-types */- index,- pulse,- formInput,- channel,- channelSpec,- handleSave,- onCancel,- onChannelPropertyChange,- onChannelScheduleChange,- testPulse,- toggleSkipIfEmpty,- setPulse,- users,- handleArchive,- dashboard,- setPulseParameters,- /* eslint-enable react/prop-types */-}) {- /**- * Memoized because it's used in `AddEditEmailSidebar.tsx` as a dependency- */- const handleChannelPropertyChange = useMemo(- () => _.partial(onChannelPropertyChange, index),- [index, onChannelPropertyChange],- );-- const handleChannelScheduleChange = _.partial(onChannelScheduleChange, index);-- return (- <AddEditEmailSidebar- pulse={pulse}- formInput={formInput}- channel={channel}- channelSpec={channelSpec}- handleSave={handleSave}- onCancel={onCancel}- onChannelPropertyChange={handleChannelPropertyChange}- onChannelScheduleChange={handleChannelScheduleChange}- testPulse={testPulse}- toggleSkipIfEmpty={toggleSkipIfEmpty}- setPulse={setPulse}- users={users}- handleArchive={handleArchive}- dashboard={dashboard}- setPulseParameters={setPulseParameters}- />- );-}--function shouldDisplayNewPulse(editingMode, pulses) {- if (editingMode === EDITING_MODES.NEW_PULSE) {- return true;- }-- if (- editingMode === EDITING_MODES.LIST_PULSES_OR_NEW_PULSE &&- pulses?.length === 0- ) {- return true;- }-- return false;-}--const DashboardSubscriptionsSidebarConnected = _.compose(- Pulses.loadList({- query: (state, { dashboard }) => ({ dashboard_id: dashboard.id }),- loadingAndErrorWrapper: false,- }),- connect(mapStateToProps, mapDispatchToProps),-)(DashboardSubscriptionsSidebarInner);--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default function DashboardSubscriptionsSidebar() {- const { dashboard, setSharing } = useDashboardContext();-- if (!dashboard) {- return null;- }-- return (- <DashboardSubscriptionsSidebarConnected- dashboard={dashboard}- onCancel={() => setSharing(false)}- />- );-}diff --git a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsxnew file mode 100644index 00000000000..49b158addff--- /dev/null+++ b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/DashboardSubscriptionsSidebar.tsx@@ -0,0 +1,633 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import _ from "underscore";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import type { ScheduleChangeProp } from "metabase/common/components/SchedulePicker";+import { Sidebar } from "metabase/dashboard/components/Sidebar";+import { useDashboardContext } from "metabase/dashboard/context";+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";+import { Pulses } from "metabase/entities/pulses";+import {+ NEW_PULSE_TEMPLATE,+ cleanPulse,+ createChannel,+} from "metabase/lib/pulse";+import { connect } from "metabase/lib/redux";+import {+ AddEditEmailSidebar,+ AddEditSlackSidebar,+} from "metabase/notifications/AddEditSidebar/AddEditSidebar";+import { NewPulseSidebar } from "metabase/notifications/NewPulseSidebar";+import { PulsesListSidebar } from "metabase/notifications/PulsesListSidebar";+import {+ cancelEditingPulse,+ fetchPulseFormInput,+ saveEditingPulse,+ testPulse,+ updateEditingPulse,+} from "metabase/notifications/pulse/actions";+import {+ getEditingPulse,+ getPulseFormInput,+} from "metabase/notifications/pulse/selectors";+import { getUser, getUserIsAdmin } from "metabase/selectors/user";+import { UserApi } from "metabase/services";+import type { UiParameter } from "metabase-lib/v1/parameters/types";+import type {+ Channel,+ ChannelApiResponse,+ ChannelSpec,+ ChannelSpecs,+ ChannelType,+ Dashboard,+ DashboardSubscription,+ ScheduleSettings,+ SubscriptionSupportingCard,+ User,+} from "metabase-types/api";+import type { State } from "metabase-types/store";++import { getSupportedCardsForSubscriptions } from "./get-supported-cards-for-subscriptions";++export const CHANNEL_ICONS: Record<string, string> = {+ email: "mail",+ slack: "slack",+};++const EDITING_MODES = {+ ADD_EMAIL: "add-edit-email",+ ADD_SLACK: "add-edit-slack",+ NEW_PULSE: "new-pulse",+ LIST_PULSES_OR_NEW_PULSE: "list-pulses-or-new-pulse",+} as const;++type EditingMode = (typeof EDITING_MODES)[keyof typeof EDITING_MODES];++const CHANNEL_TYPES = {+ EMAIL: "email",+ SLACK: "slack",+} as const;++const cardsToPulseCards = (+ cards: SubscriptionSupportingCard[],+ pulseCards: DashboardSubscription["cards"],+) => {+ return cards.map((card) => {+ const pulseCard =+ pulseCards.find(+ (pc) =>+ pc.id === card.id && pc.dashboard_card_id === card.dashboard_card_id,+ ) || card;+ return {+ ...card,+ format_rows: pulseCard.format_rows,+ pivot_results: pulseCard.pivot_results,+ include_csv: pulseCard.include_csv,+ include_xls: pulseCard.include_xls,+ download_perms: pulseCard.download_perms,+ };+ });+};++const getEditingPulseWithDefaults = (+ state: State,+ props: { dashboard: Dashboard },+): DashboardSubscription => {+ const pulse: DashboardSubscription = 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;+ }+ pulse.cards = cardsToPulseCards(+ getSupportedCardsForSubscriptions(props.dashboard),+ pulse.cards,+ );++ return pulse;+};++const mapStateToProps = (state: State, props: { dashboard: Dashboard }) => ({+ isAdmin: getUserIsAdmin(state),+ pulse: getEditingPulseWithDefaults(state, props),+ formInput: getPulseFormInput(state),+ user: getUser(state),+});++const mapDispatchToProps = {+ updateEditingPulse,+ saveEditingPulse,+ cancelEditingPulse,+ fetchPulseFormInput,+ setPulseArchived: Pulses.actions.setArchived,+ testPulse,+};++function shouldDisplayNewPulse(+ editingMode: EditingMode,+ pulses?: DashboardSubscription[],+): boolean {+ if (editingMode === EDITING_MODES.NEW_PULSE) {+ return true;+ }++ if (+ editingMode === EDITING_MODES.LIST_PULSES_OR_NEW_PULSE &&+ pulses?.length === 0+ ) {+ return true;+ }++ return false;+}++interface DashboardSubscriptionsSidebarInnerProps {+ dashboard: Dashboard;+ fetchPulseFormInput: () => void;+ formInput: ChannelApiResponse;+ initialCollectionId?: number;+ isAdmin?: boolean;+ pulse: DashboardSubscription;+ saveEditingPulse: () => Promise<DashboardSubscription>;+ testPulse: () => void;+ updateEditingPulse: (pulse: Partial<DashboardSubscription>) => void;+ cancelEditingPulse: () => void;+ pulses?: DashboardSubscription[];+ onCancel: () => void;+ setPulseArchived: (+ pulse: DashboardSubscription,+ archived: boolean,+ ) => Promise<void>;+ params?: Record<string, string>;+ loading?: boolean;+}++function DashboardSubscriptionsSidebarInner({+ dashboard,+ fetchPulseFormInput: fetchFormInput,+ formInput,+ isAdmin,+ pulse,+ saveEditingPulse: saveEditing,+ testPulse: testPulseFn,+ updateEditingPulse: updateEditing,+ cancelEditingPulse: cancelEditing,+ pulses,+ onCancel,+ setPulseArchived,+ loading: isSubscriptionListLoading,+}: DashboardSubscriptionsSidebarInnerProps) {+ const [editingMode, setEditingMode] = useState<EditingMode>(+ EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,+ );+ const [returnMode, setReturnMode] = useState<EditingMode[]>([]);+ const [isSaving, setIsSaving] = useState(false);+ const [users, setUsers] = useState<User[] | undefined>(undefined);++ const prevPulsesRef = useRef(pulses);+ const pulseRef = useRef(pulse);+ pulseRef.current = pulse;++ const setPulse = useCallback(+ (p: Partial<DashboardSubscription>) => {+ updateEditing(p);+ },+ [updateEditing],+ );++ const setPulseWithChannel = useCallback(+ (type: ChannelType) => {+ const channelSpec = formInput.channels[type];+ if (!channelSpec) {+ return;+ }++ const channel = createChannel(channelSpec);++ const newPulse = {+ ...NEW_PULSE_TEMPLATE,+ channels: [channel],+ cards: getSupportedCardsForSubscriptions(dashboard),+ } satisfies Partial<DashboardSubscription>;+ setPulse(newPulse);+ },+ [dashboard, formInput, setPulse],+ );++ // componentDidMount+ useEffect(() => {+ fetchFormInput();++ async function fetchUsers() {+ if (isEmbeddingSdk()) {+ // We don't need the the list of users in modular embedding/SDK context because we will hard code the recipient to the logged in user.+ setUsers([]);+ } else {+ setUsers((await UserApi.list()).data);+ }+ }+ fetchUsers();+ }, []); // eslint-disable-line react-hooks/exhaustive-deps++ // componentDidUpdate - SDK forwarding+ useEffect(() => {+ /**+ * (EMB-976): In modular embedding/modular embedding SDK context we need to avoid showing the NEW_PULSE view+ * (the view that lets users select * between Email and Slack options) because we only allow email subscriptions there.+ *+ * And it's guaranteed that email would already be set up in modular embedding/SDK context.+ * Otherwise, we won't show the subscription button to open this sidebar+ * in the first place.+ */+ if (+ isEmbeddingSdk() &&+ shouldDisplayNewPulse(editingMode, pulses) &&+ /**+ * Ensure we don't prematurely switch to ADD_EMAIL while the pulse list is loading.+ * When loading completes, shouldDisplayNewPulse() will correctly return false if the list is empty.+ */+ !isSubscriptionListLoading+ ) {+ setEditingMode(EDITING_MODES.ADD_EMAIL);+ setPulseWithChannel(CHANNEL_TYPES.EMAIL);+ }+ }, [editingMode, pulses, isSubscriptionListLoading, setPulseWithChannel]);++ // componentDidUpdate - non-admin forwarding+ useEffect(() => {+ if (isAdmin) {+ return;+ }++ const prevPulses = prevPulsesRef.current;+ prevPulsesRef.current = pulses;++ // prevent forwarding to add-pulse editingMode after creating a new pulse+ // when none existed previously+ if (pulses && pulses.length > 0 && prevPulses?.length === 0) {+ setEditingMode(EDITING_MODES.LIST_PULSES_OR_NEW_PULSE);+ setReturnMode([]);+ return;+ }++ const isEditingModeForwardable = shouldDisplayNewPulse(editingMode, pulses);++ if (isEditingModeForwardable) {+ const emailConfigured = formInput?.channels?.email?.configured || false;+ const slackConfigured = formInput?.channels?.slack?.configured || false;++ const shouldForwardToAddEmail = emailConfigured && !slackConfigured;+ const shouldForwardToAddSlack = slackConfigured && !emailConfigured;++ if (shouldForwardToAddEmail) {+ setEditingMode(EDITING_MODES.ADD_EMAIL);+ setPulseWithChannel(CHANNEL_TYPES.EMAIL);+ return;+ }++ if (shouldForwardToAddSlack) {+ setEditingMode(EDITING_MODES.ADD_SLACK);+ setPulseWithChannel(CHANNEL_TYPES.SLACK);+ return;+ }+ }+ }, [isAdmin, editingMode, formInput, pulses, setPulseWithChannel]);++ const onChannelPropertyChange = useCallback(+ (index: number, name: string, value: unknown) => {+ const p = pulseRef.current;+ const channels = [...p.channels];+ channels[index] = { ...channels[index], [name]: value };+ setPulse({ ...p, channels });+ },+ [setPulse],+ );++ // changedProp contains the schedule property that user just changed+ // newSchedule may contain also other changed properties as some property changes reset other properties+ const onChannelScheduleChange = useCallback(+ (+ index: number,+ newSchedule: ScheduleSettings,+ _changedProp: ScheduleChangeProp,+ ) => {+ const p = pulseRef.current;+ const channels = [...p.channels];+ channels[index] = { ...channels[index], ...newSchedule };+ setPulse({ ...p, channels });+ },+ [setPulse],+ );++ const toggleSkipIfEmpty = useCallback(() => {+ const p = pulseRef.current;+ setPulse({ ...p, skip_if_empty: !p.skip_if_empty });+ }, [setPulse]);++ const setPulseParameters = useCallback(+ (parameters: UiParameter[]) => {+ const p = pulseRef.current;+ setPulse({ ...p, parameters });+ },+ [setPulse],+ );++ const handleSave = useCallback(async () => {+ if (isSaving) {+ return;+ }++ const cleanedPulse = cleanPulse(pulse, formInput.channels as ChannelSpecs);+ cleanedPulse.name = dashboard.name;++ try {+ setIsSaving(true);+ await updateEditing(cleanedPulse);+ await saveEditing();+ setEditingMode(EDITING_MODES.LIST_PULSES_OR_NEW_PULSE);+ setReturnMode([]);+ } finally {+ setIsSaving(false);+ }+ }, [isSaving, pulse, formInput, dashboard.name, updateEditing, saveEditing]);++ const createSubscription = useCallback(() => {+ setReturnMode((prev) => [...prev, editingMode]);+ setEditingMode(EDITING_MODES.NEW_PULSE);+ }, [editingMode]);++ const editPulse = useCallback(+ (p: DashboardSubscription, channelType: ChannelType) => {+ setPulse(p);+ const editingModeMap: Partial<Record<ChannelType, EditingMode>> = {+ [CHANNEL_TYPES.EMAIL]: EDITING_MODES.ADD_EMAIL,+ [CHANNEL_TYPES.SLACK]: EDITING_MODES.ADD_SLACK,+ };+ setReturnMode((prev) => [+ ...prev,+ editingMode || EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,+ ]);+ setEditingMode(+ editingModeMap[channelType] ?? EDITING_MODES.LIST_PULSES_OR_NEW_PULSE,+ );+ },+ [editingMode, setPulse],+ );++ const handleArchive = useCallback(async () => {+ await setPulseArchived(pulse, true);++ if (isEmbeddingSdk() && pulses?.length === 1) {+ onCancel();+ } else {+ setEditingMode(EDITING_MODES.LIST_PULSES_OR_NEW_PULSE);+ setReturnMode([]);+ }+ }, [pulse, pulses, setPulseArchived, onCancel]);++ // Because you can navigate down the sidebar, we need to wrap+ // onCancel from props and either call that or reset back a screen+ const handleCancel = useCallback(() => {+ if (returnMode.length) {+ // set the current mode back to what it should be+ setEditingMode(returnMode[returnMode.length - 1]);+ setReturnMode(returnMode.slice(0, -1));+ } else {+ onCancel();+ }+ cancelEditing();+ }, [returnMode, onCancel, cancelEditing]);++ const isLoading = !pulses || !users || !pulse || !formInput?.channels;++ if (isLoading) {+ return (+ <Sidebar>+ <LoadingAndErrorWrapper loading />+ </Sidebar>+ );+ }++ if (+ editingMode === EDITING_MODES.LIST_PULSES_OR_NEW_PULSE &&+ pulses.length > 0+ ) {+ return (+ <PulsesListSidebar+ pulses={pulses}+ formInput={formInput}+ createSubscription={createSubscription}+ onCancel={handleCancel}+ editPulse={editPulse}+ />+ );+ }++ if (+ editingMode === EDITING_MODES.ADD_EMAIL &&+ pulse.channels &&+ pulse.channels.length > 0+ ) {+ const channelDetails = pulse.channels+ .map((c, i) => [c, i] as const)+ .filter(([c]) => c.enabled && c.channel_type === CHANNEL_TYPES.EMAIL);+ // protection from a failure where the channels aren't loaded yet+ if (channelDetails.length === 0) {+ return <Sidebar>{null}</Sidebar>;+ }++ const [channel, index] = channelDetails[0];+ const channelSpec = formInput.channels.email;++ return (+ <AddEditEmailSidebarWithHooks+ index={index}+ pulse={pulse}+ formInput={formInput}+ channel={channel}+ channelSpec={channelSpec}+ handleSave={handleSave}+ onCancel={handleCancel}+ onChannelPropertyChange={onChannelPropertyChange}+ onChannelScheduleChange={onChannelScheduleChange}+ testPulse={testPulseFn}+ toggleSkipIfEmpty={toggleSkipIfEmpty}+ setPulse={setPulse}+ users={users}+ handleArchive={handleArchive}+ dashboard={dashboard}+ setPulseParameters={setPulseParameters}+ />+ );+ }++ if (+ editingMode === EDITING_MODES.ADD_SLACK &&+ pulse.channels &&+ pulse.channels.length > 0+ ) {+ const channelDetails = pulse.channels+ .map((c, i) => [c, i] as const)+ .filter(([c]) => c.enabled && c.channel_type === CHANNEL_TYPES.SLACK);++ // protection from a failure where the channels aren't loaded yet+ if (channelDetails.length === 0) {+ return <Sidebar>{null}</Sidebar>;+ }++ const [channel, index] = channelDetails[0];+ const channelSpec = formInput.channels.slack;+ return (+ <AddEditSlackSidebar+ pulse={pulse}+ formInput={formInput}+ channel={channel}+ channelSpec={channelSpec}+ handleSave={handleSave}+ onCancel={handleCancel}+ onChannelPropertyChange={_.partial(onChannelPropertyChange, index)}+ onChannelScheduleChange={_.partial(onChannelScheduleChange, index)}+ testPulse={testPulseFn}+ toggleSkipIfEmpty={toggleSkipIfEmpty}+ handleArchive={handleArchive}+ dashboard={dashboard}+ setPulseParameters={setPulseParameters}+ />+ );+ }++ if (shouldDisplayNewPulse(editingMode, pulses) && !isEmbeddingSdk()) {+ const emailConfigured = formInput?.channels?.email?.configured || false;+ const slackConfigured = formInput?.channels?.slack?.configured || false;++ return (+ <NewPulseSidebar+ onCancel={handleCancel}+ emailConfigured={emailConfigured}+ slackConfigured={slackConfigured}+ onNewEmailPulse={() => {+ if (emailConfigured) {+ setReturnMode((prev) => [...prev, editingMode]);+ setEditingMode(EDITING_MODES.ADD_EMAIL);+ setPulseWithChannel(CHANNEL_TYPES.EMAIL);+ }+ }}+ onNewSlackPulse={() => {+ if (slackConfigured) {+ setReturnMode((prev) => [...prev, editingMode]);+ setEditingMode(EDITING_MODES.ADD_SLACK);+ setPulseWithChannel(CHANNEL_TYPES.SLACK);+ }+ }}+ />+ );+ }++ return <Sidebar>{null}</Sidebar>;+}++interface AddEditEmailSidebarWithHooksProps {+ index: number;+ pulse: DashboardSubscription;+ formInput: ChannelApiResponse;+ channel: Channel;+ channelSpec: ChannelSpec | undefined;+ handleSave: () => void;+ onCancel: () => void;+ onChannelPropertyChange: (+ index: number,+ name: string,+ value: unknown,+ ) => void;+ onChannelScheduleChange: (+ index: number,+ schedule: ScheduleSettings,+ changedProp: ScheduleChangeProp,+ ) => void;+ testPulse: () => void;+ toggleSkipIfEmpty: () => void;+ setPulse: (pulse: DashboardSubscription) => void;+ users: User[];+ handleArchive: () => void;+ dashboard: Dashboard;+ setPulseParameters: (parameters: UiParameter[]) => void;+}++function AddEditEmailSidebarWithHooks({+ index,+ pulse,+ formInput,+ channel,+ channelSpec,+ handleSave,+ onCancel,+ onChannelPropertyChange,+ onChannelScheduleChange,+ testPulse: testPulseFn,+ toggleSkipIfEmpty,+ setPulse,+ users,+ handleArchive,+ dashboard,+ setPulseParameters,+}: AddEditEmailSidebarWithHooksProps) {+ /**+ * Memoized because it's used in `AddEditEmailSidebar.tsx` as a dependency+ */+ const handleChannelPropertyChange = useMemo(+ () => _.partial(onChannelPropertyChange, index),+ [index, onChannelPropertyChange],+ );++ const handleChannelScheduleChange = _.partial(onChannelScheduleChange, index);++ return (+ <AddEditEmailSidebar+ pulse={pulse}+ formInput={formInput}+ channel={channel}+ channelSpec={channelSpec}+ handleSave={handleSave}+ onCancel={onCancel}+ onChannelPropertyChange={handleChannelPropertyChange}+ onChannelScheduleChange={handleChannelScheduleChange}+ testPulse={testPulseFn}+ toggleSkipIfEmpty={toggleSkipIfEmpty}+ setPulse={setPulse}+ users={users}+ handleArchive={handleArchive}+ dashboard={dashboard}+ setPulseParameters={setPulseParameters}+ />+ );+}++const DashboardSubscriptionsSidebarConnected = _.compose(+ Pulses.loadList({+ query: (_state: State, { dashboard }: { dashboard: Dashboard }) => ({+ dashboard_id: dashboard.id,+ }),+ loadingAndErrorWrapper: false,+ }),+ connect(mapStateToProps, mapDispatchToProps),+)(DashboardSubscriptionsSidebarInner);++// eslint-disable-next-line import/no-default-export -- deprecated usage+export default function DashboardSubscriptionsSidebar() {+ const { dashboard, setSharing } = useDashboardContext();++ if (!dashboard) {+ return null;+ }++ return (+ <DashboardSubscriptionsSidebarConnected+ dashboard={dashboard}+ onCancel={() => setSharing(false)}+ />+ );+}diff --git a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/common.unit.spec.tsindex a905f256656..905b5bc76f6 100644--- a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts+++ b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/common.unit.spec.ts@@ -2,7 +2,7 @@ import userEvent from "@testing-library/user-event";import fetchMock from "fetch-mock";import { screen, within } from "__support__/ui";-import type { Pulse } from "metabase-types/api";+import type { DashboardSubscription } from "metabase-types/api";import { dashcard, hasBasicFilterOptions, setup, user } from "./setup";@@ -116,7 +116,7 @@ describe("DashboardSubscriptionsSidebar", () => {id: 11,cards: [],},- ] satisfies (Pulse & { id: number })[];+ ] satisfies (Partial<DashboardSubscription> & { id: number })[];// Dynamically modify `pulses` so that we get the new updated list of pulses after archivingfetchMock.put({diff --git a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsx b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsxindex 977f2e38e9b..7123867b6ae 100644--- a/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsx+++ b/frontend/src/metabase/notifications/DashboardSubscriptionsSidebar/tests/setup.tsx@@ -14,7 +14,7 @@ import type { UiParameter } from "metabase-lib/v1/parameters/types";import type {Dashboard,DashboardCard,- Pulse,+ DashboardSubscription,TokenFeatures,} from "metabase-types/api";import {@@ -91,7 +91,7 @@ type SetupOpts = {parameters?: UiParameter[];isEmbeddingSdk?: boolean;setSharing?: (sharing: boolean) => void;- pulses?: (Partial<Pulse> & { id: number })[];+ pulses?: (Partial<DashboardSubscription> & { id: number })[];currentUser?: {firstName: string;lastName: string;@@ -174,7 +174,7 @@ export function setup({// Mock POST that updates the GET responsefetchMock.post("path:/api/pulse", ({ options }) => {const body = JSON.parse(options.body as string);- const newPulse = { ...body, id: getNextId() } as Pulse & { id: number };+ const newPulse = { ...body, id: getNextId() } as DashboardSubscription;pulses.push(newPulse);return newPulse;});diff --git a/frontend/src/metabase/notifications/EmailAttachmentPicker.jsx b/frontend/src/metabase/notifications/EmailAttachmentPicker.jsxdeleted file mode 100644index 99bc492ac39..00000000000--- a/frontend/src/metabase/notifications/EmailAttachmentPicker.jsx+++ /dev/null@@ -1,422 +0,0 @@-import cx from "classnames";-import PropTypes from "prop-types";-import { Component } from "react";-import { t } from "ttag";-import _ from "underscore";--import { ExportSettingsWidget } from "metabase/common/components/ExportSettingsWidget";-import { Toggle } from "metabase/common/components/Toggle";-import CS from "metabase/css/core/index.css";-import { Box, Checkbox, Group, Icon, Text, Tooltip } from "metabase/ui";--function getCardIdPair(card) {- return card.id + "|" + card.dashboard_card_id;-}--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default class EmailAttachmentPicker extends Component {- DEFAULT_ATTACHMENT_TYPE = "csv";-- state = {- isEnabled: false,- isFormattingEnabled: true,- isPivotingEnabled: false,- isAttachmentOnly: false,- selectedAttachmentType: this.DEFAULT_ATTACHMENT_TYPE,- selectedCardIds: new Set(),- };-- static propTypes = {- pulse: PropTypes.object.isRequired,- setPulse: PropTypes.func.isRequired,- cards: PropTypes.array.isRequired,- allowDownload: PropTypes.bool.isRequired,- };-- componentDidMount() {- this.setState(this.calculateStateFromCards());- }-- componentDidUpdate() {- const newState = this.calculateStateFromCards();-- newState.isEnabled = newState.isEnabled || this.state.isEnabled;- if (newState.selectedCardIds.size === 0) {- newState.selectedAttachmentType = this.state.selectedAttachmentType;- }-- if (!this.shouldUpdateState(newState, this.state)) {- this.setState(newState);- }- }-- _getCardsWithAttachments() {- return this.props.cards.filter((card) => {- return card.include_csv || card.include_xls;- });- }-- calculateStateFromCards() {- const selectedCards = this._getCardsWithAttachments();- const { pulse } = this.props;-- return {- isEnabled: selectedCards.length > 0,- selectedAttachmentType:- this.attachmentTypeFor(selectedCards) || this.DEFAULT_ATTACHMENT_TYPE,- selectedCardIds: new Set(- selectedCards.map((card) => getCardIdPair(card)),- ),- isFormattingEnabled: getInitialFormattingState(selectedCards),- isPivotingEnabled: getInitialPivotingState(selectedCards),- isAttachmentOnly: getInitialAttachmentOnlyState(pulse),- };- }-- canConfigurePivoting() {- return this.props.cards.some((card) => card.display === "pivot");- }-- canAttachFiles() {- const { allowDownload } = this.props;- return allowDownload;- }-- getAttachmentDisabledReason() {- if (!this.canAttachFiles()) {- return t`You don't have permission to download results and therefore cannot attach files to subscriptions.`;- }- return null;- }-- shouldUpdateState(newState, currentState) {- return (- (currentState.isEnabled || !newState.isEnabled) &&- newState.selectedAttachmentType === currentState.selectedAttachmentType &&- _.isEqual(newState.selectedCardIds, currentState.selectedCardIds)- );- }-- /*- * Reaches into the parent component (via setPulse) to update its pulsecard's include_{csv,xls} values- * based on this component's state.- */- updatePulseCards(attachmentType, selectedCardIds) {- const { pulse, setPulse } = this.props;- const { isFormattingEnabled, isPivotingEnabled, isAttachmentOnly } =- this.state;-- const isXls = attachmentType === "xlsx",- isCsv = attachmentType === "csv";-- this.setState({ selectedAttachmentType: attachmentType });-- setPulse({- ...pulse,- cards: pulse.cards.map((card) => {- card.include_csv = selectedCardIds.has(getCardIdPair(card)) && isCsv;- card.include_xls = selectedCardIds.has(getCardIdPair(card)) && isXls;- card.format_rows = isCsv && isFormattingEnabled; // Excel always uses formatting- card.pivot_results = card.display === "pivot" && isPivotingEnabled;- return card;- }),- channels: pulse.channels.map((channel) => ({- ...channel,- details: {- ...channel.details,- attachment_only: isAttachmentOnly,- },- })),- });- }-- cardIds() {- return new Set(this.props.cards.map((card) => getCardIdPair(card)));- }-- cardIdsToCards(cardIds) {- const { pulse } = this.props;- return pulse.cards.filter((card) => cardIds.has(getCardIdPair(card)));- }-- attachmentTypeFor(cards) {- if (cards.some((c) => c.include_xls)) {- return "xlsx";- } else if (cards.some((c) => c.include_csv)) {- return "csv";- } else {- return null;- }- }-- /*- * Called when the attachment type toggle (csv/xls) is clicked- */- setAttachmentType = (newAttachmentType) => {- this.updatePulseCards(newAttachmentType, this.state.selectedCardIds);- };-- /*- * Called when attachments are enabled/disabled at all- */- toggleAttach = (includeAttachment) => {- if (!includeAttachment) {- this.disableAllCards();- }-- this.setState({- isEnabled: includeAttachment,- isAttachmentOnly: includeAttachment ? this.state.isAttachmentOnly : false,- });- };-- /*- * Called on card selection- */- onToggleCard(card) {- this.setState(({ selectedAttachmentType, selectedCardIds }) => {- const id = getCardIdPair(card);- const attachmentType =- this.attachmentTypeFor(this.cardIdsToCards(selectedCardIds)) ||- selectedAttachmentType;-- if (selectedCardIds.has(id)) {- selectedCardIds.delete(id);- } else {- selectedCardIds.add(id);- }-- this.updatePulseCards(attachmentType, selectedCardIds);- return { selectedCardIds };- });- }-- /*- * Called when (de)select-all checkbox is clicked- */- onToggleAll = () => {- const { cards } = this.props;-- this.setState(({ selectedAttachmentType, selectedCardIds }) => {- const attachmentType =- this.attachmentTypeFor(this.cardIdsToCards(selectedCardIds)) ||- selectedAttachmentType;- let newSelectedCardIds = this.cardIds();- if (this.areAllSelected(cards, selectedCardIds)) {- newSelectedCardIds = new Set();- }-- this.updatePulseCards(attachmentType, newSelectedCardIds);- return { selectedCardIds: newSelectedCardIds };- });- };-- onToggleFormatting = () => {- this.setState(- (prevState) => ({- ...prevState,- isFormattingEnabled: !prevState.isFormattingEnabled,- }),- () => {- this.updatePulseCards(- this.state.selectedAttachmentType,- this.state.selectedCardIds,- );- },- );- };-- onTogglePivoting = () => {- this.setState(- (prevState) => ({- ...prevState,- isPivotingEnabled: !prevState.isPivotingEnabled,- }),- () => {- this.updatePulseCards(- this.state.selectedAttachmentType,- this.state.selectedCardIds,- );- },- );- };-- onToggleAttachmentOnly = () => {- this.setState(- (prevState) => ({- ...prevState,- isAttachmentOnly: !prevState.isAttachmentOnly,- }),- () => {- this.updatePulseCards(- this.state.selectedAttachmentType,- this.state.selectedCardIds,- );- },- );- };-- disableAllCards() {- const selectedCardIds = new Set();- this.updatePulseCards(this.state.selectedAttachmentType, selectedCardIds);- this.setState({ selectedCardIds });- }-- areAllSelected(allCards, selectedCardSet) {- return allCards.length === selectedCardSet.size;- }-- areOnlySomeSelected(allCards, selectedCardSet) {- return 0 < selectedCardSet.size && selectedCardSet.size < allCards.length;- }-- render() {- const { cards } = this.props;- const {- isEnabled,- isFormattingEnabled,- isPivotingEnabled,- isAttachmentOnly,- selectedAttachmentType,- selectedCardIds,- } = this.state;-- const canAttachFiles = this.canAttachFiles();- const disabledReason = this.getAttachmentDisabledReason();-- return (- <div>- <Group- className={CS.borderTop}- justify="space-between"- pt="1.5rem"- pb="1.5rem"- opacity={canAttachFiles ? 1 : 0.6}- >- <Group position="left" gap="0">- <Text fw="bold">{t`Attach results as files`}</Text>- <Icon- name="info"- c="gray.6"- ml="0.5rem"- size={12}- tooltip={- disabledReason ||- t`Attachments can contain up to 2,000 rows of data.`- }- />- </Group>- <Tooltip label={disabledReason} disabled={!disabledReason}>- <Toggle- aria-label={t`Attach results`}- value={isEnabled && canAttachFiles}- onChange={this.toggleAttach}- disabled={!canAttachFiles}- />- </Tooltip>- </Group>- {isEnabled && canAttachFiles && (- <div>- <Box py="1rem">- <ExportSettingsWidget- selectedFormat={selectedAttachmentType}- formats={["csv", "xlsx"]}- isFormattingEnabled={isFormattingEnabled}- isPivotingEnabled={isPivotingEnabled}- canConfigureFormatting={selectedAttachmentType === "csv"}- canConfigurePivoting={this.canConfigurePivoting()}- onChangeFormat={this.setAttachmentType}- onToggleFormatting={this.onToggleFormatting}- onTogglePivoting={this.onTogglePivoting}- />- </Box>- <div- className={cx(- CS.pt1,- CS.pb2,- CS.flex,- CS.justifyBetween,- CS.alignCenter,- )}- >- <ul className={CS.full}>- <li- className={cx(- CS.mb2,- CS.pb1,- CS.flex,- CS.alignCenter,- CS.cursorPointer,- CS.borderBottom,- )}- >- <Checkbox- variant="stacked"- label={t`Questions to attach`}- checked={this.areAllSelected(cards, selectedCardIds)}- indeterminate={this.areOnlySomeSelected(- cards,- selectedCardIds,- )}- onChange={this.onToggleAll}- />- </li>- {cards.map((card) => (- <li key={card.id}>- <Checkbox- mb="1rem"- mr="0.5rem"- checked={selectedCardIds.has(getCardIdPair(card))}- label={card.name}- onChange={() => {- this.onToggleCard(card);- }}- />- </li>- ))}- </ul>- </div>- <Group justify="space-between" pt="1rem">- <Group position="left" gap="0">- <Text fw="bold">{t`Send only attachments (no charts)`}</Text>- <Icon- name="info"- c="gray"- ml="0.5rem"- size={12}- tooltip={t`When enabled, only file attachments will be sent (no email content).`}- />- </Group>- <Toggle- aria-label={t`Send only attachments`}- value={isAttachmentOnly}- onChange={this.onToggleAttachmentOnly}- />- </Group>- </div>- )}- </div>- );- }-}--function getInitialFormattingState(cards) {- if (cards.length > 0) {- return cards.some((card) => !!card.format_rows);- }- return true;-}--function getInitialPivotingState(cards) {- if (cards.length > 0) {- return cards.some((card) => !!card.pivot_results);- }- return false;-}--function getInitialAttachmentOnlyState(pulse) {- if (pulse && pulse.channels && pulse.channels.length > 0) {- return pulse.channels.some((channel) => !!channel.details?.attachment_only);- }- return false;-}diff --git a/frontend/src/metabase/notifications/EmailAttachmentPicker.tsx b/frontend/src/metabase/notifications/EmailAttachmentPicker.tsxnew file mode 100644index 00000000000..55a86917236--- /dev/null+++ b/frontend/src/metabase/notifications/EmailAttachmentPicker.tsx@@ -0,0 +1,479 @@+import cx from "classnames";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { t } from "ttag";+import _ from "underscore";++import { ExportSettingsWidget } from "metabase/common/components/ExportSettingsWidget";+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";++const DEFAULT_ATTACHMENT_TYPE: AttachmentType = "csv";++type AttachmentType = "csv" | "xlsx";++function getCardIdPair(card: SubscriptionSupportingCard): string {+ return card.id + "|" + card.dashboard_card_id;+}++function getAttachmentTypeFor(+ cards: SubscriptionSupportingCard[],+): AttachmentType | null {+ if (cards.some((c) => c.include_xls)) {+ return "xlsx";+ } else if (cards.some((c) => c.include_csv)) {+ return "csv";+ }+ return null;+}++function getInitialFormattingState(+ cards: SubscriptionSupportingCard[],+): boolean {+ if (cards.length > 0) {+ return cards.some((card) => !!card.format_rows);+ }+ return true;+}++function getInitialPivotingState(cards: SubscriptionSupportingCard[]): boolean {+ if (cards.length > 0) {+ return cards.some((card) => !!card.pivot_results);+ }+ return false;+}++function getInitialAttachmentOnlyState(pulse: DashboardSubscription): boolean {+ if (pulse?.channels?.length > 0) {+ return pulse.channels.some((channel) => !!channel.details?.attachment_only);+ }+ return false;+}++function calculateStateFromCards(+ cards: SubscriptionSupportingCard[],+ pulse: DashboardSubscription,+) {+ const selectedCards = cards.filter(+ (card) => card.include_csv || card.include_xls,+ );+ return {+ isEnabled: selectedCards.length > 0,+ selectedAttachmentType:+ getAttachmentTypeFor(selectedCards) || DEFAULT_ATTACHMENT_TYPE,+ selectedCardIds: new Set(selectedCards.map(getCardIdPair)),+ isFormattingEnabled: getInitialFormattingState(selectedCards),+ isPivotingEnabled: getInitialPivotingState(selectedCards),+ isAttachmentOnly: getInitialAttachmentOnlyState(pulse),+ };+}++type EmailAttachmentPickerProps = {+ pulse: DashboardSubscription;+ setPulse: (pulse: DashboardSubscription) => void;+ cards: SubscriptionSupportingCard[];+ allowDownload: boolean | undefined;+};++export function EmailAttachmentPicker({+ pulse,+ setPulse,+ cards,+ 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 updatePulseCards = useCallback(+ /*+ * Reaches into the parent component (via setPulse) to update its pulsecard's include_{csv,xls} values+ * based on this component's state.+ */+ (+ attachmentType: AttachmentType,+ cardIds: Set<string>,+ options: {+ isFormattingEnabled: boolean;+ isPivotingEnabled: boolean;+ isAttachmentOnly: boolean;+ },+ ) => {+ const isXls = attachmentType === "xlsx";+ const isCsv = attachmentType === "csv";++ setSelectedAttachmentType(attachmentType);++ setPulse({+ ...pulse,+ cards: pulse.cards.map((card) => ({+ ...card,+ include_csv: cardIds.has(getCardIdPair(card)) && isCsv,+ include_xls: cardIds.has(getCardIdPair(card)) && isXls,+ format_rows: isCsv && options.isFormattingEnabled,+ pivot_results: card.display === "pivot" && options.isPivotingEnabled,+ })),+ channels: pulse.channels.map((channel) => ({+ ...channel,+ details: {+ ...channel.details,+ attachment_only: options.isAttachmentOnly,+ },+ })),+ });+ },+ [pulse, setPulse],+ );++ // Sync state from cards on mount and when cards/pulse change+ const isInitialMount = useRef(true);+ const prevComputedStateRef = useRef<ReturnType<+ typeof calculateStateFromCards+ > | null>(null);++ useEffect(() => {+ const newState = calculateStateFromCards(cards, pulse);++ 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);+ return;+ }++ const prev = prevComputedStateRef.current;+ // Match class component's shouldUpdateState: skip if nothing meaningful changed+ if (+ 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+ ) {+ 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);+ }, [cards, pulse]);++ const canAttachFiles = !!allowDownload;+ const canConfigurePivoting = cards.some((card) => card.display === "pivot");+ const areAllSelected = cards.length === selectedCardIds.size;+ const areOnlySomeSelected =+ selectedCardIds.size > 0 && selectedCardIds.size < cards.length;++ const disabledReason = !canAttachFiles+ ? t`You don't have permission to download results and therefore cannot attach files to subscriptions.`+ : null;++ const allCardIds = useMemo(() => new Set(cards.map(getCardIdPair)), [cards]);++ const cardIdsToCards = useCallback(+ (cardIds: Set<string>) =>+ pulse.cards.filter((card) => cardIds.has(getCardIdPair(card))),+ [pulse.cards],+ );++ const toggleAttach = useCallback(+ /*+ * Called when attachments are enabled/disabled at all+ */+ (includeAttachment: boolean) => {+ if (!includeAttachment) {+ const emptySet = new Set<string>();+ setSelectedCardIds(emptySet);+ updatePulseCards(selectedAttachmentType, emptySet, {+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly: false,+ });+ }++ setIsEnabled(includeAttachment);+ setIsAttachmentOnly((prev) => (includeAttachment ? prev : false));+ },+ [+ selectedAttachmentType,+ updatePulseCards,+ isFormattingEnabled,+ isPivotingEnabled,+ ],+ );++ const setAttachmentType = useCallback(+ /*+ * Called when the attachment type toggle (csv/xls) is clicked+ */+ (format: ExportFormat) => {+ if (format === "csv" || format === "xlsx") {+ updatePulseCards(format, selectedCardIds, {+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ });+ }+ },+ [+ selectedCardIds,+ updatePulseCards,+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ ],+ );++ const onToggleCard = useCallback(+ (card: SubscriptionSupportingCard) => {+ const id = getCardIdPair(card);+ const attachmentType =+ getAttachmentTypeFor(cardIdsToCards(selectedCardIds)) ||+ selectedAttachmentType;++ const next = new Set(selectedCardIds);+ if (next.has(id)) {+ next.delete(id);+ } else {+ next.add(id);+ }++ setSelectedCardIds(next);+ updatePulseCards(attachmentType, next, {+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ });+ },+ [+ cardIdsToCards,+ selectedCardIds,+ selectedAttachmentType,+ updatePulseCards,+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ ],+ );++ const onToggleAll = useCallback(() => {+ /*+ * Called when (de)select-all checkbox is clicked+ */+ const attachmentType =+ getAttachmentTypeFor(cardIdsToCards(selectedCardIds)) ||+ selectedAttachmentType;+ const newSelectedCardIds =+ cards.length === selectedCardIds.size ? new Set<string>() : allCardIds;++ setSelectedCardIds(newSelectedCardIds);+ updatePulseCards(attachmentType, newSelectedCardIds, {+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ });+ }, [+ allCardIds,+ cardIdsToCards,+ cards.length,+ selectedCardIds,+ selectedAttachmentType,+ updatePulseCards,+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ ]);++ const onToggleFormatting = useCallback(() => {+ const newValue = !isFormattingEnabled;+ setIsFormattingEnabled(newValue);+ updatePulseCards(selectedAttachmentType, selectedCardIds, {+ isFormattingEnabled: newValue,+ isPivotingEnabled,+ isAttachmentOnly,+ });+ }, [+ selectedAttachmentType,+ selectedCardIds,+ updatePulseCards,+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ ]);++ const onTogglePivoting = useCallback(() => {+ const newValue = !isPivotingEnabled;+ setIsPivotingEnabled(newValue);+ updatePulseCards(selectedAttachmentType, selectedCardIds, {+ isFormattingEnabled,+ isPivotingEnabled: newValue,+ isAttachmentOnly,+ });+ }, [+ selectedAttachmentType,+ selectedCardIds,+ updatePulseCards,+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ ]);++ const onToggleAttachmentOnly = useCallback(() => {+ const newValue = !isAttachmentOnly;+ setIsAttachmentOnly(newValue);+ updatePulseCards(selectedAttachmentType, selectedCardIds, {+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly: newValue,+ });+ }, [+ selectedAttachmentType,+ selectedCardIds,+ updatePulseCards,+ isFormattingEnabled,+ isPivotingEnabled,+ isAttachmentOnly,+ ]);++ return (+ <div>+ <Group+ className={CS.borderTop}+ justify="space-between"+ pt="1.5rem"+ pb="1.5rem"+ opacity={canAttachFiles ? 1 : 0.6}+ >+ <Group gap="0">+ <Text fw="bold">{t`Attach results as files`}</Text>+ <Icon+ name="info"+ c="text-secondary"+ ml="0.5rem"+ size={12}+ tooltip={+ disabledReason ||+ t`Attachments can contain up to 2,000 rows of data.`+ }+ />+ </Group>+ <Tooltip label={disabledReason} disabled={!disabledReason}>+ <Toggle+ aria-label={t`Attach results`}+ value={isEnabled && canAttachFiles}+ onChange={toggleAttach}+ disabled={!canAttachFiles}+ />+ </Tooltip>+ </Group>+ {isEnabled && canAttachFiles && (+ <div>+ <Box py="1rem">+ <ExportSettingsWidget+ selectedFormat={selectedAttachmentType}+ formats={["csv", "xlsx"]}+ isFormattingEnabled={isFormattingEnabled}+ isPivotingEnabled={isPivotingEnabled}+ canConfigureFormatting={selectedAttachmentType === "csv"}+ canConfigurePivoting={canConfigurePivoting}+ onChangeFormat={setAttachmentType}+ onToggleFormatting={onToggleFormatting}+ onTogglePivoting={onTogglePivoting}+ />+ </Box>+ <div+ className={cx(+ CS.pt1,+ CS.pb2,+ CS.flex,+ CS.justifyBetween,+ CS.alignCenter,+ )}+ >+ <ul className={CS.full}>+ <li+ className={cx(+ CS.mb2,+ CS.pb1,+ CS.flex,+ CS.alignCenter,+ CS.cursorPointer,+ CS.borderBottom,+ )}+ >+ <Checkbox+ variant="stacked"+ label={t`Questions to attach`}+ checked={areAllSelected}+ indeterminate={areOnlySomeSelected}+ onChange={onToggleAll}+ />+ </li>+ {cards.map((card) => (+ <li key={getCardIdPair(card)}>+ <Checkbox+ mb="1rem"+ mr="0.5rem"+ checked={selectedCardIds.has(getCardIdPair(card))}+ label={card.name}+ onChange={() => {+ onToggleCard(card);+ }}+ />+ </li>+ ))}+ </ul>+ </div>+ <Group justify="space-between" pt="1rem">+ <Group gap="0">+ <Text fw="bold">{t`Send only attachments (no charts)`}</Text>+ <Icon+ name="info"+ c="text-secondary"+ ml="0.5rem"+ size={12}+ tooltip={t`When enabled, only file attachments will be sent (no email content).`}+ />+ </Group>+ <Toggle+ aria-label={t`Send only attachments`}+ value={isAttachmentOnly}+ onChange={onToggleAttachmentOnly}+ />+ </Group>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/metabase/notifications/EmailAttachmentPicker.unit.spec.js b/frontend/src/metabase/notifications/EmailAttachmentPicker.unit.spec.tsxsimilarity index 91%rename from frontend/src/metabase/notifications/EmailAttachmentPicker.unit.spec.jsrename to frontend/src/metabase/notifications/EmailAttachmentPicker.unit.spec.tsxindex 7dafc99cd1a..dc26dc7c455 100644--- a/frontend/src/metabase/notifications/EmailAttachmentPicker.unit.spec.js+++ b/frontend/src/metabase/notifications/EmailAttachmentPicker.unit.spec.tsx@@ -1,8 +1,12 @@import { mockSettings } from "__support__/settings";import { fireEvent, renderWithProviders, screen } from "__support__/ui";+import type {+ DashboardSubscription,+ VisualizationDisplay,+} from "metabase-types/api";import { createMockState } from "metabase-types/store/mocks";-import EmailAttachmentPicker from "./EmailAttachmentPicker";+import { EmailAttachmentPicker } from "./EmailAttachmentPicker";function setup({pulse = createPulse(),@@ -282,7 +286,7 @@ describe("EmailAttachmentPicker", () => {});});-function createPulse() {+function createPulse(): DashboardSubscription {return {name: "Parameters",cards: [@@ -290,7 +294,7 @@ function createPulse() {id: 4,collection_id: null,description: null,- display: "map",+ display: "map" as VisualizationDisplay,name: "card1",include_csv: false,include_xls: false,@@ -302,7 +306,7 @@ function createPulse() {id: 6,collection_id: null,description: null,- display: "scalar",+ display: "scalar" as VisualizationDisplay,name: "card2",include_csv: false,include_xls: false,@@ -337,10 +341,20 @@ function createPulse() {collection_id: null,parameters: [],dashboard_id: 1,+ archived: false,+ can_write: true,+ collection_position: null,+ created_at: "2024-01-01T00:00:00Z",+ creator: { id: 1, common_name: "Test", email: "[email protected]" } as any,+ creator_id: 1,+ disable_links: false,+ entity_id: "test-entity-id" as any,+ id: 1,+ updated_at: "2024-01-01T00:00:00Z",};}-function createPulseWithDuplicateCardId() {+function createPulseWithDuplicateCardId(): DashboardSubscription {return {name: "Duplicate Card ID Pulse",cards: [@@ -348,7 +362,7 @@ function createPulseWithDuplicateCardId() {id: 10,collection_id: null,description: null,- display: "table",+ display: "table" as VisualizationDisplay,name: "Original Card",include_csv: false,include_xls: false,@@ -360,7 +374,7 @@ function createPulseWithDuplicateCardId() {id: 10, // Same card ID as abovecollection_id: null,description: null,- display: "line",+ display: "line" as VisualizationDisplay,name: "Visualizer Card",include_csv: false,include_xls: false,@@ -382,5 +396,15 @@ function createPulseWithDuplicateCardId() {collection_id: null,parameters: [],dashboard_id: 2,+ archived: false,+ can_write: true,+ collection_position: null,+ created_at: "2024-01-01T00:00:00Z",+ creator: { id: 1, common_name: "Test", email: "[email protected]" } as any,+ creator_id: 1,+ disable_links: false,+ entity_id: "test-entity-id" as any,+ id: 2,+ updated_at: "2024-01-01T00:00:00Z",};}diff --git a/frontend/src/metabase/notifications/PulsesListSidebar.jsx b/frontend/src/metabase/notifications/PulsesListSidebar.tsxsimilarity index 81%rename from frontend/src/metabase/notifications/PulsesListSidebar.jsxrename to frontend/src/metabase/notifications/PulsesListSidebar.tsxindex 49becb877df..801336a951c 100644--- a/frontend/src/metabase/notifications/PulsesListSidebar.jsx+++ b/frontend/src/metabase/notifications/PulsesListSidebar.tsx@@ -1,7 +1,4 @@-/* eslint "react/prop-types": "error" */-import cx from "classnames";-import PropTypes from "prop-types";import { msgid, ngettext, t } from "ttag";import _ from "underscore";@@ -20,12 +17,35 @@ import { connect } from "metabase/lib/redux";import { formatFrame } from "metabase/lib/time-dayjs";import { formatDateValue } from "metabase/parameters/utils/date-formatting";import { Button, Icon, Tooltip } from "metabase/ui";+import type { UiParameter } from "metabase-lib/v1/parameters/types";+import type {+ Channel,+ ChannelApiResponse,+ ChannelType,+ DashboardSubscription,+} from "metabase-types/api";+import type { State } from "metabase-types/store";import { PulseCard, SidebarActions } from "./PulsesListSidebar.styled";-const mapStateToProps = (state, props) => {+type PulsesListSidebarOwnProps = {+ pulses: DashboardSubscription[];+ formInput: ChannelApiResponse;+ createSubscription: () => void;+ onCancel: () => void;+ editPulse: (pulse: DashboardSubscription, channelType: ChannelType) => void;+};++type PulsesListSidebarStateProps = {+ parameters: UiParameter[];+};++type PulsesListSidebarProps = PulsesListSidebarOwnProps &+ PulsesListSidebarStateProps;++const mapStateToProps = (state: State): PulsesListSidebarStateProps => {return {- parameters: getParameters(state, props),+ parameters: getParameters(state),};};@@ -38,7 +58,7 @@ function _PulsesListSidebar({onCancel,editPulse,parameters,-}) {+}: PulsesListSidebarProps) {const createSubscriptionLabel = t`Set up a new schedule`;const closeSidebarLabel = t`Close`;return (@@ -88,7 +108,8 @@ function _PulsesListSidebar({flatcanEdit={canEdit}onClick={() =>- canEdit && editPulse(pulse, pulse.channels[0].channel_type)+ canEdit &&+ editPulse(pulse, pulse.channels[0].channel_type as ChannelType)}><div@@ -128,25 +149,21 @@ function _PulsesListSidebar({);}-_PulsesListSidebar.propTypes = {- pulses: PropTypes.array.isRequired,- formInput: PropTypes.object.isRequired,- createSubscription: PropTypes.func.isRequired,- onCancel: PropTypes.func.isRequired,- editPulse: PropTypes.func.isRequired,- parameters: PropTypes.array.isRequired,-};--function canEditPulse(pulse, formInput) {+function canEditPulse(+ pulse: DashboardSubscription,+ formInput: ChannelApiResponse,+): boolean {switch (pulse.channels[0].channel_type) {case "email":return formInput.channels.email != null;case "slack":return formInput.channels.slack != null;+ default:+ return false;}}-function buildRecipientText(pulse) {+function buildRecipientText(pulse: DashboardSubscription): string {const {channels: [firstChannel],} = pulse;@@ -157,7 +174,7 @@ function buildRecipientText(pulse) {return "";}- const [firstRecipient, ...otherRecipients] = recipients;+ const [firstRecipient, ...otherRecipients] = recipients!;const firstRecipientText = firstRecipient.common_name || firstRecipient.email;return _.isEmpty(otherRecipients)? firstRecipientText@@ -168,7 +185,10 @@ function buildRecipientText(pulse) {)}`;}-function buildFilterText(pulse, parameters) {+function buildFilterText(+ pulse: DashboardSubscription,+ parameters: UiParameter[],+): string {const activeParameters = getActivePulseParameters(pulse, parameters);if (_.isEmpty(activeParameters)) {@@ -184,7 +204,7 @@ function buildFilterText(pulse, parameters) {? firstParameter.value: [firstParameter.value];const formattedValues = values- .map((val) => formatDateValue(firstParameter, val))+ .map((val: string) => formatDateValue(firstParameter, val)).filter(Boolean);if (formattedValues.length > 0) {formattedValue = conjunct(formattedValues, t`and`);@@ -212,7 +232,12 @@ function buildFilterText(pulse, parameters) {)}`;}-function PulseDetails({ pulse, parameters }) {+type PulseDetailsProps = {+ pulse: DashboardSubscription;+ parameters: UiParameter[];+};++function PulseDetails({ pulse, parameters }: PulseDetailsProps) {const recipientText = buildRecipientText(pulse);const filterText = buildFilterText(pulse, parameters);@@ -294,12 +319,7 @@ function PulseDetails({ pulse, parameters }) {);}-PulseDetails.propTypes = {- pulse: PropTypes.object.isRequired,- parameters: PropTypes.array.isRequired,-};--function friendlySchedule(channel) {+function friendlySchedule(channel: Channel): string {const {channel_type,details,@@ -314,7 +334,7 @@ function friendlySchedule(channel) {if (channel_type === "email") {scheduleString += t`Emailed `;} else if (channel_type === "slack") {- scheduleString += t`Sent to ` + details.channel + " ";+ scheduleString += t`Sent to ` + details?.channel + " ";} else {scheduleString += t`Sent `;}@@ -324,22 +344,22 @@ function friendlySchedule(channel) {scheduleString += t`hourly`;break;case "daily": {- const hour = formatTimeWithUnit(schedule_hour, "hour-of-day");+ const hour = formatTimeWithUnit(schedule_hour ?? 0, "hour-of-day");scheduleString += t`daily at ${hour}`;break;}case "weekly": {- const hour = formatTimeWithUnit(schedule_hour, "hour-of-day");- const day = formatDateTimeWithUnit(schedule_day, "day-of-week");+ const hour = formatTimeWithUnit(schedule_hour ?? 0, "hour-of-day");+ const day = formatDateTimeWithUnit(schedule_day ?? "mon", "day-of-week");scheduleString += t`${day} at ${hour}`;break;}case "monthly": {- const hour = formatTimeWithUnit(schedule_hour, "hour-of-day");+ const hour = formatTimeWithUnit(schedule_hour ?? 0, "hour-of-day");const day = schedule_day? formatDateTimeWithUnit(schedule_day, "day-of-week"): "calendar day";- const frame = formatFrame(schedule_frame);+ const frame = formatFrame(schedule_frame ?? "first");scheduleString += t`monthly on the ${frame} ${day} at ${hour}`;break;}diff --git a/frontend/src/metabase/notifications/channels/SlackChannelField.tsx b/frontend/src/metabase/notifications/channels/SlackChannelField.tsxindex f2e83164caa..fef8772ad04 100644--- a/frontend/src/metabase/notifications/channels/SlackChannelField.tsx+++ b/frontend/src/metabase/notifications/channels/SlackChannelField.tsx@@ -31,7 +31,7 @@ export const SlackChannelField = ({const channelField = channelSpec.fields?.find((field) => field.name === CHANNEL_FIELD_NAME,);- const value = channel?.details?.[CHANNEL_FIELD_NAME] ?? "";+ const value = String(channel?.details?.[CHANNEL_FIELD_NAME] ?? "");const updateChannel = (value: string) =>onChannelPropertyChange("details", {diff --git a/frontend/src/metabase/notifications/pulse/actions.js b/frontend/src/metabase/notifications/pulse/actions.tssimilarity index 80%rename from frontend/src/metabase/notifications/pulse/actions.jsrename to frontend/src/metabase/notifications/pulse/actions.tsindex 3298c8f7167..bf28b506239 100644--- a/frontend/src/metabase/notifications/pulse/actions.js+++ b/frontend/src/metabase/notifications/pulse/actions.ts@@ -12,6 +12,12 @@ import { createThunkAction } from "metabase/lib/redux";import { setErrorPage } from "metabase/redux/app";import { addUndo } from "metabase/redux/undo";import { PulseApi } from "metabase/services";+import type {+ ChannelApiResponse,+ ChannelSpec,+ DashboardSubscription,+ RegularCollectionId,+} from "metabase-types/api";import { getEditingPulse, getPulseFormInput } from "./selectors";@@ -30,7 +36,10 @@ export const FETCH_PULSE_LIST_BY_DASHBOARD_ID =export const setEditingPulse = createThunkAction(SET_EDITING_PULSE,- function (id, initialCollectionId = null) {+ function (+ id?: number,+ initialCollectionId: RegularCollectionId | null = null,+ ) {return async function (dispatch, getState) {if (id != null) {try {@@ -44,9 +53,11 @@ export const setEditingPulse = createThunkAction(} else {// HACK: need a way to wait for form_input to finish loadingconst channels =- getPulseFormInput(getState()).channels ||+ getPulseFormInput(getState())?.channels ||(await PulseApi.form_input()).channels;- const defaultChannelSpec = getDefaultChannel(channels);+ const defaultChannelSpec = getDefaultChannel(channels) as+ | ChannelSpec+ | undefined;return {...NEW_PULSE_TEMPLATE,channels: defaultChannelSpec@@ -59,7 +70,8 @@ export const setEditingPulse = createThunkAction(},);-export const updateEditingPulse = createAction(UPDATE_EDITING_PULSE);+export const updateEditingPulse =+ createAction<DashboardSubscription>(UPDATE_EDITING_PULSE);export const cancelEditingPulse = createAction(CANCEL_EDITING_PULSE);export const saveEditingPulse = createThunkAction(@@ -98,16 +110,19 @@ export const saveEditingPulse = createThunkAction(},);-export const testPulse = createThunkAction(TEST_PULSE, function (pulse) {- return async function (dispatch, getState) {- return await PulseApi.test(pulse);- };-});+export const testPulse = createThunkAction(+ TEST_PULSE,+ function (pulse: DashboardSubscription) {+ return async function () {+ return await PulseApi.test(pulse);+ };+ },+);export const fetchPulseFormInput = createThunkAction(FETCH_PULSE_FORM_INPUT,function () {- return async function (dispatch, getState) {+ return async function (): Promise<ChannelApiResponse> {return await PulseApi.form_input();};},@@ -115,8 +130,8 @@ export const fetchPulseFormInput = createThunkAction(export const fetchPulseCardPreview = createThunkAction(FETCH_PULSE_CARD_PREVIEW,- function (id) {- return async function (dispatch, getState) {+ function (id: number) {+ return async function () {return await PulseApi.preview_card({ id: id });};},@@ -124,8 +139,8 @@ export const fetchPulseCardPreview = createThunkAction(export const fetchPulsesByDashboardId = createThunkAction(FETCH_PULSE_LIST_BY_DASHBOARD_ID,- function (dashboard_id) {- return async function (dispatch, getState) {+ function (dashboard_id: number) {+ return async function () {return await PulseApi.list({ dashboard_id: dashboard_id });};},diff --git a/frontend/src/metabase/notifications/pulse/reducers.js b/frontend/src/metabase/notifications/pulse/reducers.jsdeleted file mode 100644index 5852a55711a..00000000000--- a/frontend/src/metabase/notifications/pulse/reducers.js+++ /dev/null@@ -1,48 +0,0 @@-import { handleActions } from "redux-actions";--import {- CANCEL_EDITING_PULSE,- FETCH_PULSE_CARD_PREVIEW,- FETCH_PULSE_FORM_INPUT,- FETCH_PULSE_LIST_BY_DASHBOARD_ID,- SAVE_EDITING_PULSE,- SET_EDITING_PULSE,- UPDATE_EDITING_PULSE,-} from "./actions";--const DEFAULT_EDITING_PULSE = { name: null, cards: [], channels: [] };--export const editingPulse = handleActions(- {- [SET_EDITING_PULSE]: { next: (state, { payload }) => payload },- [UPDATE_EDITING_PULSE]: { next: (state, { payload }) => payload },- [SAVE_EDITING_PULSE]: { next: (state, { payload }) => payload },- [CANCEL_EDITING_PULSE]: { next: () => DEFAULT_EDITING_PULSE },- },- DEFAULT_EDITING_PULSE,-);--export const formInput = handleActions(- {- [FETCH_PULSE_FORM_INPUT]: { next: (state, { payload }) => payload },- },- {},-);--export const cardPreviews = handleActions(- {- [FETCH_PULSE_CARD_PREVIEW]: {- next: (state, { payload }) => ({ ...state, [payload.id]: payload }),- },- },- {},-);--export const pulseList = handleActions(- {- [FETCH_PULSE_LIST_BY_DASHBOARD_ID]: {- next: (state, { payload }) => payload,- },- },- [],-);diff --git a/frontend/src/metabase/notifications/pulse/reducers.ts b/frontend/src/metabase/notifications/pulse/reducers.tsnew file mode 100644index 00000000000..a109ac32fb6--- /dev/null+++ b/frontend/src/metabase/notifications/pulse/reducers.ts@@ -0,0 +1,92 @@+import { handleActions } from "redux-actions";++import type {+ ChannelApiResponse,+ DashboardSubscription,+} from "metabase-types/api";++import {+ CANCEL_EDITING_PULSE,+ FETCH_PULSE_CARD_PREVIEW,+ FETCH_PULSE_FORM_INPUT,+ FETCH_PULSE_LIST_BY_DASHBOARD_ID,+ SAVE_EDITING_PULSE,+ SET_EDITING_PULSE,+ UPDATE_EDITING_PULSE,+} from "./actions";++const DEFAULT_EDITING_PULSE = {+ name: null,+ cards: [],+ channels: [],+ // Required casting because we can't fully instantiate DashboardSubscription on the client.+} as unknown as DashboardSubscription;++export const editingPulse = handleActions(+ {+ [SET_EDITING_PULSE]: {+ next: (+ _state: DashboardSubscription,+ { payload }: { payload: DashboardSubscription },+ ) => payload,+ },+ [UPDATE_EDITING_PULSE]: {+ next: (+ _state: DashboardSubscription,+ { payload }: { payload: DashboardSubscription },+ ) => payload,+ },+ [SAVE_EDITING_PULSE]: {+ next: (+ _state: DashboardSubscription,+ { payload }: { payload: DashboardSubscription },+ ) => payload,+ },+ [CANCEL_EDITING_PULSE]: {+ next: () => DEFAULT_EDITING_PULSE,+ },+ },+ DEFAULT_EDITING_PULSE,+);++export const formInput = handleActions(+ {+ [FETCH_PULSE_FORM_INPUT]: {+ next: (+ _state: ChannelApiResponse,+ { payload }: { payload: ChannelApiResponse },+ ) => payload,+ },+ },+ {} as ChannelApiResponse,+);++type CardPreviewEntry = { id: number };+type CardPreviewsState = Record<number, CardPreviewEntry>;++export const cardPreviews = handleActions(+ {+ [FETCH_PULSE_CARD_PREVIEW]: {+ next: (+ state: CardPreviewsState,+ { payload }: { payload: CardPreviewEntry },+ ) => ({+ ...state,+ [payload.id]: payload,+ }),+ },+ },+ {} as CardPreviewsState,+);++export const pulseList = handleActions(+ {+ [FETCH_PULSE_LIST_BY_DASHBOARD_ID]: {+ next: (+ _state: DashboardSubscription[],+ { payload }: { payload: DashboardSubscription[] },+ ) => payload,+ },+ },+ [] as DashboardSubscription[],+);diff --git a/frontend/src/metabase/notifications/pulse/selectors.js b/frontend/src/metabase/notifications/pulse/selectors.jsdeleted file mode 100644index 0fa05eed7c8..00000000000--- a/frontend/src/metabase/notifications/pulse/selectors.js+++ /dev/null@@ -1,3 +0,0 @@-export const getEditingPulse = (state) => state.pulse.editingPulse;--export const getPulseFormInput = (state) => state.pulse?.formInput;diff --git a/frontend/src/metabase/notifications/pulse/selectors.ts b/frontend/src/metabase/notifications/pulse/selectors.tsnew file mode 100644index 00000000000..f69133b2144--- /dev/null+++ b/frontend/src/metabase/notifications/pulse/selectors.ts@@ -0,0 +1,12 @@+import type {+ ChannelApiResponse,+ DashboardSubscription,+} from "metabase-types/api";+import type { State } from "metabase-types/store";++export const getEditingPulse = (state: State): DashboardSubscription =>+ state.pulse.editingPulse;++export const getPulseFormInput = (+ state: State,+): ChannelApiResponse | undefined => state.pulse?.formInput;diff --git a/frontend/src/metabase/plugins/oss/core.ts b/frontend/src/metabase/plugins/oss/core.tsindex c1d28275384..8ec340c848a 100644--- a/frontend/src/metabase/plugins/oss/core.ts+++ b/frontend/src/metabase/plugins/oss/core.ts@@ -5,7 +5,7 @@ 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, Pulse } from "metabase-types/api";+import type { Dashboard, DashboardSubscription } from "metabase-types/api";import type { AdminPathKey, State } from "metabase-types/store";// Types@@ -20,7 +20,7 @@ interface PluginDashboardSubscriptionParametersSectionOverride {parameters: UiParameter[];hiddenParameters?: string;dashboard: Dashboard;- pulse: Pulse;+ pulse: DashboardSubscription;setPulseParameters: (parameters: UiParameter[]) => void;}>;}