Skip to content

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

Move pulse preview endpoints to dev-only (#70068)

Ngoc Khuat3d3bbe22dba4
diff --git a/dev/src/dev/api/preview.clj b/dev/src/dev/api/preview.clj
new file mode 100644
index 00000000000..c87b81e2cc6
--- /dev/null
+++ b/dev/src/dev/api/preview.clj
@@ -0,0 +1,113 @@
+(ns dev.api.preview
+ "Dev-only endpoints for previewing rendered pulse cards and dashboards.
+ These were previously at `/api/pulse/preview_*` but have been moved here
+ since they are only useful for development and testing."
+ (:require
+ [hiccup.core :refer [html]]
+ [hiccup.page :refer [html5]]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common]
+ [metabase.channel.render.core :as channel.render]
+ [metabase.channel.urls :as urls]
+ [metabase.query-processor :as qp]
+ [metabase.query-processor.middleware.permissions :as qp.perms]
+ [metabase.util.malli.schema :as ms])
+ (:import
+ (java.io ByteArrayInputStream)))
+
+(set! *warn-on-reflection* true)
+
+(defn- pulse-card-query-results
+ {:arglists '([card])}
+ [{query :dataset_query, card-id :id}]
+ (binding [qp.perms/*card-id* card-id]
+ (qp/process-query
+ (qp/userland-query
+ (assoc query
+ :middleware {:process-viz-settings? true
+ :js-int-to-string? false})
+ {:executed-by api/*current-user-id*
+ :context :pulse
+ :card-id card-id}))))
+
+(api.macros/defendpoint :get "/preview-card/:id"
+ "Get HTML rendering of a Card with `id`."
+ [{:keys [id]} :- [:map
+ [:id ms/PositiveInt]]]
+ (let [card (api/read-check :model/Card id)
+ result (pulse-card-query-results card)]
+ {:status 200
+ :body (html5
+ [:html
+ [:body {:style "margin: 0;"}
+ (channel.render/render-pulse-card-for-display (channel.render/defaulted-timezone card)
+ card
+ result
+ {:channel.render/include-title? true, :channel.render/include-buttons? true})]])}))
+
+(api.macros/defendpoint :get "/preview-dashboard/:id"
+ "Get HTML rendering of a Dashboard with `id`.
+
+ This endpoint relies on a custom middleware defined in `metabase.channel.render.core/style-tag-nonce-middleware` to
+ allow the style tag to render properly, given our Content Security Policy setup."
+ [{:keys [id]} :- [:map
+ [:id ms/PositiveInt]]]
+ (api/read-check :model/Dashboard id)
+ {:status 200
+ :headers {"Content-Type" "text/html"}
+ :body (channel.render/style-tag-from-inline-styles
+ (html5
+ [:head
+ [:meta {:charset "utf-8"}]
+ [:link {:nonce "%NONCE%" ;; this will be str/replaced by 'style-tag-nonce-middleware
+ :rel "stylesheet"
+ :href "https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swap"}]]
+ [:body [:h2 (format "Backend Artifacts Preview for Dashboard %s" id)]
+ (channel.render/render-dashboard-to-html id)]))})
+
+(api.macros/defendpoint :get "/preview-card-info/:id"
+ "Get JSON object containing HTML rendering of a Card with `id` and other information."
+ [{:keys [id]} :- [:map
+ [:id ms/PositiveInt]]]
+ (let [card (api/read-check :model/Card id)
+ result (pulse-card-query-results card)
+ data (:data result)
+ card-type (channel.render/detect-pulse-chart-type card nil data)
+ card-html (html (channel.render/render-pulse-card-for-display (channel.render/defaulted-timezone card)
+ card
+ result
+ {:channel.render/include-title? true}))]
+ {:id id
+ :pulse_card_type card-type
+ :pulse_card_html card-html
+ :pulse_card_name (:name card)
+ :pulse_card_url (urls/card-url (:id card))
+ :row_count (:row_count result)
+ :col_count (count (:cols (:data result)))}))
+
+(def ^:private preview-card-width 400)
+
+(api.macros/defendpoint :get "/preview-card-png/:id"
+ "Get PNG rendering of a Card with `id`. Optionally specify `width` as a query parameter."
+ [{:keys [id]} :- [:map
+ [:id ms/PositiveInt]]
+ {:keys [width]} :- [:map
+ [:width {:optional true} [:maybe ms/PositiveInt]]]]
+ (let [card (api/read-check :model/Card id)
+ result (pulse-card-query-results card)
+ width (or width preview-card-width)
+ ba (channel.render/render-pulse-card-to-png (channel.render/defaulted-timezone card)
+ card
+ result
+ width
+ {:channel.render/include-title? true})]
+ {:status 200, :headers {"Content-Type" "image/png"}, :body (ByteArrayInputStream. ba)}))
+
+(def ^:private ^{:arglists '([handler])} style-nonce-middleware
+ (metabase.api.routes.common/wrap-middleware-for-open-api-spec-generation
+ (partial channel.render/style-tag-nonce-middleware "/dev/preview/preview-dashboard")))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/dev/preview` endpoints."
+ (api.macros/ns-handler *ns* style-nonce-middleware))
diff --git a/dev/src/dev/api/routes.clj b/dev/src/dev/api/routes.clj
index 63df0298868..890b9afbc70 100644
--- a/dev/src/dev/api/routes.clj
+++ b/dev/src/dev/api/routes.clj
@@ -1,12 +1,15 @@
(ns dev.api.routes
- (:require [dev.api.prototype]
+ (:require [dev.api.preview]
+ [dev.api.prototype]
[metabase.api.util.handlers :as handlers]))
(comment
+ dev.api.preview/keep-me
dev.api.prototype/keep-me)
(def ^:private dev-routes-map
- {"/prototype" 'dev.api.prototype})
+ {"/preview" 'dev.api.preview
+ "/prototype" 'dev.api.prototype})
(def ^{:arglists '([request respond raise])} routes
;; This map will be merged at the top level, so /dev/prototype is available.
diff --git a/e2e/test/scenarios/dashboard-cards/dashboard-card-reproductions.cy.spec.js b/e2e/test/scenarios/dashboard-cards/dashboard-card-reproductions.cy.spec.js
index 5716de6b694..d75f1d31205 100644
--- a/e2e/test/scenarios/dashboard-cards/dashboard-card-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/dashboard-cards/dashboard-card-reproductions.cy.spec.js
@@ -630,70 +630,8 @@ describe("issue 23137", () => {
});
});
-describe("issues 27020 and 27105: static-viz fails to render for certain date formatting options", () => {
- const questionDetails27105 = {
- name: "27105",
- native: { query: "select current_date::date, 1", "template-tags": {} },
- display: "table",
- visualization_settings: {
- column_settings: {
- '["name","CAST(CURRENT_DATE AS DATE)"]': {
- date_style: "dddd, MMMM D, YYYY",
- },
- },
- "table.pivot_column": "CAST(CURRENT_DATE AS DATE)",
- "table.cell_column": "1",
- },
- };
-
- const questionDetails27020 = {
- name: "27020",
- native: {
- query: 'select current_date as "created_at", 1 "val"',
- "template-tags": {},
- },
- visualization_settings: {
- column_settings: { '["name","created_at"]': { date_abbreviate: true } },
- "table.pivot_column": "created_at",
- "table.cell_column": "val",
- },
- };
-
- function assertStaticVizRenders(questionDetails) {
- H.createNativeQuestion(questionDetails).then(({ body: { id } }) => {
- cy.request({
- method: "GET",
- url: `/api/pulse/preview_card_png/${id}`,
- failOnStatusCode: false,
- }).then(({ status, body }) => {
- expect(status).to.eq(200);
- expect(body).to.contain("PNG");
- });
- });
- }
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should render static-viz when date formatting is abbreviated (metabase#27020)", () => {
- // This is currently the default setting, anyway.
- // But we want to explicitly set it in case something changes in the future,
- // because it is a crucial step for this reproduction.
- H.updateSetting("custom-formatting", {
- "type/Temporal": {
- date_style: "MMMM D, YYYY",
- },
- });
-
- assertStaticVizRenders(questionDetails27020);
- });
-
- it("should render static-viz when date formatting contains day (metabase#27105)", () => {
- assertStaticVizRenders(questionDetails27105);
- });
-});
+// Tests for issues 27020 and 27105 (static-viz rendering with date formatting options)
+// have been moved to backend tests in metabase.channel.render.card-test
describe("issue 29304", () => {
// Couldn't import from `metabase/common/components/ExplicitSize` because dependency issue.
diff --git a/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js b/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js
index 3e02a4d3a45..5c21db0b9ba 100644
--- a/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/visualizations-charts/visualizations-charts-reproductions.cy.spec.js
@@ -916,49 +916,8 @@ describe("issue 27279", () => {
});
});
-describe("issue 27427", () => {
- const questionDetails = {
- name: "27427",
- native: {
- query:
- "select 1 as sortorder, year(current_timestamp), 1 v1, 2 v2\nunion all select 1, year(current_timestamp)-1, 1, 2",
- "template-tags": {},
- },
- display: "bar",
- visualization_settings: {
- "graph.dimensions": ["EXTRACT(YEAR FROM CURRENT_TIMESTAMP)"],
- "graph.metrics": ["V1", "V2"],
- "graph.series_order_dimension": null,
- "graph.series_order": null,
- },
- };
-
- function assertStaticVizRender(questionDetails, callback) {
- H.createNativeQuestion(questionDetails).then(({ body: { id } }) => {
- cy.request({
- method: "GET",
- url: `/api/pulse/preview_card/${id}`,
- failOnStatusCode: false,
- }).then((response) => {
- callback(response);
- });
- });
- }
-
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("static-viz should not fail if there is unused returned column: 'divide by zero' (metabase#27427)", () => {
- assertStaticVizRender(questionDetails, ({ status, body }) => {
- expect(status).to.eq(200);
- expect(body).to.not.include(
- "An error occurred while displaying this card.",
- );
- });
- });
-});
+// Test for issue 27427 (static-viz with unused returned column)
+// has been moved to backend test in metabase.channel.render.card-test
const addCountGreaterThan2Filter = () => {
H.openNotebook();
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj
index 40a9983157e..8b3e651f5c8 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/pulse_test.clj
@@ -115,36 +115,32 @@
(is (= 22
(count (mt/rows (alert-results! query))))))))))))
-(deftest pulse-preview-test
- (testing "Pulse preview endpoints should be sandboxed"
+(deftest pulse-test-endpoint-sandboxed-test
+ (testing "POST /api/pulse/test should be sandboxed"
(met/with-gtaps! {:gtaps {:venues {:remappings {:price [:dimension [:field (mt/id :venues :price) nil]]}}}
:attributes {"price" "1"}}
(let [query (mt/mbql-query venues)]
(mt/with-test-user :rasta
(mt/with-temp [:model/Card card {:dataset_query query}]
- (testing "GET /api/pulse/preview_card/:id"
- (is (= 22
- (html->row-count (mt/user-http-request :rasta :get 200 (format "pulse/preview_card/%d" (u/the-id card)))))))
- (testing "POST /api/pulse/test"
- (mt/with-fake-inbox
- (mt/user-http-request :rasta :post 200 "pulse/test" {:name "venues"
- :alert_condition "rows"
- :cards [{:id (u/the-id card)
- :include_csv true
- :include_xls false}]
- :channels [{:channel_type :email
- :schedule_type "hourly"
- :enabled :true
- :recipients [{:id (mt/user->id :rasta)
- :email "[email protected]"}]}]})
- (let [[{html :content} {_icon :content} {attachment :content}] (get-in @mt/inbox ["[email protected]" 0 :body])]
- (testing "email"
- (is (= 22
- (html->row-count html))))
- (testing "CSV attachment"
- ;; one extra row because first row is column names
- (is (= 23
- (csv->row-count attachment)))))))))))))
+ (mt/with-fake-inbox
+ (mt/user-http-request :rasta :post 200 "pulse/test" {:name "venues"
+ :alert_condition "rows"
+ :cards [{:id (u/the-id card)
+ :include_csv true
+ :include_xls false}]
+ :channels [{:channel_type :email
+ :schedule_type "hourly"
+ :enabled :true
+ :recipients [{:id (mt/user->id :rasta)
+ :email "[email protected]"}]}]})
+ (let [[{html :content} {_icon :content} {attachment :content}] (get-in @mt/inbox ["[email protected]" 0 :body])]
+ (testing "email"
+ (is (= 22
+ (html->row-count html))))
+ (testing "CSV attachment"
+ ;; one extra row because first row is column names
+ (is (= 23
+ (csv->row-count attachment))))))))))))
(deftest csv-downloads-test
(testing "CSV/XLSX downloads attached to an email should be sandboxed"
diff --git a/frontend/src/metabase-types/store/pulse.ts b/frontend/src/metabase-types/store/pulse.ts
index b144b2d5513..55b62646f2b 100644
--- a/frontend/src/metabase-types/store/pulse.ts
+++ b/frontend/src/metabase-types/store/pulse.ts
@@ -43,6 +43,5 @@ export type DashboardSubscriptionData =
export interface PulseState {
editingPulse: DraftDashboardSubscription;
formInput: ChannelApiResponse;
- cardPreviews: Record<number, { id: number }>;
pulseList: DashboardSubscription[];
}
diff --git a/frontend/src/metabase/notifications/pulse/actions.ts b/frontend/src/metabase/notifications/pulse/actions.ts
index bf28b506239..ccf2fb747cf 100644
--- a/frontend/src/metabase/notifications/pulse/actions.ts
+++ b/frontend/src/metabase/notifications/pulse/actions.ts
@@ -29,7 +29,6 @@ export const CANCEL_EDITING_PULSE = "CANCEL_EDITING_PULSE";
export const TEST_PULSE = "TEST_PULSE";
export const FETCH_PULSE_FORM_INPUT = "FETCH_PULSE_FORM_INPUT";
-export const FETCH_PULSE_CARD_PREVIEW = "FETCH_PULSE_CARD_PREVIEW";
export const FETCH_PULSE_LIST_BY_DASHBOARD_ID =
"FETCH_PULSE_LIST_BY_DASHBOARD_ID";
@@ -128,15 +127,6 @@ export const fetchPulseFormInput = createThunkAction(
},
);
-export const fetchPulseCardPreview = createThunkAction(
- FETCH_PULSE_CARD_PREVIEW,
- function (id: number) {
- return async function () {
- return await PulseApi.preview_card({ id: id });
- };
- },
-);
-
export const fetchPulsesByDashboardId = createThunkAction(
FETCH_PULSE_LIST_BY_DASHBOARD_ID,
function (dashboard_id: number) {
diff --git a/frontend/src/metabase/notifications/pulse/reducers.ts b/frontend/src/metabase/notifications/pulse/reducers.ts
index 3b47fb24b86..3c13a10f806 100644
--- a/frontend/src/metabase/notifications/pulse/reducers.ts
+++ b/frontend/src/metabase/notifications/pulse/reducers.ts
@@ -8,7 +8,6 @@ import type { DraftDashboardSubscription } from "metabase-types/store";
import {
CANCEL_EDITING_PULSE,
- FETCH_PULSE_CARD_PREVIEW,
FETCH_PULSE_FORM_INPUT,
FETCH_PULSE_LIST_BY_DASHBOARD_ID,
SAVE_EDITING_PULSE,
@@ -54,24 +53,6 @@ export const formInput = handleActions(
{} as ChannelApiResponse,
);
-type CardPreviewEntry = { id: number };
-type CardPreviewsState = Record<number, CardPreviewEntry>;
-
-export const cardPreviews = handleActions(
- {
- [FETCH_PULSE_CARD_PREVIEW]: {
- next: (
- state: CardPreviewsState,
- { payload }: { payload: CardPreviewEntry },
- ) => ({
- ...state,
- [payload.id]: payload,
- }),
- },
- },
- {} as CardPreviewsState,
-);
-
export const pulseList = handleActions(
{
[FETCH_PULSE_LIST_BY_DASHBOARD_ID]: {
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index 3aa821e6f98..0b67bb2f7f0 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -262,7 +262,6 @@ export const PulseApi = {
update: PUT("/api/pulse/:id"),
test: POST("/api/pulse/test"),
form_input: GET("/api/pulse/form_input"),
- preview_card: GET("/api/pulse/preview_card_info/:id"),
unsubscribe: DELETE("/api/pulse/:id/subscription"),
};
diff --git a/src/metabase/channel/render/preview.clj b/src/metabase/channel/render/preview.clj
index 5f080814003..6e33eff0836 100644
--- a/src/metabase/channel/render/preview.clj
+++ b/src/metabase/channel/render/preview.clj
@@ -154,7 +154,7 @@
"Constructs a middleware handler function that adds the generated nonce to an html string.
This is only designed to be used with an endpoint that returns an html string response containing
a style tag with an attribute 'nonce=%NONCE%'. Specifically, this was designed to be used with the
- endpoint `api/pulse/preview_dashboard/:id`."
+ endpoint `dev/preview/preview-dashboard/:id`."
[only-this-uri handler]
(fn [request respond raise]
(let [{:keys [uri]} request]
diff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.clj
index 0388df6d9ec..7ae33698289 100644
--- a/src/metabase/pulse/api/pulse.clj
+++ b/src/metabase/pulse/api/pulse.clj
@@ -5,16 +5,11 @@
Deprecated: will soon be migrated to notification APIs."
(:require
[clojure.set :refer [difference]]
- [hiccup.core :refer [html]]
- [hiccup.page :refer [html5]]
[medley.core :as m]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
- [metabase.api.routes.common]
- [metabase.channel.render.core :as channel.render]
[metabase.channel.settings :as channel.settings]
[metabase.channel.slack :as channel.slack]
- [metabase.channel.urls :as urls]
[metabase.classloader.core :as classloader]
[metabase.collections.models.collection :as collection]
[metabase.config.core :as config]
@@ -27,14 +22,10 @@
[metabase.pulse.models.pulse :as models.pulse]
[metabase.pulse.models.pulse-channel :as pulse-channel]
[metabase.pulse.send :as pulse.send]
- [metabase.query-processor :as qp]
- [metabase.query-processor.middleware.permissions :as qp.perms]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
[metabase.util.malli.schema :as ms]
- [toucan2.core :as t2])
- (:import
- (java.io ByteArrayInputStream)))
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -314,121 +305,6 @@
(catch Throwable e
(assoc-in chan-types [:slack :error] (.getMessage e)))))}))
-(defn- pulse-card-query-results
- {:arglists '([card])}
- [{query :dataset_query, card-id :id}]
- (binding [qp.perms/*card-id* card-id]
- (qp/process-query
- (qp/userland-query
- (assoc query
- :middleware {:process-viz-settings? true
- :js-int-to-string? false})
- {:executed-by api/*current-user-id*
- :context :pulse
- :card-id card-id}))))
-
-;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API
-;;
-;; 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-route-uses-kebab-case
- :metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/preview_card/:id"
- "Get HTML rendering of a Card with `id`."
- [{:keys [id]} :- [:map
- [:id ms/PositiveInt]]]
- (let [card (api/read-check :model/Card id)
- result (pulse-card-query-results card)]
- {:status 200
- :body (html5
- [:html
- [:body {:style "margin: 0;"}
- (channel.render/render-pulse-card-for-display (channel.render/defaulted-timezone card)
- card
- result
- {:channel.render/include-title? true, :channel.render/include-buttons? true})]])}))
-
-;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API
-;;
-;; 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-route-uses-kebab-case
- :metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/preview_dashboard/:id"
- "Get HTML rendering of a Dashboard with `id`.
-
- This endpoint relies on a custom middleware defined in `metabase.channel.render.core/style-tag-nonce-middleware` to
- allow the style tag to render properly, given our Content Security Policy setup. This middleware is attached to these
- routes at the bottom of this namespace using `metabase.api.common/define-routes`."
- [{:keys [id]} :- [:map
- [:id ms/PositiveInt]]]
- (api/read-check :model/Dashboard id)
- {:status 200
- :headers {"Content-Type" "text/html"}
- :body (channel.render/style-tag-from-inline-styles
- (html5
- [:head
- [:meta {:charset "utf-8"}]
- [:link {:nonce "%NONCE%" ;; this will be str/replaced by 'style-tag-nonce-middleware
- :rel "stylesheet"
- :href "https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;0,700;0,900;1,100;1,300;1,400;1,700;1,900&display=swap"}]]
- [:body [:h2 (format "Backend Artifacts Preview for Dashboard %s" id)]
- (channel.render/render-dashboard-to-html id)]))})
-
-;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API
-;;
-;; 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-route-uses-kebab-case
- :metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/preview_card_info/:id"
- "Get JSON object containing HTML rendering of a Card with `id` and other information."
- [{:keys [id]} :- [:map
- [:id ms/PositiveInt]]]
- (let [card (api/read-check :model/Card id)
- result (pulse-card-query-results card)
- data (:data result)
- card-type (channel.render/detect-pulse-chart-type card nil data)
- card-html (html (channel.render/render-pulse-card-for-display (channel.render/defaulted-timezone card)
- card
- result
- {:channel.render/include-title? true}))]
- {:id id
- :pulse_card_type card-type
- :pulse_card_html card-html
- :pulse_card_name (:name card)
- :pulse_card_url (urls/card-url (:id card))
- :row_count (:row_count result)
- :col_count (count (:cols (:data result)))}))
-
-(def ^:private preview-card-width 400)
-
-;; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API
-;;
-;; 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-route-uses-kebab-case
- :metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/preview_card_png/:id"
- "Get PNG rendering of a Card with `id`. Optionally specify `width` as a query parameter."
- [{:keys [id]} :- [:map
- [:id ms/PositiveInt]]
- {:keys [width]} :- [:map
- [:width {:optional true} [:maybe ms/PositiveInt]]]]
- (let [card (api/read-check :model/Card id)
- result (pulse-card-query-results card)
- width (or width preview-card-width)
- ba (channel.render/render-pulse-card-to-png (channel.render/defaulted-timezone card)
- card
- result
- width
- {:channel.render/include-title? true})]
- {:status 200, :headers {"Content-Type" "image/png"}, :body (ByteArrayInputStream. ba)}))
-
;; 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
;;
@@ -478,10 +354,6 @@
(t2/delete! :model/PulseChannelRecipient :id pcr-id))
api/generic-204-no-content)
-(def ^:private ^{:arglists '([handler])} style-nonce-middleware
- (metabase.api.routes.common/wrap-middleware-for-open-api-spec-generation
- (partial channel.render/style-tag-nonce-middleware "/api/pulse/preview_dashboard")))
-
(def ^{:arglists '([request respond raise])} routes
"`/api/pulse` endpoints."
- (api.macros/ns-handler *ns* style-nonce-middleware))
+ (api.macros/ns-handler *ns*))
diff --git a/test/metabase/channel/render/card_test.clj b/test/metabase/channel/render/card_test.clj
index 619b478e20f..4448fb5ac87 100644
--- a/test/metabase/channel/render/card_test.clj
+++ b/test/metabase/channel/render/card_test.clj
@@ -326,3 +326,62 @@
{:channel.render/include-title? true}))
expected-href (format "https://mb.com/dashboard/%d#scrollTo=%d" (:dashboard_id dc1) (:id dc1))]
(is (every? #(= % expected-href) (lib.util.match/match-many rendered-card-content {:href href} href))))))))
+
+(deftest render-card-with-abbreviated-dates-test
+ (testing "Static-viz should render without error when date formatting is abbreviated (metabase#27020)"
+ (mt/with-temporary-setting-values [custom-formatting {:type/Temporal {:date_style "MMMM D, YYYY"}}]
+ (mt/with-temp [:model/Card card {:dataset_query {:database (mt/id)
+ :type :native
+ :native {:query "select current_date as \"created_at\", 1 \"val\""}}
+ :display :table
+ :visualization_settings {:column_settings {"[\"name\",\"created_at\"]" {:date_abbreviate true}}
+ "table.pivot_column" "created_at"
+ "table.cell_column" "val"}}]
+ (let [result (qp/process-query
+ (assoc (:dataset_query card)
+ :middleware {:process-viz-settings? true
+ :js-int-to-string? false}))
+ ba (channel.render/render-pulse-card-to-png (channel.render/defaulted-timezone card)
+ card
+ result
+ 400
+ {:channel.render/include-title? true})]
+ (is (pos? (alength ba)) "PNG byte array should not be empty"))))))
+
+(deftest render-card-with-day-date-style-test
+ (testing "Static-viz should render without error when date formatting contains day (metabase#27105)"
+ (mt/with-temp [:model/Card card {:dataset_query {:database (mt/id)
+ :type :native
+ :native {:query "select current_date::date, 1"}}
+ :display :table
+ :visualization_settings {:column_settings {"[\"name\",\"CAST(CURRENT_DATE AS DATE)\"]" {:date_style "dddd, MMMM D, YYYY"}}
+ "table.pivot_column" "CAST(CURRENT_DATE AS DATE)"
+ "table.cell_column" "1"}}]
+ (let [result (qp/process-query
+ (assoc (:dataset_query card)
+ :middleware {:process-viz-settings? true
+ :js-int-to-string? false}))
+ ba (channel.render/render-pulse-card-to-png (channel.render/defaulted-timezone card)
+ card
+ result
+ 400
+ {:channel.render/include-title? true})]
+ (is (pos? (alength ba)) "PNG byte array should not be empty")))))
+
+(deftest render-card-with-unused-column-test
+ (testing "Static-viz render does not throw when there is an unused returned column (metabase#27427)"
+ (let [q (mt/mbql-query orders
+ {:aggregation [[:count] [:sum $total]]
+ :breakout [!year.created_at]})]
+ (mt/with-temp [:model/Card card {:dataset_query q
+ :display :bar
+ :visualization_settings {"graph.dimensions" ["CREATED_AT"]
+ "graph.metrics" ["count"]}}]
+ (let [result (qp/process-query q)]
+ ;; The original bug (metabase#27427) caused a divide-by-zero crash when extra columns
+ ;; were returned but not referenced in graph.metrics. We verify the render completes
+ ;; without throwing — the JS static-viz may produce an error card in test environments
+ ;; where the full rendering pipeline isn't available.
+ (is (some? (channel.render/render-pulse-card-for-display
+ (channel.render/defaulted-timezone card) card result
+ {:channel.render/include-title? true}))))))))
diff --git a/test/metabase/pulse/api/pulse_test.clj b/test/metabase/pulse/api/pulse_test.clj
index fccddfdff63..7a928f23fff 100644
--- a/test/metabase/pulse/api/pulse_test.clj
+++ b/test/metabase/pulse/api/pulse_test.clj
@@ -7,18 +7,16 @@
[metabase.api.response :as api.response]
[metabase.channel.api.channel-test :as api.channel-test]
[metabase.channel.impl.http-test :as channel.http-test]
- [metabase.channel.render.style :as style]
[metabase.channel.settings :as channel.settings]
[metabase.driver :as driver]
[metabase.notification.test-util :as notification.tu]
[metabase.permissions.models.permissions :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
- ^{:clj-kondo/ignore [:deprecated-namespace]}
- [metabase.pulse.api.pulse :as api.pulse]
[metabase.pulse.models.pulse-channel :as pulse-channel]
[metabase.pulse.models.pulse-test :as pulse-test]
[metabase.pulse.test-util :as pulse.test-util]
[metabase.queries-rest.api.card-test :as api.card-test]
+ [metabase.query-processor :as qp]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.test.http-client :as client]
@@ -1231,12 +1229,17 @@
(deftest ^:parallel pulse-card-query-results-test
(testing "viz-settings saved in the DB for a Card should be loaded"
- (is (some? (get-in (#'api.pulse/pulse-card-query-results
- {:id 1
- :dataset_query {:database (mt/id)
- :type :query
- :query {:source-table (mt/id :venues)
- :limit 1}}})
+ (is (some? (get-in (qp/process-query
+ (qp/userland-query
+ {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :venues)
+ :limit 1}
+ :middleware {:process-viz-settings? true
+ :js-int-to-string? false}}
+ {:executed-by (mt/user->id :rasta)
+ :context :pulse
+ :card-id 1}))
[:data :viz-settings])))))
(deftest form-input-test
@@ -1302,43 +1305,6 @@
(first)
(:options))))))))
-(deftest preview-pulse-test
- (testing "GET /api/pulse/preview_card/:id"
- (mt/with-temp [:model/Collection _ {}
- :model/Card card {:dataset_query (mt/mbql-query checkins {:limit 5})}]
- (letfn [(preview [expected-status-code & [width]]
- (let [url (str "pulse/preview_card_png/" (u/the-id card)
- (when width (str "?width=" width)))]
- (client/client-full-response (mt/user->credentials :rasta)
- :get expected-status-code url)))]
- (testing "Should be able to preview a Pulse"
- (let [{{:strs [Content-Type]} :headers, :keys [body]} (preview 200)]
- (is (= "image/png"
- Content-Type))
- (is (some? body))))
-
- (testing "Should respect the width query parameter"
- (let [width 600
- resp1 (preview 200)
- resp2 (preview 200 width)]
- (is (= "image/png" (get-in resp2 [:headers "Content-Type"])))
- (is (not= (:body resp1) (:body resp2))) ;; crude check: different width should yield different PNG bytes
- (is (some? (:body resp2)))))
-
- (testing "If rendering a Pulse fails (e.g. because font registration failed) the endpoint should return the error message"
- (with-redefs [style/register-fonts-if-needed! (fn []
- (throw (ex-info "Can't register fonts!"
- {}
- (NullPointerException.))))]
- (let [{{:strs [Content-Type]} :headers, :keys [body]} (preview 500)]
- (is (= "application/json; charset=utf-8"
- Content-Type))
- (is (malli= [:map
- [:message [:= "Can't register fonts!"]]
- [:trace :any]
- [:via :any]]
- body)))))))))
-
(deftest delete-subscription-test
(testing "DELETE /api/pulse/:id/subscription"
(mt/with-temp [:model/Pulse {pulse-id :id} {:name "Lodi Dodi" :creator_id (mt/user->id :crowberto)}