Skip to content

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

GDGT-2751 Apply the Table viz's pivot toggle in subscriptions (#82277)

Bartosz Rybackif3d13602406e
diff --git a/src/metabase/channel/render/body.clj b/src/metabase/channel/render/body.clj
index 4450796681e..7e620eb44e2 100644
--- a/src/metabase/channel/render/body.clj
+++ b/src/metabase/channel/render/body.clj
@@ -325,6 +325,183 @@
(fn [chart-type _render-type _timezone-id _card _dashcard _data]
chart-type))
+;;; --------------------------------------------------- pivot grids ---------------------------------------------------
+
+(defn- setting-value
+ "Look up `k` in a viz-settings map that may be keyed by either keywords or strings."
+ [settings k]
+ (or (get settings k) (get settings (name k))))
+
+(defn- pivot-cell->str
+ "Display string for an assembled pivot cell (a formatter wrapper, a plain string, or nil)."
+ [x]
+ (cond
+ (nil? x) ""
+ (string? x) x
+ :else (or (:num-str x) (:text-str x) (str x))))
+
+(defn- pivot->hiccup
+ "Render the assembled 2D pivot `rows` (header row first, then data rows) as an HTML table. Cells are
+ `white-space: nowrap` so the table takes whatever width it needs (the surrounding pulse body provides
+ horizontal scrolling). `opts` may include `:color-data`/`:color-settings` (the query results and viz-settings the
+ conditional-formatting rules evaluate against, see [[js.color/cell-background-colors]]), `:left-width` (number of
+ leading row-label columns), and `:measure-names` (ordered measure column names) to apply the card's conditional
+ formatting to the measure value cells."
+ [rows {:keys [color-data color-settings left-width measure-names]}]
+ (let [measure-count (max 1 (count measure-names))
+ colorable-cell (fn [cell ^long c]
+ ;; value cells are NumericWrapper; map each value column back to its measure column
+ ;; so the matching conditional-formatting rule applies. Row highlighting is disabled
+ ;; for pivots (:table.pivot in pivot-table-content and simple-pivot-content), so the
+ ;; row index is unused.
+ (when (and color-data (formatter/NumericWrapper? cell))
+ (let [vpos (- c (long left-width))]
+ (when (nat-int? vpos)
+ [cell 0 (nth measure-names (mod vpos measure-count))]))))
+ ;; all value-cell colors are fetched in one batched JS call up front, keyed by [row col] position
+ keyed-cells (for [[r row] (map-indexed vector rows)
+ [c cell] (map-indexed vector row)
+ :let [colorable (colorable-cell cell c)]
+ :when colorable]
+ [[r c] colorable])
+ cell-colors (zipmap (map first keyed-cells)
+ (js.color/cell-background-colors (or color-data {:cols [] :rows []})
+ color-settings
+ (mapv second keyed-cells)))]
+ [:table {:style (style/style (style/pivot-table-style))}
+ [:tbody
+ (map-indexed
+ (fn [r row]
+ [:tr
+ (map-indexed
+ (fn [c cell]
+ (let [header? (zero? r)
+ first-col? (zero? c)
+ label? (and (pos? r) first-col?)
+ bg (get cell-colors [r c])]
+ [(if (or header? label?) :th :td)
+ {:style (style/style (style/pivot-cell-style header? label? first-col? bg))}
+ (h (pivot-cell->str cell))]))
+ row)])
+ rows)]]))
+
+;;; --------------------------------------------------- simple pivot ---------------------------------------------------
+
+(defn- simple-pivot-indexes
+ "Column indexes `{:normal i, :pivot j, :cell k}` when the Table viz's \"Pivot table\" toggle applies to `cols`, else
+ nil. Mirrors the browser's `isPivoted` and `isValid` (viz-core/lib/settings/column.ts, Table/definition.ts):
+ `:table.pivot` is set, there are exactly three columns, and `:table.pivot_column` and `:table.cell_column` name two
+ different columns. The remaining column is the normal one; its values become the row labels."
+ [cols viz-settings]
+ (when (and (setting-value viz-settings :table.pivot)
+ (= 3 (count cols)))
+ (let [index-of (fn [k]
+ (let [col-name (setting-value viz-settings k)]
+ (u/index-of #(= (:name %) col-name) cols)))
+ pivot-idx (index-of :table.pivot_column)
+ cell-idx (index-of :table.cell_column)]
+ (when (and pivot-idx cell-idx (not= pivot-idx cell-idx))
+ {:normal (first (remove #{pivot-idx cell-idx} (range 3)))
+ :pivot pivot-idx
+ :cell cell-idx}))))
+
+(defn- compare-pivot-values
+ "Like the browser's `DEFAULT_COMPARE` (visualizations/lib/data_grid.ts), but nil sorts first."
+ [a b]
+ (if (or (nil? a)
+ (nil? b)
+ (and (number? a) (number? b))
+ (and (instance? Comparable a) (= (class a) (class b))))
+ (compare a b)
+ 0))
+
+(def ^:private unsorted-state
+ {:asc true, :desc true, :group-asc true, :group-desc true, :grouped? false})
+
+(defn- track-order
+ "One step of the browser's `SortState.update` (visualizations/lib/data_grid.ts): fold `value` into `state`, noting
+ whether the values seen so far are monotonic overall, and monotonic within runs of one `group-key`."
+ [{:keys [last-value last-group] :as state} value group-key]
+ (let [state (if (contains? state :last-value)
+ (let [result (compare-pivot-values value last-value)
+ state (-> state
+ (update :asc #(and % (>= result 0)))
+ (update :desc #(and % (<= result 0))))]
+ (if (and (not (zero? result)) (= last-group group-key))
+ (-> state
+ (update :group-asc #(and % (>= result 0)))
+ (update :group-desc #(and % (<= result 0)))
+ (assoc :grouped? true))
+ state))
+ state)]
+ (assoc state :last-value value :last-group group-key)))
+
+(defn- order-distinct-values
+ "The browser's `SortState.sort`: keep `values` in first-seen order, and re-sort them only when the source rows were
+ sorted within groups of the other column but not overall. A two-breakout query therefore gets both axes sorted,
+ while a native query's deliberate row order is kept."
+ [{:keys [grouped? asc desc group-asc group-desc]} values]
+ (cond
+ (not grouped?) values
+ (and group-asc (not asc)) (sort compare-pivot-values values)
+ (and group-desc (not desc)) (sort #(compare-pivot-values %2 %1) values)
+ :else values))
+
+(defn- distinct-values-sorted
+ "Distinct values of column `value-idx` across `rows`, in the order the browser's `distinctValuesSorted` gives them,
+ with column `group-idx` as the grouping column."
+ [rows value-idx group-idx]
+ (let [state (reduce (fn [state row]
+ (track-order state (nth row value-idx) (nth row group-idx)))
+ unsorted-state
+ rows)]
+ (order-distinct-values state (distinct (map #(nth % value-idx) rows)))))
+
+(defn- simple-pivot-grid
+ "Port of the browser's `pivot` (visualizations/lib/data_grid.ts): fold a three-column result into a 2D grid, header
+ row first. Column 0 holds the normal column's title and its values; the other columns are the distinct pivot values.
+ Each cell is the cell column's value for that (normal, pivot) pair, or nil when no row has the pair."
+ [timezone-id {:keys [cols rows viz-settings] :as data} {:keys [normal pivot cell]}]
+ (let [format-rows? (get data :format-rows? true)
+ formatter-for (fn [idx]
+ (formatter/create-formatter timezone-id (nth cols idx) viz-settings format-rows?))
+ format-normal (formatter-for normal)
+ format-pivot (formatter-for pivot)
+ format-cell (formatter-for cell)
+ pivot-values (distinct-values-sorted rows pivot normal)
+ normal-values (distinct-values-sorted rows normal pivot)
+ ;; the last row wins for a repeated (normal, pivot) pair, as the browser's `lastIndexOf` does
+ cells (into {} (map (fn [row] [[(nth row normal) (nth row pivot)] (nth row cell)])) rows)]
+ ;; the browser's `getTitleForColumn` skips the column title override when the table is pivoted
+ (into [(into [(table-data/remapped-display-name (nth cols normal))]
+ ;; headers are plain strings so that pivot->hiccup does not color a numeric pivot value
+ (map (comp pivot-cell->str format-pivot))
+ pivot-values)]
+ (map (fn [normal-value]
+ (into [(format-normal normal-value)]
+ (map (fn [pivot-value]
+ (let [k [normal-value pivot-value]]
+ (when (contains? cells k)
+ (format-cell (get cells k))))))
+ pivot-values)))
+ normal-values)))
+
+(defn simple-pivot?
+ "Does the Table viz's \"Pivot table\" toggle apply to this query result? See [[simple-pivot-indexes]]."
+ [{:keys [cols viz-settings]}]
+ (some? (simple-pivot-indexes cols viz-settings)))
+
+(defn- simple-pivot-content
+ "Hiccup for a Table card whose \"Pivot table\" toggle applies (see [[simple-pivot-indexes]]). The grid is built from
+ every row and, like `render :pivot`, is not cut at the attachment row limit."
+ [timezone-id {:keys [cols viz-settings] :as data} {:keys [cell] :as indexes}]
+ (pivot->hiccup (simple-pivot-grid timezone-id data indexes)
+ {:color-data (select-keys data [:cols :rows])
+ ;; viz-settings carries :table.pivot, which tells the shared color JS to skip row-highlight rules
+ :color-settings viz-settings
+ :left-width 1
+ :measure-names [(:name (nth cols cell))]}))
+
(defn- order-data [data viz-settings]
(if (some? (::mb.viz/table-columns viz-settings))
(let [;; Deduplicate table-columns by name to handle duplicated viz settings
@@ -351,12 +528,11 @@
::mb.viz/show-mini-bar]))
cols))
-(mu/defmethod render :table :- ::RenderedPartCard
- [_chart-type
- _render-type
- timezone-id :- [:maybe :string]
+(mu/defn- flat-table-content
+ "Hiccup for a Table card as a flat table: the columns in `table.columns` order, the rows cut at the attachment row
+ limit with a \"Showing N of M rows\" line when some are cut."
+ [timezone-id :- [:maybe :string]
card
- _dashcard
{:keys [rows viz-settings format-rows?] :as unordered-data}]
(let [[ordered-cols ordered-rows] (order-data unordered-data viz-settings)
data (-> unordered-data
@@ -377,8 +553,19 @@
viz-settings
minibar-cols)
(render-truncation-warning (channel.settings/attachment-table-row-limit) (count rows))]]
- {:content table-body
- :attachments nil}))
+ table-body))
+
+(mu/defmethod render :table :- ::RenderedPartCard
+ [_chart-type
+ _render-type
+ timezone-id :- [:maybe :string]
+ card
+ _dashcard
+ {:keys [cols viz-settings] :as data}]
+ {:content (if-let [indexes (simple-pivot-indexes cols viz-settings)]
+ (simple-pivot-content timezone-id data indexes)
+ (flat-table-content timezone-id card data))
+ :attachments nil})
(defn- blank-cell-value?
"True when a raw cell value should render as an empty placeholder (nil, or a blank string)."
@@ -786,63 +973,6 @@
;;; ------------------------------------------------ pivot tables ------------------------------------------------
-(defn- setting-value
- "Look up `k` in a viz-settings map that may be keyed by either keywords or strings."
- [settings k]
- (or (get settings k) (get settings (name k))))
-
-(defn- pivot-cell->str
- "Display string for an assembled pivot cell (a formatter wrapper, a plain string, or nil)."
- [x]
- (cond
- (nil? x) ""
- (string? x) x
- :else (or (:num-str x) (:text-str x) (str x))))
-
-(defn- pivot->hiccup
- "Render the assembled 2D pivot `rows` (header row first, then data rows) as an HTML table. Cells are
- `white-space: nowrap` so the table takes whatever width it needs (the surrounding pulse body provides
- horizontal scrolling). `opts` may include `:color-data`/`:color-settings` (the query results and viz-settings the
- conditional-formatting rules evaluate against, see [[js.color/cell-background-colors]]), `:left-width` (number of
- leading row-label columns), and `:measure-names` (ordered measure column names) to apply the card's conditional
- formatting to the measure value cells."
- [rows {:keys [color-data color-settings left-width measure-names]}]
- (let [measure-count (max 1 (count measure-names))
- colorable-cell (fn [cell ^long c]
- ;; value cells are NumericWrapper; map each value column back to its measure column
- ;; so the matching conditional-formatting rule applies. Row highlighting is disabled
- ;; for pivots (:table.pivot in pivot-table-content), so the row index is unused.
- (when (and color-data (formatter/NumericWrapper? cell))
- (let [vpos (- c (long left-width))]
- (when (nat-int? vpos)
- [cell 0 (nth measure-names (mod vpos measure-count))]))))
- ;; all value-cell colors are fetched in one batched JS call up front, keyed by [row col] position
- keyed-cells (for [[r row] (map-indexed vector rows)
- [c cell] (map-indexed vector row)
- :let [colorable (colorable-cell cell c)]
- :when colorable]
- [[r c] colorable])
- cell-colors (zipmap (map first keyed-cells)
- (js.color/cell-background-colors (or color-data {:cols [] :rows []})
- color-settings
- (mapv second keyed-cells)))]
- [:table {:style (style/style (style/pivot-table-style))}
- [:tbody
- (map-indexed
- (fn [r row]
- [:tr
- (map-indexed
- (fn [c cell]
- (let [header? (zero? r)
- first-col? (zero? c)
- label? (and (pos? r) first-col?)
- bg (get cell-colors [r c])]
- [(if (or header? label?) :th :td)
- {:style (style/style (style/pivot-cell-style header? label? first-col? bg))}
- (h (pivot-cell->str cell))]))
- row)])
- rows)]]))
-
(defn- pivot-table-content
"Assemble a `:pivot` card's flat (pivot-grouping) result into a Hiccup pivot table, or nil if it can't be
assembled — no column split, a native pivot without a pivot-grouping column, etc. Reuses the pivot-export
diff --git a/src/metabase/channel/render/pdf.clj b/src/metabase/channel/render/pdf.clj
index 2c53f9cffe9..bde7ef70d5e 100644
--- a/src/metabase/channel/render/pdf.clj
+++ b/src/metabase/channel/render/pdf.clj
@@ -930,6 +930,14 @@
:else
{:footer nil :footer-h 0}))
+(defn- body-chart-type
+ "The chart type the table body is styled and footered as. A `:table` card whose \"Pivot table\" toggle applies
+ renders as an assembled grid, so it takes a pivot's treatment: no header dividers and no source row count."
+ [chart-type data]
+ (if (and (= :table chart-type) (body/simple-pivot? data))
+ :pivot
+ chart-type))
+
(defn- table-body-png
"Render a table-like card body (`:table`, `:pivot`, or `:object`) to PNG bytes sized to the `px-w` x `px-h`
cell (logical pixels), supersampled at [[table-supersample]]x. The body is a `width:100%` table inside a
@@ -947,15 +955,16 @@
;; width would only overflow the page and clip the text (see [[table/*text-wrapping-fallback-width*]]).
info (binding [table/*text-wrapping-fallback-width* nil]
(body/render chart-type :inline timezone card dashcard (:data result)))
+ body-type (body-chart-type chart-type (:data result))
note (when (= :object chart-type) (object-detail-note (:content info)))
;; the note is body/render's trailing element, so drop it from the clipped body (it's pinned below)
body (cond-> (:content info) note pop)
- {:keys [footer footer-h]} (card-footer chart-type note (count (get-in result [:data :rows])))
+ {:keys [footer footer-h]} (card-footer body-type note (count (get-in result [:data :rows])))
max-h (max 0 (- (long px-h) footer-h 2))
clip-css (format "width:%dpx;max-height:%dpx;overflow:hidden" (long px-w) max-h)
;; the frame is stroked natively in draw-table-card!, so this wrapper has no border
content [:div
- [:div {:style clip-css} (restyle-table body (= :table chart-type))]
+ [:div {:style clip-css} (restyle-table body (= :table body-type))]
footer]]
(png/render-html-to-png (assoc info :content content) px-w {:channel.render/scale table-supersample})))
diff --git a/test/metabase/channel/render/body_test.clj b/test/metabase/channel/render/body_test.clj
index 627a73e7b33..f96d66ca644 100644
--- a/test/metabase/channel/render/body_test.clj
+++ b/test/metabase/channel/render/body_test.clj
@@ -1521,6 +1521,144 @@
(testing "only the four m2 value cells (> 50) are colored"
(is (= 4 (count (re-seq #"background-color" h))))))))
+(def ^:private simple-pivot-cols
+ [{:name "CATEGORY" :display_name "Category" :base_type :type/Text}
+ {:name "SOURCE" :display_name "Source" :base_type :type/Text}
+ {:name "count" :display_name "Count" :base_type :type/Integer}])
+
+(def ^:private simple-pivot-rows
+ "Ordered by category then source, as a two-breakout query returns them: sorted within each category but not
+ overall, so the browser sorts both axes."
+ [["Gizmo" "Google" 1] ["Gizmo" "Organic" 2]
+ ["Widget" "Affiliate" 3] ["Widget" "Google" 4]])
+
+(def ^:private simple-pivot-settings
+ {:table.pivot true :table.pivot_column "SOURCE" :table.cell_column "count"})
+
+(defn- rendered-grid
+ "The text of every <th> and <td> of a rendered part, one vector per <tr>."
+ [part]
+ (for [tr (render.tu/nodes-with-tag (:content part) :tr)]
+ (->> (tree-seq #(and (seqable? %) (not (map? %)) (not (string? %))) seq tr)
+ (filter #(and (vector? %) (#{:th :td} (first %))))
+ (mapv last))))
+
+(defn- render-simple-pivot
+ ([viz-settings] (render-simple-pivot viz-settings simple-pivot-cols simple-pivot-rows))
+ ([viz-settings cols rows]
+ (body/render :table :inline "UTC" {:display :table :visualization_settings viz-settings} nil
+ {:cols cols :rows rows :viz-settings viz-settings})))
+
+(deftest ^:parallel simple-pivot-test
+ (testing "a Table card with the \"Pivot table\" toggle on renders as the browser's simple pivot (#76931)"
+ (is (= [["Category" "Affiliate" "Google" "Organic"]
+ ["Gizmo" "" "1" "2"]
+ ["Widget" "3" "4" ""]]
+ (rendered-grid (render-simple-pivot simple-pivot-settings)))))
+ (testing "string-keyed settings pivot too"
+ (is (= (rendered-grid (render-simple-pivot simple-pivot-settings))
+ (rendered-grid (render-simple-pivot (update-keys simple-pivot-settings name))))))
+ (testing "the row-label header is the column's display name; a column title override is ignored, as in the browser"
+ (let [card {:display :table
+ :visualization_settings {:column_settings {"[\"name\",\"CATEGORY\"]" {:column_title "Cat"}}}}
+ part (body/render :table :inline "UTC" card nil
+ {:cols simple-pivot-cols :rows simple-pivot-rows :viz-settings simple-pivot-settings})]
+ (is (= "Category" (ffirst (rendered-grid part))))))
+ (testing "the flat table is unchanged when the toggle does not apply"
+ (let [flat (html (:content (render-simple-pivot {})))]
+ (doseq [[reason settings] [["toggle off" (assoc simple-pivot-settings :table.pivot false)]
+ ["unknown pivot column" (assoc simple-pivot-settings :table.pivot_column "NOPE")]
+ ["cell column missing" (dissoc simple-pivot-settings :table.cell_column)]
+ ["pivot and cell alike" (assoc simple-pivot-settings :table.cell_column "SOURCE")]]]
+ (testing reason
+ (is (= flat (html (:content (render-simple-pivot settings)))))))))
+ (testing "a result with four columns stays flat"
+ (let [cols (conj simple-pivot-cols {:name "extra" :display_name "Extra" :base_type :type/Text})
+ rows (mapv #(conj % "x") simple-pivot-rows)]
+ (is (= [["Category" "Source" "Count" "Extra"]
+ ["Gizmo" "Google" "1" "x"]
+ ["Gizmo" "Organic" "2" "x"]
+ ["Widget" "Affiliate" "3" "x"]
+ ["Widget" "Google" "4" "x"]]
+ (rendered-grid (render-simple-pivot simple-pivot-settings cols rows)))))))
+
+(deftest simple-pivot-row-limit-test
+ (testing "the grid is built from every row, not only the first attachment-table-row-limit rows"
+ (mt/with-temporary-setting-values [attachment-table-row-limit 2]
+ (is (= [["Category" "Affiliate" "Google" "Organic"]
+ ["Gizmo" "" "1" "2"]
+ ["Widget" "3" "4" ""]]
+ (rendered-grid (render-simple-pivot simple-pivot-settings)))))))
+
+(deftest ^:parallel simple-pivot-compare-values-test
+ (let [day (fn [d] (java.time.LocalDate/of 2024 1 (int d)))]
+ (doseq [[a b expected] [[nil nil 0] [nil "a" -1] ["a" nil 1] [nil 1 -1] [nil {:a 1} -1] [{:a 1} nil 1]
+ ["a" "b" -1] ["b" "a" 1] ["a" "a" 0]
+ [1 2.5 -1] [3N 2 1] [2 2.0 0]
+ [(day 1) (day 2) -1] [:a :b -1] [false true -1]
+ ["1" 1 0] [(day 1) "2024-01-01" 0] [{:a 1} {:b 2} 0]]]
+ (testing (pr-str [a b])
+ (is (= expected (Integer/signum (int (#'body/compare-pivot-values a b)))))))))
+
+(deftest ^:parallel simple-pivot-order-test
+ (testing "a native query's deliberate row order is kept when the rows are not sorted within groups"
+ (is (= [["Category" "Organic" "Google"]
+ ["Widget" "1" ""]
+ ["Gizmo" "" "2"]]
+ (rendered-grid (render-simple-pivot simple-pivot-settings simple-pivot-cols
+ [["Widget" "Organic" 1] ["Gizmo" "Google" 2]])))))
+ (testing "rows sorted descending within groups sort the headings descending"
+ (is (= [["Category" "Organic" "Google"]
+ ["Gizmo" "2" "1"]
+ ["Widget" "4" "3"]]
+ (rendered-grid (render-simple-pivot simple-pivot-settings simple-pivot-cols
+ [["Gizmo" "Organic" 2] ["Gizmo" "Google" 1]
+ ["Widget" "Organic" 4] ["Widget" "Google" 3]])))))
+ (testing "nil pivot values sort first and get an empty heading"
+ (is (= [["Category" "" "Google"]
+ ["Gizmo" "1" "2"]
+ ["Widget" "3" "4"]]
+ (rendered-grid (render-simple-pivot simple-pivot-settings simple-pivot-cols
+ [["Gizmo" nil 1] ["Gizmo" "Google" 2]
+ ["Widget" nil 3] ["Widget" "Google" 4]]))))
+ (is (= [nil nil 1 2] (sort @#'body/compare-pivot-values [2 nil 1 nil]))))
+ (testing "numeric pivot values are formatted as headings and sorted numerically"
+ (let [cols [{:name "CATEGORY" :display_name "Category" :base_type :type/Text}
+ {:name "YEAR" :display_name "Year" :base_type :type/Integer}
+ {:name "count" :display_name "Count" :base_type :type/Integer}]]
+ (is (= [["Category" "2" "10"]
+ ["Gizmo" "1" "2"]
+ ["Widget" "3" "4"]]
+ (rendered-grid (render-simple-pivot (assoc simple-pivot-settings :table.pivot_column "YEAR") cols
+ [["Gizmo" 2 1] ["Gizmo" 10 2] ["Widget" 2 3] ["Widget" 10 4]])))))))
+
+(deftest ^:parallel simple-pivot-sort-state-test
+ (testing "no row sequence leaves a grouped sort state both ascending and descending within groups"
+ ;; every sequence of four rows over these values and groups, and every state along the way
+ (let [row-choices (for [value [nil 1 2 "a"], group [:x :y]] [value group])
+ row-seqs (reduce (fn [acc _] (for [rows acc, row row-choices] (conj rows row)))
+ [[]]
+ (range 4))]
+ (is (empty? (for [rows row-seqs
+ state (reductions (fn [state [value group]] (#'body/track-order state value group))
+ @#'body/unsorted-state
+ rows)
+ :when (and (:grouped? state) (:group-asc state) (:group-desc state))]
+ rows))))))
+
+(deftest simple-pivot-conditional-formatting-test
+ (let [render-with (fn [rule]
+ (html (:content (render-simple-pivot (assoc simple-pivot-settings
+ :table.column_formatting [rule])))))]
+ (testing "a value rule on the cell column colors the matching cells, and nothing else"
+ (is (= 2 (count (re-seq #"background-color"
+ (render-with {:type "single" :columns ["count"] :color "#ff0000"
+ :operator ">" :value 2}))))))
+ (testing "a row-highlight rule colors only the matching cells, as in the browser's pivoted table"
+ (is (= 2 (count (re-seq #"background-color"
+ (render-with {:type "single" :columns ["count"] :color "#ff0000"
+ :operator ">" :value 2 :highlight_row true}))))))))
+
(deftest render-pin-map-resolves-columns-by-semantic-type-test
(testing "render :pin_map finds lat/long columns by semantic type when the column settings aren't persisted"
(fake/with-fake-routes (render.tu/fake-tile-routes #"https://.*tile\.openstreetmap\.org/.*")
diff --git a/test/metabase/channel/render/pdf_test.clj b/test/metabase/channel/render/pdf_test.clj
index b5750482369..f8bdf7a17e0 100644
--- a/test/metabase/channel/render/pdf_test.clj
+++ b/test/metabase/channel/render/pdf_test.clj
@@ -903,6 +903,17 @@
;; :pivot's own renderer degrades to :table internally, hence the trailing :table
(is (= [:table :pivot :table :object] @rendered)))))
+(deftest ^:parallel simple-pivot-body-chart-type-test
+ (let [cols [{:name "R" :base_type :type/Text} {:name "C" :base_type :type/Text} {:name "m" :base_type :type/Integer}]
+ rows [["a" "x" 10] ["a" "y" 20]]
+ vs {:table.pivot true :table.pivot_column "C" :table.cell_column "m"}]
+ (testing "a :table card with the \"Pivot table\" toggle on takes the pivot treatment: no row-count footer"
+ (is (= :pivot (#'pdf/body-chart-type :table {:cols cols :rows rows :viz-settings vs})))
+ (is (nil? (:footer (#'pdf/card-footer :pivot nil 20)))))
+ (testing "a :table card with the toggle off keeps its row-count footer"
+ (is (= :table (#'pdf/body-chart-type :table {:cols cols :rows rows :viz-settings (assoc vs :table.pivot false)})))
+ (is (some? (:footer (#'pdf/card-footer :table nil 20)))))))
+
(deftest ^:parallel table-like-chart-types-test
(testing "native table, pivot, and object-detail cards all classify into the framed table path"
(let [data {:cols [{:name "n" :display_name "N" :base_type :type/Integer}]
diff --git a/test/metabase/pulse/dashboard_subscription_test.clj b/test/metabase/pulse/dashboard_subscription_test.clj
index 55203a70c26..f4fee4ce8fe 100644
--- a/test/metabase/pulse/dashboard_subscription_test.clj
+++ b/test/metabase/pulse/dashboard_subscription_test.clj
@@ -4,6 +4,7 @@
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer :all]
+ [hiccup.core :refer [html]]
[medley.core :as m]
[metabase.channel.core :as channel]
[metabase.channel.email.result-attachment :as email.result-attachment]
@@ -1219,6 +1220,42 @@
[{:keys [name field_ref]} enabled?]
{:name name :field_ref field_ref :enabled enabled?})
+(deftest simple-pivot-table-test
+ (testing "a Table card with the \"Pivot table\" toggle on is pivoted in email and Slack alike (#76931)"
+ (tests!
+ {:pulse {:skip_if_empty false}
+ :display :table
+ :card {:dataset_query (mt/mbql-query orders
+ {:aggregation [[:count]]
+ :breakout [$product_id->products.category
+ $user_id->people.source]})
+ :visualization_settings {:table.pivot true
+ :table.pivot_column "SOURCE"
+ :table.cell_column "count"}}
+ ;; Slack rasterizes the rendered hiccup; wrap the rasterizer to see what it was given
+ :fixture (fn [_ thunk]
+ (with-redefs [channel.render/png-from-render-info
+ (pulse.test-util/wrap-function @#'channel.render/png-from-render-info)]
+ (thunk)))
+ :assert
+ {:email
+ (fn [_ [email]]
+ (is (= (rasta-dashsub-message {:message [{">Facebook</th>" true
+ ">Product → Category</th>" true}
+ pulse.test-util/png-attachment]})
+ (mt/summarize-multipart-single-email email
+ #">Facebook</th>"
+ #">Product → Category</th>"))))
+ :slack
+ (fn [_ _]
+ (let [[[rendered-info]] (pulse.test-util/input @#'channel.render/png-from-render-info)
+ h (html (:content rendered-info))]
+ (testing "the hiccup handed to the rasterizer is the pivoted grid"
+ (is (str/includes? h ">Facebook</th>"))
+ (is (str/includes? h ">Product → Category</th>"))
+ ;; header row + Doohickey, Gadget, Gizmo, Widget
+ (is (= 5 (count (re-seq #"<tr" h)))))))}})))
+
(deftest dashboard-subscription-attachments-test
(testing "Dashboard subscription attachments respect dashcard viz settings."
(mt/with-fake-inbox
diff --git a/test/metabase/pulse/pulse_integration_test.clj b/test/metabase/pulse/pulse_integration_test.clj
index 701c1a9a47b..b211a8c4efa 100644
--- a/test/metabase/pulse/pulse_integration_test.clj
+++ b/test/metabase/pulse/pulse_integration_test.clj
@@ -974,3 +974,48 @@
(mt/with-test-user nil
(pulse.send/send-pulse! pulse)))
(is (string? (get-in @mt/inbox ["[email protected]" 0 :body 0 :content])))))))))
+
+(deftest simple-pivot-table-is-pivoted-test
+ (testing "a Table card with the \"Pivot table\" toggle on arrives pivoted, as in the browser (#76931)"
+ (mt/dataset test-data
+ (mt/with-temp [:model/Card {card-id :id} {:name "Orders by category and source"
+ :display :table
+ :dataset_query (mt/mbql-query orders
+ {:aggregation [[:count]]
+ :breakout [$product_id->products.category
+ $user_id->people.source]})
+ :visualization_settings {:table.pivot true
+ :table.pivot_column "SOURCE"
+ :table.cell_column "count"}}
+ :model/Dashboard {dash-id :id} {:name "Simple pivot dashboard"}
+ :model/DashboardCard {pivoted-dashcard-id :id} {:dashboard_id dash-id
+ :card_id card-id}
+ ;; the dashcard can turn the toggle off again; the email must follow the dashcard
+ :model/DashboardCard {flat-dashcard-id :id} {:dashboard_id dash-id
+ :card_id card-id
+ :visualization_settings {:table.pivot false}}
+ :model/Pulse {pulse-id :id :as pulse} {:name "Test Pulse"
+ :dashboard_id dash-id}
+ :model/PulseCard _ {:pulse_id pulse-id
+ :card_id card-id
+ :dashboard_card_id pivoted-dashcard-id
+ :position 0}
+ :model/PulseCard _ {:pulse_id pulse-id
+ :card_id card-id
+ :dashboard_card_id flat-dashcard-id
+ :position 1}
+ :model/PulseChannel {pulse-channel-id :id} {:channel_type :email
+ :pulse_id pulse-id
+ :enabled true}
+ :model/PulseChannelRecipient _ {:pulse_channel_id pulse-channel-id
+ :user_id (mt/user->id :rasta)}]
+ (let [[[header & pivoted-rows] flat-rows] (run-pulse-and-return-data-tables! pulse)]
+ (testing "the pivoted dashcard: sources across, categories down, one count per cell"
+ (is (= ["Product → Category" "Affiliate" "Facebook" "Google" "Organic" "Twitter"]
+ header))
+ (is (= ["Doohickey" "Gadget" "Gizmo" "Widget"]
+ (map first pivoted-rows)))
+ (is (every? #(= 6 (count %)) pivoted-rows)))
+ (testing "the dashcard with the toggle off: the flat three-column table"
+ (is (= 20 (count flat-rows)))
+ (is (every? #(= 3 (count %)) flat-rows))))))))