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
Add support for pivot table static viz (#75337)
Nick Fitzpatrickdd1ec2032132
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 3d1f36b7ef6..e2cd2b8f19d 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -498,6 +498,7 @@notificationparameterspermissions+ pivotpremium-featuresquery-processorsettings@@ -1542,7 +1543,8 @@pivot{:team "UX West"- :api #{metabase.pivot.core}+ :api #{metabase.pivot.core+ metabase.pivot.postprocess}:uses #{modelsutil}}diff --git a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.jsindex e8ebadaee27..b6ca2a36027 100644--- a/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js+++ b/e2e/test/scenarios/sharing/sharing-reproductions.cy.spec.js@@ -996,6 +996,15 @@ describe("issue 49525", { tags: "@external" }, () => {columns: ["CATEGORY"],values: ["COUNT"],},+ "table.column_formatting": [+ {+ type: "single",+ columns: ["count"],+ color: "#84BB4C",+ operator: ">",+ value: 10,+ },+ ],},};@@ -1053,6 +1062,45 @@ describe("issue 49525", { tags: "@external" }, () => {});});});++ it("renders the pivot table inline in the subscription email body (UXW-4378)", () => {+ H.openDashboardMenu("Subscriptions");+ H.sidebar().within(() => {+ cy.findByText("Email it").click();+ cy.findByPlaceholderText("Enter user names or email addresses").click();+ });++ H.popover().findByText(`${first_name} ${last_name}`).click();++ // Close the recipient popover so the send button is clickable+ H.sidebar().findByText("To:").click();++ H.sendEmailAndVisitIt();++ cy.get(".container").within(() => {+ // Transposed pivot: row dimension as the top-left label, categories across the top,+ // a grand-totals column appended, and no internal pivot-grouping column.+ cy.findByText("Created At: Year").should("exist");+ ["Doohickey", "Gadget", "Gizmo", "Widget"].forEach((category) =>+ cy.findByText(category).should("exist"),+ );+ cy.findByText("Row totals").should("exist");+ cy.contains("pivot-grouping").should("not.exist");++ // Conditional formatting (count > 10 -> green) colors only the larger value cells:+ // the 8 cell stays transparent, the 200 grand total is green.+ cy.contains("td", /^8$/).should(+ "have.css",+ "background-color",+ "rgba(0, 0, 0, 0)",+ );+ cy.contains("td", /^200$/).should(+ "have.css",+ "background-color",+ "rgba(132, 187, 76, 0.65)",+ );+ });+ });});describe("issue 54603", () => {diff --git a/src/metabase/channel/render/body.clj b/src/metabase/channel/render/body.cljindex 427422f8dc4..7b133a4fb86 100644--- a/src/metabase/channel/render/body.clj+++ b/src/metabase/channel/render/body.clj@@ -14,12 +14,15 @@[metabase.channel.settings :as channel.settings][metabase.formatter.core :as formatter][metabase.models.visualization-settings :as mb.viz]+ [metabase.pivot.core :as pivot.core]+ [metabase.pivot.postprocess :as pivot.postprocess][metabase.query-processor.streaming :as qp.streaming][metabase.query-processor.streaming.common :as streaming.common][metabase.timeline.core :as timeline][metabase.types.core :as types][metabase.util :as u][metabase.util.i18n :refer [deferred-trs trs tru]]+ [metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms])@@ -416,6 +419,112 @@:html{:content [:div content] :attachments nil})))+;;; ------------------------------------------------ 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-selector` (from [[js.color/make-color-selector]]),+ `: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-selector left-width measure-names]}]+ (let [measure-count (max 1 (count measure-names))+ cell-bg (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-selector (formatter/NumericWrapper? cell))+ (let [vpos (- c (long left-width))]+ (when (nat-int? vpos)+ (let [mname (nth measure-names (mod vpos measure-count))]+ (js.color/get-background-color color-selector cell mname 0))))))]+ [:table {:style (style/style (style/pivot-table-style))}+ [:tbody+ (map-indexed+ (fn [r row]+ [:tr+ (map-indexed+ (fn [c cell]+ (let [header? (zero? r)+ label? (and (pos? r) (zero? c))+ bg (cell-bg cell c)]+ [(if (or header? label?) :th :td)+ {:style (style/style (style/pivot-cell-style header? label? 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+ assembly ([[pivot.postprocess/build-pivot-output]] + [[pivot.core]]) and the row/col/measure indices the+ pivot QP already computed in `:pivot-export-options`."+ [card dashcard {:keys [cols pivot-export-options] :as data}]+ (let [settings (merge (:visualization_settings card) (:visualization_settings dashcard))+ split (setting-value settings :pivot_table.column_split)+ pg-idx (pivot.postprocess/pivot-grouping-index (mapv :name cols))]+ (when (and split pivot-export-options pg-idx)+ (let [columns (pivot.core/columns-without-pivot-group cols)+ row-idxs (vec (:pivot-rows pivot-export-options))+ col-idxs (vec (:pivot-cols pivot-export-options))+ ;; The pivot QP only fills :pivot-measures when the split's measure names resolve to result+ ;; columns; when they don't (e.g. a casing mismatch) default to every non row/col column,+ ;; mirroring pivot.postprocess/add-pivot-measures.+ val-idxs (if-let [measures (seq (:pivot-measures pivot-export-options))]+ (vec measures)+ (into [] (remove (set (concat row-idxs col-idxs))) (range (count columns))))]+ (when (and (seq val-idxs) (or (seq row-idxs) (seq col-idxs)))+ (let [tz (:results_timezone data)+ fr? (get data :format-rows? true)+ ;; Totals visibility is read from `settings` (:pivot.show_row_totals / :pivot.show_column_totals)+ ;; by build-pivot-output, not from pivot-export-options.+ peo {:pivot-rows row-idxs+ :pivot-cols col-idxs+ :pivot-measures val-idxs}+ fmts (formatter/make-formatters columns row-idxs col-idxs val-idxs settings tz fr?)+ output (pivot.postprocess/build-pivot-output+ {:data data :settings settings :format-rows? fr? :pivot-export-options peo}+ fmts)+ ;; Build a color selector from the card's conditional formatting, over the displayed data+ ;; (group=0 rows with the pivot-grouping column removed, aligned with `columns`).+ color-selector (when (seq (setting-value settings :table.column_formatting))+ (let [base-rows (into [] (comp (filter #(zero? (nth % pg-idx)))+ (map #(vec (m/remove-nth pg-idx %))))+ (:rows data))]+ ;; :table.pivot tells the shared color JS to skip row-highlight rules (which+ ;; don't map onto an assembled pivot); only value/range cell rules run.+ (js.color/make-color-selector {:cols columns :rows base-rows}+ (assoc settings :table.pivot true))))]+ ;; Unlike the flat :table path, a pivot aggregates all rows into a bounded grid rather than+ ;; truncating displayed rows, so the flat-table row-count truncation warning doesn't apply.+ (pivot->hiccup output {:color-selector color-selector+ :left-width (count row-idxs)+ :measure-names (mapv #(:name (nth columns %)) val-idxs)})))))))++(mu/defmethod render :pivot :- ::RenderedPartCard+ [_chart-type render-type timezone-id card dashcard data]+ (or (try+ (when-let [content (pivot-table-content card dashcard data)]+ {:content content :attachments nil})+ (catch Throwable e+ (log/warn e "Failed to render pivot table; falling back to a flat table")+ nil))+ ;; Native pivots, field-ref splits, or assembly errors degrade to the existing flat table.+ (render :table render-type timezone-id card dashcard data)))+(defn- smart-scalar-comparison-statement[unit value](case unitdiff --git a/src/metabase/channel/render/card.clj b/src/metabase/channel/render/card.cljindex 774ac096f5f..4ee4ea31b69 100644--- a/src/metabase/channel/render/card.clj+++ b/src/metabase/channel/render/card.clj@@ -143,6 +143,9 @@:combo} display-type)(chart-type :javascript_visualization "display-type is javascript_visualization")+ (= :pivot display-type)+ (chart-type :pivot "display-type is pivot")+:else(chart-type :table "no other chart types match")))))diff --git a/src/metabase/channel/render/style.clj b/src/metabase/channel/render/style.cljindex 1d8d7dfe7a7..d9f5d6a26a6 100644--- a/src/metabase/channel/render/style.clj+++ b/src/metabase/channel/render/style.clj@@ -75,6 +75,14 @@"Used as color for the border of table, table header, and table body rows for charts with `:table` visualization.""#F0F0F0")+(def ^:const color-pivot-header-bg+ "Background fill for the column-header cells of a rendered `:pivot` table."+ "#F5F6F7")++(def ^:const color-pivot-label-bg+ "Background fill for the row-label cells of a rendered `:pivot` table."+ "#FAFAFA")+;; don't try to improve the code and make this a plain variable, in EE it's customizable which is why it's a function.;; Too much of a hassle to have it be a fn in one version of the code an a constant in another(defn primary-color@@ -191,3 +199,27 @@:max-height "30px":object-fit "contain":display "block"})++(defn pivot-table-style+ "Style for the `<table>` element of a rendered `:pivot` table."+ []+ (merge (font-style)+ {:border-collapse :collapse+ :font-size (format "%spx" font-size)}))++(defn pivot-cell-style+ "Style for one cell of a rendered `:pivot` table. `header?`/`label?` select the cell role; `bg`, when+ non-nil, is the conditional-formatting background color for a value cell."+ [header? label? bg]+ (merge {:border (str "1px solid " color-border)+ :padding "5px 10px"+ :white-space :nowrap}+ (cond+ header? {:background color-pivot-header-bg+ :font-weight 700+ :text-align :left}+ label? {:background color-pivot-label-bg+ :font-weight 600+ :text-align :left}+ :else {:text-align :right})+ (when bg {:background-color bg})))diff --git a/src/metabase/formatter/core.clj b/src/metabase/formatter/core.cljindex 4fc87d980c8..2bc78bff339 100644--- a/src/metabase/formatter/core.clj+++ b/src/metabase/formatter/core.clj@@ -15,7 +15,9 @@create-formatterformat-geographic-coordinatesformat-scalar-number+ get-formattergraphing-column-row-fns+ make-formattersmake-temporal-str-formattermap->NumericWrappermap->TextWrapperdiff --git a/src/metabase/formatter/impl.clj b/src/metabase/formatter/impl.cljindex 20d26bb58eb..06b879f52c5 100644--- a/src/metabase/formatter/impl.clj+++ b/src/metabase/formatter/impl.clj@@ -316,6 +316,42 @@(->TextWrapper (str value) value))identity))))+(defn get-formatter+ "Returns a memoized fn that builds a column formatter (via [[create-formatter]]) for a column."+ [timezone settings format-rows?]+ (memoize+ (fn [column]+ (create-formatter timezone column settings format-rows?))))++(defn- create-formatters+ "Value formatters for the columns at `indexes`; each formats a raw value via+ [[metabase.query-processor.streaming.common/format-value]] then the column's formatter."+ [columns indexes timezone settings format-rows?]+ (let [formatter-fn (get-formatter timezone settings format-rows?)]+ (mapv (fn [idx]+ (let [formatter (formatter-fn (nth columns idx))]+ (fn [value]+ (formatter (streaming.common/format-value value)))))+ indexes)))++(mu/defn make-formatters :- [:map+ [:row-formatters [:sequential ifn?]]+ [:col-formatters [:sequential ifn?]]+ [:val-formatters [:sequential ifn?]]]+ "Row/col/measure value formatters for a pivot export, keyed by `:row-formatters`/`:col-formatters`/`:val-formatters`.+ Shared by the CSV export and static-viz pivot render paths. `row-indexes`/`col-indexes`/`val-indexes` are column+ indexes into `columns`."+ [columns :- [:sequential :map]+ row-indexes :- [:maybe [:sequential :int]]+ col-indexes :- [:maybe [:sequential :int]]+ val-indexes :- [:maybe [:sequential :int]]+ settings :- [:maybe :map]+ timezone :- [:maybe :string]+ format-rows? :- :boolean]+ {:row-formatters (create-formatters columns row-indexes timezone settings format-rows?)+ :col-formatters (create-formatters columns col-indexes timezone settings format-rows?)+ :val-formatters (create-formatters columns val-indexes timezone settings format-rows?)})+(defn NumericWrapper?"Is `x` an instance of `NumericWrapper`?"[x]diff --git a/src/metabase/query_processor/pivot/postprocess.clj b/src/metabase/pivot/postprocess.cljsimilarity index 99%rename from src/metabase/query_processor/pivot/postprocess.cljrename to src/metabase/pivot/postprocess.cljindex 4f7673a5baa..efeb97290c8 100644--- a/src/metabase/query_processor/pivot/postprocess.clj+++ b/src/metabase/pivot/postprocess.clj@@ -1,4 +1,4 @@-(ns metabase.query-processor.pivot.postprocess+(ns metabase.pivot.postprocess"Post-process utils for pivot exportsThe shape returned by the pivot qp is not the same visually as what a pivot table looks like in the app.diff --git a/src/metabase/query_processor/streaming/csv.clj b/src/metabase/query_processor/streaming/csv.cljindex d259d17778e..9ce61ff51b3 100644--- a/src/metabase/query_processor/streaming/csv.clj+++ b/src/metabase/query_processor/streaming/csv.clj@@ -5,7 +5,7 @@[medley.core :as m][metabase.formatter.core :as formatter][metabase.pivot.core :as pivot]- [metabase.query-processor.pivot.postprocess :as qp.pivot.postprocess]+ [metabase.pivot.postprocess :as pivot.postprocess][metabase.query-processor.settings :as qp.settings][metabase.query-processor.streaming.common :as streaming.common][metabase.query-processor.streaming.interface :as qp.si]@@ -60,29 +60,6 @@string))(when must-quote (.write writer "\"")))))-(defn get-formatter- "Returns a memoized formatter for a column"- [timezone settings format-rows?]- (memoize- (fn [column]- (formatter/create-formatter timezone column settings format-rows?))))--(defn- create-formatters- [columns indexes timezone settings format-rows?]- (let [formatter-fn (get-formatter timezone settings format-rows?)]- (mapv (fn [idx]- (let [column (nth columns idx)- formatter (formatter-fn column)]- (fn [value]- (formatter (streaming.common/format-value value)))))- indexes)))--(defn- make-formatters- [columns row-indexes col-indexes val-indexes settings timezone format-rows?]- {:row-formatters (create-formatters columns row-indexes timezone settings format-rows?)- :col-formatters (create-formatters columns col-indexes timezone settings format-rows?)- :val-formatters (create-formatters columns val-indexes timezone settings format-rows?)})-(defmethod qp.si/streaming-results-writer :csv[_ ^OutputStream os](let [writer (BufferedWriter. (OutputStreamWriter. os StandardCharsets/UTF_8))@@ -94,7 +71,7 @@:or {format-rows? truepivot? false}} :data} viz-settings](let [col-names (vec (streaming.common/column-titles ordered-cols viz-settings format-rows?))- pivot-grouping-index (qp.pivot.postprocess/pivot-grouping-index col-names)]+ pivot-grouping-index (pivot.postprocess/pivot-grouping-index col-names)](cond(and pivot? pivot-export-options)(vreset! pivot-data@@ -128,7 +105,7 @@(vswap! pivot-data update-in [:data :rows] conj! ordered-row)(if pivot-group;; Non-pivoted pivot table: we have to remove the pivot-grouping column- (when (= qp.pivot.postprocess/non-pivot-row-group (int pivot-group))+ (when (= pivot.postprocess/non-pivot-row-group (int pivot-group))(let [formatted-row (->> (mapv (fn [formatter r](formatter (streaming.common/format-value r)))@ordered-formatters ordered-row)@@ -145,8 +122,8 @@(let [{:keys [data settings timezone format-rows? pivot-export-options]} @pivot-data{:keys [pivot-rows pivot-cols pivot-measures]} pivot-export-optionscolumns (pivot/columns-without-pivot-group (:cols data))- formatters (make-formatters columns pivot-rows pivot-cols pivot-measures settings timezone format-rows?)- output (qp.pivot.postprocess/build-pivot-output+ formatters (formatter/make-formatters columns pivot-rows pivot-cols pivot-measures settings timezone format-rows?)+ output (pivot.postprocess/build-pivot-output(update-in @pivot-data [:data :rows] persistent!)formatters)](doseq [xf-row output]diff --git a/src/metabase/query_processor/streaming/json.clj b/src/metabase/query_processor/streaming/json.cljindex 19946c9273c..7d5feca1c43 100644--- a/src/metabase/query_processor/streaming/json.clj+++ b/src/metabase/query_processor/streaming/json.clj@@ -5,7 +5,7 @@(:require[medley.core :as m][metabase.formatter.core :as formatter]- [metabase.query-processor.pivot.postprocess :as qp.pivot.postprocess]+ [metabase.pivot.postprocess :as pivot.postprocess][metabase.query-processor.streaming.common :as streaming.common][metabase.query-processor.streaming.interface :as qp.si][metabase.util.json :as json]@@ -39,7 +39,7 @@(begin! [_ {{:keys [ordered-cols results_timezone format-rows?]:or {format-rows? true}} :data} viz-settings](let [cols (streaming.common/column-titles ordered-cols viz-settings format-rows?)- pivot-grouping (qp.pivot.postprocess/pivot-grouping-index cols)]+ pivot-grouping (pivot.postprocess/pivot-grouping-index cols)](when pivot-grouping (vreset! pivot-grouping-idx pivot-grouping))(let [names (cond->> colspivot-grouping (m/remove-nth pivot-grouping))]@@ -61,7 +61,7 @@;; when a pivot-grouping col exists, we check its group number. When it's zero,;; we keep it, otherwise don't include it in the results as it's a row representing a subtotal of some kind(when (or (not group)- (= qp.pivot.postprocess/non-pivot-row-group (int group)))+ (= pivot.postprocess/non-pivot-row-group (int group)))(when-not (zero? row-num)(.write writer ",\n"))(json/encode-todiff --git a/src/metabase/query_processor/streaming/xlsx.clj b/src/metabase/query_processor/streaming/xlsx.cljindex 17c62411183..9b7fa6e6a7a 100644--- a/src/metabase/query_processor/streaming/xlsx.clj+++ b/src/metabase/query_processor/streaming/xlsx.clj@@ -9,7 +9,7 @@[metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing][metabase.models.visualization-settings :as mb.viz][metabase.pivot.core :as pivot]- [metabase.query-processor.pivot.postprocess :as qp.pivot.postprocess]+ [metabase.pivot.postprocess :as pivot.postprocess][metabase.query-processor.settings :as qp.settings][metabase.query-processor.streaming.common :as streaming.common][metabase.query-processor.streaming.interface :as qp.si]@@ -615,9 +615,9 @@agg-fns (mapv col->aggregation-fn cols)](-> pivot-opts(assoc :column-titles titles)- qp.pivot.postprocess/add-pivot-measures+ pivot.postprocess/add-pivot-measures(assoc :aggregation-functions agg-fns)- (assoc :pivot-grouping-key (qp.pivot.postprocess/pivot-grouping-index titles)))))+ (assoc :pivot-grouping-key (pivot.postprocess/pivot-grouping-index titles)))))(defn- track-n-cols-for-autosizing![n sheet]@@ -634,18 +634,11 @@(spreadsheet/add-row! sheet (streaming.common/column-titles ordered-cols (or viz-settings {}) format-rows?)))sheet))-(defn get-formatter- "Returns a memoized formatter for a column"- [timezone settings format-rows?]- (memoize- (fn [column]- (formatter/create-formatter timezone column settings format-rows?))))-(defn- create-formatters[cell-styles cols indexes timezone settings format-rows?](let [cell-styles (vec cell-styles)cols (vec cols)- formatter-fn (get-formatter timezone settings format-rows?)]+ formatter-fn (formatter/get-formatter timezone settings format-rows?)](mapv (fn [idx](let [col (nth cols idx)formatter (formatter-fn col)]@@ -685,7 +678,7 @@:pivot-rows []}(m/filter-vals some? pivot-export-options)) ordered-cols))non-pivot-cols (pivot/columns-without-pivot-group ordered-cols)]- (vreset! pivot-grouping-index (qp.pivot.postprocess/pivot-grouping-index (mapv :display_name ordered-cols)))+ (vreset! pivot-grouping-index (pivot.postprocess/pivot-grouping-index (mapv :display_name ordered-cols)))(if pivot-spec;; If we're generating a pivot table, just initialize the `pivot-data` volatile but not the workbook, yet(vreset! pivot-data@@ -719,7 +712,7 @@(if @pivot-data(vswap! pivot-data update-in [:data :rows] conj! ordered-row)(when (or (not group)- (= qp.pivot.postprocess/non-pivot-row-group (int group)))+ (= pivot.postprocess/non-pivot-row-group (int group)))(let [{:keys [cell-styles typed-cell-styles]} @styles](add-row! @workbook-sheet (inc row-num) row' ordered-cols' viz-settings cell-styles typed-cell-styles)(when (= (inc row-num) *auto-sizing-threshold*)@@ -743,7 +736,7 @@settingstimezoneformat-rows?)- output (qp.pivot.postprocess/build-pivot-output+ output (pivot.postprocess/build-pivot-output(update-in @pivot-data [:data :rows] persistent!)formatters)sheet (init-workbook {:workbook workbookdiff --git a/test/metabase/channel/render/body_test.clj b/test/metabase/channel/render/body_test.cljindex baf5bfdd06d..cf8368ff340 100644--- a/test/metabase/channel/render/body_test.clj+++ b/test/metabase/channel/render/body_test.clj@@ -9,6 +9,7 @@[hickory.select :as hik.s][metabase.channel.render.body :as body][metabase.channel.render.core :as channel.render]+ [metabase.channel.render.js.color :as js.color][metabase.config.core :as config][metabase.formatter.core :as formatter][metabase.notification.payload.execute :as notification.execute]@@ -1088,9 +1089,14 @@:breakout [$category !year.created_at]})}](mt/with-current-user (mt/user->id :rasta)(let [card-doc (render.tu/render-pivot-card-as-hickory! card-id)- card-header-els (hik.s/select (hik.s/tag :th) card-doc)]- (is (= ["Category" "Created At: Year" "Sum of Price"]- (mapv (comp first :content) card-header-els)))))))))+ card-header-els (hik.s/select (hik.s/tag :th) card-doc)+ headers (mapv (comp first :content) card-header-els)]+ ;; A pivot card renders as an assembled (transposed) table: the row-dimension label is the+ ;; top-left header, the pivot-grouping column is excluded, and row/grand totals are added.+ (is (= "Category" (first headers)))+ (is (not (some #{"pivot-grouping"} headers)))+ (is (some #{"Row totals"} headers))+ (is (> (count headers) 3))))))))(deftest render-sankey-chart-test(testing "The static-viz sankey chart renders correctly."@@ -1247,3 +1253,104 @@"ID""Product ID [external remap]"](map (comp :title second) (-> table :content second (nth 2) second last)))))))))++(def ^:private pivot-test-split+ "Single-measure pivot split shared by the render-pivot tests (rows R, cols C, measure m)."+ {:rows ["R"] :columns ["C"] :values ["m"]})++(def ^:private pivot-test-data+ "A `:pivot` query result: rows R, cols C, single measure m, plus the pivot-grouping column the QP emits.+ `:pivot-export-options` carries the row/col/measure column indexes in the pivot-grouping-free space (R=0, C=1, m=2)."+ {:cols [{:name "R" :base_type :type/Text} {:name "C" :base_type :type/Text}+ {:name "pivot-grouping" :base_type :type/Integer} {:name "m" :base_type :type/Integer}]+ :rows [["a" "x" 0 10] ["a" "y" 0 20] ["b" "x" 0 30] ["b" "y" 0 40]]+ :format-rows? true+ :pivot-export-options {:pivot-rows [0] :pivot-cols [1] :pivot-measures [2]}})++(deftest ^:parallel render-pivot-test+ (let [pcard {:display :pivot :visualization_settings {:pivot_table.column_split pivot-test-split}}]+ (testing "a pivot card renders as an assembled (transposed) pivot table"+ (let [part (body/render :pivot :inline "UTC" pcard nil pivot-test-data)+ h (html (:content part))]+ (is (= :table (-> part :content first)))+ (is (nil? (:attachments part)))+ (is (not (str/includes? h "pivot-grouping")))+ (is (every? #(str/includes? h %) ["x" "y" "a" "b" "10" "20" "30" "40"]))+ ;; transposed pivot: header (x, y) + a + b + grand-totals row = 4 <tr> (a flat table would be 5)+ (is (= 4 (count (re-seq #"<tr" h))))))+ (testing "measures are derived from the non row/col columns when the QP left :pivot-measures empty"+ ;; happens when the split's measure name doesn't resolve to a result column (e.g. a casing mismatch)+ (let [data (assoc-in pivot-test-data [:pivot-export-options :pivot-measures] [])+ h (html (:content (body/render :pivot :inline "UTC" pcard nil data)))]+ (is (not (str/includes? h "pivot-grouping")))+ (is (every? #(str/includes? h %) ["x" "y" "a" "b" "10" "20" "30" "40"]))))+ (testing "a pivot card with no column split degrades to a flat table without erroring"+ (let [part (body/render :pivot :inline "UTC"+ {:display :pivot :visualization_settings {}} nil+ {:cols [{:name "a" :base_type :type/Text} {:name "b" :base_type :type/Number}]+ :rows [["x" 1]]})]+ (is (some? (:content part)))))+ (testing "the card's conditional formatting colors the measure value cells"+ (mt/with-dynamic-fn-redefs [js.color/make-color-selector (fn [_ _] ::selector)+ js.color/get-background-color (fn [_sel cell _col _row]+ (when (formatter/NumericWrapper? cell)+ "rgb(1, 2, 3)"))]+ (let [pcard {:display :pivot+ :visualization_settings {:pivot_table.column_split pivot-test-split+ :table.column_formatting [{:type "single"+ :columns ["m"]+ :color "#ff0000"+ :operator ">"+ :value 0}]}}+ h (html (:content (body/render :pivot :inline "UTC" pcard nil pivot-test-data)))]+ ;; numeric cells get the (stubbed) conditional-formatting background; headers/labels don't+ (is (str/includes? h "rgb(1, 2, 3)")))))))++(deftest render-pivot-conditional-formatting-test+ (testing "pivot value cells get value-based conditional-formatting colors via the real shared color JS"+ (let [render-with (fn [formatting]+ (let [settings (cond-> {:pivot_table.column_split pivot-test-split}+ formatting (assoc :table.column_formatting formatting))]+ (html (:content (body/render :pivot :inline "UTC"+ {:display :pivot :visualization_settings settings}+ nil pivot-test-data)))))]+ (testing "a `>` rule colors the matching measure cells"+ (is (str/includes? (render-with [{:type "single"+ :columns ["m"]+ :color "#ff0000"+ :operator ">"+ :value 25}])+ "background-color")))+ (testing "no conditional formatting means no cell background colors"+ (is (not (str/includes? (render-with nil) "background-color")))))))++(deftest render-pivot-multi-measure-conditional-formatting-test+ (testing "with multiple measures, conditional formatting maps to the correct measure column"+ ;; Two measures: m1 values are all < 50, m2 values all > 50, and the rule targets m2 (> 50). If cell-bg's+ ;; (mod vpos measure-count) mis-maps value columns to measures, the m2 cells would be labeled m1 (no rule ->+ ;; uncolored) and the m1 cells labeled m2 (11-44, not > 50 -> uncolored) -- so the m2 cells being the colored+ ;; ones confirms the measure mapping. Totals are off so only the data cells remain.+ (let [split {:rows ["R"] :columns ["C"] :values ["m1" "m2"]}+ cols [{:name "R" :base_type :type/Text} {:name "C" :base_type :type/Text}+ {:name "pivot-grouping" :base_type :type/Integer}+ {:name "m1" :base_type :type/Integer} {:name "m2" :base_type :type/Integer}]+ data {:cols cols+ :rows [["a" "x" 0 11 100] ["a" "y" 0 22 200]+ ["b" "x" 0 33 300] ["b" "y" 0 44 400]]+ :format-rows? true+ :pivot-export-options {:pivot-rows [0] :pivot-cols [1] :pivot-measures [2 3]}}+ settings {:pivot_table.column_split split+ :pivot.show_row_totals false+ :pivot.show_column_totals false+ :table.column_formatting [{:type "single"+ :columns ["m2"]+ :color "#ff0000"+ :operator ">"+ :value 50}]}+ h (html (:content (body/render :pivot :inline "UTC"+ {:display :pivot :visualization_settings settings}+ nil data)))]+ (testing "both measures' values render"+ (is (every? #(str/includes? h %) ["11" "22" "33" "44" "100" "200" "300" "400"])))+ (testing "only the four m2 value cells (> 50) are colored"+ (is (= 4 (count (re-seq #"background-color" h))))))))diff --git a/test/metabase/channel/render/card_test.clj b/test/metabase/channel/render/card_test.cljindex 1add9383331..8fe1103fe80 100644--- a/test/metabase/channel/render/card_test.clj+++ b/test/metabase/channel/render/card_test.clj@@ -62,6 +62,12 @@:state:country)))+(deftest ^:parallel detect-pulse-chart-type-pivot-test+ (testing "pivot cards route to :pivot"+ (is (= :pivot (channel.render/detect-pulse-chart-type+ {:display :pivot} nil+ {:cols [{:base_type :type/Text} {:base_type :type/Number}] :rows [["a" 1]]})))))+(deftest ^:parallel detect-pulse-chart-type-test-2(testing "Queries resulting in no rows return `:empty`."(is (= :emptydiff --git a/test/metabase/query_processor/pivot/postprocess_test.clj b/test/metabase/pivot/postprocess_test.cljsimilarity index 98%rename from test/metabase/query_processor/pivot/postprocess_test.cljrename to test/metabase/pivot/postprocess_test.cljindex 2ff97a83ef8..f5a67b55298 100644--- a/test/metabase/query_processor/pivot/postprocess_test.clj+++ b/test/metabase/pivot/postprocess_test.clj@@ -1,7 +1,7 @@-(ns metabase.query-processor.pivot.postprocess-test+(ns metabase.pivot.postprocess-test(:require[clojure.test :refer :all]- [metabase.query-processor.pivot.postprocess :as pivot.postprocess]))+ [metabase.pivot.postprocess :as pivot.postprocess]))(deftest ^:parallel build-top-headers-test(testing "builds top headers with single level hierarchy"