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
Admin page for managing notifications and alerts (#72909)
Ngoc Khuat761a8527ad56
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex eefd5fb81c5..6b5653e7734 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -2203,6 +2203,7 @@tasktracingutil}+ :model-exports #{:model/TaskHistory}:model-imports #{:model/Card :model/Dashboard :model/Database}}tenants@@ -3167,6 +3168,20 @@util}:model-imports #{:model/MetabotConversation :model/MetabotFeedback :model/MetabotMessage}}+ enterprise/notification-admin+ {:team "Gadget"+ :api #{metabase-enterprise.notification-admin.api}+ :uses #{api+ app-db+ models+ notification+ request+ util}+ :model-imports #{:model/Notification+ :model/NotificationHandler+ :model/NotificationRecipient+ :model/TaskHistory}}+enterprise/permission-debug{:team "UX West":api #{metabase-enterprise.permission-debug.api}diff --git a/e2e/test/scenarios/admin/tools/tools.cy.spec.ts b/e2e/test/scenarios/admin/tools/tools.cy.spec.tsindex df0e9a0ce6e..22d5db89d99 100644--- a/e2e/test/scenarios/admin/tools/tools.cy.spec.ts+++ b/e2e/test/scenarios/admin/tools/tools.cy.spec.ts@@ -832,8 +832,7 @@ describe("scenarios > admin > tools > task runs filtering", () => {cy.location("search").should("contain", "run-type=sync");cy.wait("@getTaskRuns");cy.log("Filter by started at");- getFilterByStartedAt().click();- H.popover().findByText("Previous 30 days").click();+ selectStartedAt("Previous 30 days");cy.location("search").should("contain", "started-at=past30days");cy.wait("@getTaskRuns");@@ -885,8 +884,7 @@ describe("scenarios > admin > tools > task runs filtering", () => {cy.log("Should show tooltip 'Select a start time' when hovering");assertFilterByEntityTooltipText("Select a start time first");- getFilterByStartedAt().click();- H.popover().findByText("Previous 30 days").click();+ selectStartedAt("Previous 30 days");cy.log("Should show loader while loading entities");getFilterByEntity()@@ -921,8 +919,7 @@ describe("scenarios > admin > tools > task runs filtering", () => {getFilterByRun().click();H.popover().findByText("Alert").click();- getFilterByStartedAt().click();- H.popover().findByText("Previous 30 days").click();+ selectStartedAt("Previous 30 days");cy.wait("@getEmptyEntities");getFilterByEntity().should("be.disabled");@@ -934,7 +931,14 @@ function getFilterByRun() {return cy.findByPlaceholderText("Filter by run type");}function getFilterByStartedAt() {- return cy.findByPlaceholderText("Filter by started at");+ return cy.findByTestId("task-run-date-picker");+}++function selectStartedAt(label: string) {+ getFilterByStartedAt().click();+ H.popover().findByPlaceholderText("Started at").click();+ H.popover().findByRole("option", { name: label }).click();+ getFilterByStartedAt().click();}function getFilterByEntity() {diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.cljindex 9b068d27335..17d56a2544a 100644--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj@@ -30,6 +30,7 @@[metabase-enterprise.metabot-analytics.api][metabase-enterprise.metabot.api][metabase-enterprise.metabot.api.routes]+ [metabase-enterprise.notification-admin.api][metabase-enterprise.permission-debug.api][metabase-enterprise.remote-sync.api][metabase-enterprise.replacement.api]@@ -132,6 +133,7 @@"/logs" (premium-handler 'metabase-enterprise.advanced-config.api.logs :audit-app)"/metabot" (premium-handler 'metabase-enterprise.metabot.api :metabot-v3)"/metabot-analytics" (premium-handler metabase-enterprise.metabot-analytics.api/routes :audit-app)+ "/notifications" (premium-handler 'metabase-enterprise.notification-admin.api :audit-app)"/permission_debug" (premium-handler metabase-enterprise.permission-debug.api/routes :advanced-permissions);; TODO (Ngoc 2026-03-25) -- use :transforms-advanced feature flag once it exists"/transforms" (premium-handler metabase-enterprise.transforms.api/routes :transforms-python)diff --git a/enterprise/backend/src/metabase_enterprise/notification_admin/api.clj b/enterprise/backend/src/metabase_enterprise/notification_admin/api.cljnew file mode 100644index 00000000000..dcf0b51e7d7--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/notification_admin/api.clj@@ -0,0 +1,743 @@+(ns metabase-enterprise.notification-admin.api+ "Admin endpoints for notifications (card-type alerts). Gated behind the `:audit-app` feature flag+ and `check-superuser`. Each row carries `:last_check` (latest scheduler tick — any terminal+ outcome) and `:last_send` (latest channel-send delivery attempt — any outcome, including+ failures) computed from windowed subqueries; both expose `{at, error, status}`. The API surface+ uses `creator_*` throughout — matching `notification.creator_id` and the hydrated `:creator` map,+ and consistent with the public `metabase.notification.api` endpoints. (The admin UI labels these+ as \"owner\", but that's a frontend-only term and never appears on the wire.)++ Supported filters:+ - `active` boolean — notification.active+ - `creator_id` int — notification.creator_id = ?+ - `creator_active` boolean — core_user.is_active = ? (active creators only / deactivated only)+ - `creatorless` boolean — true: creator_id IS NULL OR is_active = false;+ false: inverse (has a live creator). Powers the Ownerless tab.+ - `card_id` int — notification_card.card_id = ?+ - `recipient_email` string — exact email match across user + raw-value recipients+ - `channel` string or vec of strings — handler channel_type IN (...), OR semantics+ - `last_send_status` :successful/:failing — filters on the latest channel-send outcome+ - `query` string — substring match across card name + creator first/last/email++ `last_send_status=failing` corresponds to the Failing tab — notifications whose most recent+ send tick (rolled up across all channels) had at least one channel failure."+ (:require+ [clojure.string :as str]+ [honey.sql.helpers :as sql.helpers]+ [medley.core :as m]+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.app-db.core :as mdb]+ [metabase.models.interface :as mi]+ [metabase.notification.api :as notification-api]+ [metabase.notification.models :as models.notification]+ [metabase.request.core :as request]+ [metabase.util :as u]+ [metabase.util.honey-sql-2 :as h2x]+ [metabase.util.malli.registry :as mr]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]+ [toucan2.realize :as t2.realize]))++(set! *warn-on-reflection* true)++;; ---------------------------------------------------------------------------+;; String-literal constants — hoisted to avoid scattered raw strings+;; ---------------------------------------------------------------------------++(def ^:private run-type-alert "alert")+(def ^:private entity-type-card "card")+(def ^:private task-notification-send "notification-send")+(def ^:private task-channel-send "channel-send")+(def ^:private terminal-statuses ["success" "failed" "abandoned"])++;; ---------------------------------------------------------------------------+;; Schema definitions+;; ---------------------------------------------------------------------------++(mr/def ::run-status+ [:enum :failing :successful])++(mr/def ::run-summary+ [:map {:closed true}+ [:at ms/TemporalInstant]+ [:error [:maybe :string]]+ [:status ::run-status]])++(mr/def ::channel-entry+ "One channel delivery attempt within a tick."+ [:map {:closed true}+ [:channel_type :keyword]+ [:status ::run-status]+ [:error [:maybe :string]]])++(mr/def ::tick-send-entry+ "One tick's worth of sends, rolled up across all channels that fired in that tick."+ [:map {:closed true}+ [:at ms/TemporalInstant]+ [:status ::run-status]+ [:error [:maybe :string]]+ [:channels [:sequential ::channel-entry]]])++(mr/def ::sort-column+ [:enum :id :last_send :last_check :card_name :creator_name :updated_at])++(mr/def ::sort-direction+ [:enum :asc :desc])++(mr/def ::list-row+ [:map+ [:id ms/PositiveInt]+ [:active :boolean]+ [:creator_id [:maybe ms/PositiveInt]]+ [:created_at ms/TemporalInstant]+ [:updated_at ms/TemporalInstant]+ [:payload_type :keyword]+ [:payload_id [:maybe ms/PositiveInt]]+ [:last_check [:maybe ::run-summary]]+ [:last_send [:maybe ::run-summary]]])++(mr/def ::list-response+ [:map+ [:data [:sequential ::list-row]]+ [:total ms/IntGreaterThanOrEqualToZero]+ [:limit [:maybe ms/PositiveInt]]+ [:offset [:maybe ms/IntGreaterThanOrEqualToZero]]])++(mr/def ::detail-response+ [:merge ::list-row+ [:map+ [:check_history [:sequential ::run-summary]]+ [:send_history [:sequential ::tick-send-entry]]]])++(mr/def ::bulk-response+ [:map+ [:updated ms/IntGreaterThanOrEqualToZero]])++(defn- handler-ids-with-raw-value-matching+ "Set of notification_handler IDs whose raw-value (external) recipients have `details.value`+ equal to (lowercased) `email`. Used by `?recipient_email=` only — the `?query=` substring+ search no longer descends into recipients (per design iteration)."+ [email]+ (let [lower-email (u/lower-case-en email)]+ ;; reducible-select so the (necessarily) in-memory `details.value` scan streams rows rather+ ;; than realizing the whole raw-value recipient table at once.+ (into #{}+ (comp (filter #(some-> % :details :value u/lower-case-en (= lower-email)))+ (map :notification_handler_id))+ (t2/reducible-select [:model/NotificationRecipient :notification_handler_id :details]+ :type :notification-recipient/raw-value))))++(defn- notification-ids-with-recipient-email+ "Notification IDs whose recipients (user or raw-value) match `email` exactly. One SQL query+ unions both paths: user-recipients via an indexed `core_user.email` equality, raw-value+ recipients via a pre-resolved set of handler IDs from an in-memory scan."+ [email]+ (let [lower-email (u/lower-case-en email)+ raw-handler-ids (handler-ids-with-raw-value-matching email)+ user-clause [:and+ [:= :nr.type "notification-recipient/user"]+ [:= [:lower :cu.email] lower-email]]+ where-clause (if (seq raw-handler-ids)+ [:or user-clause [:in :notification_handler.id raw-handler-ids]]+ user-clause)]+ (t2/select-fn-set+ :notification_id (t2/table-name :model/NotificationHandler)+ {:join [[(t2/table-name :model/NotificationRecipient) :nr]+ [:= :nr.notification_handler_id :notification_handler.id]]+ :left-join [[:core_user :cu] [:= :cu.id :nr.user_id]]+ :where where-clause})))++(defn- wildcard-string+ "`%foo%` substring pattern with the input lowercased and LIKE metacharacters (`\\`, `%`, `_`)+ escaped so they match literally rather than as wildcards. Relies on the default `\\` LIKE escape+ character, which H2, Postgres, and MySQL all share."+ [s]+ (let [escaped (-> (u/lower-case-en s)+ (str/replace "\\" "\\\\")+ (str/replace "_" "\\_")+ (str/replace "%" "\\%"))]+ (str "%" escaped "%")))++(defn- query-where-clause+ "WHERE clause for the fuzzy `?query=` filter. Substring ILIKE OR'd across card name and creator+ first/last/email. Recipient branches were removed in the design iteration — recipients stay as+ the structured `?recipient_email=` filter."+ [query]+ (let [wildcard (wildcard-string query)]+ [:or+ [:like [:lower :c.name] wildcard]+ [:like [:lower :cu.first_name] wildcard]+ [:like [:lower :cu.last_name] wildcard]+ [:like [:lower :cu.email] wildcard]]))++(def ^:private run-lookback-days+ "How far back to consider alert-type TaskRuns / TaskHistory rows when computing run summaries."+ 90)++(defn- lookback-cutoff []+ (h2x/add-interval-honeysql-form (mdb/db-type) (mi/now) (- run-lookback-days) :day))++(defn- latest-run-per-card+ "Honey.sql subquery: one row per card with the most recent terminal alert-type TaskRun+ (status :success / :failed / :abandoned) within [[run-lookback-days]]. Excludes :started+ in-flight runs — they shouldn't surface as a `last_check`. Uses+ `ROW_NUMBER() OVER (PARTITION BY entity_id ORDER BY started_at DESC)`."+ []+ {:select [:id :entity_id :status :started_at :ended_at]+ :from [[{:select [:id :entity_id :status :started_at :ended_at+ [[:over [[:row_number]+ {:partition-by [:entity_id]+ :order-by [[:started_at :desc]]}]]+ :rn]]+ :from [:task_run]+ :where [:and+ [:= :run_type run-type-alert]+ [:= :entity_type entity-type-card]+ [:in :status terminal-statuses]+ [:> :started_at (lookback-cutoff)]]}+ :sub]]+ :where [:= :sub.rn 1]})++(defn- latest-send-tick-per-card+ "Honey.sql subquery: one row per card summarising the LATEST tick that had channel-send+ attempts within [[run-lookback-days]].++ Strategy (cross-dialect — no JSON, no SUM/aggregate type issues):+ 1. Inner subquery `lr` — rank `task_run` rows that have at least one `channel-send`+ child, by `started_at DESC` per card. Keep only rank=1 (the latest send-tick).+ 2. Outer query — expose `entity_id` and `started_at`, plus `has_failure`: 1 if ANY+ channel-send row under that run has status='failed', 0 otherwise. Uses a correlated+ EXISTS rather than GROUP BY + SUM to stay H2/Postgres/MySQL compatible.++ Result columns:+ - `:entity_id` — card ID (join key used by base-list-query)+ - `:id` — task_run.id of the latest send tick (for looking up channel-send error msg)+ - `:started_at` — the tick's started_at (for sort + `:last_send.at`)+ - `:has_failure` — 1 if any channel-send in the tick failed, 0 otherwise++ Note: `:last_send` on the list endpoint is card-level (not per-notification). Per-notification+ filtering is handled in `send-history-for-notification` on the detail page."+ []+ (let [lookback (lookback-cutoff)]+ {:select [:lr.entity_id+ [:lr.run_id :id]+ [:lr.tick_started_at :started_at]+ ;; Boolean CASE, read back in Clojure — same pattern as+ ;; `metabase.search.in-place.legacy/bookmark-col`. `has-failure?` runs it through+ ;; `bit->boolean` to absorb the MySQL/MariaDB bit-vs-boolean JDBC quirk.+ [[:case+ [:exists {:select [[1]]+ :from [[:task_history :tf]]+ :where [:and+ [:= :tf.run_id :lr.run_id]+ [:= :tf.task task-channel-send]+ [:= :tf.status "failed"]]}]+ true+ :else false]+ :has_failure]]+ :from [[{:select [:tr2.entity_id+ [:tr2.id :run_id]+ [:tr2.started_at :tick_started_at]+ [[:over [[:row_number]+ {:partition-by [:tr2.entity_id]+ :order-by [[:tr2.started_at :desc]]}]]+ :rn]]+ :from [[:task_run :tr2]]+ :where [:and+ [:= :tr2.run_type run-type-alert]+ [:= :tr2.entity_type entity-type-card]+ [:in :tr2.status terminal-statuses]+ [:> :tr2.started_at lookback]+ ;; only keep runs that actually had channel-send rows+ [:exists {:select [[1]]+ :from [[:task_history :tx]]+ :where [:and+ [:= :tx.run_id :tr2.id]+ [:= :tx.task task-channel-send]]}]]}+ :lr]]+ :where [:= :lr.rn 1]}))++(def ^:private sort-column->order-by+ "Maps the public `sort_column` enum to the SQL expression used in `ORDER BY`. Uses raw+ expressions rather than the SELECT aliases because H2 does not resolve aliases inside+ expressions. Whitelist; values outside this map are rejected by the `::sort-column` malli enum+ upstream."+ {:id :notification.id+ :last_send :ls.started_at+ :last_check :lc.started_at+ :card_name :c.name+ :creator_name [:coalesce :cu.last_name :cu.first_name :cu.email]+ :updated_at :notification.updated_at})++(defn- channel-exists+ "Honey `EXISTS` correlated with `:notification.id`: TRUE when the notification has at least one+ handler whose channel_type is IN `channels`. Accepts either a single string or a vector of+ strings (OR semantics across multiple channel types). Subquery instead of JOIN so the outer+ query needs no `DISTINCT`."+ [channels]+ (let [channels (if (sequential? channels) channels [channels])]+ [:exists+ {:select [[1]]+ :from [(t2/table-name :model/NotificationHandler)]+ :where [:and+ [:= :notification_handler.notification_id :notification.id]+ [:in :notification_handler.channel_type channels]]}]))++(defn- list-where-clauses+ "Optional WHERE clauses for the list/detail query, returned as data (a seq with inactive filters+ elided) so `base-list-query` can `(reduce sql.helpers/where ...)` them onto the query."+ [{:keys [active creator_id creator_active creatorless card_id recipient_email channel+ last_send_status query]}]+ (keep+ identity+ [(when (some? active) [:= :notification.active active])+ (when (some? creator_active) [:= :cu.is_active creator_active])+ ;; `creatorless` = true: no creator at all, OR a deactivated creator (both are "creatorless")+ ;; `creatorless` = false: has a live (active) creator+ ;; [:= col nil] is IS NULL and [:is-not col nil] is IS NOT NULL per HoneySQL 2 semantics.+ (when (true? creatorless)+ [:or [:= :notification.creator_id nil] [:= :cu.is_active false]])+ (when (false? creatorless)+ [:and [:is-not :notification.creator_id nil] [:= :cu.is_active true]])+ (when creator_id [:= :notification.creator_id creator_id])+ (when card_id [:= :nc.card_id card_id])+ (when (seq channel) (channel-exists channel))+ (when last_send_status+ (case last_send_status+ :successful [:= :ls.has_failure false]+ :failing [:= :ls.has_failure true]))+ (when recipient_email+ (let [ids (notification-ids-with-recipient-email recipient_email)]+ ;; No recipient matched → an always-false predicate so the page comes back empty. We use+ ;; the truthy `[:= 1 0]` (renders `WHERE 1 = 0`) rather than `false`/`nil`, which the+ ;; `keep identity` above would elide — turning "no matches" into "no filter".+ (if (seq ids) [:in :notification.id ids] [:= 1 0])))+ (when-not (str/blank? query) (query-where-clause query))]))++(defn- base-list-query+ "Select notifications plus run-summary columns, card name, and creator name computed inline.++ When `skip-run-joins?` is true (detail path only), the `lc`/`ls` window subqueries and their+ select columns are omitted — the detail endpoint overwrites `last_check`/`last_send` from+ per-notification histories anyway, so those joins are pure waste on that path."+ [{:keys [skip-run-joins?] :as filters}]+ (reduce+ sql.helpers/where+ (cond-> {:select (cond-> [:notification.id+ :notification.active+ :notification.creator_id+ :notification.created_at+ :notification.updated_at+ :notification.payload_type+ :notification.payload_id+ [:c.name :card_name]+ [:cu.is_active :creator_is_active]+ [[:coalesce :cu.last_name :cu.first_name :cu.email] :creator_name]]+ (not skip-run-joins?)+ (into [[:lc.id :lc_id]+ [:lc.status :lc_status]+ [:lc.started_at :lc_started_at]+ [:ls.id :ls_id]+ [:ls.started_at :ls_started_at]+ [:ls.has_failure :ls_has_failure]]))+ :from [:notification]+ ;; A `notification/card` row with no payload_id is orphaned — it has no card, so+ ;; every card-derived column is null and it can't be managed here. Exclude it.+ :where [:and+ [:= :notification.payload_type "notification/card"]+ [:is-not :notification.payload_id nil]]}++ ;; These joins are always present regardless of the path.+ true+ (-> (sql.helpers/left-join [:notification_card :nc] [:= :nc.id :notification.payload_id])+ (sql.helpers/left-join [:report_card :c] [:= :c.id :nc.card_id])+ (sql.helpers/left-join [:core_user :cu] [:= :cu.id :notification.creator_id]))++ ;; Window subquery joins — skipped on the detail path (see docstring).+ (not skip-run-joins?)+ (-> (sql.helpers/left-join [(latest-run-per-card) :lc] [:= :lc.entity_id :nc.card_id])+ (sql.helpers/left-join [(latest-send-tick-per-card) :ls] [:= :ls.entity_id :nc.card_id])))+ (list-where-clauses filters)))++(defn- order-by-clauses+ "Resolve `sort_column` + `sort_direction` (both already malli-validated enums) into an+ honeysql `:order-by` vector. Pushes nulls last unconditionally — H2/Postgres/MySQL all default+ to NULLS-FIRST under DESC. Always tie-breaks on `notification.id desc` so paging is stable."+ [sort-column sort-direction]+ (let [col (sort-column->order-by sort-column)+ dir (or sort-direction :desc)]+ [[[:case [:= col nil] 1 :else 0] :asc]+ [col dir]+ [:notification.id :desc]]))++(defn- list-query+ [{:keys [sort_column sort_direction] :as filters}]+ (assoc (base-list-query (dissoc filters :sort_column :sort_direction))+ :order-by (order-by-clauses (or sort_column :last_send) sort_direction)))++(defn- count-query+ [filters]+ (-> (list-query filters)+ (assoc :select [[[:count :notification.id] :count]])+ (dissoc :order-by)))++(defn- coerce-run-status+ "Map a task_run/task_history `:status` keyword to the public `::run-status` enum.+ :success → :successful+ :failed / :abandoned → :failing+ Returns nil when `status` is nil (no run exists)."+ [status]+ (when status+ (case status+ :success :successful+ (:failed :abandoned) :failing)))++(defn- run->summary+ "Build a `::run-summary` map (or nil) from a task_run row joined onto the list query.+ Inputs:+ - status ; :success / :failed / :abandoned, or nil if no run exists+ - at ; started_at timestamp+ - error ; string from task_history.task_details->>'message', or nil++ Mapping:+ - :success → :successful+ - :failed → :failing+ - :abandoned → :failing (heartbeat-killed in-flight runs roll up to failing —+ the FE only cares about success/failure, not the+ lifecycle reason)+ - nil / no row → nil (never run / not visible to admin)+ - :started → not reachable here — the lc/ls subqueries exclude :started runs."+ [{:keys [status at error]}]+ (when (and status at)+ (let [run-status (coerce-run-status status)]+ {:at at+ :error (when (= run-status :failing) error)+ :status run-status})))++(defn- coerce-status+ [status]+ (some-> status keyword))++(defn- error-by-run-id+ "Map run_id → error message for the given failed/abandoned run IDs. When `task-name` is non-nil,+ restrict to that task type (used by `last_send`, which is specifically about channel-send). When+ nil, the ORDER BY tiebreaker prefers `notification-send` then falls back to the latest by+ `ended_at` (used by `last_check`, which wants the most-signal message for the whole run). The+ CASE is a no-op when `task-name` is supplied — all candidate rows share the same `:task`."+ [task-name run-ids]+ (when (seq run-ids)+ (->> (t2/select :model/TaskHistory+ {:select [:run_id :task_details]+ :from [[{:select [:run_id :task_details+ [[:over [[:row_number]+ {:partition-by [:run_id]+ :order-by [[[:case+ [:= :task task-notification-send] 0+ :else 1] :asc]+ [:ended_at :desc]]}]]+ :rn]]+ :from [:task_history]+ :where (cond-> [:and+ [:in :run_id run-ids]+ [:in :status ["failed" "abandoned"]]]+ task-name (conj [:= :task task-name]))}+ :sub]]+ :where [:= :sub.rn 1]})+ (into {} (map (juxt :run_id (comp :message :task_details)))))))++(defn- has-failure?+ "True when the `has_failure` value from `latest-send-tick-per-card` indicates at least one+ channel failure. `bit->boolean` absorbs the MySQL/MariaDB bit-vs-boolean JDBC quirk so H2,+ Postgres, and MySQL all read uniformly."+ [v]+ (boolean (api/bit->boolean v)))++(defn- decorate-runs+ "Build :last_check / :last_send maps on each row from the joined run columns + per-page+ task_history lookups for the error messages on any failed runs.++ :last_check error uses the tiebreaker (prefer the outer notification-send message; fall back to+ the latest by ended_at). :last_send error is restricted to channel-send rows — `last_send` is+ specifically about the send tick, and the outer notification-send may have succeeded.+ :last_send is nil when ls_started_at is nil (no send ever attempted for this card)."+ [rows]+ (let [failed-lc-ids (into #{} (keep (fn [{:keys [lc_id lc_status]}]+ (when (#{"failed" "abandoned"} lc_status) lc_id)))+ rows)+ failed-ls-ids (into #{} (keep (fn [{:keys [ls_id ls_has_failure]}]+ (when (and ls_id (has-failure? ls_has_failure)) ls_id)))+ rows)+ lc->error (error-by-run-id nil failed-lc-ids)+ ls->error (error-by-run-id task-channel-send failed-ls-ids)]+ (mapv (fn [{:keys [lc_id lc_status lc_started_at+ ls_id ls_started_at ls_has_failure] :as row}]+ (-> row+ (assoc :last_check (run->summary {:status (coerce-status lc_status)+ :at lc_started_at+ :error (get lc->error lc_id)}))+ (assoc :last_send (when ls_started_at+ {:at ls_started_at+ :error (get ls->error ls_id)+ :status (if (has-failure? ls_has_failure)+ :failing+ :successful)}))+ (dissoc :lc_id :lc_status :lc_started_at+ :ls_id :ls_started_at :ls_has_failure)))+ rows)))++(defn- splice-creator-active+ "Splice `:is_active` (joined from `core_user`) onto the hydrated `:creator` map — `t2/hydrate+ :creator` strips it because `default-user-columns` omits it — and drop the internal+ `:creator_is_active` carrier column. The response keeps `creator_id` / `creator` as-is."+ [{:keys [creator creator_is_active] :as row}]+ (-> row+ (cond-> creator (assoc :creator (assoc creator :is_active creator_is_active)))+ (dissoc :creator_is_active)))++(defn- list-notifications+ "Single SQL query for the page; one extra query for failed-run error messages on that page."+ [{:keys [limit offset] :as filters}]+ (let [base-filters (dissoc filters :limit :offset)+ page-rows (t2/select :model/Notification+ (assoc (list-query base-filters)+ :limit limit+ :offset offset))+ total (or (:count (t2/query-one (count-query base-filters))) 0)+ decorated (-> page-rows+ decorate-runs+ models.notification/hydrate-notification)]+ {:data (mapv splice-creator-active decorated)+ :total total+ :limit limit+ :offset offset}))++;; snake_case query params are intentional here — they match the existing+;; `metabase.notification.api.notification` endpoints so clients can share param names between+;; the public and admin surfaces.+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-query-params-use-kebab-case]}+(api.macros/defendpoint :get "/" :- ::list-response+ "List card-type notifications (alerts) for admin management. Supports pagination (`limit` ++ `offset` query params — handled by the offset-paging middleware), filtering, and sorting.++ `last_send_status` filter operates on the latest channel-send task_history row for the+ notification's card (`successful` = latest channel-send succeeded; `failing` = latest+ channel-send failed). The Failing tab uses `?last_send_status=failing`.++ `creatorless=true` selects notifications with no creator or a deactivated creator (the Ownerless+ tab). `creatorless=false` selects the inverse.++ `channel` accepts a single string or a repeated query param for multi-select (OR logic)."+ [_route+ {:keys [active creator_id creator_active creatorless card_id recipient_email channel last_send_status+ query sort_column sort_direction]} :-+ [:map+ [:active {:optional true} [:maybe ms/BooleanValue]]+ [:creator_id {:optional true} ms/PositiveInt]+ [:creator_active {:optional true} [:maybe ms/BooleanValue]]+ [:creatorless {:optional true} [:maybe ms/BooleanValue]]+ [:card_id {:optional true} ms/PositiveInt]+ [:recipient_email {:optional true} ms/NonBlankString]+ [:channel {:optional true} [:maybe [:or ms/NonBlankString [:sequential ms/NonBlankString]]]]+ [:last_send_status {:optional true} ::run-status]+ [:query {:optional true} ms/NonBlankString]+ [:sort_column {:default :last_send} ::sort-column]+ [:sort_direction {:default :desc} ::sort-direction]]]+ (api/check-superuser)+ (list-notifications {:limit (or (request/limit) 50)+ :offset (or (request/offset) 0)+ :active active+ :creator_id creator_id+ :creator_active creator_active+ :creatorless creatorless+ :card_id card_id+ :recipient_email recipient_email+ :channel channel+ :last_send_status last_send_status+ :query query+ :sort_column sort_column+ :sort_direction sort_direction}))++;; ---------------------------------------------------------------------------+;; Detail endpoint helpers+;; ---------------------------------------------------------------------------++(defn- task-history-rows-for-card+ "Reducible source of `task-name` task_history rows for `card-id`, joined to task_run for tick+ metadata, newest first. Bounded at `:fetch-limit` rows as a safety upper bound — callers should+ combine with `(take …)` in the transducer so the JDBC cursor short-circuits once the+ in-memory `notification_id` filter has yielded enough matches."+ [card-id task-name & {:keys [fetch-limit extra-where] :or {fetch-limit 500}}]+ (t2/reducible-select :model/TaskHistory+ {:select [:th.run_id :th.task_details :th.status+ [:tr.id :task_run_id]+ [:tr.status :run_status]+ [:tr.started_at :run_started_at]]+ :from [[:task_history :th]]+ :join [[:task_run :tr] [:= :tr.id :th.run_id]]+ :where (cond-> [:and+ [:= :tr.run_type run-type-alert]+ [:= :tr.entity_type entity-type-card]+ [:= :tr.entity_id card-id]+ [:= :th.task task-name]+ [:> :tr.started_at (lookback-cutoff)]]+ extra-where (conj extra-where))+ :order-by [[:tr.started_at :desc]]+ :limit fetch-limit}))++(defn- task-details-key+ "Look up `k` in `task_details`, checking top level then `:original-info` (where+ `with-task-history` nests the caller's payload on failure)."+ [task_details k]+ (or (get task_details k)+ (get-in task_details [:original-info k])))++(defn- matches-notification?+ "Row predicate: true when `task_details.notification_id` matches `notification-id`."+ [notification-id]+ (fn [{:keys [task_details]}]+ (= notification-id (task-details-key task_details :notification_id))))++(defn- check-history-for-notification+ "Up to `:result-limit` most-recent terminal TaskRuns for `notification-id`, newest first, as+ `::run-summary` maps."+ [card-id notification-id & {:keys [fetch-limit result-limit] :or {fetch-limit 500 result-limit 10}}]+ (let [matching (into []+ ;; `realize` each matched row before exiting the reduction — the+ ;; reducible-select rows are transient views over the JDBC cursor and+ ;; become unreadable once `take` closes the reducible.+ (comp (filter (matches-notification? notification-id))+ (take result-limit)+ (map t2.realize/realize))+ (task-history-rows-for-card card-id task-notification-send+ :fetch-limit fetch-limit+ :extra-where [:in :tr.status terminal-statuses]))+ failed-ids (into #{} (keep #(when (#{"failed" "abandoned"} (:run_status %)) (:task_run_id %)) matching))+ errors (error-by-run-id nil failed-ids)]+ (mapv (fn [{:keys [task_run_id run_status run_started_at]}]+ (run->summary {:status (coerce-status run_status)+ :at run_started_at+ :error (get errors task_run_id)}))+ matching)))++(defn- ->channel-entry+ "Build a single `::channel-entry` from a channel-send task_history row."+ [{:keys [status task_details]}]+ (let [status-kw (coerce-status status)+ run-status (coerce-run-status (or status-kw :failed))+ channel-type (some-> (task-details-key task_details :channel_type) keyword)]+ {:channel_type (or channel-type :channel/unknown)+ :status run-status+ :error (when (= run-status :failing)+ (:message task_details))}))++(defn- send-history-for-notification+ "Up to `:result-limit` most-recent send ticks for `notification-id`, newest first, each a+ `::tick-send-entry` rolling up all channels in that tick. Ticks with no channel-send rows+ (e.g. goal-not-met) only appear in check_history."+ [card-id notification-id & {:keys [fetch-limit result-limit] :or {fetch-limit 500 result-limit 10}}]+ ;; Stream channel-send rows newest-first, filter to this notification, partition into ticks+ ;; (rows of one tick are adjacent in started_at-desc order), take `result-limit` ticks, build+ ;; the tick-send entries. The transducer short-circuits once `result-limit` partitions are seen.+ ;; `realize` each matched row before `partition-by` holds it — reducible-select rows are+ ;; transient views over the JDBC cursor that go invalid once `take` closes the reducible.+ (into []+ (comp (filter (matches-notification? notification-id))+ (map t2.realize/realize)+ (partition-by :run_id)+ (take result-limit)+ (map (fn [tick-rows]+ (let [channel-entries (mapv ->channel-entry tick-rows)]+ {:at (:run_started_at (first tick-rows))+ :status (if (some #(= :failing (:status %)) channel-entries) :failing :successful)+ :error (some :error channel-entries)+ :channels channel-entries}))))+ (task-history-rows-for-card card-id task-channel-send :fetch-limit fetch-limit)))++(defn- get-notification-detail+ "Fetch a single card-type notification with `:last_check`, `:last_send`, `:check_history`, and+ `:send_history` (each per-notification, not card-level). Returns nil for a missing or non-card+ notification."+ [id]+ (when-let [row (t2/select-one :model/Notification+ (-> (base-list-query {:skip-run-joins? true})+ (sql.helpers/where [:= :notification.id id])))]+ ;; `base-list-query` with `:skip-run-joins?` doesn't project lc_*/ls_* columns, so we go+ ;; straight from hydration to splice and derive last_check / last_send from the+ ;; per-notification histories (which are also internally consistent and not subject to+ ;; card-level bleed from other notifications sharing the same card).+ (let [decorated (-> (models.notification/hydrate-notification [row])+ first+ splice-creator-active)+ card-id (get-in decorated [:payload :card_id])+ check-history (if card-id (check-history-for-notification card-id id) [])+ send-history (if card-id (send-history-for-notification card-id id) [])]+ (assoc decorated+ :last_check (first check-history)+ :last_send (some-> (first send-history) (select-keys [:at :status :error]))+ :check_history check-history+ :send_history send-history))))++(api.macros/defendpoint :get "/:id" :- ::detail-response+ "Get a single card-type notification with last_check, last_send, check_history (up to 10+ most-recent terminal alert-type TaskRuns) and send_history (up to 10 most-recent channel-send+ delivery attempts). 404 if the notification doesn't exist or isn't a card-type notification."+ [{:keys [id]} :- [:map+ [:id ms/PositiveInt]]]+ (api/check-superuser)+ (api/check-404 (get-notification-detail id)))++(defn- action->update-map+ [action creator-id]+ (case (keyword action)+ :archive {:active false}+ :change-creator (do (api/check (integer? creator-id) [400 "creator_id required for change-creator"])+ {:creator_id creator-id})))++(defn- bulk-update!+ "Apply `update-map` to all card-type notifications in `ids` in a single SQL update. Returns the+ hydrated before-state so the caller can drive post-commit side effects via+ [[notification-api/publish-notification-update!]]."+ [update-map ids]+ ;; Guard empty `ids`: `[:in :id []]` is degenerate SQL, and there's nothing to select/update or+ ;; publish side effects for. (The endpoint schema also enforces `:min 1`.)+ (if (empty? ids)+ []+ ;; The endpoint is superuser-gated (`api/check-superuser`), which is what the model's+ ;; before-update hook checks before permitting a `creator_id` change. (Harmless for the+ ;; archive action, whose update-map never touches creator_id.)+ (t2/with-transaction [_conn]+ (let [before (-> (t2/select :model/Notification+ :id [:in ids]+ :payload_type :notification/card)+ models.notification/hydrate-notification+ vec)]+ (t2/update! :model/Notification+ :id [:in ids]+ :payload_type :notification/card+ update-map)+ before))))++(api.macros/defendpoint :post "/bulk" :- ::bulk-response+ "Bulk-archive or -change-creator a set of notifications. The per-notification `:active` flip goes+ through `:model/Notification`'s `before-update` hook, which creates / tears down the Quartz+ triggers. Recipient emails and `:event/notification-update` audit events are+ published via the shared [[notification-api/publish-notification-update!]] helper so this+ endpoint's side-effect contract can't drift from `PUT /api/notification/:id`."+ [_route _query+ {:keys [notification_ids action creator_id]} :-+ [:map+ [:notification_ids [:sequential {:min 1} ms/PositiveInt]]+ [:action [:enum "archive" "change-creator"]]+ [:creator_id {:optional true} ms/PositiveInt]]]+ (api/check-superuser)+ (let [update-map (action->update-map action creator_id)+ before (bulk-update! update-map notification_ids)+ after (->> (t2/select :model/Notification :id [:in (mapv :id before)])+ models.notification/hydrate-notification+ (m/index-by :id))]+ (doseq [b before+ :let [a (get after (:id b))]+ :when a]+ (notification-api/publish-notification-update! a b))+ {:updated (count before)}))diff --git a/enterprise/backend/test/metabase_enterprise/notification_admin/api_test.clj b/enterprise/backend/test/metabase_enterprise/notification_admin/api_test.cljnew file mode 100644index 00000000000..50a77bb7e97--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/notification_admin/api_test.clj@@ -0,0 +1,1638 @@+(ns metabase-enterprise.notification-admin.api-test+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase.test :as mt]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(deftest list-stub-returns-shape-test+ (testing "GET /api/ee/notifications returns :data + :total shape for superuser with :audit-app"+ (mt/with-premium-features #{:audit-app}+ (let [resp (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (contains? resp :data))+ (is (contains? resp :total))+ (is (sequential? (:data resp)))+ (is (integer? (:total resp)))))))++(deftest requires-premium-feature-test+ (testing "GET /api/ee/notifications returns 402 without :audit-app premium feature"+ (mt/with-premium-features #{}+ (mt/assert-has-premium-feature-error+ "Audit app"+ (mt/user-http-request :crowberto :get 402 "ee/notifications")))))++(deftest requires-superuser-test+ (testing "GET /api/ee/notifications returns 403 for non-superuser"+ (mt/with-premium-features #{:audit-app}+ (mt/user-http-request :rasta :get 403 "ee/notifications"))))++(deftest list-returns-only-card-notifications-test+ (testing "GET /api/ee/notifications only returns :notification/card rows"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {ncard-id :id} {:card_id card-id}+ :model/Notification card-notif {:payload_type :notification/card+ :payload_id ncard-id+ :creator_id (mt/user->id :crowberto)}+ :model/Notification sys-notif {:payload_type :notification/system-event+ :creator_id (mt/user->id :crowberto)}]+ (let [{:keys [data total]} (mt/user-http-request :crowberto :get 200 "ee/notifications")+ ids (set (map :id data))]+ (is (contains? ids (:id card-notif)))+ (is (not (contains? ids (:id sys-notif))))+ (is (pos? total)))))))++(deftest list-pagination-test+ (testing "limit + offset paginate the result"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification _n1 {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)}+ :model/Notification _n2 {:payload_type :notification/card+ :payload_id nc2+ :creator_id (mt/user->id :crowberto)}]+ (let [resp (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :limit 1 :offset 0)]+ (is (= 1 (count (:data resp))))+ (is (>= (:total resp) 2)))+ (let [resp (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :limit 100 :offset 0)]+ (is (>= (count (:data resp)) 2)))))))++(deftest filter-by-active-test+ (testing "?active=true|false filters on the notification.active boolean; omitted = both"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification active-notif {:payload_type :notification/card+ :payload_id nc1+ :active true+ :creator_id (mt/user->id :crowberto)}+ :model/Notification archived-notif {:payload_type :notification/card+ :payload_id nc2+ :active false+ :creator_id (mt/user->id :crowberto)}]+ (testing "?active=true returns only active"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :active true)+ ids (set (map :id data))]+ (is (contains? ids (:id active-notif)))+ (is (not (contains? ids (:id archived-notif))))))+ (testing "?active=false returns only archived"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :active false)+ ids (set (map :id data))]+ (is (not (contains? ids (:id active-notif))))+ (is (contains? ids (:id archived-notif)))))+ (testing "omitting ?active returns both"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")+ ids (set (map :id data))]+ (is (contains? ids (:id active-notif)))+ (is (contains? ids (:id archived-notif)))))))))++(deftest filter-by-owner-test+ (testing "creator_id filters to notifications owned by that user"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {user-a :id} {}+ :model/User {user-b :id} {}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification notif-a {:payload_type :notification/card+ :payload_id nc1+ :creator_id user-a}+ :model/Notification notif-b {:payload_type :notification/card+ :payload_id nc2+ :creator_id user-b}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :creator_id user-a)+ ids (set (map :id data))]+ (is (contains? ids (:id notif-a)))+ (is (not (contains? ids (:id notif-b)))))))))++(deftest owner-includes-is-active-test+ (testing "the hydrated :creator map carries :is_active so FE can render the deactivated-owner state"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {active :id} {:is_active true}+ :model/User {deactivated :id} {:is_active false}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification {active-n :id} {:payload_type :notification/card+ :payload_id nc1+ :creator_id active}+ :model/Notification {deact-n :id} {:payload_type :notification/card+ :payload_id nc2+ :creator_id deactivated}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")+ by-id (into {} (map (juxt :id identity) data))]+ (is (=? {:creator {:id active :is_active true}} (by-id active-n)))+ (is (=? {:creator {:id deactivated :is_active false}} (by-id deact-n))))))))++(deftest filter-by-owner-active-test+ (testing "?creator_active=true|false filters on the creator user's is_active flag"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {active :id} {:is_active true}+ :model/User {deactivated :id} {:is_active false}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification active-notif {:payload_type :notification/card+ :payload_id nc1+ :creator_id active}+ :model/Notification deact-notif {:payload_type :notification/card+ :payload_id nc2+ :creator_id deactivated}]+ (testing "creator_active=true keeps only notifications whose creator is active"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :creator_active true)+ ids (set (map :id data))]+ (is (contains? ids (:id active-notif)))+ (is (not (contains? ids (:id deact-notif))))))+ (testing "creator_active=false keeps only notifications whose creator is deactivated"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :creator_active false)+ ids (set (map :id data))]+ (is (contains? ids (:id deact-notif)))+ (is (not (contains? ids (:id active-notif))))))))))++(deftest filter-by-card-test+ (testing "card_id filters to notifications whose notification_card.card_id matches"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {target-card :id} {}+ :model/Card {other-card :id} {}+ :model/NotificationCard {nc-target :id} {:card_id target-card}+ :model/NotificationCard {nc-other :id} {:card_id other-card}+ :model/Notification notif-target {:payload_type :notification/card+ :payload_id nc-target+ :creator_id (mt/user->id :crowberto)}+ :model/Notification notif-other {:payload_type :notification/card+ :payload_id nc-other+ :creator_id (mt/user->id :crowberto)}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :card_id target-card)+ ids (set (map :id data))]+ (is (contains? ids (:id notif-target)))+ (is (not (contains? ids (:id notif-other)))))))))++(deftest filter-by-channel-test+ (testing "channel filters to notifications with a matching handler channel_type"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification email-notif {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)}+ :model/Notification slack-notif {:payload_type :notification/card+ :payload_id nc2+ :creator_id (mt/user->id :crowberto)}+ :model/NotificationHandler _email-handler {:notification_id (:id email-notif)+ :channel_type :channel/email}+ :model/NotificationHandler _slack-handler {:notification_id (:id slack-notif)+ :channel_type :channel/slack}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :channel "channel/email")+ ids (set (map :id data))]+ (is (contains? ids (:id email-notif)))+ (is (not (contains? ids (:id slack-notif)))))))))++(deftest filter-by-recipient-email-user-recipient-test+ (testing "recipient_email matches a user recipient via case-insensitive core_user.email"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {target-user :id+ target-email :email} {}+ :model/User {other-user :id} {}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification target-notif {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)}+ :model/Notification other-notif {:payload_type :notification/card+ :payload_id nc2+ :creator_id (mt/user->id :crowberto)}+ :model/NotificationHandler {target-handler :id} {:notification_id (:id target-notif)+ :channel_type :channel/email}+ :model/NotificationHandler {other-handler :id} {:notification_id (:id other-notif)+ :channel_type :channel/email}+ :model/NotificationRecipient _target-r {:notification_handler_id target-handler+ :type :notification-recipient/user+ :user_id target-user}+ :model/NotificationRecipient _other-r {:notification_handler_id other-handler+ :type :notification-recipient/user+ :user_id other-user}]+ (testing "exact (case-sensitive original)"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :recipient_email target-email)+ ids (set (map :id data))]+ (is (contains? ids (:id target-notif)))+ (is (not (contains? ids (:id other-notif))))))+ (testing "case-insensitive — uppercased query still matches a lowercased stored email"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :recipient_email (u/upper-case-en target-email))+ ids (set (map :id data))]+ (is (contains? ids (:id target-notif)))))))))++(deftest filter-by-recipient-email-raw-value-test+ (testing "recipient_email also matches raw-value (external) recipients via the JSON details column"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification raw-notif {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)}+ :model/Notification unrelated-notif {:payload_type :notification/card+ :payload_id nc2+ :creator_id (mt/user->id :crowberto)}+ :model/NotificationHandler {raw-handler :id} {:notification_id (:id raw-notif)+ :channel_type :channel/email}+ :model/NotificationHandler {un-handler :id} {:notification_id (:id unrelated-notif)+ :channel_type :channel/email}+ :model/NotificationRecipient _raw-r {:notification_handler_id raw-handler+ :type :notification-recipient/raw-value+ :details {:value "[email protected]"}}+ :model/NotificationRecipient _other-raw {:notification_handler_id un-handler+ :type :notification-recipient/raw-value+ :details {:value "[email protected]"}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :recipient_email "[email protected]")+ ids (set (map :id data))]+ (is (contains? ids (:id raw-notif)))+ (is (not (contains? ids (:id unrelated-notif)))))))))++;; ---------------------------------------------------------------------------------------------+;; Fuzzy ?query= search — matches card name + owner name/email only (recipients no longer)+;; ---------------------------------------------------------------------------------------------++(deftest query-matches-card-name-test+ (testing "?query= substring-matches the card name (case-insensitive)"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {sales :id} {:name "Sales report"}+ :model/Card {orders :id} {:name "Orders dashboard"}+ :model/NotificationCard {nc-sales :id} {:card_id sales}+ :model/NotificationCard {nc-orders :id} {:card_id orders}+ :model/Notification sales-n {:payload_type :notification/card+ :payload_id nc-sales+ :creator_id (mt/user->id :crowberto)}+ :model/Notification orders-n {:payload_type :notification/card+ :payload_id nc-orders+ :creator_id (mt/user->id :crowberto)}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "SALES")+ ids (set (map :id data))]+ (is (contains? ids (:id sales-n)))+ (is (not (contains? ids (:id orders-n)))))))))++(deftest query-matches-owner-name-test+ (testing "?query= substring-matches owner first/last/email"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {alice :id} {:first_name "Alice" :last_name "Stone"+ :email "[email protected]"}+ :model/User {bob :id} {:first_name "Bob" :last_name "Jones"+ :email "[email protected]"}+ :model/Card {card :id} {}+ :model/NotificationCard {nc-a :id} {:card_id card}+ :model/NotificationCard {nc-b :id} {:card_id card}+ :model/Notification alice-n {:payload_type :notification/card+ :payload_id nc-a+ :creator_id alice}+ :model/Notification bob-n {:payload_type :notification/card+ :payload_id nc-b+ :creator_id bob}]+ (testing "by first_name"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "alic")+ ids (set (map :id data))]+ (is (contains? ids (:id alice-n)))+ (is (not (contains? ids (:id bob-n))))))+ (testing "by last_name"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "stone")+ ids (set (map :id data))]+ (is (contains? ids (:id alice-n)))+ (is (not (contains? ids (:id bob-n))))))+ (testing "by email"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "bob@example")+ ids (set (map :id data))]+ (is (contains? ids (:id bob-n)))+ (is (not (contains? ids (:id alice-n))))))))))++(deftest query-does-not-match-recipients-test+ (testing "?query= no longer descends into recipient emails or slack channels — only card + owner"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {recipient :id} {:email "[email protected]"}+ :model/Card {card :id} {:name "Innocuous card"}+ :model/NotificationCard {nc-user :id} {:card_id card}+ :model/NotificationCard {nc-raw :id} {:card_id card}+ :model/NotificationCard {nc-slack :id} {:card_id card}+ :model/Notification user-recipient-n {:payload_type :notification/card+ :payload_id nc-user+ :creator_id (mt/user->id :crowberto)}+ :model/Notification raw-recipient-n {:payload_type :notification/card+ :payload_id nc-raw+ :creator_id (mt/user->id :crowberto)}+ :model/Notification slack-recipient-n {:payload_type :notification/card+ :payload_id nc-slack+ :creator_id (mt/user->id :crowberto)}+ :model/NotificationHandler {h-user :id} {:notification_id (:id user-recipient-n)+ :channel_type :channel/email}+ :model/NotificationHandler {h-raw :id} {:notification_id (:id raw-recipient-n)+ :channel_type :channel/email}+ :model/NotificationHandler {h-slack :id} {:notification_id (:id slack-recipient-n)+ :channel_type :channel/slack}+ :model/NotificationRecipient _r-user {:notification_handler_id h-user+ :type :notification-recipient/user+ :user_id recipient}+ :model/NotificationRecipient _r-raw {:notification_handler_id h-raw+ :type :notification-recipient/raw-value+ :details {:value "[email protected]"}}+ :model/NotificationRecipient _r-slack {:notification_handler_id h-slack+ :type :notification-recipient/raw-value+ :details {:value "#fuzzy-channel"}}]+ (testing "user-recipient email is NOT matched by ?query="+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "unique-domain")+ ids (set (map :id data))]+ (is (not (contains? ids (:id user-recipient-n))))))+ (testing "raw-value email recipient is NOT matched by ?query="+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "fuzzy-target")+ ids (set (map :id data))]+ (is (not (contains? ids (:id raw-recipient-n))))))+ (testing "slack-channel raw-value recipient is NOT matched by ?query="+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "fuzzy-channel")+ ids (set (map :id data))]+ (is (not (contains? ids (:id slack-recipient-n))))))))))++(deftest query-and-other-filters-and-together-test+ (testing "?query= AND'd with other filters; structured filters narrow the fuzzy result"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card :id} {:name "Quarterly fizzbuzz"}+ :model/NotificationCard {nc-a :id} {:card_id card}+ :model/NotificationCard {nc-b :id} {:card_id card}+ :model/Notification active-match {:payload_type :notification/card+ :payload_id nc-a+ :active true+ :creator_id (mt/user->id :crowberto)}+ :model/Notification archived-match {:payload_type :notification/card+ :payload_id nc-b+ :active false+ :creator_id (mt/user->id :crowberto)}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :query "fizzbuzz"+ :active true)+ ids (set (map :id data))]+ (is (contains? ids (:id active-match)))+ (is (not (contains? ids (:id archived-match)))))))))++(defn- find-row-by-id [data id]+ (some #(when (= id (:id %)) %) data))++;; ---------------------------------------------------------------------------------------------+;; :last_check / :last_send shape+;; ---------------------------------------------------------------------------------------------++(deftest last-send-from-channel-send-task-history-test+ (testing ":last_send reflects the latest channel-send task_history row (any outcome)"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-a :id} {:archived false}+ :model/Card {card-b :id} {:archived false}+ :model/NotificationCard {nc-a :id} {:card_id card-a}+ :model/NotificationCard {nc-b :id} {:card_id card-b}+ :model/Notification {n-sent :id} {:payload_type :notification/card+ :payload_id nc-a+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {n-unsent :id} {:payload_type :notification/card+ :payload_id nc-b+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-a+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _th {:task "channel-send"+ :run_id run-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"+ :notification_id (:id n-sent)}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")+ by-id (into {} (map (juxt :id identity) data))]+ (is (=? {:last_send {:at some?+ :status "successful"+ :error nil}}+ (by-id n-sent)))+ (is (=? {:last_send nil}+ (by-id n-unsent))))))))++(deftest last-send-failing-channel-send-surfaces-status-and-error-test+ (testing ":last_send on the list shows :failing status AND the channel-send error message+ when the latest send-tick had a channel failure"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _th {:task "channel-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:message "SMTP connection refused"+ :channel_type "channel/email"+ :notification_id nid}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_send {:at some?+ :status "failing"+ :error "SMTP connection refused"}}+ (find-row-by-id data nid))))))))++(deftest last-check-shape-success-test+ (testing ":last_check on a successful run reports status=successful with no error"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun _run {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_check {:at some?+ :status "successful"+ :error nil}}+ (find-row-by-id data nid))))))))++(deftest last-check-shape-failing-includes-error-test+ (testing ":last_check on a failed run reports status=failing and pulls the error from task_history"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _th {:task "notification-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:message "SMTP host unreachable"}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_check {:at some?+ :status "failing"+ :error "SMTP host unreachable"}}+ (find-row-by-id data nid))))))))++(deftest last-send-shape-failing-includes-error-test+ (testing ":last_send on the list endpoint surfaces the channel-send error message (not just status=failing)"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}+ ;; Outer notification-send succeeded; only the channel-send failed.+ :model/TaskHistory _ns-th {:task "notification-send"+ :run_id run-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:notification_id nid}}+ :model/TaskHistory _cs-th {:task "channel-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:status :failed+ :message "Slack token invalid"+ :original-info {:channel_type "channel/slack"+ :notification_id nid}}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_send {:at some?+ :status "failing"+ :error "Slack token invalid"}}+ (find-row-by-id data nid))))))))++(deftest last-check-abandoned-folds-into-failing-test+ (testing ":abandoned (heartbeat-killed) runs surface as last_check.status=failing"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun _run {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :abandoned+ :started_at (t/instant)+ :ended_at (t/instant)}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_check {:status "failing"}}+ (find-row-by-id data nid))))))))++(deftest last-check-skips-in-flight-runs-test+ (testing "an :started in-flight run is invisible to the admin list — last_check stays nil"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun _run {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :started+ :started_at (t/instant)}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_check nil+ :last_send nil}+ (find-row-by-id data nid))))))))++(deftest response-shape-includes-pagination-metadata-test+ (testing "GET / response shape echoes the {:data :total :limit :offset} pagination convention"+ (mt/with-premium-features #{:audit-app}+ (let [resp (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (contains? resp :data))+ (is (contains? resp :total))+ (is (contains? resp :limit))+ (is (contains? resp :offset))))))++(deftest response-shape-does-not-include-counts-test+ (testing "GET / response does NOT include a :counts key — tab counts are dropped"+ (mt/with-premium-features #{:audit-app}+ (let [resp (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (not (contains? resp :counts)))))))++(deftest filter-by-last-send-status-test+ (testing "?last_send_status=successful|failing filters by the latest channel-send outcome"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {success-card :id} {:archived false}+ :model/Card {fail-card :id} {:archived false}+ :model/Card {no-send-card :id} {:archived false}+ :model/NotificationCard {nc-success :id} {:card_id success-card}+ :model/NotificationCard {nc-fail :id} {:card_id fail-card}+ :model/NotificationCard {nc-no-send :id} {:card_id no-send-card}+ :model/Notification success-n {:payload_type :notification/card+ :payload_id nc-success+ :creator_id (mt/user->id :crowberto)}+ :model/Notification fail-n {:payload_type :notification/card+ :payload_id nc-fail+ :creator_id (mt/user->id :crowberto)}+ :model/Notification no-send-n {:payload_type :notification/card+ :payload_id nc-no-send+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {ok-run :id} {:run_type :alert+ :entity_type :card+ :entity_id success-card+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskRun {fail-run :id} {:run_type :alert+ :entity_type :card+ :entity_id fail-card+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}+ ;; channel-send rows drive the filter+ :model/TaskHistory _ok-th {:task "channel-send"+ :run_id ok-run+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"}}+ :model/TaskHistory _fail-th {:task "channel-send"+ :run_id fail-run+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"}}]+ (testing "successful"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :last_send_status "successful")+ ids (set (map :id data))]+ (is (contains? ids (:id success-n)))+ (is (not (contains? ids (:id fail-n))))+ (is (not (contains? ids (:id no-send-n))))))+ (testing "failing"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :last_send_status "failing")+ ids (set (map :id data))]+ (is (contains? ids (:id fail-n)))+ (is (not (contains? ids (:id success-n))))+ (is (not (contains? ids (:id no-send-n))))))))))++(deftest filter-compound-test+ (testing "multiple filters AND together (active + owner_id)"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {target-user :id} {}+ :model/User {other-user :id} {}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/NotificationCard {nc3 :id} {:card_id card-id}+ :model/Notification matching {:payload_type :notification/card+ :payload_id nc1+ :active true+ :creator_id target-user}+ :model/Notification wrong-active {:payload_type :notification/card+ :payload_id nc2+ :active false+ :creator_id target-user}+ :model/Notification wrong-owner {:payload_type :notification/card+ :payload_id nc3+ :active true+ :creator_id other-user}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :active true+ :creator_id target-user)+ ids (set (map :id data))]+ (is (contains? ids (:id matching)))+ (is (not (contains? ids (:id wrong-active))))+ (is (not (contains? ids (:id wrong-owner)))))))))++;; ---------------------------------------------------------------------------------------------+;; Sort+;; ---------------------------------------------------------------------------------------------++(deftest sort-by-last-send-test+ (testing "?sort_column=last_send orders rows by the latest channel-send started_at"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-old :id} {:archived false}+ :model/Card {card-new :id} {:archived false}+ :model/Card {card-never :id} {:archived false}+ :model/NotificationCard {nc-old :id} {:card_id card-old}+ :model/NotificationCard {nc-new :id} {:card_id card-new}+ :model/NotificationCard {nc-never :id} {:card_id card-never}+ :model/Notification {old-id :id} {:payload_type :notification/card+ :payload_id nc-old+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {new-id :id} {:payload_type :notification/card+ :payload_id nc-new+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {never-id :id} {:payload_type :notification/card+ :payload_id nc-never+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {old-run :id} {:run_type :alert+ :entity_type :card+ :entity_id card-old+ :status :success+ :started_at (t/minus (t/instant) (t/days 5))+ :ended_at (t/minus (t/instant) (t/days 5))}+ :model/TaskRun {new-run :id} {:run_type :alert+ :entity_type :card+ :entity_id card-new+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _old-th {:task "channel-send"+ :run_id old-run+ :status :success+ :started_at (t/minus (t/instant) (t/days 5))+ :ended_at (t/minus (t/instant) (t/days 5))+ :task_details {:channel_type "channel/email"}}+ :model/TaskHistory _new-th {:task "channel-send"+ :run_id new-run+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :sort_column "last_send"+ :sort_direction "desc")+ ids (->> data (map :id) (filter #{old-id new-id never-id}) vec)]+ (is (= [new-id old-id never-id] ids)+ "newest-sent first, oldest-sent next, never-sent last (desc + null-trailing)"))))))++(deftest sort-by-updated-at-test+ (testing "?sort_column=updated_at orders rows by notification.updated_at"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification n-older {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)+ :updated_at (t/minus (t/instant) (t/days 2))}+ :model/Notification n-newer {:payload_type :notification/card+ :payload_id nc2+ :creator_id (mt/user->id :crowberto)+ :updated_at (t/instant)}]+ (testing "desc puts newer first"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :sort_column "updated_at"+ :sort_direction "desc")+ seen (->> data (map :id) (filter #{(:id n-older) (:id n-newer)}) vec)]+ (is (= [(:id n-newer) (:id n-older)] seen))))+ (testing "asc puts older first"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :sort_column "updated_at"+ :sort_direction "asc")+ seen (->> data (map :id) (filter #{(:id n-older) (:id n-newer)}) vec)]+ (is (= [(:id n-older) (:id n-newer)] seen))))))))++(deftest sort-rejects-unknown-column-test+ (testing "?sort_column=<unknown> is rejected with 400 by the malli enum"+ (mt/with-premium-features #{:audit-app}+ (mt/user-http-request :crowberto :get 400 "ee/notifications"+ :sort_column "name; DROP TABLE notification"))))++(deftest default-sort-is-last-send-test+ (testing "default sort_column is :last_send (null-trailing desc), driven by channel-send rows"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-sent :id} {:archived false}+ :model/Card {card-unsent :id} {:archived false}+ :model/NotificationCard {nc-sent :id} {:card_id card-sent}+ :model/NotificationCard {nc-unsent :id} {:card_id card-unsent}+ :model/Notification {sent-id :id} {:payload_type :notification/card+ :payload_id nc-sent+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {unsent-id :id} {:payload_type :notification/card+ :payload_id nc-unsent+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-sent+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _th {:task "channel-send"+ :run_id run-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")+ ids (->> data (map :id) (filter #{sent-id unsent-id}) vec)]+ (is (= [sent-id unsent-id] ids)+ "notification with a last_send appears before the never-sent one under the default sort"))))))++;; ---------------------------------------------------------------------------------------------+;; POST /bulk+;; ---------------------------------------------------------------------------------------------++(deftest bulk-archive-test+ (testing "POST /bulk with action=archive flips :active to false for each id"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification n1 {:payload_type :notification/card+ :payload_id nc1+ :active true+ :creator_id (mt/user->id :crowberto)}+ :model/Notification n2 {:payload_type :notification/card+ :payload_id nc2+ :active true+ :creator_id (mt/user->id :crowberto)}]+ (let [resp (mt/user-http-request :crowberto :post 200 "ee/notifications/bulk"+ {:notification_ids [(:id n1) (:id n2)]+ :action "archive"})]+ (is (= 2 (:updated resp)))+ (is (false? (t2/select-one-fn :active :model/Notification (:id n1))))+ (is (false? (t2/select-one-fn :active :model/Notification (:id n2))))+ (testing "publishes :event/notification-update per notification so the admin action is audited"+ (doseq [n [n1 n2]]+ (is (= {:topic :notification-update+ :user_id (mt/user->id :crowberto)+ :model "Notification"+ :model_id (:id n)+ :details {:previous {:active true}+ :new {:active false}}}+ (mt/latest-audit-log-entry :notification-update (:id n)))))))))))++(deftest bulk-change-owner-test+ (testing "POST /bulk with action=change-creator sets :creator_id to creator_id for each id"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {new-owner :id} {}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/Notification n1 {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :rasta)}]+ (mt/user-http-request :crowberto :post 200 "ee/notifications/bulk"+ {:notification_ids [(:id n1)]+ :action "change-creator"+ :creator_id new-owner})+ (is (= new-owner (t2/select-one-fn :creator_id :model/Notification (:id n1))))))))++(deftest bulk-change-owner-requires-owner-id-test+ (testing "POST /bulk with action=change-creator and no creator_id returns 400"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/Notification n1 {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)}]+ (mt/user-http-request :crowberto :post 400 "ee/notifications/bulk"+ {:notification_ids [(:id n1)]+ :action "change-creator"})))))++;; ---------------------------------------------------------------------------------------------+;; Auth + feature-flag gating for POST /bulk (mirrors the GET triad above)+;; ---------------------------------------------------------------------------------------------++(deftest bulk-requires-premium-feature-test+ (testing "POST /api/ee/notifications/bulk returns 402 without :audit-app premium feature"+ (mt/with-premium-features #{}+ (mt/assert-has-premium-feature-error+ "Audit app"+ (mt/user-http-request :crowberto :post 402 "ee/notifications/bulk"+ {:notification_ids [1]+ :action "archive"})))))++(deftest bulk-requires-superuser-test+ (testing "POST /api/ee/notifications/bulk returns 403 for non-superuser"+ (mt/with-premium-features #{:audit-app}+ (mt/user-http-request :rasta :post 403 "ee/notifications/bulk"+ {:notification_ids [1]+ :action "archive"}))))++(deftest bulk-happy-path-test+ (testing "POST /api/ee/notifications/bulk returns 200 + :updated for superuser with premium"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification n {:payload_type :notification/card+ :payload_id nc+ :active true+ :creator_id (mt/user->id :crowberto)}]+ (let [resp (mt/user-http-request :crowberto :post 200 "ee/notifications/bulk"+ {:notification_ids [(:id n)]+ :action "archive"})]+ (is (= 1 (:updated resp))))))))++;; ---------------------------------------------------------------------------------------------+;; GET /:id detail endpoint+;; ---------------------------------------------------------------------------------------------++(deftest detail-returns-notification-with-run-summaries-test+ (testing "GET /:id returns the hydrated notification with :last_check / :last_send slots and creator_id"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}]+ (is (=? {:id nid+ :creator_id (mt/user->id :crowberto)+ :last_check any?+ :last_send any?}+ (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))))))))++(deftest detail-404-for-missing-id-test+ (testing "GET /:id returns 404 for a non-existent notification id"+ (mt/with-premium-features #{:audit-app}+ (let [max-id (or (t2/select-one-fn :id :model/Notification {:order-by [[:id :desc]]}) 0)]+ (mt/user-http-request :crowberto :get 404+ (str "ee/notifications/" (+ max-id 100000)))))))++(deftest detail-404-for-non-card-notification-test+ (testing "GET /:id returns 404 when the notification exists but isn't a :notification/card"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Notification {nid :id} {:payload_type :notification/system-event+ :creator_id (mt/user->id :crowberto)}]+ (mt/user-http-request :crowberto :get 404 (str "ee/notifications/" nid))))))++(deftest detail-requires-premium-feature-test+ (testing "GET /:id returns 402 without :audit-app premium feature"+ (mt/with-premium-features #{}+ (mt/assert-has-premium-feature-error+ "Audit app"+ (mt/user-http-request :crowberto :get 402 "ee/notifications/1")))))++(deftest detail-requires-superuser-test+ (testing "GET /:id returns 403 for a non-superuser"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}]+ (mt/user-http-request :rasta :get 403 (str "ee/notifications/" nid))))))++;; ---------------------------------------------------------------------------------------------+;; B. Ownerless filter+;; ---------------------------------------------------------------------------------------------++(deftest filter-by-ownerless-true-test+ (testing "?creatorless=true includes notifications with a deactivated creator and excludes active owners"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {active-user :id} {:is_active true}+ :model/User {deact-user :id} {:is_active false}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification active-owner-n {:payload_type :notification/card+ :payload_id nc1+ :creator_id active-user}+ :model/Notification deact-owner-n {:payload_type :notification/card+ :payload_id nc2+ :creator_id deact-user}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :creatorless true)+ ids (set (map :id data))]+ (is (contains? ids (:id deact-owner-n))+ "deactivated creator = ownerless")+ (is (not (contains? ids (:id active-owner-n)))+ "active owner is excluded"))))))++(deftest filter-by-ownerless-false-test+ (testing "?creatorless=false includes only notifications with an active owner"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/User {active-user :id} {:is_active true}+ :model/User {deact-user :id} {:is_active false}+ :model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification active-owner-n {:payload_type :notification/card+ :payload_id nc1+ :creator_id active-user}+ :model/Notification deact-owner-n {:payload_type :notification/card+ :payload_id nc2+ :creator_id deact-user}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :creatorless false)+ ids (set (map :id data))]+ (is (contains? ids (:id active-owner-n))+ "active owner is included")+ (is (not (contains? ids (:id deact-owner-n)))+ "deactivated owner is excluded"))))))++;; ---------------------------------------------------------------------------------------------+;; C. Multi-value channel filter+;; ---------------------------------------------------------------------------------------------++(deftest filter-by-channel-multi-value-test+ (testing "?channel= accepts multiple values (OR semantics across channel types)"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/NotificationCard {nc3 :id} {:card_id card-id}+ :model/Notification email-notif {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)}+ :model/Notification slack-notif {:payload_type :notification/card+ :payload_id nc2+ :creator_id (mt/user->id :crowberto)}+ :model/Notification other-notif {:payload_type :notification/card+ :payload_id nc3+ :creator_id (mt/user->id :crowberto)}+ :model/NotificationHandler _email-handler {:notification_id (:id email-notif)+ :channel_type :channel/email}+ :model/NotificationHandler _slack-handler {:notification_id (:id slack-notif)+ :channel_type :channel/slack}]+ (testing "single channel still works"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :channel "channel/email")+ ids (set (map :id data))]+ (is (contains? ids (:id email-notif)))+ (is (not (contains? ids (:id slack-notif))))+ (is (not (contains? ids (:id other-notif))))))+ (testing "multiple channels (vector) returns union"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :channel ["channel/email" "channel/slack"])+ ids (set (map :id data))]+ (is (contains? ids (:id email-notif)))+ (is (contains? ids (:id slack-notif)))+ (is (not (contains? ids (:id other-notif))))))))))++;; ---------------------------------------------------------------------------------------------+;; D. New sort columns + default sort+;; ---------------------------------------------------------------------------------------------++(deftest sort-by-last-check-test+ (testing "?sort_column=last_check orders rows by the latest task_run started_at"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-old :id} {:archived false}+ :model/Card {card-new :id} {:archived false}+ :model/Card {card-never :id} {:archived false}+ :model/NotificationCard {nc-old :id} {:card_id card-old}+ :model/NotificationCard {nc-new :id} {:card_id card-new}+ :model/NotificationCard {nc-never :id} {:card_id card-never}+ :model/Notification {old-id :id} {:payload_type :notification/card+ :payload_id nc-old+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {new-id :id} {:payload_type :notification/card+ :payload_id nc-new+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {never-id :id} {:payload_type :notification/card+ :payload_id nc-never+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun _old-run {:run_type :alert+ :entity_type :card+ :entity_id card-old+ :status :failed+ :started_at (t/minus (t/instant) (t/days 5))+ :ended_at (t/minus (t/instant) (t/days 5))}+ :model/TaskRun _new-run {:run_type :alert+ :entity_type :card+ :entity_id card-new+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :sort_column "last_check"+ :sort_direction "desc")+ ids (->> data (map :id) (filter #{old-id new-id never-id}) vec)]+ (is (= [new-id old-id never-id] ids)+ "newest-checked first, oldest-checked next, never-checked last (nulls trailing)"))))))++(deftest sort-by-id-test+ (testing "?sort_column=id orders rows by notification.id"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc1 :id} {:card_id card-id}+ :model/NotificationCard {nc2 :id} {:card_id card-id}+ :model/Notification {n1 :id} {:payload_type :notification/card+ :payload_id nc1+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {n2 :id} {:payload_type :notification/card+ :payload_id nc2+ :creator_id (mt/user->id :crowberto)}]+ (testing "asc puts smaller id first"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :sort_column "id"+ :sort_direction "asc")+ seen (->> data (map :id) (filter #{n1 n2}) vec)]+ (is (= [(min n1 n2) (max n1 n2)] seen))))+ (testing "desc puts larger id first"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications"+ :sort_column "id"+ :sort_direction "desc")+ seen (->> data (map :id) (filter #{n1 n2}) vec)]+ (is (= [(max n1 n2) (min n1 n2)] seen))))))))++;; ---------------------------------------------------------------------------------------------+;; E. check_history / send_history in the detail endpoint+;; ---------------------------------------------------------------------------------------------++(deftest detail-includes-check-history-test+ (testing "GET /:id includes :check_history — up to 10 most-recent terminal runs for THIS notification, newest first"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {r1 :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))}+ :model/TaskRun {r2 :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))}+ ;; notification-send rows with notification_id — required for per-notification filter+ :model/TaskHistory _th1 {:task "notification-send"+ :run_id r1+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))+ :task_details {:notification_id nid}}+ :model/TaskHistory _th2 {:task "notification-send"+ :run_id r2+ :status :failed+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))+ :task_details {:notification_id nid+ :message "Connection refused"}}]+ (let [resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))+ check-history (:check_history resp)]+ (is (sequential? check-history))+ (is (= 2 (count check-history))+ "two terminal runs for this notification, newest first")+ (is (=? {:status "failing" :error "Connection refused"} (first check-history))+ "most-recent (the failed one) is first")+ (is (=? {:status "successful" :error nil} (second check-history))+ "older successful run is second"))))))++(deftest detail-includes-send-history-test+ (testing "GET /:id includes :send_history — per-tick rollup, newest tick first, with :channels breakdown"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-ok :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))}+ :model/TaskRun {run-fail :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))}+ :model/TaskHistory _ok-th {:task "channel-send"+ :run_id run-ok+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))+ :task_details {:channel_type "channel/email"+ :notification_id nid}}+ :model/TaskHistory _fail-th {:task "channel-send"+ :run_id run-fail+ :status :failed+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))+ :task_details {:channel_type "channel/slack"+ :message "Slack token invalid"+ :notification_id nid}}]+ (let [resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))+ send-history (:send_history resp)]+ (is (sequential? send-history))+ (is (= 2 (count send-history))+ "two ticks (one channel-send each)")+ (testing "most-recent tick (failed slack) is first"+ (is (=? {:status "failing"+ :error "Slack token invalid"+ :channels [{:channel_type "channel/slack"+ :status "failing"+ :error "Slack token invalid"}]}+ (first send-history))))+ (testing "older successful email tick is second"+ (is (=? {:status "successful"+ :error nil+ :channels [{:channel_type "channel/email"+ :status "successful"+ :error nil}]}+ (second send-history)))))))))++(deftest detail-surfaces-history-when-task-details-failure-wrapped-test+ (testing "GET /:id surfaces last_check/last_send/error for ticks whose task_details is wrapped by with-task-history's failure handler"+ ;; Regression: `metabase.task_history/do-with-task-history` rewrites task_details on exception as+ ;; `{:status :failed :message ... :original-info <caller-task_details>}`. The per-notification+ ;; filter has to look in both the top level (success rows) and `:original-info` (failure rows),+ ;; or failing ticks silently disappear from the detail histories and `last_check`/`last_send`+ ;; come back nil — even though the list endpoint shows the notification as failing.+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}+ ;; notification-send: failure-wrapped (notification_id only under :original-info)+ :model/TaskHistory _ns-th {:task "notification-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:status :failed+ :message "Notification handler exploded"+ :original-info {:notification_id nid}}}+ ;; channel-send: failure-wrapped (channel_type + notification_id only under :original-info)+ :model/TaskHistory _cs-th {:task "channel-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:status :failed+ :message "Slack token invalid"+ :original-info {:channel_type "channel/slack"+ :notification_id nid}}}]+ (let [resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))]+ (testing "check_history surfaces the failed notification-send tick + its error"+ (is (=? [{:status "failing" :error "Notification handler exploded"}]+ (:check_history resp))))+ (testing "send_history surfaces the failed channel-send tick + its error and channel type"+ (is (=? [{:status "failing"+ :error "Slack token invalid"+ :channels [{:channel_type "channel/slack"+ :status "failing"+ :error "Slack token invalid"}]}]+ (:send_history resp))))+ (testing "last_check and last_send are derived from those histories"+ (is (=? {:status "failing" :error "Notification handler exploded"}+ (:last_check resp)))+ (is (=? {:status "failing" :error "Slack token invalid"}+ (:last_send resp)))))))))++(deftest list-last-check-surfaces-channel-error-when-outer-send-succeeded-test+ (testing "list endpoint last_check.error surfaces the channel-send error when the outer notification-send succeeded but a channel failed"+ ;; Regression: `complete-task-run!` derives task_run.status as :failed when ANY child task is+ ;; not :success — so a tick where notification-send succeeded but a channel-send failed has+ ;; task_run.status = :failed. `error-by-run-id` must surface the channel-send's message in+ ;; that case (no notification-send failure row exists). If it filtered to notification-send+ ;; only, last_check would show status:failing error:nil for the Failing tab.+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}+ ;; Outer notification-send: succeeded+ :model/TaskHistory _ns-th {:task "notification-send"+ :run_id run-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:notification_id nid}}+ ;; Channel-send: failed (failure-wrapped task_details)+ :model/TaskHistory _cs-th {:task "channel-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:status :failed+ :message "Slack token invalid"+ :original-info {:channel_type "channel/slack"+ :notification_id nid}}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_check {:status "failing" :error "Slack token invalid"}}+ (find-row-by-id data nid))))))))++(deftest list-last-check-prefers-outer-notification-send-error-test+ (testing "when both notification-send and channel-send failed in one run, last_check.error prefers the outer notification-send message"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _ns-th {:task "notification-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:message "Payload generation failed"}}+ :model/TaskHistory _cs-th {:task "channel-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:message "Slack token invalid"}}]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 "ee/notifications")]+ (is (=? {:last_check {:status "failing" :error "Payload generation failed"}}+ (find-row-by-id data nid))+ "outer notification-send error wins over inner channel-send error"))))))++(deftest detail-send-history-multi-channel-tick-test+ (testing "GET /:id: one tick with email+slack both succeeding → ONE send entry, status successful"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _email-th {:task "channel-send"+ :run_id run-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"+ :notification_id nid}}+ :model/TaskHistory _slack-th {:task "channel-send"+ :run_id run-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/slack"+ :notification_id nid}}]+ (let [resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))+ send-history (:send_history resp)]+ (is (= 1 (count send-history))+ "two channels in the same tick collapse to ONE send entry")+ (is (=? {:status "successful"+ :error nil+ :channels [{:channel_type "channel/email" :status "successful"}+ {:channel_type "channel/slack" :status "successful"}]}+ (first send-history))))))))++(deftest detail-send-history-mixed-channels-test+ (testing "GET /:id: one tick with email success + slack failure → failing, :channels shows both"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/TaskRun {run-id :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _email-th {:task "channel-send"+ :run_id run-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"+ :notification_id nid}}+ :model/TaskHistory _slack-th {:task "channel-send"+ :run_id run-id+ :status :failed+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/slack"+ :message "Rate limited"+ :notification_id nid}}]+ (let [resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))+ entry (first (:send_history resp))]+ (is (= 1 (count (:send_history resp)))+ "two channels in the same tick → ONE send entry")+ (is (=? {:status "failing" :error "Rate limited"} entry))+ (is (= 2 (count (:channels entry)))+ "channels breakdown has one entry per channel-send row")+ (let [by-type (into {} (map (juxt :channel_type identity) (:channels entry)))]+ (is (=? {:status "successful"} (get by-type "channel/email")))+ (is (=? {:status "failing" :error "Rate limited"} (get by-type "channel/slack")))))))))++(deftest detail-check-history-empty-when-no-runs-test+ (testing "GET /:id returns :check_history as empty vector when no terminal runs exist"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}]+ (let [resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))]+ (is (= [] (:check_history resp)))+ (is (= [] (:send_history resp))))))))++(deftest detail-check-history-respects-limit-test+ (testing "GET /:id returns at most 10 runs in :check_history"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}]+ ;; create 12 runs, each with a matching notification-send row so the per-notification filter passes+ (doseq [i (range 12)]+ (let [run-id (t2/insert-returning-pk! :model/TaskRun+ {:run_type "alert"+ :entity_type "card"+ :entity_id card-id+ :status "success"+ :started_at (t/minus (t/instant) (t/hours (inc i)))+ :ended_at (t/minus (t/instant) (t/hours (inc i)))+ :process_uuid "test"})]+ (t2/insert! :model/TaskHistory+ {:task "notification-send"+ :run_id run-id+ :status "success"+ :started_at (t/minus (t/instant) (t/hours (inc i)))+ :ended_at (t/minus (t/instant) (t/hours (inc i)))+ :task_details (str "{\"notification_id\":" nid "}")})))+ (let [resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))]+ (is (<= (count (:check_history resp)) 10)))))))++;; ---------------------------------------------------------------------------------------------+;; F. creator_id (owner) cannot be reassigned via the public PUT endpoint — only via POST /bulk+;; ---------------------------------------------------------------------------------------------++(deftest put-creator-id-superuser-only-test+ (testing "PUT /api/notification/:id: superusers can reassign owner; non-superusers get a 400"+ (mt/with-temp [:model/Card {card-id :id} {}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :rasta)}]+ (testing "non-superuser (the current owner) is forbidden from reassigning (403 from mi/can-update?)"+ (let [notification (mt/user-http-request :rasta :get 200 (format "notification/%d" nid))]+ (mt/user-http-request :rasta :put 403 (format "notification/%d" nid)+ (assoc notification :creator_id (mt/user->id :lucky)))+ (is (= (mt/user->id :rasta)+ (t2/select-one-fn :creator_id :model/Notification nid))+ "owner unchanged after non-superuser attempt")))+ (testing "superuser can reassign owner"+ (let [notification (mt/user-http-request :crowberto :get 200 (format "notification/%d" nid))]+ (mt/user-http-request :crowberto :put 200 (format "notification/%d" nid)+ (assoc notification :creator_id (mt/user->id :lucky)))+ (is (= (mt/user->id :lucky)+ (t2/select-one-fn :creator_id :model/Notification nid))+ "owner reassigned after superuser PUT"))))))++;; ---------------------------------------------------------------------------------------------+;; Per-notification isolation — two notifications on the same card+;; ---------------------------------------------------------------------------------------------++(deftest detail-per-notification-isolation-test+ (testing "Two notifications on the same card each see only their own ticks in check_history and send_history"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ ;; Two distinct notifications sharing the same card+ :model/Notification {n1 :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {n2 :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ ;; tick-A: fires for n1 only+ :model/TaskRun {run-a :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))}+ :model/TaskHistory _ns-a {:task "notification-send"+ :run_id run-a+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))+ :task_details {:notification_id n1}}+ :model/TaskHistory _cs-a {:task "channel-send"+ :run_id run-a+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))+ :task_details {:channel_type "channel/email"+ :notification_id n1}}+ ;; tick-B: fires for n2 only+ :model/TaskRun {run-b :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))}+ :model/TaskHistory _ns-b {:task "notification-send"+ :run_id run-b+ :status :success+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))+ :task_details {:notification_id n2}}+ :model/TaskHistory _cs-b {:task "channel-send"+ :run_id run-b+ :status :success+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))+ :task_details {:channel_type "channel/slack"+ :notification_id n2}}]+ ;; suppress unused-var warnings+ (let [_ [run-a run-b]]+ (testing "detail for n1 sees only tick-A in check_history and send_history"+ (let [resp-n1 (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" n1))]+ (is (= 1 (count (:check_history resp-n1)))+ "n1 check_history has exactly 1 tick (tick-A)")+ (is (= 1 (count (:send_history resp-n1)))+ "n1 send_history has exactly 1 tick (tick-A)")+ (is (=? {:channels [{:channel_type "channel/email"}]}+ (first (:send_history resp-n1))))))+ (testing "detail for n2 sees only tick-B in check_history and send_history"+ (let [resp-n2 (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" n2))]+ (is (= 1 (count (:check_history resp-n2)))+ "n2 check_history has exactly 1 tick (tick-B)")+ (is (= 1 (count (:send_history resp-n2)))+ "n2 send_history has exactly 1 tick (tick-B)")+ (is (=? {:channels [{:channel_type "channel/slack"}]}+ (first (:send_history resp-n2)))))))))))++(deftest detail-goal-not-met-tick-absent-from-send-history-test+ (testing "A tick where the goal was not met (no channel-send rows) appears in check_history but NOT send_history"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {nid :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ ;; tick-1: goal not met — notification-send row exists but no channel-send+ :model/TaskRun {run-skip :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))}+ :model/TaskHistory _ns-skip {:task "notification-send"+ :run_id run-skip+ :status :success+ :started_at (t/minus (t/instant) (t/hours 2))+ :ended_at (t/minus (t/instant) (t/hours 2))+ :task_details {:notification_id nid+ :skip_reason "goal-not-met"}}+ ;; tick-2: goal met — has channel-send+ :model/TaskRun {run-sent :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))}+ :model/TaskHistory _ns-sent {:task "notification-send"+ :run_id run-sent+ :status :success+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))+ :task_details {:notification_id nid}}+ :model/TaskHistory _cs-sent {:task "channel-send"+ :run_id run-sent+ :status :success+ :started_at (t/minus (t/instant) (t/hours 1))+ :ended_at (t/minus (t/instant) (t/hours 1))+ :task_details {:channel_type "channel/email"+ :notification_id nid}}]+ ;; suppress unused-var warnings+ (let [_ [run-skip run-sent]+ resp (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" nid))]+ (is (= 2 (count (:check_history resp)))+ "both ticks appear in check_history")+ (is (= 1 (count (:send_history resp)))+ "only the goal-met tick appears in send_history — goal-not-met tick is absent")+ (is (=? {:channels [{:channel_type "channel/email" :status "successful"}]}+ (first (:send_history resp)))))))))++(deftest detail-last-check-and-last-send-derived-from-histories-test+ (testing "GET /:id: last_check and last_send are derived per-notification from histories, not from card-level join"+ (mt/with-premium-features #{:audit-app}+ (mt/with-temp [:model/Card {card-id :id} {:archived false}+ :model/NotificationCard {nc :id} {:card_id card-id}+ :model/Notification {n1 :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ :model/Notification {n2 :id} {:payload_type :notification/card+ :payload_id nc+ :creator_id (mt/user->id :crowberto)}+ ;; Only n2 has ever fired+ :model/TaskRun {run2 :id} {:run_type :alert+ :entity_type :card+ :entity_id card-id+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)}+ :model/TaskHistory _ns2 {:task "notification-send"+ :run_id run2+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:notification_id n2}}+ :model/TaskHistory _cs2 {:task "channel-send"+ :run_id run2+ :status :success+ :started_at (t/instant)+ :ended_at (t/instant)+ :task_details {:channel_type "channel/email"+ :notification_id n2}}]+ (let [_ run2+ resp-n1 (mt/user-http-request :crowberto :get 200 (str "ee/notifications/" n1))]+ (testing "n1 has nil last_check and nil last_send because it has never fired"+ (is (nil? (:last_check resp-n1))+ "n1 last_check is nil — the card-level task_run is for n2 only")+ (is (nil? (:last_send resp-n1))+ "n1 last_send is nil — the channel-send belongs to n2")))))))diff --git a/frontend/src/metabase-types/api/icon.ts b/frontend/src/metabase-types/api/icon.tsindex 3340fb54ba7..0bda3c41f9e 100644--- a/frontend/src/metabase-types/api/icon.ts+++ b/frontend/src/metabase-types/api/icon.ts@@ -281,6 +281,7 @@ export type IconName =| "verified_round"| "view_archive"| "warning"+ | "warning_round"| "warning_round_filled"| "warning_triangle_filled"| "waterfall"diff --git a/frontend/src/metabase-types/api/mocks/notification.ts b/frontend/src/metabase-types/api/mocks/notification.tsindex 9326a52b7bf..6e66d234d91 100644--- a/frontend/src/metabase-types/api/mocks/notification.ts+++ b/frontend/src/metabase-types/api/mocks/notification.ts@@ -1,4 +1,5 @@import type {+ AdminNotification,Notification,NotificationCronSubscription,NotificationHandlerEmail,@@ -104,3 +105,14 @@ export const createMockNotificationCronSubscription = (ui_display_type: "cron/builder",...opts,});++export const createMockAdminNotification = (+ opts?: Partial<AdminNotification>,+): AdminNotification => ({+ ...createMockNotification(),+ creator_id: 1,+ creator: createMockUserInfo({ is_active: true }),+ last_check: null,+ last_send: null,+ ...opts,+});diff --git a/frontend/src/metabase-types/api/mocks/user.ts b/frontend/src/metabase-types/api/mocks/user.tsindex f84c6062c03..d34793d1286 100644--- a/frontend/src/metabase-types/api/mocks/user.ts+++ b/frontend/src/metabase-types/api/mocks/user.ts@@ -65,6 +65,7 @@ export const createMockUserInfo = (opts?: Partial<UserInfo>): UserInfo => ({email: "[email protected]",is_qbnewb: false,is_superuser: false,+ is_active: true,date_joined: new Date().toISOString(),last_login: new Date().toISOString(),...opts,diff --git a/frontend/src/metabase-types/api/notification.ts b/frontend/src/metabase-types/api/notification.tsindex 679b71088db..04c864e8916 100644--- a/frontend/src/metabase-types/api/notification.ts+++ b/frontend/src/metabase-types/api/notification.ts@@ -1,3 +1,5 @@+import type { SortDirection } from "metabase-types/api/sorting";+import type { Card, CardId } from "./card";import type { Channel, SlackChannelId } from "./notification-channels";import type { PaginationRequest } from "./pagination";@@ -11,7 +13,6 @@ export type NotificationCardSendCondition =| "goal_below"| "has_result";-//#region Payload union typetype NotificationCardPayload = {payload_type: "notification/card";payload: {@@ -29,9 +30,6 @@ type NotificationCardPayload = {type NotificationPayload = NotificationCardPayload; // will be populated with more variants later on-//#endregion--//#region Handler union typeexport type NotificationRecipientUser = {type: "notification-recipient/user";user_id: number;@@ -111,9 +109,6 @@ export type NotificationHandler =| NotificationHandlerSlack| NotificationHandlerHttp;-//#endregion--//#region Subscription typeexport type NotificationCronSubscription = {type: "notification-subscription/cron";event_name: null;@@ -127,8 +122,6 @@ export type NotificationCronSubscription = {updated_at?: string;};-//#endregion-export interface ListNotificationsRequest extends PaginationRequest {include_inactive?: boolean;creator_id?: UserId;@@ -150,6 +143,7 @@ export type UpdateAlertNotificationRequest = NotificationCardPayload & {active: boolean;handlers: NotificationHandler[];subscriptions: NotificationCronSubscription[];+ creator_id?: UserId;};export type UpdateNotificationRequest = UpdateAlertNotificationRequest; // will be populated with more variants later on@@ -167,3 +161,77 @@ export type Notification = NotificationPayload & {updated_at?: string;created_at?: string;};++export type NotificationRunStatus = "failing" | "successful";++export type NotificationRunSummary = {+ at: string;+ error: string | null;+ status: NotificationRunStatus;+};++export type NotificationChannelSendEntry = {+ channel_type: NotificationChannelType;+ status: NotificationRunStatus;+ error: string | null;+};++export type NotificationTickSendEntry = {+ at: string;+ status: NotificationRunStatus;+ error: string | null;+ channels: NotificationChannelSendEntry[];+};++export type AdminNotificationSortColumn =+ | "id"+ | "last_send"+ | "last_check"+ | "card_name"+ | "creator_name"+ | "updated_at";++// Admin notifications carry a nullable creator: the row may have no creator, or+// a deactivated one (the "Ownerless" tab). The UI labels the creator as "Owner".+export type AdminNotification = Omit<Notification, "creator_id" | "creator"> & {+ creator_id: UserId | null;+ creator: UserInfo | null;+ last_check: NotificationRunSummary | null;+ last_send: NotificationRunSummary | null;+};++export type AdminNotificationDetail = AdminNotification & {+ check_history: NotificationRunSummary[];+ send_history: NotificationTickSendEntry[];+};++export type AdminNotificationListParams = {+ limit?: number;+ offset?: number;+ active?: boolean;+ creator_id?: UserId;+ creator_active?: boolean;+ creatorless?: boolean;+ card_id?: CardId;+ recipient_email?: string;+ channel?: NotificationChannelType | NotificationChannelType[];+ last_send_status?: NotificationRunStatus;+ query?: string;+ sort_column?: AdminNotificationSortColumn;+ sort_direction?: SortDirection;+};++export type AdminNotificationListResponse = {+ data: AdminNotification[];+ total: number;+ limit: number | null;+ offset: number | null;+};++export type BulkNotificationAction = "archive" | "change-creator";++export type BulkNotificationPayload = {+ notification_ids: NotificationId[];+ action: BulkNotificationAction;+ creator_id?: UserId;+};diff --git a/frontend/src/metabase-types/api/sorting.ts b/frontend/src/metabase-types/api/sorting.tsindex 07906b1de0c..5c98b6f0f78 100644--- a/frontend/src/metabase-types/api/sorting.ts+++ b/frontend/src/metabase-types/api/sorting.ts@@ -5,3 +5,8 @@ export type SortingOptions<SortColumn extends string> = {sort_column: SortColumn;sort_direction: SortDirection;};++export const guardSortDirection = (value: string): value is SortDirection =>+ (SORT_DIRECTIONS satisfies readonly SortDirection[]).includes(+ value as SortDirection,+ );diff --git a/frontend/src/metabase-types/api/task.ts b/frontend/src/metabase-types/api/task.tsindex e134cab35f4..6cb75490a39 100644--- a/frontend/src/metabase-types/api/task.ts+++ b/frontend/src/metabase-types/api/task.ts@@ -101,12 +101,16 @@ export interface RunEntity {entity_name?: string;}+export type TaskRunStartedAtParam =+ | TaskRunDateFilterOption+ | `${TaskRunDateFilterOption}~`;+export type ListTaskRunsRequest = {"run-type"?: TaskRunType;"entity-type"?: TaskRunEntityType;"entity-id"?: number;status?: TaskRunStatus;- "started-at"?: TaskRunDateFilterOption;+ "started-at"?: TaskRunStartedAtParam;} & PaginationRequest;export type ListTaskRunsResponse = {@@ -115,5 +119,5 @@ export type ListTaskRunsResponse = {export type ListTaskRunEntitiesRequest = {"run-type": TaskRunType;- "started-at": TaskRunDateFilterOption;+ "started-at": TaskRunStartedAtParam;};diff --git a/frontend/src/metabase-types/api/user.ts b/frontend/src/metabase-types/api/user.tsindex dfa072a8d92..c5be1d4dad5 100644--- a/frontend/src/metabase-types/api/user.ts+++ b/frontend/src/metabase-types/api/user.ts@@ -108,6 +108,7 @@ export type UserInfo = Pick<| "last_login"| "is_superuser"| "is_qbnewb"+ | "is_active">;export type UserListQuery = {diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsxindex d82f9cb2185..216b3df407f 100644--- a/frontend/src/metabase/admin/routes.tsx+++ b/frontend/src/metabase/admin/routes.tsx@@ -75,7 +75,7 @@ import { PerformanceTabId } from "./performance/types";import { getSettingsRoutes } from "./settingsRoutes";import { ToolsApp } from "./tools/components/ToolsApp";import { ToolsUpsell } from "./tools/components/ToolsUpsell";-import { getTasksRoutes } from "./tools/routes";+import { getNotificationsRoutes, getTasksRoutes } from "./tools/routes";import { UpsellTenants } from "./upsells/UpsellTenants";import {RedirectToAllowedSettings,@@ -88,10 +88,9 @@ export const getRoutes = (CanAccessSettings: RouteComponent,IsAdmin: RouteComponent,) => {- const hasSimpleEmbedding = getTokenFeature(- store.getState(),- "embedding_simple",- );+ const state = store.getState();+ const hasSimpleEmbedding = getTokenFeature(state, "embedding_simple");+ const hasAuditApp = getTokenFeature(state, "audit_app");return (<Route path="/admin" component={CanAccessSettings}>@@ -328,6 +327,9 @@ export const getRoutes = ()}</Route><Route path="tasks">{getTasksRoutes()}</Route>+ {hasAuditApp && (+ <Route path="notifications">{getNotificationsRoutes()}</Route>+ )}<Route path="jobs" component={JobInfoApp}><ModalRoutepath=":jobKey"diff --git a/frontend/src/metabase/admin/tools/components/TaskRunEntityPicker/TaskRunEntityPicker.tsx b/frontend/src/metabase/admin/tools/components/TaskRunEntityPicker/TaskRunEntityPicker.tsxindex 5f139d69d11..bce4399dfc7 100644--- a/frontend/src/metabase/admin/tools/components/TaskRunEntityPicker/TaskRunEntityPicker.tsx+++ b/frontend/src/metabase/admin/tools/components/TaskRunEntityPicker/TaskRunEntityPicker.tsx@@ -5,6 +5,8 @@ import { skipToken, useListTaskRunEntitiesQuery } from "metabase/api";import { Loader, Select, type SelectProps, Tooltip } from "metabase/ui";import type { TaskRunDateFilterOption, TaskRunType } from "metabase-types/api";+import { toBackendStartedAt } from "../../utils";+import type { EntityValue } from "./types";import {convertEntitiesToSelectOptions,@@ -18,6 +20,7 @@ type TaskRunEntityPickerProps = Omit<> & {runType: TaskRunType | null;startedAt: TaskRunDateFilterOption | null;+ includeToday: boolean;value: EntityValue | null;onChange: (value: EntityValue | null) => void;};@@ -25,16 +28,18 @@ type TaskRunEntityPickerProps = Omit<export const TaskRunEntityPicker = ({runType,startedAt,+ includeToday,value,onChange,...props}: TaskRunEntityPickerProps) => {- const hasAllRequiredParams = runType && startedAt;+ const effectiveStartedAt = toBackendStartedAt(startedAt, includeToday);+ const hasAllRequiredParams = runType && effectiveStartedAt;const { data: entities, isLoading } = useListTaskRunEntitiesQuery(hasAllRequiredParams? {"run-type": runType,- "started-at": startedAt,+ "started-at": effectiveStartedAt,}: skipToken,);diff --git a/frontend/src/metabase/admin/tools/components/TaskRunStartedAtPicker/TaskRunDatePicker.tsx b/frontend/src/metabase/admin/tools/components/TaskRunStartedAtPicker/TaskRunDatePicker.tsxindex ab57e9d963b..13a8c1313e2 100644--- a/frontend/src/metabase/admin/tools/components/TaskRunStartedAtPicker/TaskRunDatePicker.tsx+++ b/frontend/src/metabase/admin/tools/components/TaskRunStartedAtPicker/TaskRunDatePicker.tsx@@ -1,27 +1,61 @@+import type { MouseEvent } from "react";+import { useState } from "react";import { t } from "ttag";-import { Select, type SelectProps } from "metabase/ui";-import type { SelectData } from "metabase/ui/components/inputs/Select/Select";+import {+ Combobox,+ Group,+ Input,+ Popover,+ Select,+ Stack,+ Switch,+} from "metabase/ui";import type { TaskRunDateFilterOption } from "metabase-types/api";-type TaskRunDatePickerProps = Omit<- SelectProps,- "data" | "value" | "onChange"-> & {+import { guardTaskRunStartedAtRange } from "../../utils";++type TaskRunDatePickerProps = {value: TaskRunDateFilterOption | null;- onChange: (value: TaskRunDateFilterOption | null) => void;+ includeToday: boolean;+ placeholder?: string;+ onChange: (+ value: TaskRunDateFilterOption | null,+ includeToday: boolean,+ ) => void;+};++type DateOption = {+ label: string;+ value: TaskRunDateFilterOption;};+const PICKER_WIDTH = 260;+const RIGHT_SECTION_FULL_WIDTH = 52;++/**+ * TODO: this whole component (Select + Switch in a popover with a Select-like trigger) should be generalized.+ */export const TaskRunDatePicker = ({value,+ includeToday,+ placeholder,onChange,- ...props}: TaskRunDatePickerProps) => {+ const isIncludeTodayAllowed = (value: TaskRunDateFilterOption | null) =>+ value !== null && value !== "thisday";++ const emit = (+ next: TaskRunDateFilterOption | null,+ nextIncludeToday: boolean,+ ) => onChange(next, isIncludeTodayAllowed(next) && nextIncludeToday);++ const [opened, setOpened] = useState<boolean>(false);/*** Using a simple version of TimeFilterWidget here in order to align with a design of admin page.* That means no custom date ranges.*/- const data: SelectData<TaskRunDateFilterOption> = [+ const options: DateOption[] = [{ label: t`Today`, value: "thisday" },{ label: t`Yesterday`, value: "past1days" },{ label: t`Previous week`, value: "past1weeks" },@@ -32,23 +66,126 @@ export const TaskRunDatePicker = ({{ label: t`Previous 12 months`, value: "past12months" },];+ const includeTodayLabels: Partial<Record<TaskRunDateFilterOption, string>> = {+ past1days: t`Yesterday, including today`,+ past1weeks: t`Previous week, including today`,+ past7days: t`Previous 7 days, including today`,+ past30days: t`Previous 30 days, including today`,+ past1months: t`Previous month, including today`,+ past3months: t`Previous 3 months, including today`,+ past12months: t`Previous 12 months, including today`,+ };++ const selectedOption = options.find((option) => option.value === value);+ const includeTodayAllowed = isIncludeTodayAllowed(value);++ const displayLabel = (() => {+ if (!selectedOption) {+ return null;+ }+ const includeTodayLabel =+ value !== null ? includeTodayLabels[value] : undefined;+ if (includeToday && includeTodayAllowed && includeTodayLabel) {+ return includeTodayLabel;+ }+ return selectedOption.label;+ })();++ const handleClear = (event: MouseEvent) => {+ event.stopPropagation();+ emit(null, false);+ };++ const handleSelectChange = (next: string | null) => {+ if (next === null) {+ emit(null, false);+ return;+ }+ if (guardTaskRunStartedAtRange(next)) {+ emit(next, includeToday);+ }+ };+return (- <Select- comboboxProps={{- middlewares: {- flip: true,- size: {- padding: 6,- },- },- position: "bottom-start",- width: 300,- }}- clearable- data={data}- value={value}- onChange={onChange}- {...props}- />+ <Popover+ opened={opened}+ onChange={setOpened}+ position="bottom-start"+ withinPortal+ >+ <Popover.Target>+ <Input+ component="button"+ type="button"+ data-testid="task-run-date-picker"+ pointer+ w={PICKER_WIDTH}+ styles={{+ input: {+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ textAlign: "left",+ // Mantine's `rightSectionWidth` only sets a CSS variable that+ // the layered styles in this bundle don't pick up, so the input+ // padding doesn't follow the section. Override it directly so+ // long labels ellipsize instead of sliding under the icons.+ paddingInlineEnd: RIGHT_SECTION_FULL_WIDTH,+ },+ section: {+ width: "auto",+ paddingRight: "10px",+ },+ }}+ onClick={() => setOpened((open) => !open)}+ rightSection={+ <Group gap="xs" wrap="nowrap">+ {value !== null && (+ <Input.ClearButton+ size="sm"+ aria-label={t`Clear`}+ style={{+ pointerEvents: "all",+ color: "var(--mb-color-text-primary)",+ }}+ onClick={handleClear}+ />+ )}+ <Combobox.Chevron />+ </Group>+ }+ rightSectionPointerEvents="none"+ >+ {displayLabel ?? (+ <Input.Placeholder c="text-tertiary">+ {placeholder}+ </Input.Placeholder>+ )}+ </Input>+ </Popover.Target>++ <Popover.Dropdown p="md">+ <Stack gap="md" w={PICKER_WIDTH}>+ <Select+ data={options}+ value={value}+ aria-label={t`Date range`}+ placeholder={t`Started at`}+ comboboxProps={{+ withinPortal: false,+ floatingStrategy: "fixed",+ position: "bottom-start",+ }}+ onChange={handleSelectChange}+ />+ <Switch+ label={t`Include today`}+ checked={includeToday && includeTodayAllowed}+ disabled={!includeTodayAllowed}+ onChange={(event) => emit(value, event.currentTarget.checked)}+ />+ </Stack>+ </Popover.Dropdown>+ </Popover>);};diff --git a/frontend/src/metabase/admin/tools/components/TaskRunStartedAtPicker/TaskRunDatePicker.unit.spec.tsx b/frontend/src/metabase/admin/tools/components/TaskRunStartedAtPicker/TaskRunDatePicker.unit.spec.tsxnew file mode 100644index 00000000000..9cac0108760--- /dev/null+++ b/frontend/src/metabase/admin/tools/components/TaskRunStartedAtPicker/TaskRunDatePicker.unit.spec.tsx@@ -0,0 +1,121 @@+import userEvent from "@testing-library/user-event";+import { useState } from "react";++import { renderWithProviders, screen } from "__support__/ui";+import type { TaskRunDateFilterOption } from "metabase-types/api";++import { TaskRunDatePicker } from "./TaskRunDatePicker";++const PLACEHOLDER = "Filter by started at";++type SetupOpts = {+ value?: TaskRunDateFilterOption | null;+ includeToday?: boolean;+};++const setup = ({ value = null, includeToday = false }: SetupOpts = {}) => {+ const onChange = jest.fn();++ const Wrapper = () => {+ const [innerValue, setInnerValue] =+ useState<TaskRunDateFilterOption | null>(value);+ const [innerIncludeToday, setInnerIncludeToday] = useState(includeToday);++ return (+ <TaskRunDatePicker+ value={innerValue}+ includeToday={innerIncludeToday}+ placeholder={PLACEHOLDER}+ onChange={(nextValue, nextIncludeToday) => {+ onChange(nextValue, nextIncludeToday);+ setInnerValue(nextValue);+ setInnerIncludeToday(nextIncludeToday);+ }}+ />+ );+ };++ renderWithProviders(<Wrapper />);++ return { onChange };+};++const openPicker = async () => {+ await userEvent.click(screen.getByTestId("task-run-date-picker"));+};++const selectRange = async (label: string) => {+ await userEvent.click(screen.getByPlaceholderText("Started at"));+ await userEvent.click(await screen.findByRole("option", { name: label }));+};++describe("TaskRunDatePicker", () => {+ it("renders the placeholder when there is no value", () => {+ setup();+ expect(screen.getByText(PLACEHOLDER)).toBeInTheDocument();+ });++ it("emits the selected range with the current include-today flag", async () => {+ const { onChange } = setup();++ await openPicker();+ await selectRange("Previous week");++ expect(onChange).toHaveBeenCalledWith("past1weeks", false);+ });++ it("disables the include-today switch when no range is selected", async () => {+ setup();+ await openPicker();++ expect(+ screen.getByRole("switch", { name: "Include today" }),+ ).toBeDisabled();+ });++ it("disables the include-today switch and forces it off for Today", async () => {+ const { onChange } = setup({ includeToday: true });++ await openPicker();+ await selectRange("Today");++ expect(onChange).toHaveBeenCalledWith("thisday", false);+ expect(+ screen.getByRole("switch", { name: "Include today" }),+ ).toBeDisabled();+ });++ it("emits the include-today flag when the switch is toggled", async () => {+ const { onChange } = setup({ value: "past1weeks" });++ await openPicker();+ await userEvent.click(+ screen.getByRole("switch", { name: "Include today" }),+ );++ expect(onChange).toHaveBeenCalledWith("past1weeks", true);+ });++ it("shows the including-today suffix in the trigger label", async () => {+ setup({ value: "past1weeks", includeToday: true });++ expect(+ screen.getByText("Previous week, including today"),+ ).toBeInTheDocument();+ });++ it("does not show the suffix for a range that disallows today", () => {+ setup({ value: "thisday", includeToday: true });++ expect(screen.getByText("Today")).toBeInTheDocument();+ expect(screen.queryByText(/including today/)).not.toBeInTheDocument();+ });++ it("clears the value through the clear button", async () => {+ const { onChange } = setup({ value: "past1weeks", includeToday: true });++ await userEvent.click(screen.getByLabelText("Clear"));++ expect(onChange).toHaveBeenCalledWith(null, false);+ });+});diff --git a/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.tsx b/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.tsxindex c1ab0e0698e..8d71fd06290 100644--- a/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.tsx+++ b/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.tsx@@ -6,6 +6,7 @@ import { PaginationControls } from "metabase/common/components/PaginationControlimport { useUrlState } from "metabase/common/hooks/use-url-state";import { Flex } from "metabase/ui";+import { toBackendStartedAt } from "../../utils";import { TaskRunTypePicker } from "../RunTypePicker";import { TaskRunEntityPicker } from "../TaskRunEntityPicker";import { TaskRunDatePicker } from "../TaskRunStartedAtPicker";@@ -24,6 +25,7 @@ const TaskRunsPageBase = ({ location }: WithRouterProps) => {"entity-type": entityType,"entity-id": entityId,"started-at": startedAt,+ "include-today": includeToday,status,},{ patchUrlState },@@ -40,7 +42,7 @@ const TaskRunsPageBase = ({ location }: WithRouterProps) => {"run-type": runType ?? undefined,"entity-type": entityType ?? undefined,"entity-id": entityId ?? undefined,- "started-at": startedAt ?? undefined,+ "started-at": toBackendStartedAt(startedAt, includeToday),status: status ?? undefined,},{@@ -71,12 +73,16 @@ const TaskRunsPageBase = ({ location }: WithRouterProps) => {<TaskRunDatePickervalue={startedAt}+ includeToday={includeToday}placeholder={t`Filter by started at`}- onChange={(startedAt) =>+ onChange={(nextStartedAt, nextIncludeToday) =>patchUrlState({- "started-at": startedAt,- "entity-type": null,- "entity-id": null,+ "started-at": nextStartedAt,+ "include-today": nextIncludeToday,+ ...(nextStartedAt !== startedAt && {+ "entity-type": null,+ "entity-id": null,+ }),page: 0,})}@@ -85,6 +91,7 @@ const TaskRunsPageBase = ({ location }: WithRouterProps) => {<TaskRunEntityPickerrunType={runType}startedAt={startedAt}+ includeToday={includeToday}value={entityValue}onChange={(entity) =>patchUrlState({diff --git a/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.unit.spec.tsx b/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.unit.spec.tsxindex d652f3ee163..8a8d3db1f79 100644--- a/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.unit.spec.tsx+++ b/frontend/src/metabase/admin/tools/components/TaskRunsPage/TaskRunsPage.unit.spec.tsx@@ -6,6 +6,7 @@ import { setupTaskRunsEndpoints } from "__support__/server-mocks";import {renderWithProviders,screen,+ waitFor,waitForLoaderToBeRemoved,} from "__support__/ui";import * as Urls from "metabase/urls";@@ -19,11 +20,13 @@ const PATHNAME = Urls.adminToolsTasksRuns();interface SetupOpts {taskRunsResponse?: ListTaskRunsResponse;error?: boolean;+ initialRoute?: string;}const setup = ({taskRunsResponse = createMockTaskRunsResponse(),error,+ initialRoute = PATHNAME,}: SetupOpts = {}) => {if (error) {fetchMock.get("path:/api/task/runs", { status: 500 });@@ -34,12 +37,27 @@ const setup = ({return renderWithProviders(<Route path={PATHNAME} component={TaskRunsPage} />,{- initialRoute: PATHNAME,+ initialRoute,withRouter: true,},);};+const getLastRunsParams = () => {+ const calls = fetchMock.callHistory.calls("path:/api/task/runs");+ const lastCall = calls[calls.length - 1];+ return new URL(lastCall.url).searchParams;+};++const openDatePicker = async () => {+ await userEvent.click(screen.getByTestId("task-run-date-picker"));+};++const selectRange = async (label: string) => {+ await userEvent.click(screen.getByPlaceholderText("Started at"));+ await userEvent.click(await screen.findByRole("option", { name: label }));+};+describe("TaskRunsPage", () => {it("should display formatted datetime for started_at and ended_at", async () => {setup({@@ -81,6 +99,76 @@ describe("TaskRunsPage", () => {expect(await screen.findByRole("tooltip")).toHaveTextContent(rawTimestamp);});++ describe("started-at filter with include-today", () => {+ it("requests with the ~ suffix when today is included", async () => {+ setup();+ await waitForLoaderToBeRemoved();++ await openDatePicker();+ await selectRange("Previous week");++ await waitFor(() => {+ expect(getLastRunsParams().get("started-at")).toBe("past1weeks");+ });++ await userEvent.click(+ screen.getByRole("switch", { name: "Include today" }),+ );++ await waitFor(() => {+ expect(getLastRunsParams().get("started-at")).toBe("past1weeks~");+ });+ });++ it("keeps the selected entity when only include-today changes", async () => {+ setup({+ initialRoute: `${PATHNAME}?run-type=alert&started-at=past1weeks&entity-type=card&entity-id=42`,+ });+ await waitForLoaderToBeRemoved();++ await openDatePicker();+ await userEvent.click(+ screen.getByRole("switch", { name: "Include today" }),+ );++ await waitFor(() => {+ const params = getLastRunsParams();+ expect(params.get("started-at")).toBe("past1weeks~");+ expect(params.get("entity-type")).toBe("card");+ expect(params.get("entity-id")).toBe("42");+ });+ });++ it("clears the selected entity when the range changes", async () => {+ setup({+ initialRoute: `${PATHNAME}?run-type=alert&started-at=past1weeks&entity-type=card&entity-id=42`,+ });+ await waitForLoaderToBeRemoved();++ await openDatePicker();+ await selectRange("Previous 30 days");++ await waitFor(() => {+ const params = getLastRunsParams();+ expect(params.get("started-at")).toBe("past30days");+ expect(params.get("entity-type")).toBeNull();+ expect(params.get("entity-id")).toBeNull();+ });+ });++ it("restores the include-today filter from the URL", async () => {+ setup({+ initialRoute: `${PATHNAME}?started-at=past1weeks&include-today=true`,+ });+ await waitForLoaderToBeRemoved();++ expect(+ screen.getByText("Previous week, including today"),+ ).toBeInTheDocument();+ expect(getLastRunsParams().get("started-at")).toBe("past1weeks~");+ });+ });});function createMockTaskRunsResponse(diff --git a/frontend/src/metabase/admin/tools/components/TaskRunsPage/utils.ts b/frontend/src/metabase/admin/tools/components/TaskRunsPage/utils.tsindex fff4afbebc5..1d2c73a09f5 100644--- a/frontend/src/metabase/admin/tools/components/TaskRunsPage/utils.ts+++ b/frontend/src/metabase/admin/tools/components/TaskRunsPage/utils.ts@@ -24,6 +24,7 @@ type UrlState = {"entity-id": number | null;status: TaskRunStatus | null;"started-at": TaskRunDateFilterOption | null;+ "include-today": boolean;};export const urlStateConfig: UrlStateConfig<UrlState> = {@@ -34,6 +35,7 @@ export const urlStateConfig: UrlStateConfig<UrlState> = {"entity-id": parseTaskRunEntityId(query["entity-id"]),status: parseTaskRunStatus(query.status),"started-at": parseTaskRunStartedAt(query["started-at"]),+ "include-today": parseIncludeToday(query["include-today"]),}),serialize: ({page,@@ -42,6 +44,7 @@ export const urlStateConfig: UrlStateConfig<UrlState> = {"entity-id": entityId,status,"started-at": startedAt,+ "include-today": includeToday,}) => ({page: page === 0 ? undefined : String(page),"run-type": runType === null ? undefined : runType,@@ -49,6 +52,7 @@ export const urlStateConfig: UrlStateConfig<UrlState> = {"entity-id": entityId === null ? undefined : String(entityId),status: status === null ? undefined : status,"started-at": startedAt === null ? undefined : startedAt,+ "include-today": includeToday ? "true" : undefined,}),};@@ -86,3 +90,7 @@ const parseTaskRunStartedAt = (param: QueryParam): UrlState["started-at"] => {const value = getFirstParamValue(param);return value && guardTaskRunStartedAtRange(value) ? value : null;};++const parseIncludeToday = (param: QueryParam): UrlState["include-today"] => {+ return getFirstParamValue(param) === "true";+};diff --git a/frontend/src/metabase/admin/tools/components/ToolsApp.tsx b/frontend/src/metabase/admin/tools/components/ToolsApp.tsxindex 9ebd9bb4732..73da70bb91b 100644--- a/frontend/src/metabase/admin/tools/components/ToolsApp.tsx+++ b/frontend/src/metabase/admin/tools/components/ToolsApp.tsx@@ -8,6 +8,7 @@ import {type AdminNavItemProps,AdminNavWrapper,} from "metabase/admin/components/AdminNav";+import { useHasTokenFeature } from "metabase/common/hooks";import * as Urls from "metabase/urls";type ToolsAppProps = {@@ -16,6 +17,8 @@ type ToolsAppProps = {};export function ToolsApp({ location, children }: ToolsAppProps) {+ const hasAuditApp = useHasTokenFeature("audit_app");+return (<AdminSettingsLayoutmaw="100rem"@@ -58,6 +61,14 @@ export function ToolsApp({ location, children }: ToolsAppProps) {icon="database"location={location}/>+ {hasAuditApp && (+ <ToolsNavItem+ label={t`Alerts management`}+ path={Urls.adminToolsNotifications()}+ icon="bell"+ location={location}+ />+ )}</AdminNavWrapper>}>diff --git a/frontend/src/metabase/admin/tools/notifications/ChangeOwnerModal/ChangeOwnerModal.tsx b/frontend/src/metabase/admin/tools/notifications/ChangeOwnerModal/ChangeOwnerModal.tsxnew file mode 100644index 00000000000..461bbbc1ed2--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/ChangeOwnerModal/ChangeOwnerModal.tsx@@ -0,0 +1,68 @@+import { useState } from "react";+import { t } from "ttag";++import { Button, Flex, Modal } from "metabase/ui";+import type { AdminNotification, UserId } from "metabase-types/api";++import { type UserOption, UserPicker } from "../UserPicker";++type Props = {+ opened: boolean;+ notifications: AdminNotification[];+ isSubmitting?: boolean;+ onClose: () => void;+ onConfirm: (creatorId: UserId) => void;+};++export const ChangeOwnerModal = ({+ opened,+ notifications,+ isSubmitting,+ onClose,+ onConfirm,+}: Props) => {+ const count = notifications.length;++ const [selectedCreator, setSelectedCreator] = useState<UserOption | null>(+ () => {+ if (notifications.length !== 1) {+ return null;+ }+ const creator = notifications[0].creator;+ return creator ? { id: creator.id, label: creator.common_name } : null;+ },+ );++ const handleSubmit = () => {+ if (selectedCreator !== null) {+ onConfirm(selectedCreator.id);+ }+ };++ const title =+ count === 1+ ? t`Select new owner of 1 alert`+ : t`Select new owner of ${count} alerts`;++ return (+ <Modal opened={opened} onClose={onClose} title={title} size="md">+ <Flex direction="column" gap="md">+ <UserPicker value={selectedCreator} onChange={setSelectedCreator} />++ <Flex justify="flex-end" gap="sm">+ <Button variant="default" onClick={onClose}>+ {t`Cancel`}+ </Button>+ <Button+ variant="filled"+ disabled={selectedCreator === null || isSubmitting}+ loading={isSubmitting}+ onClick={handleSubmit}+ >+ {t`Change owner`}+ </Button>+ </Flex>+ </Flex>+ </Modal>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/ChangeOwnerModal/index.ts b/frontend/src/metabase/admin/tools/notifications/ChangeOwnerModal/index.tsnew file mode 100644index 00000000000..e27ed01d7dc--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/ChangeOwnerModal/index.ts@@ -0,0 +1 @@+export { ChangeOwnerModal } from "./ChangeOwnerModal";diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/ChannelAvatarStack.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/ChannelAvatarStack.tsxnew file mode 100644index 00000000000..fa6a0de3849--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/ChannelAvatarStack.tsx@@ -0,0 +1,69 @@+import { match } from "ts-pattern";+import _ from "underscore";++import { Box, Flex, Icon } from "metabase/ui";+import type { NotificationHandler } from "metabase-types/api";++import { getChannelIconName } from "../NotificationsAdminPage/utils";++import S from "./NotificationDetailSidebar.module.css";+import type { ChannelAvatarProps } from "./types";++const AVATAR_SIZE = 36;++export const ChannelAvatarStack = ({+ handlers,+}: {+ handlers: NotificationHandler[] | undefined;+}) => {+ const channels = _.uniq(+ handlers?.map((handler) => handler.channel_type) ?? [],+ );++ return (+ <Flex align="center" className={S.avatarStack}>+ {channels.map((channel, index) => (+ <Box+ key={channel}+ style={{+ marginLeft: index === 0 ? 0 : -AVATAR_SIZE / 2,+ zIndex: channels.length - index,+ }}+ >+ <ChannelAvatar channel={channel} bordered={channels.length > 1} />+ </Box>+ ))}+ </Flex>+ );+};++const ChannelAvatar = ({ channel, bordered }: ChannelAvatarProps) => {+ const { backgroundColor, iconColor } = match(channel)+ .with("channel/slack", () => ({+ backgroundColor:+ "color-mix(in srgb, var(--mb-color-saturated-purple) 10%, var(--mb-color-background-primary))",+ iconColor: "saturated-purple" as const,+ }))+ .otherwise(() => ({+ backgroundColor: "var(--mb-color-background-brand)",+ iconColor: "brand" as const,+ }));++ return (+ <Flex+ align="center"+ justify="center"+ w={AVATAR_SIZE}+ h={AVATAR_SIZE}+ bd={bordered ? "2px solid var(--mb-color-background-primary)" : undefined}+ bdrs="50%"+ className={S.channelAvatar}+ style={{ backgroundColor }}+ >+ <Icon+ name={channel ? getChannelIconName(channel) : "bell"}+ c={iconColor}+ />+ </Flex>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsRow.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsRow.tsxnew file mode 100644index 00000000000..39e9e10cc2e--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsRow.tsx@@ -0,0 +1,39 @@+import { Box, Divider, Flex, Text } from "metabase/ui";++import type { DetailsRowProps } from "./types";++export const DetailsRow = ({+ label,+ value,+ bold,+ spanLabel,+}: DetailsRowProps) => {+ if (spanLabel) {+ return (+ <Flex align="center" px="md" py="sm" bg="background-primary">+ <Text size="md" c="text-secondary">+ {label}+ </Text>+ </Flex>+ );+ }+ return (+ <Flex>+ <Flex w={160} px="md" py="sm" bg="background-secondary">+ <Text size="md" c="text-secondary">+ {label}+ </Text>+ </Flex>+ <Divider orientation="vertical" />+ <Flex flex={1} align="center" px="md" py="sm" miw={0}>+ {typeof value === "string" ? (+ <Text size="md" fw={bold ? "bold" : "normal"} c="text-primary">+ {value}+ </Text>+ ) : (+ <Box w="100%">{value}</Box>+ )}+ </Flex>+ </Flex>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsSection.tsxnew file mode 100644index 00000000000..fe03cce94ad--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx@@ -0,0 +1,75 @@+import { t } from "ttag";++import { Link as MBLink } from "metabase/common/components/Link";+import * as Urls from "metabase/urls";++import { NotificationSummary } from "../NotificationSummary";++import { DetailsRow } from "./DetailsRow";+import { DetailsTable } from "./DetailsTable";+import { SidebarSection } from "./SidebarSection";+import type { DetailsSectionProps } from "./types";+import { formatChannelSummary } from "./utils";++export const DetailsSection = ({+ notification,+ emailRecipientCount,+ slackChannelCount,+ httpHandler,+}: DetailsSectionProps) => {+ const cardId = notification.payload.card_id;+ const cardName = notification.payload.card?.name;+ const channelSummary = formatChannelSummary({+ emailRecipientCount,+ slackChannelCount,+ httpHandler,+ });+ const creator = notification.creator;+ const ownerName = creator?.common_name ?? creator?.email ?? t`Unknown`;++ return (+ <SidebarSection title={t`Details`}>+ <DetailsTable>+ <DetailsRow+ label={t`Question`}+ value={+ cardName ? (+ <MBLink+ variant="brandBold"+ to={Urls.card({ id: cardId, name: cardName })}+ >+ {cardName}+ </MBLink>+ ) : (+ t`Unknown`+ )+ }+ bold+ />+ <DetailsRow label={t`Owner`} value={ownerName} />+ <DetailsRow+ label={t`Channel`}+ value={channelSummary || t`No channels`}+ />+ <DetailsRow+ label={t`Last checked`}+ value={+ <NotificationSummary+ run={notification.last_check}+ isCompact={false}+ />+ }+ />+ <DetailsRow+ label={t`Last send attempt`}+ value={+ <NotificationSummary+ run={notification.last_send}+ isCompact={false}+ />+ }+ />+ </DetailsTable>+ </SidebarSection>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsTable.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsTable.tsxnew file mode 100644index 00000000000..44b33be45bf--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/DetailsTable.tsx@@ -0,0 +1,24 @@+import type { ReactNode } from "react";+import { Children, Fragment } from "react";++import { Box, Divider } from "metabase/ui";++import S from "./NotificationDetailSidebar.module.css";++export const DetailsTable = ({ children }: { children: ReactNode }) => {+ const items = Children.toArray(children).filter(Boolean);+ return (+ <Box+ bd="1px solid var(--mb-color-border)"+ bdrs="lg"+ className={S.detailsTable}+ >+ {items.map((item, i) => (+ <Fragment key={i}>+ {i > 0 && <Divider />}+ {item}+ </Fragment>+ ))}+ </Box>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.module.css b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.module.cssnew file mode 100644index 00000000000..c11a109e174--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.module.css@@ -0,0 +1,30 @@+.navButton {+ color: var(--mb-color-text-primary);+ background: var(--mb-color-background);+ border: 1px solid var(--mb-color-border);++ &:hover {+ background: var(--mb-color-background-hover);+ }++ &[data-disabled] {+ color: var(--mb-color-text-tertiary);+ background: var(--mb-color-background);++ &:hover {+ background: var(--mb-color-background);+ }+ }+}++.avatarStack {+ flex-shrink: 0;+}++.channelAvatar {+ flex-shrink: 0;+}++.detailsTable {+ overflow: hidden;+}diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.tsxnew file mode 100644index 00000000000..9d759b8a50c--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.tsx@@ -0,0 +1,113 @@+import { useEffect, useMemo, useState } from "react";++import {+ skipToken,+ useAdminNotificationDetailQuery,+ useGetCardQuery,+} from "metabase/api";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { ADMIN_NAVBAR_HEIGHT } from "metabase/nav/constants";+import { CreateOrEditQuestionAlertModal } from "metabase/notifications/modals/CreateOrEditQuestionAlertModal";+import { loadMetadataForCard } from "metabase/questions/actions";+import { useDispatch, useSelector } from "metabase/redux";+import { getMetadata } from "metabase/selectors/metadata";+import { Drawer, Stack } from "metabase/ui";+import Question from "metabase-lib/v1/Question";++import { SidebarBody } from "./SidebarBody";+import { SidebarHeader } from "./SidebarHeader";+import { SIDEBAR_WIDTH } from "./constants";+import type { SidebarProps } from "./types";++export const NotificationDetailSidebar = ({+ notificationId,+ notificationSummary,+ isBulkLoading,+ prevNotificationId,+ nextNotificationId,+ onClose,+ onDelete,+}: SidebarProps) => {+ const { currentData: detail, isFetching: isDetailFetching } =+ useAdminNotificationDetailQuery(notificationId);+ const notification = detail ?? notificationSummary;++ const [isEditModalOpen, setIsEditModalOpen] = useState(false);++ useEffect(() => {+ setIsEditModalOpen(false);+ }, [notificationId]);++ const dispatch = useDispatch();+ const metadata = useSelector(getMetadata);+ const cardId = notification?.payload.card_id;+ const { currentData: card, isFetching: isCardLoading } = useGetCardQuery(+ cardId !== undefined ? { id: cardId } : skipToken,+ );++ useEffect(() => {+ if (card) {+ dispatch(loadMetadataForCard(card));+ }+ }, [card, dispatch]);++ const question = useMemo(+ () => (card ? new Question(card, metadata) : undefined),+ [card, metadata],+ );++ return (+ <>+ <Drawer+ opened+ onClose={onClose}+ position="right"+ size={SIDEBAR_WIDTH}+ withCloseButton={false}+ padding={0}+ withOverlay={false}+ lockScroll={false}+ shadow="lg"+ zIndex={100}+ styles={{+ inner: {+ top: ADMIN_NAVBAR_HEIGHT,+ height: `calc(100vh - ${ADMIN_NAVBAR_HEIGHT})`,+ },+ }}+ >+ <Stack h="100%" p="lg" gap="lg">+ <SidebarHeader+ isBulkLoading={isBulkLoading}+ notificationId={notificationId}+ notification={notification}+ prevNotificationId={prevNotificationId}+ nextNotificationId={nextNotificationId}+ isQuestionLoading={isCardLoading}+ onClose={onClose}+ onDelete={onDelete}+ onEdit={() => setIsEditModalOpen(true)}+ />+ {notification ? (+ <SidebarBody+ notification={notification}+ detail={detail}+ isDetailFetching={isDetailFetching}+ />+ ) : (+ <LoadingAndErrorWrapper loading />+ )}+ </Stack>+ </Drawer>+ {isEditModalOpen && notification && question && (+ <CreateOrEditQuestionAlertModal+ editingNotification={notification}+ question={question}+ skipUrlUpdate+ onAlertUpdated={() => setIsEditModalOpen(false)}+ onClose={() => setIsEditModalOpen(false)}+ />+ )}+ </>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationRunSummaryLog.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationRunSummaryLog.tsxnew file mode 100644index 00000000000..27311ae0431--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/NotificationRunSummaryLog.tsx@@ -0,0 +1,102 @@+import dayjs from "dayjs";+import { Link } from "react-router";+import { t } from "ttag";++import { Anchor, Badge, Flex, Loader, Text, Tooltip } from "metabase/ui";+import * as Urls from "metabase/urls";++import { formatRelativeDate } from "../NotificationsAdminPage/utils";++import { DetailsRow } from "./DetailsRow";+import { DetailsTable } from "./DetailsTable";+import { SidebarSection } from "./SidebarSection";+import type { NotificationRunSummaryLogProps } from "./types";++export const NotificationRunSummaryLog = ({+ title,+ runs,+ isLoading,+ cardId,+}: NotificationRunSummaryLogProps) => {+ const viewAllUrl = Urls.adminToolsTasksRunsFor({+ runType: "alert",+ entityType: "card",+ entityId: cardId,+ startedAt: "past3months",+ includeToday: true,+ });++ const renderRuns = () => {+ if (isLoading) {+ return (+ <Flex align="center" justify="center" py="lg">+ <Loader size="sm" data-testid="run-summary-loader" />+ </Flex>+ );+ }+ if (runs && runs.length === 0) {+ return (+ <DetailsRow+ label={t`No runs in the past 90 days.`}+ value=""+ bold={false}+ spanLabel+ />+ );+ }+ return runs?.map((run, index) => {+ const isFailing = run.status === "failing";+ const hasError = isFailing && !!run.error;+ return (+ <Flex+ key={index}+ align="center"+ justify="space-between"+ px="md"+ py="sm"+ gap="sm"+ >+ <Tooltip label={dayjs(run.at).fromNow()}>+ <Text size="md" c="text-primary" component="span">+ {formatRelativeDate(run.at)}+ </Text>+ </Tooltip>+ <Tooltip label={run.error} disabled={!hasError}>+ <Badge+ color={isFailing ? "error" : undefined}+ variant={isFailing ? "light" : "outline"}+ radius="lg"+ tt="none"+ fw="normal"+ c={isFailing ? undefined : "text-secondary"}+ bd={isFailing ? undefined : "1px solid var(--mb-color-border)"}+ style={hasError ? { cursor: "pointer" } : undefined}+ >+ {isFailing ? t`Failed` : t`Successful`}+ </Badge>+ </Tooltip>+ </Flex>+ );+ });+ };++ return (+ <SidebarSection+ title={title}+ titleAside={+ <Anchor+ component={Link}+ to={viewAllUrl}+ c="brand"+ fz="md"+ lh="1rem"+ fw="bold"+ >+ {t`View all`}+ </Anchor>+ }+ >+ <DetailsTable>{renderRuns()}</DetailsTable>+ </SidebarSection>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarBody.tsxnew file mode 100644index 00000000000..120b0812577--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx@@ -0,0 +1,107 @@+import { t } from "ttag";++import { Flex, Stack, Text } from "metabase/ui";+import type {+ NotificationHandlerEmail,+ NotificationHandlerHttp,+ NotificationHandlerSlack,+} from "metabase-types/api";++import { DetailsSection } from "./DetailsSection";+import { DetailsTable } from "./DetailsTable";+import { NotificationRunSummaryLog } from "./NotificationRunSummaryLog";+import { SidebarSection } from "./SidebarSection";+import type { SidebarBodyProps } from "./types";+import {+ getEmailRecipientLabel,+ getEmailRowText,+ getSlackChannelLabel,+} from "./utils";++export const SidebarBody = ({+ notification,+ isDetailFetching,+ detail,+}: SidebarBodyProps) => {+ const handlers = notification.handlers ?? [];+ const emailHandler = handlers.find(+ (handler): handler is NotificationHandlerEmail =>+ handler.channel_type === "channel/email",+ );+ const slackHandler = handlers.find(+ (handler): handler is NotificationHandlerSlack =>+ handler.channel_type === "channel/slack",+ );+ const httpHandler = handlers.find(+ (handler): handler is NotificationHandlerHttp =>+ handler.channel_type === "channel/http",+ );+ const emailRecipientCount = emailHandler?.recipients.length ?? 0;+ const slackChannelCount = slackHandler?.recipients.length ?? 0;++ const cardId = notification.payload.card_id;++ return (+ <Stack gap="xl">+ <DetailsSection+ notification={notification}+ emailRecipientCount={emailRecipientCount}+ slackChannelCount={slackChannelCount}+ httpHandler={httpHandler}+ />+ <NotificationRunSummaryLog+ title={t`Check history`}+ runs={detail?.check_history}+ isLoading={isDetailFetching}+ cardId={cardId}+ />+ <NotificationRunSummaryLog+ title={t`Send history`}+ runs={detail?.send_history}+ isLoading={isDetailFetching}+ cardId={cardId}+ />+ {emailHandler && emailRecipientCount > 0 && (+ <SidebarSection title={getEmailRecipientLabel(emailRecipientCount)}>+ <DetailsTable>+ {emailHandler.recipients.map((recipient, index) => {+ const { name, email } = getEmailRowText(recipient);+ return (+ <Flex+ key={recipient.id ?? index}+ align="center"+ justify="space-between"+ px="md"+ py="sm"+ gap="sm"+ >+ <Text size="md" c="text-primary">+ {name}+ </Text>+ {email && (+ <Text size="md" c="text-secondary">+ {email}+ </Text>+ )}+ </Flex>+ );+ })}+ </DetailsTable>+ </SidebarSection>+ )}+ {slackHandler && slackChannelCount > 0 && (+ <SidebarSection title={getSlackChannelLabel(slackChannelCount)}>+ <DetailsTable>+ {slackHandler.recipients.map((recipient, index) => (+ <Flex key={recipient.id ?? index} align="center" px="md" py="sm">+ <Text size="md" c="text-primary">+ {recipient.details?.value ?? ""}+ </Text>+ </Flex>+ ))}+ </DetailsTable>+ </SidebarSection>+ )}+ </Stack>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarHeader.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarHeader.tsxnew file mode 100644index 00000000000..552503fe1c2--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarHeader.tsx@@ -0,0 +1,140 @@+import { push } from "react-router-redux";+import { t } from "ttag";++import { useDispatch } from "metabase/redux";+import { addUndo } from "metabase/redux/undo";+import {+ ActionIcon,+ Flex,+ Group,+ Icon,+ Loader,+ Menu,+ Stack,+ Text,+ Title,+} from "metabase/ui";+import * as Urls from "metabase/urls";+import type { NotificationId } from "metabase-types/api";++import { ChannelAvatarStack } from "./ChannelAvatarStack";+import S from "./NotificationDetailSidebar.module.css";+import type { SidebarHeaderProps } from "./types";++export const SidebarHeader = ({+ isBulkLoading,+ notificationId,+ notification,+ prevNotificationId,+ nextNotificationId,+ isQuestionLoading,+ onClose,+ onDelete,+ onEdit,+}: SidebarHeaderProps) => {+ const cardName = notification?.payload.card?.name ?? t`Untitled question`;+ const dispatch = useDispatch();++ const handleCopyLink = async () => {+ const url = `${window.location.origin}${Urls.adminToolsNotificationDetail(notificationId)}`;+ await navigator.clipboard.writeText(url);+ dispatch(addUndo({ message: t`Link copied to clipboard` }));+ };++ const handleNavigate = (id: NotificationId | undefined) => {+ if (id !== undefined) {+ dispatch(push(Urls.adminToolsNotificationDetail(id)));+ }+ };++ return (+ <Stack gap="lg">+ <Flex justify="space-between" align="center">+ <Group gap="sm">+ <ActionIcon+ aria-label={t`Previous alert`}+ size="lg"+ variant="default"+ className={S.navButton}+ disabled={prevNotificationId === undefined}+ onClick={() => handleNavigate(prevNotificationId)}+ >+ <Icon name="chevronup" />+ </ActionIcon>+ <ActionIcon+ aria-label={t`Next alert`}+ size="lg"+ variant="default"+ className={S.navButton}+ disabled={nextNotificationId === undefined}+ onClick={() => handleNavigate(nextNotificationId)}+ >+ <Icon name="chevrondown" />+ </ActionIcon>+ </Group>+ <Group gap="sm">+ <Menu position="bottom-end" withinPortal>+ <Menu.Target>+ <ActionIcon+ aria-label={t`More actions`}+ size="lg"+ c="icon-primary"+ disabled={isBulkLoading}+ >+ <Icon name="ellipsis" />+ </ActionIcon>+ </Menu.Target>+ <Menu.Dropdown>+ <Menu.Item+ leftSection={<Icon name="link" />}+ onClick={handleCopyLink}+ >+ {t`Copy link to clipboard`}+ </Menu.Item>+ {notification?.active && (+ <Menu.Item+ c="danger"+ leftSection={<Icon name="trash" />}+ onClick={() => onDelete(notification)}+ >+ {t`Delete alert`}+ </Menu.Item>+ )}+ </Menu.Dropdown>+ </Menu>+ <ActionIcon+ aria-label={t`Edit`}+ size="lg"+ c="icon-primary"+ disabled={isQuestionLoading || isBulkLoading}+ onClick={!isQuestionLoading ? onEdit : undefined}+ >+ {isQuestionLoading ? <Loader size="sm" /> : <Icon name="pencil" />}+ </ActionIcon>+ <ActionIcon+ aria-label={t`Close`}+ size="lg"+ c="icon-primary"+ onClick={onClose}+ >+ <Icon name="close" />+ </ActionIcon>+ </Group>+ </Flex>++ {notification && (+ <Flex align="center" gap="sm">+ <ChannelAvatarStack handlers={notification.handlers} />+ <Stack gap={0}>+ <Text size="sm" c="text-secondary">+ {t`Alert ${notification.id}`}+ </Text>+ <Title order={3} c="text-primary">+ {cardName}+ </Title>+ </Stack>+ </Flex>+ )}+ </Stack>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarSection.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarSection.tsxnew file mode 100644index 00000000000..018ef0335e2--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/SidebarSection.tsx@@ -0,0 +1,19 @@+import { Flex, Stack, Text } from "metabase/ui";++import type { SidebarSectionProps } from "./types";++export const SidebarSection = ({+ title,+ titleAside,+ children,+}: SidebarSectionProps) => (+ <Stack gap="md">+ <Flex justify="space-between" align="center">+ <Text fw="bold" size="md" lh="1rem" c="text-primary">+ {title}+ </Text>+ {titleAside}+ </Flex>+ {children}+ </Stack>+);diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/constants.ts b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/constants.tsnew file mode 100644index 00000000000..3a26503a65c--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/constants.ts@@ -0,0 +1 @@+export const SIDEBAR_WIDTH = 560;diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/index.ts b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/index.tsnew file mode 100644index 00000000000..db4ef23d02c--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/index.ts@@ -0,0 +1 @@+export { NotificationDetailSidebar } from "./NotificationDetailSidebar";diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/types.ts b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/types.tsnew file mode 100644index 00000000000..d8d305f62c1--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/types.ts@@ -0,0 +1,72 @@+import type { ReactNode } from "react";++import type {+ AdminNotification,+ AdminNotificationDetail,+ CardId,+ NotificationChannelType,+ NotificationHandlerHttp,+ NotificationId,+ NotificationRunSummary,+ NotificationTickSendEntry,+} from "metabase-types/api";++export type SidebarProps = {+ notificationId: NotificationId;+ notificationSummary: AdminNotification | undefined;+ isBulkLoading: boolean;+ prevNotificationId: NotificationId | undefined;+ nextNotificationId: NotificationId | undefined;+ onClose: () => void;+ onDelete: (notification: AdminNotification) => void;+};++export type SidebarHeaderProps = {+ isBulkLoading: boolean;+ notificationId: NotificationId;+ notification: AdminNotification | undefined;+ prevNotificationId: NotificationId | undefined;+ nextNotificationId: NotificationId | undefined;+ isQuestionLoading: boolean;+ onClose: () => void;+ onDelete: (notification: AdminNotification) => void;+ onEdit: () => void;+};++export type ChannelAvatarProps = {+ channel: NotificationChannelType;+ bordered: boolean;+};++export type DetailsSectionProps = {+ notification: AdminNotification;+ emailRecipientCount: number;+ slackChannelCount: number;+ httpHandler: NotificationHandlerHttp | undefined;+};++export type NotificationRunSummaryLogProps = {+ title: string;+ runs: (NotificationRunSummary | NotificationTickSendEntry)[] | undefined;+ isLoading: boolean;+ cardId: CardId;+};++export type SidebarSectionProps = {+ title: string;+ titleAside?: ReactNode;+ children: ReactNode;+};++export type DetailsRowProps = {+ label: ReactNode;+ value: ReactNode;+ bold?: boolean;+ spanLabel?: boolean;+};++export type SidebarBodyProps = {+ notification: AdminNotification;+ isDetailFetching: boolean;+ detail: AdminNotificationDetail | undefined;+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/utils.ts b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/utils.tsnew file mode 100644index 00000000000..fa41462a73b--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationDetailSidebar/utils.ts@@ -0,0 +1,59 @@+import { t } from "ttag";++import type {+ NotificationHandlerHttp,+ NotificationRecipient,+} from "metabase-types/api";++export const getEmailRowText = (+ recipient: NotificationRecipient,+): { name: string; email: string | null } => {+ if (recipient.type === "notification-recipient/user") {+ const user = recipient.user;+ if (!user) {+ return { name: t`Deactivated user`, email: null };+ }+ return {+ name: user.common_name ?? user.email ?? t`Unknown`,+ email: user.email ?? null,+ };+ }+ if (recipient.type === "notification-recipient/raw-value") {+ const value = recipient.details?.value ?? "";+ return { name: value, email: null };+ }+ return { name: t`Group recipient`, email: null };+};++export const getEmailRecipientLabel = (count: number): string =>+ count === 1 ? t`1 email recipient` : t`${count} email recipients`;++export const getSlackChannelLabel = (count: number): string =>+ count === 1 ? t`1 Slack channel` : t`${count} Slack channels`;++export const getWebhookLabel = (count: number): string =>+ count === 1 ? t`1 webhook` : t`${count} webhooks`;++type ChannelSummaryInput = {+ emailRecipientCount: number;+ slackChannelCount: number;+ httpHandler: NotificationHandlerHttp | undefined;+};++export const formatChannelSummary = ({+ emailRecipientCount,+ slackChannelCount,+ httpHandler,+}: ChannelSummaryInput): string => {+ const parts: string[] = [];+ if (emailRecipientCount > 0) {+ parts.push(getEmailRecipientLabel(emailRecipientCount));+ }+ if (slackChannelCount > 0) {+ parts.push(getSlackChannelLabel(slackChannelCount));+ }+ if (httpHandler && httpHandler.recipients.length > 0) {+ parts.push(getWebhookLabel(httpHandler.recipients.length));+ }+ return parts.join(", ");+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationSummary/NotificationSummary.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationSummary/NotificationSummary.tsxnew file mode 100644index 00000000000..e3a885a2e45--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationSummary/NotificationSummary.tsx@@ -0,0 +1,47 @@+import dayjs from "dayjs";++import { Flex, Icon, Stack, Text, Tooltip } from "metabase/ui";+import type { NotificationRunSummary } from "metabase-types/api";++import { formatRelativeDate } from "../NotificationsAdminPage/utils";++type Props = {+ run: NotificationRunSummary | null;+ isCompact?: boolean;+};++export const NotificationSummary = ({ run, isCompact }: Props) => {+ const isFailing = run?.status === "failing";+ const error = isFailing ? run.error : null;++ if (!run) {+ return formatRelativeDate(null);+ }++ return (+ <Stack gap="xs">+ <Flex gap="sm" align="center">+ <Tooltip label={dayjs(run.at).fromNow()}>+ <Text size="md" c="text-primary" component="span">+ {formatRelativeDate(run.at)}+ </Text>+ </Tooltip>+ {isCompact && isFailing && (+ <Tooltip label={error} disabled={!error}>+ <Icon name="warning_round" c="error" />+ </Tooltip>+ )}+ </Flex>+ {!isCompact && isFailing && (+ <Flex align="center" gap="xs">+ {error && (+ <Text size="sm" c="error">+ {error}+ </Text>+ )}+ <Icon name="warning_round" c="error" />+ </Flex>+ )}+ </Stack>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationSummary/index.ts b/frontend/src/metabase/admin/tools/notifications/NotificationSummary/index.tsnew file mode 100644index 00000000000..1a8d62c3c8e--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationSummary/index.ts@@ -0,0 +1 @@+export { NotificationSummary } from "./NotificationSummary";diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsxnew file mode 100644index 00000000000..6e805775f88--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx@@ -0,0 +1,411 @@+import type { Row, SortingState } from "@tanstack/react-table";+import { useCallback, useEffect, useMemo, useState } from "react";+import type { WithRouterProps } from "react-router";+import { push } from "react-router-redux";+import { t } from "ttag";++import {+ useAdminListNotificationsQuery,+ useBulkNotificationActionMutation,+} from "metabase/api";+import {+ BulkActionBar,+ BulkActionButton,+ BulkActionDangerButton,+} from "metabase/common/components/BulkActionBar";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PaginationControls } from "metabase/common/components/PaginationControls";+import { useConfirmation } from "metabase/common/hooks/use-confirmation";+import { useUrlState } from "metabase/common/hooks/use-url-state";+import { useDispatch } from "metabase/redux";+import { addUndo } from "metabase/redux/undo";+import { Flex, type SelectionState, Title } from "metabase/ui";+import * as Urls from "metabase/urls";+import type {+ AdminNotification,+ NotificationId,+ UserId,+} from "metabase-types/api";++import { SettingsPageWrapper } from "../../../components/SettingsSection";+import { ChangeOwnerModal } from "../ChangeOwnerModal";+import { NotificationDetailSidebar } from "../NotificationDetailSidebar";+import { SIDEBAR_WIDTH } from "../NotificationDetailSidebar/constants";+import { NotificationsFilters } from "../NotificationsFilters";+import { NotificationsSearchInput } from "../NotificationsSearchInput";+import { NotificationsTable } from "../NotificationsTable";+import { NotificationsTabs } from "../NotificationsTabs";++import {+ DEFAULT_SORT_COLUMN,+ DEFAULT_SORT_DIRECTION,+ PAGE_SIZE,+ SORT_COLUMN_VALUES,+} from "./constants";+import type { RouteParams } from "./types";+import { buildListParams, urlStateConfig } from "./utils";++export const NotificationsAdminPage = ({+ location,+ params,+}: WithRouterProps<RouteParams>) => {+ const notificationId = Urls.extractEntityId(params.notificationId);+ const dispatch = useDispatch();+ const [urlState, { patchUrlState }] = useUrlState(location, urlStateConfig);+ const [selectedIds, setSelectedIds] = useState<Set<NotificationId>>(+ new Set(),+ );+ const clearSelected = useCallback(() => setSelectedIds(new Set()), []);+ const getSelectionState = useCallback(+ (row: Row<AdminNotification>): SelectionState =>+ selectedIds.has(row.original.id) ? "all" : "none",+ [selectedIds],+ );+ const [isChangeOwnerOpened, setIsChangeOwnerOpened] = useState(false);++ const { modalContent: confirmContent, show: showConfirm } = useConfirmation();++ const { data, isLoading, isFetching, error } = useAdminListNotificationsQuery(+ buildListParams(urlState, PAGE_SIZE),+ );+ const notifications = useMemo(() => data?.data ?? [], [data?.data]);+ const total = data?.total ?? 0;+ const selectedCount = selectedIds.size;+ const selectedNotifications = useMemo(+ () => notifications.filter((n) => selectedIds.has(n.id)),+ [notifications, selectedIds],+ );++ const { data: failingData, isLoading: isFailingLoading } =+ useAdminListNotificationsQuery({+ limit: 1,+ offset: 0,+ active: true,+ last_send_status: "failing",+ });+ const { data: ownerlessData, isLoading: isOwnerlessLoading } =+ useAdminListNotificationsQuery({+ limit: 1,+ offset: 0,+ active: true,+ creatorless: true,+ });+ const failingCount = failingData?.total ?? 0;+ const ownerlessCount = ownerlessData?.total ?? 0;++ useEffect(() => {+ if (+ (urlState.tab === "failing" && failingData && failingCount === 0) ||+ (urlState.tab === "ownerless" && ownerlessData && ownerlessCount === 0)+ ) {+ patchUrlState({ tab: "all", page: 0 });+ }+ }, [+ urlState.tab,+ failingData,+ failingCount,+ ownerlessData,+ ownerlessCount,+ patchUrlState,+ ]);++ const [bulkAction, { isLoading: isBulkLoading }] =+ useBulkNotificationActionMutation();++ useEffect(() => {+ clearSelected();+ }, [+ clearSelected,+ urlState.page,+ urlState.active,+ urlState.tab,+ urlState.last_send_status,+ urlState.creator_active,+ urlState.query,+ urlState.channel,+ urlState.recipient_email,+ urlState.sort_column,+ urlState.sort_direction,+ ]);++ const sorting: SortingState = [+ {+ id: urlState.sort_column,+ desc: urlState.sort_direction === "desc",+ },+ ];++ const handleSortingChange = useCallback(+ (next: SortingState) => {+ if (next.length === 0) {+ patchUrlState({+ sort_column: DEFAULT_SORT_COLUMN,+ sort_direction: DEFAULT_SORT_DIRECTION,+ page: 0,+ });+ return;+ }+ const [first] = next;+ const column = SORT_COLUMN_VALUES.find((col) => col === first.id);+ if (column === undefined) {+ return;+ }+ patchUrlState({+ sort_column: column,+ sort_direction: first.desc ? "desc" : "asc",+ page: 0,+ });+ },+ [patchUrlState],+ );++ const handleToggleRow = useCallback((id: NotificationId) => {+ setSelectedIds((prev) =>+ prev.has(id)+ ? new Set([...prev].filter((x) => x !== id))+ : new Set([...prev, id]),+ );+ }, []);++ const handleToggleAll = useCallback(() => {+ setSelectedIds((prev) => {+ const allIds = notifications.map((n) => n.id);+ const allSelected =+ allIds.length > 0 && allIds.every((id) => prev.has(id));+ if (allSelected) {+ return new Set();+ }+ return new Set([...prev, ...allIds]);+ });+ }, [notifications]);++ const handleRowClick = (id: NotificationId) => {+ dispatch(push(Urls.adminToolsNotificationDetail(id)));+ };++ const handleSidebarClose = () => {+ dispatch(push(Urls.adminToolsNotifications()));+ };++ const deleteNotifications = useCallback(+ async (notificationIds: NotificationId[]) => {+ const count = notificationIds.length;+ try {+ await bulkAction({+ notification_ids: notificationIds,+ action: "archive",+ }).unwrap();+ dispatch(+ addUndo({+ message:+ count === 1 ? t`Deleted 1 alert` : t`Deleted ${count} alerts`,+ }),+ );+ clearSelected();+ if (+ notificationId !== undefined &&+ notificationIds.includes(notificationId)+ ) {+ dispatch(push(Urls.adminToolsNotifications()));+ }+ } catch {+ dispatch(+ addUndo({+ icon: "warning",+ message: t`Could not delete alerts.`,+ }),+ );+ }+ },+ [bulkAction, clearSelected, dispatch, notificationId],+ );++ const handleDeleteBulk = useCallback(() => {+ const count = selectedNotifications.length;+ showConfirm({+ title: count === 1 ? t`Delete 1 alert?` : t`Delete ${count} alerts?`,+ message: t`Recipients will stop receiving these alerts.`,+ confirmButtonText: t`Delete`,+ confirmButtonProps: { color: "danger" },+ size: "md",+ onConfirm: () =>+ deleteNotifications(selectedNotifications.map((n) => n.id)),+ });+ }, [deleteNotifications, selectedNotifications, showConfirm]);++ const handleSidebarDelete = useCallback(+ (id: NotificationId) => {+ showConfirm({+ title: t`Delete this alert?`,+ message: t`Recipients will stop receiving this alert.`,+ confirmButtonText: t`Delete`,+ confirmButtonProps: { color: "danger" },+ onConfirm: () => deleteNotifications([id]),+ });+ },+ [deleteNotifications, showConfirm],+ );++ const handleChangeOwnerConfirm = useCallback(+ async (creatorId: UserId) => {+ const count = selectedNotifications.length;+ try {+ await bulkAction({+ notification_ids: selectedNotifications.map((n) => n.id),+ action: "change-creator",+ creator_id: creatorId,+ }).unwrap();+ dispatch(+ addUndo({+ message:+ count === 1+ ? t`Changed owner for 1 alert`+ : t`Changed owner for ${count} alerts`,+ }),+ );+ clearSelected();+ setIsChangeOwnerOpened(false);+ } catch {+ dispatch(+ addUndo({+ icon: "warning",+ message: t`Could not change owner.`,+ }),+ );+ }+ },+ [bulkAction, selectedNotifications, clearSelected, dispatch],+ );++ const isSidebarOpen = notificationId !== undefined;++ if (isLoading || isFailingLoading || isOwnerlessLoading) {+ return <LoadingAndErrorWrapper loading />;+ }++ const { prevNotificationId, nextNotificationId, notificationSummary } =+ (() => {+ if (notificationId === undefined) {+ return {+ prevNotificationId: undefined,+ nextNotificationId: undefined,+ notificationSummary: undefined,+ };+ }+ const index = notifications.findIndex((n) => n.id === notificationId);+ if (index === -1) {+ return {+ prevNotificationId: undefined,+ nextNotificationId: undefined,+ notificationSummary: undefined,+ };+ }+ return {+ prevNotificationId: index > 0 ? notifications[index - 1].id : undefined,+ nextNotificationId:+ index < notifications.length - 1+ ? notifications[index + 1].id+ : undefined,+ notificationSummary: notifications[index],+ };+ })();++ return (+ <SettingsPageWrapper pr={isSidebarOpen ? `${SIDEBAR_WIDTH}px` : 0}>+ <Flex align="center" gap="sm">+ <Title order={1}>{t`Alerts management`}</Title>+ </Flex>++ <NotificationsTabs+ tab={urlState.tab}+ failingCount={failingCount}+ ownerlessCount={ownerlessCount}+ onChange={(patch) => patchUrlState({ ...patch, page: 0 })}+ />++ <Flex gap="md" align="center">+ <NotificationsSearchInput+ value={urlState.query}+ isLoading={isFetching}+ onChange={(query) => patchUrlState({ query, page: 0 })}+ />+ <NotificationsFilters state={urlState} onChange={patchUrlState} />+ </Flex>++ <NotificationsTable+ notifications={notifications}+ error={error}+ isLoading={isLoading}+ getSelectionState={getSelectionState}+ selectedDetailId={notificationId}+ sorting={sorting}+ onSortingChange={handleSortingChange}+ onToggleRow={handleToggleRow}+ onToggleAll={handleToggleAll}+ onRowClick={handleRowClick}+ />++ <Flex+ align="center"+ justify="space-between"+ p="md"+ data-testid="notifications-admin-footer"+ >+ <PaginationControls+ page={urlState.page}+ pageSize={PAGE_SIZE}+ itemsLength={notifications.length}+ total={total}+ onPreviousPage={() => patchUrlState({ page: urlState.page - 1 })}+ onNextPage={() => patchUrlState({ page: urlState.page + 1 })}+ />+ </Flex>++ {isSidebarOpen && (+ <NotificationDetailSidebar+ notificationId={notificationId}+ notificationSummary={notificationSummary}+ isBulkLoading={isBulkLoading}+ prevNotificationId={prevNotificationId}+ nextNotificationId={nextNotificationId}+ onClose={handleSidebarClose}+ onDelete={(notification) => handleSidebarDelete(notification.id)}+ />+ )}++ <BulkActionBar+ opened={selectedCount > 0}+ message={+ selectedCount === 1+ ? t`1 alert selected`+ : t`${selectedCount} alerts selected`+ }+ >+ <BulkActionDangerButton+ onClick={handleDeleteBulk}+ disabled={isBulkLoading}+ >+ {t`Delete`}+ </BulkActionDangerButton>+ <BulkActionButton+ onClick={() => setIsChangeOwnerOpened(true)}+ disabled={isBulkLoading}+ >+ {t`Change owner`}+ </BulkActionButton>+ <BulkActionButton onClick={clearSelected}>{t`Clear`}</BulkActionButton>+ </BulkActionBar>++ <ChangeOwnerModal+ key={String(isChangeOwnerOpened)}+ opened={isChangeOwnerOpened}+ notifications={selectedNotifications}+ isSubmitting={isBulkLoading}+ onClose={() => setIsChangeOwnerOpened(false)}+ onConfirm={handleChangeOwnerConfirm}+ />++ {confirmContent}+ </SettingsPageWrapper>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsxnew file mode 100644index 00000000000..d8d6bf59e1b--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.unit.spec.tsx@@ -0,0 +1,733 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";+import { Route } from "react-router";++import {+ findRequests,+ setupCardEndpoints,+ setupCardQueryMetadataEndpoint,+ setupUsersEndpoints,+} from "__support__/server-mocks";+import {+ setupAdminNotificationDetailEndpoint,+ setupBulkNotificationActionEndpoint,+} from "__support__/server-mocks/notification";+import {+ act,+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitFor,+ waitForLoaderToBeRemoved,+ within,+} from "__support__/ui";+import { URL_UPDATE_DEBOUNCE_DELAY } from "metabase/common/hooks/use-url-state";+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";+import type { AdminNotification, UserListResult } from "metabase-types/api";+import {+ createMockAdminNotification,+ createMockCard,+ createMockCardQueryMetadata,+ createMockUserInfo,+ createMockUserListResult,+} from "metabase-types/api/mocks";++import { NotificationsAdminPage } from "./NotificationsAdminPage";+import { PAGE_SIZE } from "./constants";++const PATHNAME = "/admin/tools/notifications";++const ANN = createMockUserInfo({+ id: 1,+ first_name: "Ann",+ last_name: "Admin",+ common_name: "Ann Admin",+});+const BOB = createMockUserInfo({+ id: 2,+ first_name: "Bob",+ last_name: "Boss",+ common_name: "Bob Boss",+});++const notification1 = createMockAdminNotification({ id: 1, creator: ANN });+const notification2 = createMockAdminNotification({ id: 2, creator: BOB });++type SetupOpts = {+ notifications?: AdminNotification[];+ total?: number;+ failingCount?: number;+ ownerlessCount?: number;+ users?: UserListResult[];+ initialRoute?: string;+ cardDelay?: number;+ detailDelay?: number;+};++const setup = ({+ notifications = [notification1],+ total = notifications.length,+ failingCount = 0,+ ownerlessCount = 0,+ users = [],+ initialRoute = PATHNAME,+ cardDelay,+ detailDelay,+}: SetupOpts = {}) => {+ fetchMock.get("path:/api/ee/notifications", (call) => {+ const params = new URL(call.url).searchParams;+ if (+ params.get("limit") === "1" &&+ params.get("last_send_status") === "failing"+ ) {+ return { data: [], total: failingCount, limit: 1, offset: 0 };+ }+ if (params.get("limit") === "1" && params.get("creatorless") === "true") {+ return { data: [], total: ownerlessCount, limit: 1, offset: 0 };+ }+ return { data: notifications, total, limit: PAGE_SIZE, offset: 0 };+ });++ setupBulkNotificationActionEndpoint();+ setupUsersEndpoints(users);++ const card = createMockCard({ id: 1 });+ if (cardDelay !== undefined) {+ fetchMock.get(`path:/api/card/${card.id}`, card, { delay: cardDelay });+ } else {+ setupCardEndpoints(card);+ }+ setupCardQueryMetadataEndpoint(card, createMockCardQueryMetadata());++ notifications.forEach((notification) =>+ detailDelay+ ? setupAdminNotificationDetailEndpoint(+ { ...notification, check_history: [], send_history: [] },+ { delay: detailDelay },+ )+ : setupAdminNotificationDetailEndpoint(notification),+ );++ return renderWithProviders(+ <Route+ path="/admin/tools/notifications(/:notificationId)"+ component={NotificationsAdminPage}+ />,+ { withRouter: true, initialRoute },+ );+};++const getListCalls = () =>+ fetchMock.callHistory+ .calls("path:/api/ee/notifications")+ .filter(+ (call) =>+ new URL(call.url).searchParams.get("limit") === String(PAGE_SIZE),+ );++const getBulkPosts = async () =>+ (await findRequests("POST")).filter((request) =>+ request.url.includes("/api/ee/notifications/bulk"),+ );++describe("NotificationsAdminPage", () => {+ beforeEach(() => {+ jest.useFakeTimers({ advanceTimers: true });+ mockGetBoundingClientRect({ height: 800, width: 1000 });+ });++ afterEach(() => {+ jest.useRealTimers();+ jest.restoreAllMocks();+ });++ describe("rendering", () => {+ it("shows a loader and then renders the table", async () => {+ setup();+ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();+ await waitForLoaderToBeRemoved();+ expect(+ screen.getByTestId("notifications-admin-table"),+ ).toBeInTheDocument();+ });++ it("renders a row per notification with its owner and question", async () => {+ setup({ notifications: [notification1, notification2] });+ await waitForLoaderToBeRemoved();++ const row1 = await screen.findByTestId("notification-row-1");+ const row2 = await screen.findByTestId("notification-row-2");++ expect(within(row1).getByText("Ann Admin")).toBeInTheDocument();+ expect(within(row1).getByText("#1")).toBeInTheDocument();+ expect(within(row2).getByText("Bob Boss")).toBeInTheDocument();+ });++ it("shows an empty state when there are no notifications", async () => {+ setup({ notifications: [] });+ await waitForLoaderToBeRemoved();+ expect(await screen.findByText("No results")).toBeInTheDocument();+ });+ });++ describe("tabs", () => {+ it("hides the tabs when there are no failing or ownerless alerts", async () => {+ setup({ failingCount: 0, ownerlessCount: 0 });+ await waitForLoaderToBeRemoved();+ expect(+ screen.queryByTestId("notifications-admin-tabs"),+ ).not.toBeInTheDocument();+ });++ it("renders failing and ownerless tabs with their counts", async () => {+ setup({ failingCount: 2, ownerlessCount: 3 });+ await waitForLoaderToBeRemoved();++ expect(+ screen.getByTestId("notifications-admin-tab-failing"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("notifications-admin-tab-ownerless"),+ ).toBeInTheDocument();+ });++ it("pushes the selected tab to the URL", async () => {+ const { history } = setup({ failingCount: 2 });+ await waitForLoaderToBeRemoved();++ await userEvent.click(+ screen.getByTestId("notifications-admin-tab-failing"),+ );++ act(() => {+ jest.advanceTimersByTime(URL_UPDATE_DEBOUNCE_DELAY);+ });+ await waitFor(() => {+ expect(history?.getCurrentLocation().search).toContain("tab=failing");+ });+ });++ it("redirects away from an empty failing tab", async () => {+ const { history } = setup({+ failingCount: 0,+ initialRoute: `${PATHNAME}?tab=failing`,+ });+ await waitForLoaderToBeRemoved();++ await waitFor(() => {+ expect(history?.getCurrentLocation().search).not.toContain("failing");+ });+ });+ });++ describe("search, sorting and pagination", () => {+ it("pushes the search query to the URL", async () => {+ const { history } = setup();+ await waitForLoaderToBeRemoved();++ await userEvent.type(+ screen.getByPlaceholderText(/Search by question or owner/),+ "sales",+ );+ act(() => {+ jest.advanceTimersByTime(SEARCH_DEBOUNCE_DURATION);+ });++ await waitFor(() => {+ expect(+ getListCalls().some((call) => call.url.includes("query=sales")),+ ).toBe(true);+ });++ act(() => {+ jest.advanceTimersByTime(URL_UPDATE_DEBOUNCE_DELAY);+ });+ await waitFor(() => {+ expect(history?.getCurrentLocation().search).toContain("query=sales");+ });+ });++ it("pushes sorting changes to the URL and refetches", async () => {+ const { history } = setup();+ await waitForLoaderToBeRemoved();++ await userEvent.click(screen.getByRole("columnheader", { name: "ID" }));++ await waitFor(() => {+ expect(+ getListCalls().some((call) => call.url.includes("sort_column=id")),+ ).toBe(true);+ });++ act(() => {+ jest.advanceTimersByTime(URL_UPDATE_DEBOUNCE_DELAY);+ });+ await waitFor(() => {+ expect(history?.getCurrentLocation().search).toContain(+ "sort_column=id",+ );+ });+ });++ it("paginates and refetches with the next offset", async () => {+ const { history } = setup({+ notifications: [notification1, notification2],+ total: 120,+ });+ await waitForLoaderToBeRemoved();++ const nextPage = screen.getByRole("button", { name: "Next page" });+ expect(nextPage).toBeEnabled();++ await userEvent.click(nextPage);++ await waitFor(() => {+ expect(+ getListCalls().some((call) => call.url.includes("offset=50")),+ ).toBe(true);+ });++ act(() => {+ jest.advanceTimersByTime(URL_UPDATE_DEBOUNCE_DELAY);+ });+ await waitFor(() => {+ expect(history?.getCurrentLocation().search).toContain("page=1");+ });+ });+ });++ describe("selection and bulk actions", () => {+ it("shows the bulk action bar when a row is selected", async () => {+ setup({ notifications: [notification1, notification2] });+ await waitForLoaderToBeRemoved();++ const row1 = await screen.findByTestId("notification-row-1");+ await userEvent.click(within(row1).getByRole("checkbox"));++ const bar = screen.getByTestId("toast-card");+ expect(within(bar).getByText("1 alert selected")).toBeInTheDocument();+ expect(+ within(bar).getByRole("button", { name: "Delete" }),+ ).toBeInTheDocument();+ expect(+ within(bar).getByRole("button", { name: "Change owner" }),+ ).toBeInTheDocument();+ });++ it("selects every row with the header checkbox", async () => {+ setup({ notifications: [notification1, notification2] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(+ screen.getByRole("checkbox", { name: "Select all" }),+ );++ expect(+ within(screen.getByTestId("toast-card")).getByText("2 alerts selected"),+ ).toBeInTheDocument();+ });++ it("clears the selection with the Clear button", async () => {+ setup({ notifications: [notification1, notification2] });+ await waitForLoaderToBeRemoved();++ const row1 = await screen.findByTestId("notification-row-1");+ await userEvent.click(within(row1).getByRole("checkbox"));+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Clear",+ }),+ );++ await waitFor(() => {+ expect(screen.queryByTestId("toast-card")).not.toBeInTheDocument();+ });+ });++ it("clears the selection when navigating to another page", async () => {+ setup({+ notifications: [notification1, notification2],+ total: 120,+ });+ await waitForLoaderToBeRemoved();++ const row1 = await screen.findByTestId("notification-row-1");+ await userEvent.click(within(row1).getByRole("checkbox"));+ expect(screen.getByTestId("toast-card")).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Next page" }));++ await waitFor(() => {+ expect(screen.queryByTestId("toast-card")).not.toBeInTheDocument();+ });+ });++ it("removes selected alerts after confirmation", async () => {+ setup({ notifications: [notification1, notification2] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(+ screen.getByRole("checkbox", { name: "Select all" }),+ );+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Delete",+ }),+ );++ const confirmModal = await screen.findByTestId("confirm-modal");+ await userEvent.click(+ within(confirmModal).getByRole("button", { name: "Delete" }),+ );++ await waitFor(async () => {+ expect(await getBulkPosts()).toHaveLength(1);+ });+ const posts = await getBulkPosts();+ expect(posts[0].body).toEqual({+ notification_ids: [1, 2],+ action: "archive",+ });++ await waitFor(() => {+ expect(screen.queryByTestId("toast-card")).not.toBeInTheDocument();+ });+ });++ it("changes the owner of selected alerts", async () => {+ const newOwner = createMockUserListResult({+ id: 7,+ common_name: "New Owner",+ });+ setup({+ notifications: [notification1, notification2],+ users: [newOwner],+ });+ await waitForLoaderToBeRemoved();++ await userEvent.click(+ screen.getByRole("checkbox", { name: "Select all" }),+ );+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Change owner",+ }),+ );++ const dialog = await screen.findByRole("dialog");+ expect(+ within(dialog).getByText("Select new owner of 2 alerts"),+ ).toBeInTheDocument();++ await userEvent.click(+ within(dialog).getByPlaceholderText("Select a user"),+ );+ await userEvent.click(+ await screen.findByRole("option", { name: "New Owner" }),+ );++ await userEvent.click(+ within(dialog).getByRole("button", { name: "Change owner" }),+ );++ await waitFor(async () => {+ expect(await getBulkPosts()).toHaveLength(1);+ });+ const posts = await getBulkPosts();+ expect(posts[0].body).toEqual({+ notification_ids: [1, 2],+ action: "change-creator",+ creator_id: 7,+ });+ });+ });++ describe("detail sidebar", () => {+ it("opens the sidebar on row click and closes it again", async () => {+ const { history } = setup({ notifications: [notification1] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(await screen.findByTestId("notification-row-1"));++ expect(history?.getCurrentLocation().pathname).toBe(`${PATHNAME}/1`);+ expect(await screen.findByText("Alert 1")).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Close" }));++ await waitFor(() => {+ expect(history?.getCurrentLocation().pathname).toBe(PATHNAME);+ });+ await waitFor(() => {+ expect(screen.queryByText("Alert 1")).not.toBeInTheDocument();+ });+ });++ it("clears the alert id from the URL when the open alert is deleted", async () => {+ const { history } = setup({+ notifications: [notification1, notification2],+ });+ await waitForLoaderToBeRemoved();++ await userEvent.click(await screen.findByTestId("notification-row-1"));+ expect(history?.getCurrentLocation().pathname).toBe(`${PATHNAME}/1`);+ expect(await screen.findByText("Alert 1")).toBeInTheDocument();++ const row1 = await screen.findByTestId("notification-row-1");+ await userEvent.click(within(row1).getByRole("checkbox"));+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Delete",+ }),+ );++ const confirmModal = await screen.findByTestId("confirm-modal");+ await userEvent.click(+ within(confirmModal).getByRole("button", { name: "Delete" }),+ );++ await waitFor(() => {+ expect(history?.getCurrentLocation().pathname).toBe(PATHNAME);+ });+ await waitFor(() => {+ expect(screen.queryByText("Alert 1")).not.toBeInTheDocument();+ });+ });++ it("deletes the open alert from the sidebar menu", async () => {+ const { history } = setup({ notifications: [notification1] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(await screen.findByTestId("notification-row-1"));+ expect(await screen.findByText("Alert 1")).toBeInTheDocument();++ await userEvent.click(+ screen.getByRole("button", { name: "More actions" }),+ );+ await userEvent.click(+ await screen.findByRole("menuitem", { name: /Delete alert/ }),+ );++ const confirmModal = await screen.findByTestId("confirm-modal");+ await userEvent.click(+ within(confirmModal).getByRole("button", { name: "Delete" }),+ );++ await waitFor(async () => {+ expect(await getBulkPosts()).toHaveLength(1);+ });+ const posts = await getBulkPosts();+ expect(posts[0].body).toEqual({+ notification_ids: [1],+ action: "archive",+ });++ await waitFor(() => {+ expect(history?.getCurrentLocation().pathname).toBe(PATHNAME);+ });+ });++ it("copies the alert link to the clipboard from the sidebar menu", async () => {+ setup({ notifications: [notification1] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(await screen.findByTestId("notification-row-1"));+ expect(await screen.findByText("Alert 1")).toBeInTheDocument();++ jest.mocked(navigator.clipboard.writeText).mockClear();++ await userEvent.click(+ screen.getByRole("button", { name: "More actions" }),+ );+ await userEvent.click(+ await screen.findByRole("menuitem", {+ name: /Copy link to clipboard/,+ }),+ );++ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(+ `${window.location.origin}${PATHNAME}/1`,+ );+ });++ it("keeps the edit action disabled until the question has loaded", async () => {+ setup({ notifications: [notification1], cardDelay: 10_000 });+ await waitForLoaderToBeRemoved();++ await userEvent.click(await screen.findByTestId("notification-row-1"));+ expect(await screen.findByText("Alert 1")).toBeInTheDocument();++ expect(screen.getByRole("button", { name: "Edit" })).toBeDisabled();++ act(() => {+ jest.advanceTimersByTime(10_000);+ });++ await waitFor(() => {+ expect(screen.getByRole("button", { name: "Edit" })).toBeEnabled();+ });+ });++ it("points the run-history 'View all' links at the card runs, including today", async () => {+ setup({ notifications: [notification1] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(await screen.findByTestId("notification-row-1"));+ expect(await screen.findByText("Alert 1")).toBeInTheDocument();++ const [viewAll] = screen.getAllByRole("link", { name: "View all" });+ const href = viewAll.getAttribute("href") ?? "";+ const params = new URLSearchParams(href.split("?")[1]);++ expect(params.get("run-type")).toBe("alert");+ expect(params.get("entity-type")).toBe("card");+ expect(params.get("entity-id")).toBe("1");+ expect(params.get("started-at")).toBe("past3months");+ expect(params.get("include-today")).toBe("true");+ });++ it("shows loaders in the history sections while the alert detail loads", async () => {+ setup({ notifications: [notification1], detailDelay: 10_000 });+ await waitForLoaderToBeRemoved();++ await userEvent.click(await screen.findByTestId("notification-row-1"));++ expect(await screen.findByText("Check history")).toBeInTheDocument();+ expect(screen.getByText("Send history")).toBeInTheDocument();+ expect(screen.getAllByTestId("run-summary-loader")).toHaveLength(2);+ expect(+ screen.queryByText("No runs in the past 90 days."),+ ).not.toBeInTheDocument();++ act(() => {+ jest.advanceTimersByTime(10_000);+ });++ await waitFor(() => {+ expect(+ screen.getAllByText("No runs in the past 90 days."),+ ).toHaveLength(2);+ });+ expect(screen.queryAllByTestId("run-summary-loader")).toHaveLength(0);+ });+ });++ describe("change owner modal", () => {+ it("preselects the owner when a single alert is selected", async () => {+ setup({ notifications: [notification1, notification2] });+ await waitForLoaderToBeRemoved();++ const row1 = await screen.findByTestId("notification-row-1");+ await userEvent.click(within(row1).getByRole("checkbox"));+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Change owner",+ }),+ );++ const dialog = await screen.findByRole("dialog");+ expect(+ within(dialog).getByText("Select new owner of 1 alert"),+ ).toBeInTheDocument();+ expect(+ within(dialog).getByRole("button", { name: "Change owner" }),+ ).toBeEnabled();++ await userEvent.click(+ within(dialog).getByPlaceholderText("Select a user"),+ );+ expect(+ await screen.findByRole("option", { name: "Ann Admin" }),+ ).toHaveAttribute("aria-selected", "true");+ });++ it("starts the owner picker from scratch each time it opens", async () => {+ const newOwner = createMockUserListResult({+ id: 7,+ common_name: "New Owner",+ });+ setup({+ notifications: [notification1, notification2],+ users: [newOwner],+ });+ await waitForLoaderToBeRemoved();++ await userEvent.click(+ screen.getByRole("checkbox", { name: "Select all" }),+ );+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Change owner",+ }),+ );++ const dialog = await screen.findByRole("dialog");+ expect(+ within(dialog).getByRole("button", { name: "Change owner" }),+ ).toBeDisabled();++ await userEvent.click(+ within(dialog).getByPlaceholderText("Select a user"),+ );+ await userEvent.click(+ await screen.findByRole("option", { name: "New Owner" }),+ );+ expect(+ within(dialog).getByRole("button", { name: "Change owner" }),+ ).toBeEnabled();++ await userEvent.click(+ within(dialog).getByRole("button", { name: "Cancel" }),+ );+ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Change owner",+ }),+ );++ const reopened = await screen.findByRole("dialog");+ expect(+ within(reopened).getByRole("button", { name: "Change owner" }),+ ).toBeDisabled();+ });++ it("keeps the picked user selected when the dropdown is reopened", async () => {+ const newOwner = createMockUserListResult({+ id: 7,+ common_name: "New Owner",+ });+ setup({+ notifications: [notification1, notification2],+ users: [newOwner],+ });+ await waitForLoaderToBeRemoved();++ await userEvent.click(+ screen.getByRole("checkbox", { name: "Select all" }),+ );+ await userEvent.click(+ within(screen.getByTestId("toast-card")).getByRole("button", {+ name: "Change owner",+ }),+ );++ const dialog = await screen.findByRole("dialog");+ await userEvent.click(+ within(dialog).getByPlaceholderText("Select a user"),+ );+ await userEvent.click(+ await screen.findByRole("option", { name: "New Owner" }),+ );++ await userEvent.click(+ within(dialog).getByPlaceholderText("Select a user"),+ );+ expect(+ await screen.findByRole("option", { name: "New Owner" }),+ ).toHaveAttribute("aria-selected", "true");+ });+ });+});diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/constants.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/constants.tsnew file mode 100644index 00000000000..47db4b04655--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/constants.ts@@ -0,0 +1,44 @@+import type {+ AdminNotificationSortColumn,+ NotificationChannelType,+ NotificationRunStatus,+ SortDirection,+} from "metabase-types/api";++import type { NotificationsTab, TabFilters } from "./types";++export const PAGE_SIZE = 50;++export const DEFAULT_TAB: NotificationsTab = "all";++export const DEFAULT_ACTIVE: boolean | null = true;+export const DEFAULT_SORT_COLUMN: AdminNotificationSortColumn = "last_send";+export const DEFAULT_SORT_DIRECTION: SortDirection = "desc";++export const SORT_COLUMN_VALUES: AdminNotificationSortColumn[] = [+ "id",+ "last_send",+ "last_check",+ "card_name",+ "creator_name",+ "updated_at",+];++export const TAB_FILTERS: Record<NotificationsTab, TabFilters> = {+ all: {},+ failing: { last_send_status: "failing" },+ ownerless: { creatorless: true },+};++export const CHANNEL_VALUES: NotificationChannelType[] = [+ "channel/email",+ "channel/slack",+ "channel/http",+];++export const TAB_VALUES: NotificationsTab[] = ["all", "failing", "ownerless"];++export const LAST_SEND_STATUS_VALUES: NotificationRunStatus[] = [+ "failing",+ "successful",+];diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/index.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/index.tsnew file mode 100644index 00000000000..f580e309dd5--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/index.ts@@ -0,0 +1 @@+export { NotificationsAdminPage } from "./NotificationsAdminPage";diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/types.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/types.tsnew file mode 100644index 00000000000..73997a27b81--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/types.ts@@ -0,0 +1,37 @@+import type {+ AdminNotificationListParams,+ AdminNotificationSortColumn,+ NotificationChannelType,+ NotificationRunStatus,+ SortDirection,+} from "metabase-types/api";++export type RouteParams = {+ notificationId?: string;+};++export type NotificationsTab = "all" | "failing" | "ownerless";++export type NotificationsUrlState = {+ page: number;+ active: boolean | null;+ query: string;+ channel: NotificationChannelType[];+ last_send_status: NotificationRunStatus | null;+ creator_active: boolean | null;+ recipient_email: string;+ tab: NotificationsTab;+ sort_column: AdminNotificationSortColumn;+ sort_direction: SortDirection;+};++export type TabFilters = Partial<+ Pick<AdminNotificationListParams, "last_send_status" | "creatorless">+>;++export type FilterDraft = {+ channel: NotificationChannelType[];+ creator_active: boolean | null;+ last_send_status: NotificationRunStatus | null;+ recipient_email: string;+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/utils.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/utils.tsnew file mode 100644index 00000000000..7998e732e8b--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/utils.ts@@ -0,0 +1,229 @@+import dayjs from "dayjs";+import { match } from "ts-pattern";+import { t } from "ttag";++import type {+ QueryParam,+ UrlStateConfig,+} from "metabase/common/hooks/use-url-state";+import {+ getAllParamValues,+ getFirstParamValue,+} from "metabase/common/hooks/use-url-state";+import type {+ AdminNotificationListParams,+ AdminNotificationSortColumn,+ IconName,+ NotificationChannelType,+ NotificationRunStatus,+} from "metabase-types/api";+import { guardSortDirection } from "metabase-types/api";++import {+ CHANNEL_VALUES,+ DEFAULT_ACTIVE,+ DEFAULT_SORT_COLUMN,+ DEFAULT_SORT_DIRECTION,+ DEFAULT_TAB,+ LAST_SEND_STATUS_VALUES,+ SORT_COLUMN_VALUES,+ TAB_FILTERS,+ TAB_VALUES,+} from "./constants";+import type { NotificationsTab, NotificationsUrlState } from "./types";++const parsePage = (param: QueryParam): number => {+ const value = getFirstParamValue(param);+ const parsed = parseInt(value ?? "0", 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;+};++const parseActive = (param: QueryParam): boolean | null => {+ const value = getFirstParamValue(param);+ if (value === "true") {+ return true;+ }+ if (value === "false") {+ return false;+ }+ if (value === "all") {+ return null;+ }+ return DEFAULT_ACTIVE;+};++const parseQuery = (param: QueryParam): string => {+ const value = getFirstParamValue(param);+ return typeof value === "string" ? value.trim() : "";+};++const parseRecipientEmail = (param: QueryParam): string => {+ const value = getFirstParamValue(param);+ return typeof value === "string" ? value.trim() : "";+};++const serializeActive = (active: boolean | null): string | undefined => {+ if (active === DEFAULT_ACTIVE) {+ return undefined;+ }+ if (active === null) {+ return "all";+ }+ return String(active);+};++const parseGuardedEnum = <T extends string, D extends T | null>(+ valueToParse: string | null | undefined,+ guardFn: (value: string) => value is T,+ defaultValue: D,+): T | D =>+ valueToParse !== null && valueToParse !== undefined && guardFn(valueToParse)+ ? valueToParse+ : defaultValue;++const guardChannel = (value: string): value is NotificationChannelType =>+ (CHANNEL_VALUES satisfies NotificationChannelType[]).includes(+ value as NotificationChannelType,+ );++const parseChannels = (param: QueryParam): NotificationChannelType[] =>+ getAllParamValues(param).filter(guardChannel);++const guardLastSendStatus = (value: string): value is NotificationRunStatus =>+ (LAST_SEND_STATUS_VALUES satisfies NotificationRunStatus[]).includes(+ value as NotificationRunStatus,+ );++const parseLastSendStatusEnum = (+ param: QueryParam,+): NotificationsUrlState["last_send_status"] =>+ parseGuardedEnum(getFirstParamValue(param), guardLastSendStatus, null);++const parseCreatorActive = (param: QueryParam): boolean | null => {+ const value = getFirstParamValue(param);+ if (value === "true") {+ return true;+ }+ if (value === "false") {+ return false;+ }+ return null;+};++const guardTab = (value: string): value is NotificationsTab =>+ (TAB_VALUES satisfies NotificationsTab[]).includes(value as NotificationsTab);++const parseTabEnum = (param: QueryParam): NotificationsTab =>+ parseGuardedEnum(getFirstParamValue(param), guardTab, DEFAULT_TAB);++const guardSortColumn = (value: string): value is AdminNotificationSortColumn =>+ (SORT_COLUMN_VALUES satisfies AdminNotificationSortColumn[]).includes(+ value as AdminNotificationSortColumn,+ );++const parseSortColumnEnum = (+ param: QueryParam,+): NotificationsUrlState["sort_column"] =>+ parseGuardedEnum(+ getFirstParamValue(param),+ guardSortColumn,+ DEFAULT_SORT_COLUMN,+ );++const parseSortDirectionEnum = (+ param: QueryParam,+): NotificationsUrlState["sort_direction"] =>+ parseGuardedEnum(+ getFirstParamValue(param),+ guardSortDirection,+ DEFAULT_SORT_DIRECTION,+ );++export const urlStateConfig: UrlStateConfig<NotificationsUrlState> = {+ parse: (query) => ({+ page: parsePage(query.page),+ active: parseActive(query.active),+ query: parseQuery(query.query),+ channel: parseChannels(query.channel),+ last_send_status: parseLastSendStatusEnum(query.last_send_status),+ creator_active: parseCreatorActive(query.creator_active),+ recipient_email: parseRecipientEmail(query.recipient_email),+ tab: parseTabEnum(query.tab),+ sort_column: parseSortColumnEnum(query.sort_column),+ sort_direction: parseSortDirectionEnum(query.sort_direction),+ }),+ serialize: (state) => ({+ page: state.page === 0 ? undefined : String(state.page),+ active: serializeActive(state.active),+ query: state.query || undefined,+ channel: state.channel.length === 0 ? undefined : state.channel,+ last_send_status: state.last_send_status ?? undefined,+ creator_active:+ state.creator_active === null ? undefined : String(state.creator_active),+ recipient_email: state.recipient_email || undefined,+ tab: state.tab === DEFAULT_TAB ? undefined : state.tab,+ sort_column:+ state.sort_column === DEFAULT_SORT_COLUMN ? undefined : state.sort_column,+ sort_direction:+ state.sort_direction === DEFAULT_SORT_DIRECTION+ ? undefined+ : state.sort_direction,+ }),+};++export const buildListParams = (+ state: NotificationsUrlState,+ pageSize: number,+): AdminNotificationListParams => {+ const tabFilters = TAB_FILTERS[state.tab];+ return {+ limit: pageSize,+ offset: state.page * pageSize,+ active: state.active ?? undefined,+ query: state.query || undefined,+ channel: state.channel.length === 0 ? undefined : state.channel,+ last_send_status:+ tabFilters.last_send_status ?? state.last_send_status ?? undefined,+ creatorless: tabFilters.creatorless,+ creator_active:+ state.tab === "ownerless"+ ? undefined+ : (state.creator_active ?? undefined),+ recipient_email: state.recipient_email || undefined,+ sort_column: state.sort_column,+ sort_direction: state.sort_direction,+ };+};++export const getChannelLabel = (channel: NotificationChannelType): string =>+ match(channel)+ .with("channel/email", () => t`Email`)+ .with("channel/slack", () => t`Slack`)+ .with("channel/http", () => t`Webhook`)+ .exhaustive();++export const getChannelIconName = (+ channel: NotificationChannelType,+): IconName =>+ match(channel)+ .with("channel/email", () => "mail" as const)+ .with("channel/slack", () => "slack" as const)+ .with("channel/http", () => "webhook" as const)+ .exhaustive();++export const formatRelativeDate = (+ value: string | null | undefined,+): string => {+ if (!value) {+ return t`Never`;+ }+ const date = dayjs(value);+ const now = dayjs();+ if (date.isSame(now, "day")) {+ return t`Today, ${date.format("LT")}`;+ }+ if (date.isSame(now.subtract(1, "day"), "day")) {+ return t`Yesterday, ${date.format("LT")}`;+ }+ return date.format("MMM D, LT");+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/utils.unit.spec.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/utils.unit.spec.tsnew file mode 100644index 00000000000..2b65fd10483--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsAdminPage/utils.unit.spec.ts@@ -0,0 +1,267 @@+import dayjs from "dayjs";++import type { NotificationChannelType } from "metabase-types/api";++import { PAGE_SIZE } from "./constants";+import type { NotificationsUrlState } from "./types";+import {+ buildListParams,+ formatRelativeDate,+ getChannelIconName,+ getChannelLabel,+ urlStateConfig,+} from "./utils";++const DEFAULT_STATE: NotificationsUrlState = {+ page: 0,+ active: true,+ query: "",+ channel: [],+ last_send_status: null,+ creator_active: null,+ recipient_email: "",+ tab: "all",+ sort_column: "last_send",+ sort_direction: "desc",+};++const POPULATED_STATE: NotificationsUrlState = {+ page: 2,+ active: false,+ query: "sales",+ channel: ["channel/email", "channel/http"],+ last_send_status: "failing",+ creator_active: false,+ recipient_email: "[email protected]",+ tab: "failing",+ sort_column: "id",+ sort_direction: "asc",+};++describe("NotificationsAdminPage/utils", () => {+ describe("urlStateConfig.parse", () => {+ it("returns defaults for an empty query", () => {+ expect(urlStateConfig.parse({})).toEqual(DEFAULT_STATE);+ });++ it("parses the active param, falling back to the default", () => {+ expect(urlStateConfig.parse({ active: "true" }).active).toBe(true);+ expect(urlStateConfig.parse({ active: "false" }).active).toBe(false);+ expect(urlStateConfig.parse({ active: "all" }).active).toBeNull();+ expect(urlStateConfig.parse({ active: "garbage" }).active).toBe(true);+ });++ it("clamps the page to a non-negative integer", () => {+ expect(urlStateConfig.parse({ page: "3" }).page).toBe(3);+ expect(urlStateConfig.parse({ page: "-1" }).page).toBe(0);+ expect(urlStateConfig.parse({ page: "abc" }).page).toBe(0);+ });++ it("trims free-text params", () => {+ expect(urlStateConfig.parse({ query: " sales " }).query).toBe("sales");+ expect(+ urlStateConfig.parse({ recipient_email: " [email protected] " })+ .recipient_email,+ ).toBe("[email protected]");+ });++ it("keeps only valid channels from a multi-value param", () => {+ expect(+ urlStateConfig.parse({+ channel: ["channel/email", "bogus", "channel/slack"],+ }).channel,+ ).toEqual(["channel/email", "channel/slack"]);+ });++ it("guards enum params against unknown values", () => {+ expect(urlStateConfig.parse({ tab: "failing" }).tab).toBe("failing");+ expect(urlStateConfig.parse({ tab: "bogus" }).tab).toBe("all");++ expect(urlStateConfig.parse({ sort_column: "id" }).sort_column).toBe(+ "id",+ );+ expect(urlStateConfig.parse({ sort_column: "bogus" }).sort_column).toBe(+ "last_send",+ );++ expect(+ urlStateConfig.parse({ sort_direction: "asc" }).sort_direction,+ ).toBe("asc");+ expect(+ urlStateConfig.parse({ sort_direction: "bogus" }).sort_direction,+ ).toBe("desc");++ expect(+ urlStateConfig.parse({ last_send_status: "successful" })+ .last_send_status,+ ).toBe("successful");+ expect(+ urlStateConfig.parse({ last_send_status: "bogus" }).last_send_status,+ ).toBeNull();+ });++ it("parses the creator_active tri-state", () => {+ expect(+ urlStateConfig.parse({ creator_active: "true" }).creator_active,+ ).toBe(true);+ expect(+ urlStateConfig.parse({ creator_active: "false" }).creator_active,+ ).toBe(false);+ expect(urlStateConfig.parse({}).creator_active).toBeNull();+ });+ });++ describe("urlStateConfig.serialize", () => {+ it("omits default values to keep the URL clean", () => {+ expect(urlStateConfig.serialize(DEFAULT_STATE)).toEqual({+ page: undefined,+ active: undefined,+ query: undefined,+ channel: undefined,+ last_send_status: undefined,+ creator_active: undefined,+ recipient_email: undefined,+ tab: undefined,+ sort_column: undefined,+ sort_direction: undefined,+ });+ });++ it("serializes non-default values", () => {+ expect(urlStateConfig.serialize(POPULATED_STATE)).toEqual({+ page: "2",+ active: "false",+ query: "sales",+ channel: ["channel/email", "channel/http"],+ last_send_status: "failing",+ creator_active: "false",+ recipient_email: "[email protected]",+ tab: "failing",+ sort_column: "id",+ sort_direction: "asc",+ });+ });++ it("serializes active=null as 'all'", () => {+ expect(+ urlStateConfig.serialize({ ...DEFAULT_STATE, active: null }).active,+ ).toBe("all");+ });++ it("round-trips a fully populated state", () => {+ expect(+ urlStateConfig.parse(urlStateConfig.serialize(POPULATED_STATE)),+ ).toEqual(POPULATED_STATE);+ });+ });++ describe("buildListParams", () => {+ it("maps a default state to list params", () => {+ expect(buildListParams(DEFAULT_STATE, PAGE_SIZE)).toEqual({+ limit: PAGE_SIZE,+ offset: 0,+ active: true,+ query: undefined,+ channel: undefined,+ last_send_status: undefined,+ creatorless: undefined,+ creator_active: undefined,+ recipient_email: undefined,+ sort_column: "last_send",+ sort_direction: "desc",+ });+ });++ it("derives the offset from the page", () => {+ expect(+ buildListParams({ ...DEFAULT_STATE, page: 2 }, PAGE_SIZE).offset,+ ).toBe(2 * PAGE_SIZE);+ });++ it("maps active=null to undefined", () => {+ expect(+ buildListParams({ ...DEFAULT_STATE, active: null }, PAGE_SIZE).active,+ ).toBeUndefined();+ });++ it("lets the failing tab override last_send_status", () => {+ const params = buildListParams(+ { ...DEFAULT_STATE, tab: "failing", last_send_status: "successful" },+ PAGE_SIZE,+ );+ expect(params.last_send_status).toBe("failing");+ });++ it("pins creatorless on the ownerless tab and suppresses creator_active", () => {+ const params = buildListParams(+ { ...DEFAULT_STATE, tab: "ownerless", creator_active: true },+ PAGE_SIZE,+ );+ expect(params.creatorless).toBe(true);+ expect(params.creator_active).toBeUndefined();+ });++ it("passes filter values through on the all tab", () => {+ const params = buildListParams(+ {+ ...DEFAULT_STATE,+ last_send_status: "successful",+ creator_active: false,+ channel: ["channel/slack"],+ query: "weekly",+ recipient_email: "[email protected]",+ },+ PAGE_SIZE,+ );+ expect(params).toMatchObject({+ last_send_status: "successful",+ creator_active: false,+ channel: ["channel/slack"],+ query: "weekly",+ recipient_email: "[email protected]",+ });+ expect(params.creatorless).toBeUndefined();+ });+ });++ describe("getChannelLabel / getChannelIconName", () => {+ const cases: [NotificationChannelType, string, string][] = [+ ["channel/email", "Email", "mail"],+ ["channel/slack", "Slack", "slack"],+ ["channel/http", "Webhook", "webhook"],+ ];++ it.each(cases)("maps %s to its label and icon", (channel, label, icon) => {+ expect(getChannelLabel(channel)).toBe(label);+ expect(getChannelIconName(channel)).toBe(icon);+ });+ });++ describe("formatRelativeDate", () => {+ it("returns 'Never' for empty values", () => {+ expect(formatRelativeDate(null)).toBe("Never");+ expect(formatRelativeDate(undefined)).toBe("Never");+ expect(formatRelativeDate("")).toBe("Never");+ });++ it("prefixes same-day timestamps with 'Today'", () => {+ const value = dayjs().hour(9).minute(30).second(0).toISOString();+ expect(formatRelativeDate(value).startsWith("Today,")).toBe(true);+ });++ it("prefixes yesterday's timestamps with 'Yesterday'", () => {+ const value = dayjs()+ .subtract(1, "day")+ .hour(9)+ .minute(30)+ .second(0)+ .toISOString();+ expect(formatRelativeDate(value).startsWith("Yesterday,")).toBe(true);+ });++ it("formats older timestamps as an absolute date", () => {+ const value = dayjs().subtract(10, "day").toISOString();+ expect(formatRelativeDate(value)).toBe(dayjs(value).format("MMM D, LT"));+ });+ });+});diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/NotificationsFilters.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/NotificationsFilters.tsxnew file mode 100644index 00000000000..a29cdf76d3f--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/NotificationsFilters.tsx@@ -0,0 +1,235 @@+import type { ReactNode } from "react";+import { useEffect, useState } from "react";+import { t } from "ttag";++import {+ Button,+ Flex,+ Group,+ Icon,+ Indicator,+ Popover,+ Stack,+ Text,+ TextInput,+ UnstyledButton,+} from "metabase/ui";+import type {+ IconName,+ NotificationChannelType,+ NotificationRunStatus,+} from "metabase-types/api";++import { CHANNEL_VALUES } from "../NotificationsAdminPage/constants";+import type {+ FilterDraft,+ NotificationsUrlState,+} from "../NotificationsAdminPage/types";+import {+ getChannelIconName,+ getChannelLabel,+} from "../NotificationsAdminPage/utils";++import { hasActiveFilters, stateToDraft } from "./utils";++type Props = {+ state: NotificationsUrlState;+ onChange: (patch: Partial<NotificationsUrlState>) => void;+};++export const NotificationsFilters = ({ state, onChange }: Props) => {+ const [opened, setOpened] = useState(false);+ const [draft, setDraft] = useState<FilterDraft>(() => stateToDraft(state));+ const hasActive = hasActiveFilters(state);+ const isFailingTab = state.tab === "failing";+ const isOwnerlessTab = state.tab === "ownerless";++ useEffect(() => {+ if (opened) {+ setDraft(stateToDraft(state));+ }+ }, [opened, state]);++ const handleApply = () => {+ onChange({+ channel: draft.channel,+ creator_active: draft.creator_active,+ last_send_status: draft.last_send_status,+ recipient_email: draft.recipient_email.trim(),+ page: 0,+ });+ setOpened(false);+ };++ const handleClear = () => {+ onChange({+ channel: [],+ creator_active: null,+ last_send_status: null,+ recipient_email: "",+ page: 0,+ });+ setOpened(false);+ };++ const toggleChannel = (channel: NotificationChannelType) => {+ setDraft((prev) => ({+ ...prev,+ channel: prev.channel.includes(channel)+ ? prev.channel.filter((c) => c !== channel)+ : [...prev.channel, channel],+ }));+ };++ const toggleCreatorActive = (creatorActive: boolean) => {+ setDraft((prev) => ({+ ...prev,+ creator_active:+ prev.creator_active === creatorActive ? null : creatorActive,+ }));+ };++ const toggleLastSendStatus = (status: NotificationRunStatus) => {+ setDraft((prev) => ({+ ...prev,+ last_send_status: prev.last_send_status === status ? null : status,+ }));+ };++ return (+ <Popover+ position="bottom-end"+ shadow="md"+ withinPortal+ opened={opened}+ onChange={setOpened}+ >+ <Popover.Target>+ <Indicator disabled={!hasActive} size={8} offset={8}>+ <Button+ variant="default"+ leftSection={<Icon name="filter" />}+ aria-label={t`Show filters`}+ onClick={() => setOpened((value) => !value)}+ >+ {t`Filter`}+ </Button>+ </Indicator>+ </Popover.Target>+ <Popover.Dropdown p="lg">+ <Stack gap="xl" w={300}>+ <FilterSection label={t`Channel`}>+ {CHANNEL_VALUES.map((channel) => (+ <FilterPill+ key={channel}+ icon={getChannelIconName(channel)}+ label={getChannelLabel(channel)}+ selected={draft.channel.includes(channel)}+ onClick={() => toggleChannel(channel)}+ />+ ))}+ </FilterSection>++ {!isFailingTab && (+ <FilterSection label={t`Last send attempt`}>+ <FilterPill+ icon="verified_round"+ label={t`Successful`}+ selected={draft.last_send_status === "successful"}+ onClick={() => toggleLastSendStatus("successful")}+ />+ <FilterPill+ icon="warning_round"+ label={t`Failed`}+ selected={draft.last_send_status === "failing"}+ onClick={() => toggleLastSendStatus("failing")}+ />+ </FilterSection>+ )}++ {!isOwnerlessTab && (+ <FilterSection label={t`Owner`}>+ <FilterPill+ icon="person"+ label={t`Active`}+ selected={draft.creator_active === true}+ onClick={() => toggleCreatorActive(true)}+ />+ <FilterPill+ icon="ghost"+ label={t`Deactivated`}+ selected={draft.creator_active === false}+ onClick={() => toggleCreatorActive(false)}+ />+ </FilterSection>+ )}++ <FilterSection label={t`Email recipient`}>+ <TextInput+ w="100%"+ placeholder={t`[email protected]`}+ value={draft.recipient_email}+ onChange={(event) => {+ const value = event.currentTarget.value;+ setDraft((prev) => ({+ ...prev,+ recipient_email: value,+ }));+ }}+ />+ </FilterSection>++ <Group gap="md" grow>+ <Button variant="default" onClick={handleClear}>+ {t`Clear filters`}+ </Button>+ <Button variant="filled" onClick={handleApply}>+ {t`Apply`}+ </Button>+ </Group>+ </Stack>+ </Popover.Dropdown>+ </Popover>+ );+};++type FilterSectionProps = {+ label: string;+ children: ReactNode;+};++const FilterSection = ({ label, children }: FilterSectionProps) => (+ <Stack gap="sm">+ <Text fw="bold" fz="md" c="text-primary">+ {label}+ </Text>+ <Flex gap="sm" wrap="wrap">+ {children}+ </Flex>+ </Stack>+);++type FilterPillProps = {+ icon: IconName;+ label: string;+ selected: boolean;+ onClick: () => void;+};++const FilterPill = ({ icon, label, selected, onClick }: FilterPillProps) => (+ <UnstyledButton+ onClick={onClick}+ bg={selected ? "background-selected" : "background-primary"}+ bd="1px solid var(--mb-color-border)"+ px={12}+ py="sm"+ bdrs="xl"+ >+ <Flex gap="sm" align="center">+ <Icon name={icon} size={16} c="text-secondary" />+ <Text fz="md" c="text-primary" lh="sm">+ {label}+ </Text>+ </Flex>+ </UnstyledButton>+);diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/index.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/index.tsnew file mode 100644index 00000000000..3abee2bcc8a--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/index.ts@@ -0,0 +1 @@+export { NotificationsFilters } from "./NotificationsFilters";diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/utils.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/utils.tsnew file mode 100644index 00000000000..70f41e26d5d--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsFilters/utils.ts@@ -0,0 +1,24 @@+import type {+ FilterDraft,+ NotificationsUrlState,+} from "../NotificationsAdminPage/types";++export const stateToDraft = (state: NotificationsUrlState): FilterDraft => ({+ channel: state.channel,+ creator_active: state.creator_active,+ last_send_status: state.last_send_status,+ recipient_email: state.recipient_email,+});++export const hasActiveFilters = (state: NotificationsUrlState): boolean => {+ if (state.channel.length > 0) {+ return true;+ }+ if (state.tab !== "failing" && state.last_send_status !== null) {+ return true;+ }+ if (state.recipient_email !== "") {+ return true;+ }+ return state.tab !== "ownerless" && state.creator_active !== null;+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsSearchInput/NotificationsSearchInput.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsSearchInput/NotificationsSearchInput.tsxnew file mode 100644index 00000000000..5e7d59d05bb--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsSearchInput/NotificationsSearchInput.tsx@@ -0,0 +1,69 @@+import { useEffect, useRef, useState } from "react";+import { useLatest } from "react-use";+import { t } from "ttag";++import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";+import { Icon, Input, Loader, TextInput } from "metabase/ui";+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";++type Props = {+ value: string;+ isLoading?: boolean;+ onChange: (value: string) => void;+};++export const NotificationsSearchInput = ({+ value,+ isLoading = false,+ onChange,+}: Props) => {+ const [query, setQuery] = useState(value);+ const debounced = useDebouncedValue(query, SEARCH_DEBOUNCE_DURATION);+ const onChangeRef = useLatest(onChange);+ const lastPushedRef = useRef(value);++ useEffect(() => {+ if (debounced !== lastPushedRef.current) {+ lastPushedRef.current = debounced;+ onChangeRef.current(debounced);+ }+ }, [debounced, onChangeRef]);++ useEffect(() => {+ if (value !== lastPushedRef.current) {+ lastPushedRef.current = value;+ setQuery(value);+ }+ }, [value]);++ const showLoader = isLoading || query !== debounced;++ const handleClear = () => {+ setQuery("");+ lastPushedRef.current = "";+ onChangeRef.current("");+ };++ const renderRightSection = () => {+ if (showLoader) {+ return <Loader size="xs" />;+ }+ if (query === "") {+ return null;+ }+ return <Input.ClearButton c="text-secondary" onClick={handleClear} />;+ };++ return (+ <TextInput+ flex={1}+ placeholder={t`Search by question or owner…`}+ value={query}+ radius="md"+ onChange={(event) => setQuery(event.currentTarget.value)}+ leftSection={<Icon c="text-secondary" name="search" size={16} />}+ rightSectionPointerEvents="all"+ rightSection={renderRightSection()}+ />+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsSearchInput/index.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsSearchInput/index.tsnew file mode 100644index 00000000000..64db929edc2--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsSearchInput/index.ts@@ -0,0 +1 @@+export { NotificationsSearchInput } from "./NotificationsSearchInput";diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsTable/NotificationsTable.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsTable/NotificationsTable.tsxnew file mode 100644index 00000000000..b361bc4fcfc--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsTable/NotificationsTable.tsx@@ -0,0 +1,281 @@+import type { Row, SortingState, Updater } from "@tanstack/react-table";+import { useCallback, useEffect, useMemo } from "react";+import { t } from "ttag";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import type { SelectionState, TreeTableColumnDef } from "metabase/ui";+import {+ Badge,+ Card,+ Ellipsified,+ Flex,+ Icon,+ Text,+ Tooltip,+ TreeTable,+ useTreeTableInstance,+} from "metabase/ui";+import { getUserLabel } from "metabase/utils/user";+import type {+ AdminNotification,+ NotificationChannelType,+ NotificationId,+} from "metabase-types/api";++import { NotificationSummary } from "../NotificationSummary";+import {+ getChannelIconName,+ getChannelLabel,+} from "../NotificationsAdminPage/utils";++type Props = {+ notifications: AdminNotification[];+ error: unknown;+ isLoading: boolean;+ getSelectionState: (row: Row<AdminNotification>) => SelectionState;+ selectedDetailId: NotificationId | undefined;+ sorting: SortingState;+ onSortingChange: (sorting: SortingState) => void;+ onToggleRow: (id: NotificationId) => void;+ onToggleAll: () => void;+ onRowClick?: (id: NotificationId) => void;+};++const getNodeId = (notification: AdminNotification) => String(notification.id);++type ChannelSummary = {+ channel: NotificationChannelType;+ count: number;+};++const summarizeChannels = (+ notification: AdminNotification,+): ChannelSummary[] => {+ const handlers = notification.handlers ?? [];+ const map = new Map<NotificationChannelType, number>();+ for (const handler of handlers) {+ const prev = map.get(handler.channel_type) ?? 0;+ map.set(handler.channel_type, prev + handler.recipients.length);+ }+ return Array.from(map.entries()).map(([channel, count]) => ({+ channel,+ count,+ }));+};++export const NotificationsTable = ({+ notifications,+ error,+ isLoading,+ getSelectionState,+ selectedDetailId,+ sorting,+ onSortingChange,+ onToggleRow,+ onToggleAll,+ onRowClick,+}: Props) => {+ const selectedRowId =+ selectedDetailId !== undefined ? String(selectedDetailId) : null;++ const handleSortingChange = useCallback(+ (updater: Updater<SortingState>) => {+ const next = typeof updater === "function" ? updater(sorting) : updater;+ onSortingChange(next);+ },+ [sorting, onSortingChange],+ );++ const handleCheckboxClick = useCallback(+ (row: Row<AdminNotification>) => {+ onToggleRow(row.original.id);+ },+ [onToggleRow],+ );++ const columns = useMemo<TreeTableColumnDef<AdminNotification>[]>(+ () => [+ {+ id: "id",+ header: t`ID`,+ width: 80,+ enableSorting: true,+ accessorFn: (notification) => notification.id,+ cell: ({ row }) => (+ <Flex justify="center">+ <Badge+ variant="default"+ bg="background-secondary"+ c="text-primary"+ tt="none"+ bd="1px solid var(--mb-color-border)"+ h="auto"+ px="sm"+ py="xs"+ fz="md"+ lh="xs"+ fw={400}+ miw={29}+ >+ {row.original.id}+ </Badge>+ </Flex>+ ),+ },+ {+ id: "card_name",+ header: t`Question`,+ minWidth: 200,+ enableSorting: true,+ accessorFn: (notification) => notification.payload?.card?.name ?? "",+ cell: ({ row }) => {+ const card = row.original.payload?.card;+ const cardId = row.original.payload.card_id;+ const name = card?.name ?? `#${cardId}`;+ return <Ellipsified tooltip={name}>{name}</Ellipsified>;+ },+ },+ {+ id: "creator_name",+ header: t`Owner`,+ width: "auto",+ minWidth: 140,+ maxAutoWidth: 320,+ enableSorting: true,+ accessorFn: (notification) =>+ notification.creator?.common_name ??+ notification.creator?.email ??+ "",+ cell: ({ row }) => {+ const creator = row.original.creator;+ const name = getUserLabel(creator);+ const isDeactivated = creator?.is_active === false;+ return (+ <Flex gap="xs" align="center" miw={0}>+ <Ellipsified tooltip={name}>{name}</Ellipsified>+ {isDeactivated && (+ <Tooltip label={t`Deactivated owner`}>+ <Icon name="ghost" size={16} c="text-secondary" />+ </Tooltip>+ )}+ </Flex>+ );+ },+ },+ {+ id: "channel",+ header: t`Channel`,+ width: "auto",+ enableSorting: false,+ accessorFn: (notification) =>+ summarizeChannels(notification)+ .map(({ channel, count }) => `${channel}${count}`)+ .join(" "),+ cell: ({ row }) => {+ const summaries = summarizeChannels(row.original);+ if (summaries.length === 0) {+ return "—";+ }+ return (+ <Flex gap="sm" align="center" wrap="wrap">+ {summaries.map(({ channel, count }) => (+ <Tooltip key={channel} label={getChannelLabel(channel)}>+ <Flex gap="xs" align="center">+ <Icon+ name={getChannelIconName(channel)}+ c="text-secondary"+ size={16}+ />+ <Text size="md" c="text-primary">+ {count}+ </Text>+ </Flex>+ </Tooltip>+ ))}+ </Flex>+ );+ },+ },+ {+ id: "last_check",+ header: t`Last checked`,+ width: 170,+ enableSorting: true,+ sortDescFirst: true,+ accessorFn: (notification) => notification.last_check?.at ?? "",+ cell: ({ row }) => (+ <NotificationSummary run={row.original.last_check} isCompact={true} />+ ),+ },+ {+ id: "last_send",+ header: t`Last send attempt`,+ width: 200,+ enableSorting: true,+ sortDescFirst: true,+ accessorFn: (notification) => notification.last_send?.at ?? "",+ cell: ({ row }) => (+ <NotificationSummary run={row.original.last_send} isCompact={true} />+ ),+ },+ ],+ [],+ );++ const instance = useTreeTableInstance<AdminNotification>({+ data: notifications,+ columns,+ getNodeId,+ sorting,+ manualSorting: true,+ onSortingChange: handleSortingChange,+ selectedRowId,+ });++ const { setActiveRowId } = instance;+ useEffect(() => {+ setActiveRowId(selectedRowId);+ }, [selectedRowId, setActiveRowId]);++ const handleRowClick = useCallback(+ (row: Row<AdminNotification>) => {+ onRowClick?.(row.original.id);+ },+ [onRowClick],+ );++ const getRowProps = useCallback(+ (row: Row<AdminNotification>) => ({+ "data-testid": `notification-row-${row.original.id}`,+ }),+ [],+ );++ if (isLoading || error !== undefined) {+ return (+ <Card withBorder p="lg" data-testid="notifications-admin-table">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Card>+ );+ }++ return (+ <Card withBorder p={0} data-testid="notifications-admin-table">+ <TreeTable+ instance={instance}+ hierarchical={false}+ showCheckboxes+ getSelectionState={getSelectionState}+ onCheckboxClick={handleCheckboxClick}+ onHeaderCheckboxClick={onToggleAll}+ headerCheckboxAriaLabel={t`Select all`}+ ariaLabel={t`Notifications`}+ onRowClick={handleRowClick}+ getRowProps={getRowProps}+ emptyState={+ <Flex c="text-tertiary" justify="center">{t`No results`}</Flex>+ }+ />+ </Card>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsTable/index.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsTable/index.tsnew file mode 100644index 00000000000..ed9fab38100--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsTable/index.ts@@ -0,0 +1 @@+export { NotificationsTable } from "./NotificationsTable";diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/NotificationsTabs.module.css b/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/NotificationsTabs.module.cssnew file mode 100644index 00000000000..675839ba7fd--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/NotificationsTabs.module.css@@ -0,0 +1,31 @@+.list {+ padding: 0;+ gap: var(--mantine-spacing-md);+}++.tab.tab {+ padding: 6px 12px;+ background-color: transparent;+ color: var(--mb-color-text-primary);+ gap: var(--mantine-spacing-sm);++ &:hover {+ background-color: var(--mb-color-background-hover);+ }++ &[data-active="true"] {+ background-color: var(--mb-color-background-selected);+ color: var(--mb-color-brand);+ }+}++.tabLabel {+ font-size: var(--mantine-font-size-md);+ font-weight: bold;+ line-height: 24px;+}++.tabSection[data-position="left"],+.tabSection[data-position="right"] {+ margin-inline: 0;+}diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/NotificationsTabs.tsx b/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/NotificationsTabs.tsxnew file mode 100644index 00000000000..b08c6a534c0--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/NotificationsTabs.tsx@@ -0,0 +1,99 @@+import { t } from "ttag";++import { Icon, Tabs } from "metabase/ui";+import type { IconName } from "metabase-types/api";++import type {+ NotificationsTab,+ NotificationsUrlState,+} from "../NotificationsAdminPage/types";++import S from "./NotificationsTabs.module.css";++type Props = {+ tab: NotificationsTab;+ failingCount: number;+ ownerlessCount: number;+ onChange: (patch: Partial<NotificationsUrlState>) => void;+};++type TabConfig = {+ value: NotificationsTab;+ icon: IconName;+ label: string;+ patch: Partial<NotificationsUrlState>;+};++export const NotificationsTabs = ({+ tab,+ failingCount,+ ownerlessCount,+ onChange,+}: Props) => {+ if (failingCount === 0 && ownerlessCount === 0) {+ return null;+ }++ const tabs: TabConfig[] = [+ {+ value: "all",+ icon: "alert",+ label: t`All alerts`,+ patch: { tab: "all" },+ },+ ];++ if (failingCount > 0) {+ tabs.push({+ value: "failing",+ icon: "warning_round",+ label: t`Failing`,+ patch: { tab: "failing", last_send_status: null },+ });+ }++ if (ownerlessCount > 0) {+ tabs.push({+ value: "ownerless",+ icon: "ghost",+ label: t`Ownerless`,+ patch: { tab: "ownerless", creator_active: null },+ });+ }++ const handleTabChange = (value: string | null) => {+ const next = tabs.find((config) => config.value === value);+ if (next !== undefined) {+ onChange(next.patch);+ }+ };++ return (+ <Tabs+ variant="pills"+ value={tab}+ onChange={handleTabChange}+ radius="xl"+ data-testid="notifications-admin-tabs"+ classNames={{+ list: S.list,+ tab: S.tab,+ tabLabel: S.tabLabel,+ tabSection: S.tabSection,+ }}+ >+ <Tabs.List>+ {tabs.map((config) => (+ <Tabs.Tab+ key={config.value}+ value={config.value}+ leftSection={<Icon name={config.icon} size={16} />}+ data-testid={`notifications-admin-tab-${config.value}`}+ >+ {config.label}+ </Tabs.Tab>+ ))}+ </Tabs.List>+ </Tabs>+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/index.ts b/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/index.tsnew file mode 100644index 00000000000..4f98b44ce87--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/NotificationsTabs/index.ts@@ -0,0 +1 @@+export { NotificationsTabs } from "./NotificationsTabs";diff --git a/frontend/src/metabase/admin/tools/notifications/UserPicker/UserPicker.tsx b/frontend/src/metabase/admin/tools/notifications/UserPicker/UserPicker.tsxnew file mode 100644index 00000000000..24b8c0ef0da--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/UserPicker/UserPicker.tsx@@ -0,0 +1,80 @@+import { useState } from "react";+import { t } from "ttag";++import { useListUsersQuery } from "metabase/api";+import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";+import { Select } from "metabase/ui";+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";++import type { UserOption } from "./types";++type Props = {+ value: UserOption | null;+ onChange: (next: UserOption) => void;+ label?: string;+ placeholder?: string;+ flex?: number | string;+};++export const UserPicker = ({+ value,+ onChange,+ label,+ placeholder,+ flex,+}: Props) => {+ const [search, setSearch] = useState("");+ const debouncedSearch = useDebouncedValue(search, SEARCH_DEBOUNCE_DURATION);+ const trimmedSearch = debouncedSearch.trim();++ // Mantine writes the selected label back into the search input; map that+ // case to an empty query so we show the full list instead of re-searching+ // the BE for the literal selected name (which returns empty for names with+ // spaces).+ const query = value && trimmedSearch === value.label ? "" : trimmedSearch;++ const { data, isFetching } = useListUsersQuery({+ query,+ limit: 50,+ status: "all",+ });++ const fetchedOptions = (data?.data ?? []).map((user) => ({+ value: String(user.id),+ label: user.common_name,+ }));++ const selectedOption = value && {+ value: String(value.id),+ label: value.label,+ };++ const options =+ selectedOption &&+ !fetchedOptions.some((o) => o.value === selectedOption.value)+ ? [selectedOption, ...fetchedOptions]+ : fetchedOptions;++ const handleChange = (next: string | null) => {+ const option = options.find((o) => o.value === next);+ if (option) {+ onChange({ id: Number(option.value), label: option.label });+ }+ };++ return (+ <Select+ flex={flex}+ label={label}+ placeholder={placeholder ?? t`Select a user`}+ data={options}+ value={selectedOption?.value}+ onChange={handleChange}+ searchable+ searchValue={search}+ onSearchChange={setSearch}+ filter={({ options }) => options}+ nothingFoundMessage={isFetching ? t`Searching…` : t`No users found`}+ />+ );+};diff --git a/frontend/src/metabase/admin/tools/notifications/UserPicker/UserPicker.unit.spec.tsx b/frontend/src/metabase/admin/tools/notifications/UserPicker/UserPicker.unit.spec.tsxnew file mode 100644index 00000000000..637d72372b0--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/UserPicker/UserPicker.unit.spec.tsx@@ -0,0 +1,167 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";+import { useState } from "react";++import { setupUsersEndpoints } from "__support__/server-mocks";+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";+import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";+import type { UserListResult } from "metabase-types/api";+import { createMockUserListResult } from "metabase-types/api/mocks";++import { UserPicker } from "./UserPicker";+import type { UserOption } from "./types";++const JANE = createMockUserListResult({+ id: 1,+ first_name: "Jane",+ last_name: "Doe",+ common_name: "Jane Doe",+});++const BOB = createMockUserListResult({+ id: 2,+ first_name: "Bob",+ last_name: "Boss",+ common_name: "Bob Boss",+});++type SetupOpts = {+ users?: UserListResult[];+};++const Wrapper = () => {+ const [value, setValue] = useState<UserOption | null>(null);+ return <UserPicker value={value} onChange={setValue} />;+};++const setup = ({ users = [JANE, BOB] }: SetupOpts = {}) => {+ setupUsersEndpoints(users);+ return renderWithProviders(<Wrapper />);+};++const getUserQueries = () =>+ fetchMock.callHistory+ .calls("path:/api/user")+ .map((call) => new URL(call.url).searchParams.get("query"));++const flushDebounce = () => {+ act(() => {+ jest.advanceTimersByTime(SEARCH_DEBOUNCE_DURATION);+ });+};++describe("UserPicker", () => {+ beforeEach(() => {+ jest.useFakeTimers({ advanceTimers: true });+ });++ afterEach(() => {+ jest.useRealTimers();+ jest.restoreAllMocks();+ });++ it("fetches users with an empty query on initial render", async () => {+ setup();++ await waitFor(() => {+ expect(getUserQueries().length).toBeGreaterThan(0);+ });++ expect(getUserQueries().at(-1)).toBe("");+ });++ it("sends the typed text as the backend query when nothing is selected", async () => {+ setup();+ await waitFor(() => {+ expect(getUserQueries().length).toBeGreaterThan(0);+ });++ await userEvent.click(screen.getByPlaceholderText("Select a user"));+ await userEvent.type(screen.getByPlaceholderText("Select a user"), "ja");+ flushDebounce();++ await waitFor(() => {+ expect(getUserQueries()).toContain("ja");+ });+ });++ it("does not search the BE for the selected user's literal name after selection", async () => {+ setup();+ await waitFor(() => {+ expect(getUserQueries().length).toBeGreaterThan(0);+ });++ await userEvent.click(screen.getByPlaceholderText("Select a user"));+ await userEvent.click(+ await screen.findByRole("option", { name: "Jane Doe" }),+ );+ flushDebounce();++ await waitFor(() => {+ expect(getUserQueries().at(-1)).toBe("");+ });+ expect(getUserQueries()).not.toContain("Jane Doe");+ });++ it("ignores trailing whitespace typed after the selected label", async () => {+ setup();+ await waitFor(() => {+ expect(getUserQueries().length).toBeGreaterThan(0);+ });++ const input = screen.getByPlaceholderText("Select a user");+ await userEvent.click(input);+ await userEvent.click(+ await screen.findByRole("option", { name: "Jane Doe" }),+ );+ flushDebounce();++ await userEvent.type(input, " ");+ flushDebounce();++ await waitFor(() => {+ expect(getUserQueries().at(-1)).toBe("");+ });+ expect(getUserQueries()).not.toContain("Jane Doe ");+ expect(getUserQueries()).not.toContain("Jane Doe");+ });++ it("trims whitespace before sending the typed text to the BE", async () => {+ setup();+ await waitFor(() => {+ expect(getUserQueries().length).toBeGreaterThan(0);+ });++ const input = screen.getByPlaceholderText("Select a user");+ await userEvent.click(input);+ await userEvent.type(input, "Bo ");+ flushDebounce();++ await waitFor(() => {+ expect(getUserQueries()).toContain("Bo");+ });+ expect(getUserQueries()).not.toContain("Bo ");+ });++ it("sends the typed text after clearing and typing a new search", async () => {+ setup();+ await waitFor(() => {+ expect(getUserQueries().length).toBeGreaterThan(0);+ });++ const input = screen.getByPlaceholderText("Select a user");+ await userEvent.click(input);+ await userEvent.click(+ await screen.findByRole("option", { name: "Jane Doe" }),+ );+ flushDebounce();++ await userEvent.clear(input);+ await userEvent.type(input, "Bo");+ flushDebounce();++ await waitFor(() => {+ expect(getUserQueries()).toContain("Bo");+ });+ });+});diff --git a/frontend/src/metabase/admin/tools/notifications/UserPicker/index.ts b/frontend/src/metabase/admin/tools/notifications/UserPicker/index.tsnew file mode 100644index 00000000000..2233fc5833d--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/UserPicker/index.ts@@ -0,0 +1,2 @@+export { UserPicker } from "./UserPicker";+export type { UserOption } from "./types";diff --git a/frontend/src/metabase/admin/tools/notifications/UserPicker/types.ts b/frontend/src/metabase/admin/tools/notifications/UserPicker/types.tsnew file mode 100644index 00000000000..ca48d267b39--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/UserPicker/types.ts@@ -0,0 +1,6 @@+import type { UserId } from "metabase-types/api";++export type UserOption = {+ id: UserId;+ label: string;+};diff --git a/frontend/src/metabase/admin/tools/notifications/routes.tsx b/frontend/src/metabase/admin/tools/notifications/routes.tsxnew file mode 100644index 00000000000..9f06ffd0a65--- /dev/null+++ b/frontend/src/metabase/admin/tools/notifications/routes.tsx@@ -0,0 +1,10 @@+import { IndexRoute, Route } from "react-router";++import { NotificationsAdminPage } from "./NotificationsAdminPage";++export const getRoutes = () => (+ <>+ <IndexRoute component={NotificationsAdminPage} />+ <Route path=":notificationId" component={NotificationsAdminPage} />+ </>+);diff --git a/frontend/src/metabase/admin/tools/routes.tsx b/frontend/src/metabase/admin/tools/routes.tsxindex 097af1e873e..e91f94d8d58 100644--- a/frontend/src/metabase/admin/tools/routes.tsx+++ b/frontend/src/metabase/admin/tools/routes.tsx@@ -14,3 +14,5 @@ export const getTasksRoutes = () => (<Route path="runs/:runId" component={TaskRunDetailsPage} /></>);++export { getRoutes as getNotificationsRoutes } from "./notifications/routes";diff --git a/frontend/src/metabase/admin/tools/utils.ts b/frontend/src/metabase/admin/tools/utils.tsindex b509df597ad..f4ef5da414d 100644--- a/frontend/src/metabase/admin/tools/utils.ts+++ b/frontend/src/metabase/admin/tools/utils.ts@@ -7,6 +7,7 @@ import type {TaskRun,TaskRunDateFilterOption,TaskRunEntityType,+ TaskRunStartedAtParam,TaskRunStatus,TaskRunType,TaskStatus,@@ -105,6 +106,18 @@ export const guardTaskRunStatus = (value: string): value is TaskRunStatus =>["started", "success", "failed", "abandoned"] satisfies TaskRunStatus[]).includes(value as TaskRunStatus);+export const toBackendStartedAt = (+ value: TaskRunDateFilterOption | null,+ includeToday: boolean,+): TaskRunStartedAtParam | undefined => {+ if (!value) {+ return undefined;+ }+ // A trailing "~" makes the date range open-ended on the upper bound,+ // extending it through today so the current day's runs are included.+ return includeToday ? `${value}~` : value;+};+export const guardTaskRunStartedAtRange = (value: string,): value is TaskRunDateFilterOption =>diff --git a/frontend/src/metabase/api/notification.ts b/frontend/src/metabase/api/notification.tsindex e25c767ba96..fea9922b88d 100644--- a/frontend/src/metabase/api/notification.ts+++ b/frontend/src/metabase/api/notification.ts@@ -1,4 +1,8 @@import type {+ AdminNotificationDetail,+ AdminNotificationListParams,+ AdminNotificationListResponse,+ BulkNotificationPayload,CreateNotificationRequest,ListNotificationsRequest,Notification,@@ -8,9 +12,12 @@ import type {import { Api } from "./api";import {+ adminNotificationListTag,idTag,invalidateTags,listTag,+ provideAdminNotificationListTags,+ provideAdminNotificationTags,provideNotificationListTags,provideNotificationTags,} from "./tags";@@ -46,8 +53,11 @@ export const notificationApi = Api.injectEndpoints({url: "/api/notification",body,}),- invalidatesTags: (notification, error) =>- invalidateTags(error, [listTag("notification")]),+ invalidatesTags: (_notification, error) =>+ invalidateTags(error, [+ listTag("notification"),+ adminNotificationListTag(),+ ]),}),updateNotification: builder.mutation<Notification,@@ -61,6 +71,7 @@ export const notificationApi = Api.injectEndpoints({invalidatesTags: (notification, error) =>invalidateTags(error, [listTag("notification"),+ adminNotificationListTag(),...(notification ? [idTag("notification", notification.id)] : []),]),}),@@ -87,6 +98,48 @@ export const notificationApi = Api.injectEndpoints({body,}),}),+ adminListNotifications: builder.query<+ AdminNotificationListResponse,+ AdminNotificationListParams | void+ >({+ query: (params) => ({+ method: "GET",+ url: "/api/ee/notifications",+ params: params ?? undefined,+ }),+ providesTags: (result) =>+ result+ ? provideAdminNotificationListTags(result.data)+ : [adminNotificationListTag()],+ }),+ bulkNotificationAction: builder.mutation<+ { updated: number },+ BulkNotificationPayload+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/ee/notifications/bulk",+ body,+ }),+ invalidatesTags: (_result, error, { notification_ids }) =>+ invalidateTags(+ error,+ provideAdminNotificationListTags(+ notification_ids.map((id) => ({ id })),+ ),+ ),+ }),+ adminNotificationDetail: builder.query<+ AdminNotificationDetail,+ NotificationId+ >({+ query: (id) => ({+ method: "GET",+ url: `/api/ee/notifications/${id}`,+ }),+ providesTags: (result) =>+ result ? provideAdminNotificationTags(result) : [],+ }),}),});@@ -101,4 +154,7 @@ export const {useUpdateNotificationMutation,useUnsubscribeFromNotificationMutation,useSendUnsavedNotificationMutation,+ useAdminListNotificationsQuery,+ useBulkNotificationActionMutation,+ useAdminNotificationDetailQuery,} = notificationApi;diff --git a/frontend/src/metabase/api/tags/utils.ts b/frontend/src/metabase/api/tags/utils.tsindex acb86a8b2d1..e036c5a4f58 100644--- a/frontend/src/metabase/api/tags/utils.ts+++ b/frontend/src/metabase/api/tags/utils.ts@@ -63,7 +63,10 @@ import {SEARCH_MODELS,} from "metabase-types/api";import type { CloudMigration } from "metabase-types/api/cloud-migration";-import type { Notification } from "metabase-types/api/notification";+import type {+ AdminNotification,+ Notification,+} from "metabase-types/api/notification";import { getLensKey } from "../utils/transform-inspector-lens";@@ -463,6 +466,25 @@ export function provideNotificationTags(];}+export const provideAdminNotificationTags = (+ notification: Pick<AdminNotification, "id" | "creator">,+): TagDescription<TagType>[] => [+ idTag("notification", notification.id),+ ...(notification.creator ? provideUserTags(notification.creator) : []),+];++export const adminNotificationListTag = (): TagDescription<TagType> =>+ idTag("notification", "LIST-ADMIN");++export const provideAdminNotificationListTags = (+ notifications: Pick<Notification, "id">[],+): TagDescription<TagType>[] => [+ adminNotificationListTag(),+ ...notifications.map((notification) =>+ idTag("notification", notification.id),+ ),+];+export function providePermissionsGroupListTags(groups: GroupListQuery[],): TagDescription<TagType>[] {diff --git a/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.styled.tsx b/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.styled.tsxindex f78e669a8c1..15563fd7049 100644--- a/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.styled.tsx+++ b/frontend/src/metabase/common/components/BulkActionBar/BulkActionBar.styled.tsx@@ -12,6 +12,7 @@ export const BulkActionsToast = styled.div<{ isNavbarOpen: boolean }>`props.isNavbarOpen ? `${parseInt(NAV_SIDEBAR_WIDTH) / 2}px` : "0"};margin-bottom: var(--mantine-spacing-md);transform: translateX(-50%);+ z-index: 150;`;export const ToastCard = styled(Card)`diff --git a/frontend/src/metabase/common/hooks/use-url-state/utils.ts b/frontend/src/metabase/common/hooks/use-url-state/utils.tsindex 4c33c7c914e..2f6d93592a9 100644--- a/frontend/src/metabase/common/hooks/use-url-state/utils.ts+++ b/frontend/src/metabase/common/hooks/use-url-state/utils.ts@@ -3,3 +3,10 @@ import type { QueryParam } from "./types";export function getFirstParamValue(param: QueryParam) {return Array.isArray(param) ? param[0] : param;}++export const getAllParamValues = (param: QueryParam): string[] => {+ if (Array.isArray(param)) {+ return param.filter((v): v is string => typeof v === "string");+ }+ return typeof param === "string" ? [param] : [];+};diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsxindex a9eea563de7..92a2f1b723b 100644--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.tsx@@ -28,7 +28,11 @@ import {} from "metabase/query_builder/selectors";import { useDispatch, useSelector } from "metabase/redux";import { addUndo } from "metabase/redux/undo";-import { canAccessSettings, getUser } from "metabase/selectors/user";+import {+ canAccessSettings,+ getUser,+ getUserIsAdmin,+} from "metabase/selectors/user";import {Button,Flex,@@ -43,6 +47,7 @@ import {import { getResponseErrorMessage } from "metabase/utils/errors";import type Question from "metabase-lib/v1/Question";import type {+ AdminNotification,CreateAlertNotificationRequest,Notification,NotificationCardSendCondition,@@ -50,6 +55,7 @@ import type {NotificationHandler,ScheduleType,UpdateAlertNotificationRequest,+ UserId,} from "metabase-types/api";import { ChannelSetupModal } from "../ChannelSetupModal";@@ -57,6 +63,7 @@ import { NotificationChannelsPicker } from "../components/NotificationChannelsPiimport { AlertTriggerIcon } from "./AlertTriggerIcon";import { AlertModalSettingsBlock } from "./components/AlertModalSettingsBlock/AlertModalSettingsBlock";+import { NotificationOwner } from "./components/NotificationOwner/NotificationOwner";import { NotificationSchedule } from "./components/NotificationSchedule/NotificationSchedule";import type { NotificationTriggerOption } from "./types";@@ -93,6 +100,7 @@ const ALERT_SCHEDULE_OPTIONS: ScheduleType[] = [type CreateOrEditQuestionAlertModalWithQuestionProps = {onClose: () => void;+ skipUrlUpdate?: boolean;} & (| {editingNotification?: undefined;@@ -100,7 +108,7 @@ type CreateOrEditQuestionAlertModalWithQuestionProps = {onAlertUpdated?: () => void;}| {- editingNotification: Notification;+ editingNotification: Notification | AdminNotification;onAlertUpdated: () => void;onAlertCreated?: () => void;}@@ -116,6 +124,7 @@ export const CreateOrEditQuestionAlertModalWithQuestion = ({onAlertCreated,onAlertUpdated,onClose,+ skipUrlUpdate,}: CreateOrEditQuestionAlertModalWithQuestionProps) => {const question = useSelector(getQuestion);@@ -126,6 +135,7 @@ export const CreateOrEditQuestionAlertModalWithQuestion = ({editingNotification={editingNotification}onAlertUpdated={onAlertUpdated}onClose={onClose}+ skipUrlUpdate={skipUrlUpdate}/>);} else {@@ -134,6 +144,7 @@ export const CreateOrEditQuestionAlertModalWithQuestion = ({question={question}onAlertCreated={onAlertCreated}onClose={onClose}+ skipUrlUpdate={skipUrlUpdate}/>);}@@ -145,11 +156,13 @@ export const CreateOrEditQuestionAlertModal = ({onAlertUpdated,onClose,question,+ skipUrlUpdate,}: CreateOrEditQuestionAlertModalProps) => {const dispatch = useDispatch();const visualizationSettings = useSelector(getVisualizationSettings);const user = useSelector(getUser);const userCanAccessSettings = useSelector(canAccessSettings);+ const isAdmin = useSelector(getUserIsAdmin);const [notification, setNotification] = useState<CreateAlertNotificationRequest | UpdateAlertNotificationRequest | null@@ -211,6 +224,12 @@ export const CreateOrEditQuestionAlertModal = ({userCanAccessSettings,]);+ const handleOwnerChange = (creatorId: UserId) => {+ if (notification) {+ setNotification({ ...notification, creator_id: creatorId });+ }+ };+const onCreateOrEditAlert = async () => {if (notification) {let result;@@ -252,7 +271,9 @@ export const CreateOrEditQuestionAlertModal = ({onAlertCreated();}- await dispatch(updateUrl(question, { dirty: false }));+ if (!skipUrlUpdate) {+ await dispatch(updateUrl(question, { dirty: false }));+ }}};@@ -403,6 +424,15 @@ export const CreateOrEditQuestionAlertModal = ({</AlertModalSettingsBlock>)}+ {isEditMode && isAdmin && editingNotification && (+ <AlertModalSettingsBlock title={t`Who owns this alert?`}>+ <NotificationOwner+ editingNotification={editingNotification}+ onChange={handleOwnerChange}+ />+ </AlertModalSettingsBlock>+ )}+<AlertModalSettingsBlock title={t`More options`}><Switchlabel={t`Delete this Alert after it's triggered`}diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsxindex 316c4fa90cd..44ef705a2d0 100644--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx@@ -5,6 +5,7 @@ import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";import {setupNotificationChannelsEndpoints,setupUserRecipientsEndpoint,+ setupUsersEndpoints,} from "__support__/server-mocks";import { setupWebhookChannelsEndpoint } from "__support__/server-mocks/channel";import { mockSettings } from "__support__/settings";@@ -16,11 +17,14 @@ import type {ChannelApiResponse,Notification,NotificationChannel,+ UserListResult,} from "metabase-types/api";import {createMockCard,createMockTokenFeatures,createMockUser,+ createMockUserInfo,+ createMockUserListResult,createMockVisualizationSettings,} from "metabase-types/api/mocks";import { createMockChannel } from "metabase-types/api/mocks/channel";@@ -446,6 +450,87 @@ describe("CreateOrEditQuestionAlertModalWithQuestion", () => {expect(onAlertUpdatedMock).toHaveBeenCalledTimes(1);});++ const OWNER_BLOCK_TITLE = /who owns this alert\?/i;++ it("should not show the owner picker when creating a new alert", async () => {+ setup({ isAdmin: true, isEmailSetup: true });++ expect(await screen.findByText("New alert")).toBeInTheDocument();+ expect(screen.queryByText(OWNER_BLOCK_TITLE)).not.toBeInTheDocument();+ });++ it("should not show the owner picker for non-admins editing an alert", async () => {+ setup({+ isAdmin: false,+ userCanAccessSettings: true,+ isEmailSetup: true,+ editingNotification: createMockNotification(),+ });++ expect(await screen.findByText("Edit alert")).toBeInTheDocument();+ expect(screen.queryByText(OWNER_BLOCK_TITLE)).not.toBeInTheDocument();+ });++ it("should show the current owner when an admin edits an alert", async () => {+ setup({+ isAdmin: true,+ isEmailSetup: true,+ editingNotification: createMockNotification({+ creator_id: 3,+ creator: createMockUserInfo({ common_name: "Ann Admin" }),+ }),+ });++ expect(await screen.findByText(OWNER_BLOCK_TITLE)).toBeInTheDocument();+ expect(screen.getByPlaceholderText("Select a user")).toHaveValue(+ "Ann Admin",+ );+ });++ it("should send the new creator_id when an admin changes the owner", async () => {+ const notificationId = 42;+ fetchMock.putOnce(`path:/api/notification/${notificationId}`, {+ body: { id: notificationId },+ });++ const newOwner = createMockUserListResult({+ id: 7,+ common_name: "New Owner",+ });++ setup({+ isAdmin: true,+ isEmailSetup: true,+ users: [newOwner],+ editingNotification: createMockNotification({+ id: notificationId,+ creator_id: 3,+ creator: createMockUserInfo({ common_name: "Ann Admin" }),+ }),+ });++ await screen.findByText("Edit alert");++ await userEvent.click(screen.getByPlaceholderText("Select a user"));+ await userEvent.click(+ await screen.findByRole("option", { name: "New Owner" }),+ );++ await userEvent.click(+ await screen.findByRole("button", { name: /save changes/i }),+ );++ const calls = fetchMock.callHistory.calls(+ `path:/api/notification/${notificationId}`,+ );+ expect(calls.length).toBe(1);++ await waitFor(async () => {+ const requestBody = await calls[0].options?.body;+ expect(JSON.parse(requestBody as string).creator_id).toBe(7);+ });+ });});function setup({@@ -459,6 +544,7 @@ function setup({onAlertCreatedMock = jest.fn(),onAlertUpdatedMock = jest.fn(),cardType = "question",+ users = [],}: {userCanAccessSettings?: boolean;isAdmin?: boolean;@@ -470,6 +556,7 @@ function setup({onAlertCreatedMock?: jest.Mock;onAlertUpdatedMock?: jest.Mock;cardType?: "question" | "model" | "metric";+ users?: UserListResult[];}) {const settings = mockSettings({"token-features": createMockTokenFeatures({@@ -497,6 +584,7 @@ function setup({setupWebhookChannelsEndpoint(webhooksResult);setupUserRecipientsEndpoint({ users: [] });+ setupUsersEndpoints(users);const currentUser = createMockUser(isAdmin ? { is_superuser: true } : undefined,diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationOwner/NotificationOwner.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationOwner/NotificationOwner.tsxnew file mode 100644index 00000000000..45137c55c34--- /dev/null+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/components/NotificationOwner/NotificationOwner.tsx@@ -0,0 +1,50 @@+import { useState } from "react";+import { t } from "ttag";++import type { UserOption } from "metabase/admin/tools/notifications/UserPicker";+import { UserPicker } from "metabase/admin/tools/notifications/UserPicker";+import { Flex, Text } from "metabase/ui";+import { getUserLabel } from "metabase/utils/user";+import type {+ AdminNotification,+ Notification,+ UserId,+} from "metabase-types/api";++type Props = {+ editingNotification: Notification | AdminNotification;+ onChange: (creatorId: UserId) => void;+};++export const NotificationOwner = ({ editingNotification, onChange }: Props) => {+ const [selected, setSelected] = useState<UserOption | null>(() =>+ buildInitialOwnerOption(editingNotification),+ );++ const handleChange = (next: UserOption) => {+ setSelected(next);+ onChange(next.id);+ };++ return (+ <Flex align="center" gap="md">+ <Text fw="bold" size="md" c="text-primary" w={56}>+ {t`Owner`}+ </Text>+ <UserPicker flex={1} value={selected} onChange={handleChange} />+ </Flex>+ );+};++const buildInitialOwnerOption = (+ notification: Notification | AdminNotification,+): UserOption | null => {+ const { creator, creator_id } = notification;+ if (!creator || creator_id === null || creator_id === undefined) {+ return null;+ }+ return {+ id: creator_id,+ label: getUserLabel(creator),+ };+};diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.ts b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.tsindex 4953a5ea318..eaf190d9906 100644--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.ts+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/index.ts@@ -2,3 +2,4 @@ export {CreateOrEditQuestionAlertModal,CreateOrEditQuestionAlertModalWithQuestion,} from "./CreateOrEditQuestionAlertModal";+export { AlertModalSettingsBlock } from "./components/AlertModalSettingsBlock/AlertModalSettingsBlock";diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/SelectionCheckbox/SelectionCheckbox.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/SelectionCheckbox/SelectionCheckbox.tsxindex 09a2fe101c7..4b718ee3807 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/SelectionCheckbox/SelectionCheckbox.tsx+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/SelectionCheckbox/SelectionCheckbox.tsx@@ -20,6 +20,7 @@ export function SelectionCheckbox({disabled,onClick,className,+ ariaLabel,}: SelectionCheckboxProps) {return (<Checkbox@@ -30,7 +31,7 @@ export function SelectionCheckbox({className={className}readOnlyonClick={onClick}- aria-label={getAriaLabel(isSelected, isSomeSelected)}+ aria-label={ariaLabel ?? getAriaLabel(isSelected, isSomeSelected)}/>);}diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsxindex 92a861ec0a2..2dcfc312cc2 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsx+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.tsx@@ -33,6 +33,8 @@ export function TreeTable<TData extends TreeNodeData>({onRowDoubleClick,getSelectionState,onCheckboxClick,+ onHeaderCheckboxClick,+ headerCheckboxAriaLabel,isChildrenLoading,isRowDisabled,getRowProps,@@ -209,6 +211,9 @@ export function TreeTable<TData extends TreeNodeData>({styles={styles}isMeasured={isMeasured}totalContentWidth={totalContentWidth}+ getSelectionState={getSelectionState}+ onHeaderCheckboxClick={onHeaderCheckboxClick}+ headerCheckboxAriaLabel={headerCheckboxAriaLabel}/>{topPinnedRows.length > 0 && (<Boxdiff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsxindex 2f59961569c..4c042bd389a 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsx+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableHeader/TreeTableHeader.tsx@@ -3,8 +3,13 @@ import cx from "classnames";import { Flex } from "metabase/ui";+import { SelectionCheckbox } from "../SelectionCheckbox";import { CHECKBOX_COLUMN_WIDTH } from "../constants";-import type { TreeNodeData, TreeTableHeaderProps } from "../types";+import type {+ SelectionState,+ TreeNodeData,+ TreeTableHeaderProps,+} from "../types";import { getColumnStyle } from "../utils";import { HeaderCell } from "./HeaderCell";@@ -18,8 +23,35 @@ export function TreeTableHeader<TData extends TreeNodeData>({styles,isMeasured = true,headerVariant = "pill",+ getSelectionState,+ onHeaderCheckboxClick,+ headerCheckboxAriaLabel,}: TreeTableHeaderProps<TData>) {const headerGroups = table.getHeaderGroups();+ const rows = table.getRowModel().rows;++ const headerSelectionState: SelectionState = (() => {+ if (rows.length === 0) {+ return "none";+ }+ if (getSelectionState) {+ const states = rows.map(getSelectionState);+ if (states.every((s) => s === "all")) {+ return "all";+ }+ if (states.some((s) => s !== "none")) {+ return "some";+ }+ return "none";+ }+ if (table.getIsAllRowsSelected()) {+ return "all";+ }+ if (table.getIsSomeRowsSelected()) {+ return "some";+ }+ return "none";+ })();return (<Flex@@ -39,9 +71,23 @@ export function TreeTableHeader<TData extends TreeNodeData>({<FlexclassName={cx(S.cell, classNames?.headerCell)}align="center"- p="0.75rem"- style={{ width: CHECKBOX_COLUMN_WIDTH, ...styles?.headerCell }}- />+ pl="0.75rem"+ style={{+ width: CHECKBOX_COLUMN_WIDTH,+ flexShrink: 0,+ ...styles?.headerCell,+ }}+ >+ {onHeaderCheckboxClick && (+ <SelectionCheckbox+ isSelected={headerSelectionState === "all"}+ isSomeSelected={headerSelectionState === "some"}+ onClick={onHeaderCheckboxClick}+ ariaLabel={headerCheckboxAriaLabel}+ className={classNames?.checkbox}+ />+ )}+ </Flex>)}{headerGroup.headers.map((header, index) => {const column = header.column;diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/types.ts b/frontend/src/metabase/ui/components/data-display/TreeTable/types.tsindex 48bd3d9568d..2c3baf907f6 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/types.ts+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/types.ts@@ -232,6 +232,18 @@ export interface TreeTableProps<*/onCheckboxClick?: (row: Row<TData>, index: number, event: MouseEvent) => void;+ /**+ * Click handler for the header "select all" checkbox. When provided+ * (and `showCheckboxes` is true), TreeTable renders a tri-state checkbox+ * in the header's checkbox column. Its state is inferred from the visible+ * rows via `getSelectionState` (or TanStack's built-in row selection when+ * `getSelectionState` is omitted).+ */+ onHeaderCheckboxClick?: (event: MouseEvent) => void;++ /** Custom aria-label for the header "select all" checkbox. */+ headerCheckboxAriaLabel?: string;+/*** Callback to determine if a row's children are currently loading.* When true, shows a loading spinner instead of expand button.@@ -312,6 +324,9 @@ export interface TreeTableHeaderProps<isMeasured?: boolean;totalContentWidth?: number;headerVariant?: TreeTableHeaderVariant;+ getSelectionState?: (row: Row<TData>) => SelectionState;+ onHeaderCheckboxClick?: (event: MouseEvent) => void;+ headerCheckboxAriaLabel?: string;}/**@@ -334,4 +349,5 @@ export interface SelectionCheckboxProps {disabled?: boolean;onClick: (event: MouseEvent) => void;className?: string;+ ariaLabel?: string;}diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.tsindex 2b4d5043db4..7cbe60625b8 100644--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts@@ -564,6 +564,8 @@ import view_archive_component from "./view_archive.svg?component";import view_archive_source from "./view_archive.svg?source";import warning_component from "./warning.svg?component";import warning_source from "./warning.svg?source";+import warning_round_component from "./warning_round.svg?component";+import warning_round_source from "./warning_round.svg?source";import warning_round_filled_component from "./warning_round_filled.svg?component";import warning_round_filled_source from "./warning_round_filled.svg?source";import warning_triangle_filled_component from "./warning_triangle_filled.svg?component";@@ -1695,6 +1697,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =component: warning_component,source: warning_source,},+ warning_round: {+ component: warning_round_component,+ source: warning_round_source,+ },warning_round_filled: {component: warning_round_filled_component,source: warning_round_filled_source,diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/warning_round.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/warning_round.svgnew file mode 100644index 00000000000..c13887e4ddc--- /dev/null+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/warning_round.svg@@ -0,0 +1,5 @@+<svg viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">+ <path d="M8 8.24994C7.58579 8.24994 7.25 7.91415 7.25 7.49994V4.49994C7.25 4.08573 7.58579 3.74994 8 3.74994C8.41421 3.74994 8.75 4.08573 8.75 4.49994V7.49994C8.75 7.91415 8.41421 8.24994 8 8.24994Z" />+ <path d="M7 10.5C7 9.94771 7.44772 9.5 8 9.5C8.55228 9.5 9 9.94772 9 10.5C9 11.0523 8.55228 11.5 8 11.5C7.44772 11.5 7 11.0523 7 10.5Z" />+ <path fill-rule="evenodd" clip-rule="evenodd" d="M8 1.25C4.27208 1.25 1.25 4.27208 1.25 8C1.25 11.7279 4.27208 14.75 8 14.75C11.7279 14.75 14.75 11.7279 14.75 8C14.75 4.27208 11.7279 1.25 8 1.25ZM2.75 8C2.75 5.10051 5.10051 2.75 8 2.75C10.8995 2.75 13.25 5.10051 13.25 8C13.25 10.8995 10.8995 13.25 8 13.25C5.10051 13.25 2.75 10.8995 2.75 8Z" />+</svg>diff --git a/frontend/src/metabase/urls/admin.ts b/frontend/src/metabase/urls/admin.tsindex 8206efbf9af..7db51e78e75 100644--- a/frontend/src/metabase/urls/admin.ts+++ b/frontend/src/metabase/urls/admin.ts@@ -6,6 +6,9 @@ import type {SchemaName,SegmentId,TableId,+ TaskRunDateFilterOption,+ TaskRunEntityType,+ TaskRunType,} from "metabase-types/api";export const isInternalUser = (user: Pick<BaseUser, "tenant_id">) =>@@ -183,6 +186,27 @@ export function adminToolsTaskRunDetails(runId: number) {return `${adminToolsTasksRuns()}/${runId}`;}+export function adminToolsTasksRunsFor(opts: {+ runType: TaskRunType;+ entityType: TaskRunEntityType;+ entityId: number;+ startedAt?: TaskRunDateFilterOption;+ includeToday?: boolean;+}) {+ const params: Record<string, string> = {+ "run-type": opts.runType,+ "entity-type": opts.entityType,+ "entity-id": String(opts.entityId),+ };+ if (opts.startedAt) {+ params["started-at"] = opts.startedAt;+ }+ if (opts.includeToday) {+ params["include-today"] = "true";+ }+ return `${adminToolsTasksRuns()}?${new URLSearchParams(params).toString()}`;+}+export function adminToolsJobs() {return "/admin/tools/jobs";}@@ -202,3 +226,11 @@ export function adminToolsModelCaching() {export function adminToolsGrantAccess() {return "/admin/tools/help/grant-access";}++export function adminToolsNotifications() {+ return "/admin/tools/notifications";+}++export function adminToolsNotificationDetail(id: number) {+ return `/admin/tools/notifications/${id}`;+}diff --git a/frontend/src/metabase/utils/user.ts b/frontend/src/metabase/utils/user.tsindex 9a7eb628ca4..782e9f98275 100644--- a/frontend/src/metabase/utils/user.ts+++ b/frontend/src/metabase/utils/user.ts@@ -1,3 +1,10 @@+import { t } from "ttag";++import type { UserInfo } from "metabase-types/api";++export const getUserLabel = (user: UserInfo | null | undefined): string =>+ user?.common_name || user?.email || t`Unknown`;+export function getFullName(user: NamedUser): string | null {const firstName = user.first_name?.trim() || "";const lastName = user.last_name?.trim() || "";diff --git a/frontend/test/__support__/server-mocks/notification.ts b/frontend/test/__support__/server-mocks/notification.tsindex 97115d7e27f..bb95978ed4e 100644--- a/frontend/test/__support__/server-mocks/notification.ts+++ b/frontend/test/__support__/server-mocks/notification.ts@@ -1,8 +1,12 @@import fetchMock from "fetch-mock";import type {+ AdminNotification,+ AdminNotificationDetail,+ AdminNotificationListResponse,ListNotificationsRequest,Notification,+ NotificationId,} from "metabase-types/api";import { createMockNotification } from "metabase-types/api/mocks";@@ -23,3 +27,40 @@ export const setupCreateNotificationEndpoint = () => {return createMockNotification(JSON.parse(options.body as string));});};++export const setupAdminListNotificationsEndpoint = (+ notifications: AdminNotification[] = [],+ overrides: Partial<AdminNotificationListResponse> = {},+) => {+ const response: AdminNotificationListResponse = {+ data: notifications,+ total: notifications.length,+ limit: null,+ offset: null,+ ...overrides,+ };+ fetchMock.get("path:/api/ee/notifications", response);+};++export const setupAdminNotificationDetailEndpoint = (+ notification: AdminNotification | AdminNotificationDetail,+ options?: { delay?: number },+) => {+ fetchMock.get(+ `path:/api/ee/notifications/${notification.id}`,+ notification,+ options,+ );+};++export const setupAdminNotificationDetailErrorEndpoint = (+ id: NotificationId,+) => {+ fetchMock.get(`path:/api/ee/notifications/${id}`, { status: 500 });+};++export const setupBulkNotificationActionEndpoint = (+ response: { updated: number } = { updated: 1 },+) => {+ fetchMock.post("path:/api/ee/notifications/bulk", response);+};diff --git a/src/metabase/notification/api.clj b/src/metabase/notification/api.cljindex 330adc6786b..c0628482bef 100644--- a/src/metabase/notification/api.clj+++ b/src/metabase/notification/api.clj@@ -12,6 +12,7 @@create-notification!list-notificationsget-notification+ publish-notification-update!unsubscribe-user!])(def ^{:arglists '([request respond raise])} notification-routesdiff --git a/src/metabase/notification/api/notification.clj b/src/metabase/notification/api/notification.cljindex 9cc59408bcd..167b786fd7c 100644--- a/src/metabase/notification/api/notification.clj+++ b/src/metabase/notification/api/notification.clj@@ -224,13 +224,30 @@(when (seq added-recipients)(messages/send-you-were-added-card-notification-email! notification added-recipients @api/*current-user*)))))))+(defn publish-notification-update!+ "Post-update side effects for a notification: recipient emails on `:active` transitions (or+ recipient diffs) + an `:event/notification-update` audit event. Shared between the self-service+ PUT endpoint and the admin bulk endpoint so the contract can't drift. Both args should be+ hydrated notifications (see [[models.notification/hydrate-notification]])."+ [updated-notification existing-notification]+ (when (card-notification? existing-notification)+ (notify-notification-updates! updated-notification existing-notification))+ (events/publish-event! :event/notification-update+ {:object updated-notification+ :previous-object existing-notification+ :user-id api/*current-user-id*}))+;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :put "/:id""Update a notification, can also update its subscriptions, handlers.- Return the updated notification."+ Return the updated notification.++ `creator_id` (owner) can be reassigned here only by superusers (e.g. the admin 'Edit alert'+ modal's owner picker). `mi/can-update?` rejects a non-superuser reassignment attempt with 403;+ the model's `before-update` hook is the backstop. Echoing back the unchanged value is fine."[{:keys [id]} :- [:map [:id ms/PositiveInt]]_querybody :- ::NotificationApiInput]@@ -238,12 +255,8 @@(let [existing-notification (get-notification id)](api/update-check existing-notification body)(models.notification/update-notification! existing-notification body)- (when (card-notification? existing-notification)- (notify-notification-updates! body existing-notification))(u/prog1 (get-notification id)- (events/publish-event! :event/notification-update {:object <>- :previous-object existing-notification- :user-id api/*current-user-id*}))))+ (publish-notification-update! <> existing-notification))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/src/metabase/notification/models.clj b/src/metabase/notification/models.cljindex 7f9be3cb8ae..330a31f8127 100644--- a/src/metabase/notification/models.clj+++ b/src/metabase/notification/models.clj@@ -133,10 +133,18 @@(t2/define-before-update :model/Notification[instance](validate-notification instance)- (when-let [unallowed-key (some #{:payload_type :payload_id :creator_id} (keys (t2/changes instance)))]- (throw (ex-info (format "Update %s is not allowed." (name unallowed-key))- {:status-code 400- :changes (t2/changes instance)})))+ (let [changes (t2/changes instance)]+ (when-let [unallowed-key (some #{:payload_type :payload_id} (keys changes))]+ (throw (ex-info (format "Update %s is not allowed." (name unallowed-key))+ {:status-code 400+ :changes changes})))+ ;; Only superusers can reassign ownership. Unauthenticated/system writes have no current+ ;; user, so `(mi/superuser?)` is false and they're rejected too.+ (when (and (contains? changes :creator_id)+ (not (mi/superuser?)))+ (throw (ex-info "Only superusers can change a notification's creator_id."+ {:status-code 400+ :changes changes}))))(when (contains? (t2/changes instance) :active)(let [subscriptions (t2/select :model/NotificationSubscription:notification_id (:id instance)@@ -479,17 +487,21 @@(perms/current-user-has-application-permissions? :subscription)))))(defmethod mi/can-update? :model/Notification- [instance _changes]- (or- (mi/superuser?)- (and- (current-user-is-creator? instance)- ;; if advanced-permissions is enabled, we require users to have subscription permissions- ;; and is the owner of the notification and can read the payload- (or- (not (premium-features/has-feature? :advanced-permissions))- (perms/current-user-has-application-permissions? :subscription))- (current-user-can-read-payload? instance))))+ [instance changes]+ (and+ (or (not (contains? changes :creator_id))+ (= (:creator_id changes) (:creator_id instance))+ (mi/superuser?))+ (or+ (mi/superuser?)+ (and+ (current-user-is-creator? instance)+ ;; if advanced-permissions is enabled, we require users to have subscription permissions+ ;; and is the owner of the notification and can read the payload+ (or+ (not (premium-features/has-feature? :advanced-permissions))+ (perms/current-user-has-application-permissions? :subscription))+ (current-user-can-read-payload? instance)))));; ------------------------------------------------------------------------------------------------;;;; Public APIs ;;@@ -578,7 +590,9 @@(models.u.spec-update/define-spec notification-update-spec"Spec for updating a notification."{:model :model/Notification- :compare-cols [:active]+ ;; `:creator_id` is here so PUT can flow ownership reassignment through the same spec write as+ ;; the rest of the row. Authorization lives in the model's `before-update` hook (superuser-only).+ :compare-cols [:active :creator_id]:extra-cols [:payload_type :internal_id :payload_id]:nested-specs {:payload {:model :model/NotificationCard:compare-cols [:send_condition :send_once]diff --git a/test/metabase/notification/api/notification_test.clj b/test/metabase/notification/api/notification_test.cljindex 1162133be91..08df718a5f3 100644--- a/test/metabase/notification/api/notification_test.clj+++ b/test/metabase/notification/api/notification_test.clj@@ -405,6 +405,26 @@:payload {}:payload_type "notification/card"})))))+(deftest put-creator-id-permissions-test+ (testing "PUT /api/notification/:id and creator_id"+ (notification.tu/with-card-notification+ [notification {:notification {:creator_id (mt/user->id :rasta)}}]+ (let [notification-id (:id notification)+ put! (fn [user expected-status body]+ (mt/user-http-request user :put expected-status+ (format "notification/%d" notification-id)+ (merge notification body)))]+ (testing "superuser can reassign owner"+ (put! :crowberto 200 {:creator_id (mt/user->id :lucky)})+ (is (= (mt/user->id :lucky)+ (t2/select-one-fn :creator_id :model/Notification notification-id))))+ (testing "non-superuser cannot reassign owner — even the current owner (403 from mi/can-update?)"+ (put! :lucky 403 {:creator_id (mt/user->id :rasta)})+ (is (= (mt/user->id :lucky)+ (t2/select-one-fn :creator_id :model/Notification notification-id))))+ (testing "echoing back the unchanged creator_id is fine for non-superusers"+ (put! :lucky 200 {:creator_id (mt/user->id :lucky)}))))))+(deftest send-notification-by-id-api-test(mt/with-temp [:model/Channel {http-channel-id :id} {:type :channel/http:details {:url "https://metabase.com/testhttp"@@ -575,8 +595,14 @@[notification {:card {:collection_id (t2/select-one-pk :model/Collection :personal_owner_id (mt/user->id :rasta))}:notification {:creator_id (mt/user->id :rasta)}}](let [update! (fn [user-or-id expected-status]+ ;; This test exercises card-view + subscription permissions, not owner+ ;; reassignment. Drop creator_id from the body — otherwise the stale value+ ;; left over after change-notification-creator would read as a (forbidden,+ ;; non-superuser) reassignment and 400 before the permission checks run.(mt/user-http-request user-or-id :put expected-status (format "notification/%d" (:id notification))- (assoc notification :updated_at (t/offset-date-time))))+ (-> notification+ (dissoc :creator_id)+ (assoc :updated_at (t/offset-date-time)))))change-notification-creator (fn [user-id];; :model/Notification prevents updating creator_id, so we need to use table;; namediff --git a/test/metabase/notification/models_test.clj b/test/metabase/notification/models_test.cljindex b80de8e39b1..fd8a211d63c 100644--- a/test/metabase/notification/models_test.clj+++ b/test/metabase/notification/models_test.clj@@ -60,14 +60,37 @@java.lang.Exception#"Update payload_id is not allowed."(t2/update! :model/Notification noti-id {:payload_id 1338})))))- (testing "can't change creator id"+ (testing "superusers can change creator_id"(mt/with-temp [:model/Notification {noti-id :id} {:payload_type :notification/card:payload_id 1337:creator_id (mt/user->id :crowberto)}]- (is (thrown-with-msg?- java.lang.Exception- #"Update creator_id is not allowed."- (t2/update! :model/Notification noti-id {:creator_id (mt/user->id :rasta)}))))))+ (mt/with-current-user (mt/user->id :crowberto)+ (t2/update! :model/Notification noti-id {:creator_id (mt/user->id :rasta)}))+ (is (= (mt/user->id :rasta)+ (t2/select-one-fn :creator_id :model/Notification noti-id)))))+ (testing "non-superusers and unauthenticated callers can't change creator_id"+ (mt/with-temp [:model/Notification {noti-id :id} {:payload_type :notification/card+ :payload_id 1337+ :creator_id (mt/user->id :crowberto)}]+ (testing "non-superuser (single-pk update)"+ (mt/with-current-user (mt/user->id :rasta)+ (is (thrown-with-msg?+ java.lang.Exception+ #"Only superusers can change a notification's creator_id."+ (t2/update! :model/Notification noti-id {:creator_id (mt/user->id :lucky)})))))+ (testing "non-superuser (bulk update via :id [:in …])"+ ;; The admin bulk endpoint uses this form; the model hook is the backstop in case the+ ;; endpoint's superuser check is ever relaxed or bypassed.+ (mt/with-current-user (mt/user->id :rasta)+ (is (thrown-with-msg?+ java.lang.Exception+ #"Only superusers can change a notification's creator_id."+ (t2/update! :model/Notification :id [:in [noti-id]] {:creator_id (mt/user->id :lucky)})))))+ (testing "no current user (system context)"+ (is (thrown-with-msg?+ java.lang.Exception+ #"Only superusers can change a notification's creator_id."+ (t2/update! :model/Notification noti-id {:creator_id (mt/user->id :lucky)})))))))(deftest delete-notification-clean-up-payload-test(testing "cleanup :model/NotificationCard on delete"