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
UXW-5013 Support adding a metric to recent items (#79661)
Denis Berezin7cd842e414eb
diff --git a/e2e/test/scenarios/metrics/reproductions/metrics-reproductions.cy.spec.ts b/e2e/test/scenarios/metrics/reproductions/metrics-reproductions.cy.spec.tsindex a8ffee3b18d..1b44114b0b1 100644--- a/e2e/test/scenarios/metrics/reproductions/metrics-reproductions.cy.spec.ts+++ b/e2e/test/scenarios/metrics/reproductions/metrics-reproductions.cy.spec.ts@@ -200,3 +200,51 @@ describe("issue 32037", () => {});});});++describe("issue 79571", () => {+ const METRIC_NAME = "Metric 79571";++ const ORDERS_COUNT_METRIC: StructuredQuestionDetails = {+ name: METRIC_NAME,+ type: "metric",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["count"]],+ },+ };++ beforeEach(() => {+ H.restore();+ cy.signInAsNormalUser();+ });++ it("logs choosing a metric as a recent selection and lists it under Recent items (metabase#79571)", () => {+ H.createQuestion(ORDERS_COUNT_METRIC).then(({ body: { id: metricId } }) => {+ cy.intercept("POST", "/api/activity/recents").as("logRecent");++ H.startNewQuestion();+ H.miniPicker().within(() => {+ cy.findByText("Our analytics").click();+ cy.findByText(METRIC_NAME).click();+ });++ cy.wait("@logRecent").then(({ request, response }) => {+ expect(request.body).to.deep.equal({+ model: "metric",+ model_id: metricId,+ context: "selection",+ });+ expect(response?.statusCode).to.eq(204);+ });++ // Reopening the picker now surfaces the metric under Recent items+ H.getNotebookStep("data").findByText("Orders").click();+ H.miniPickerHeader().click();+ H.miniPickerBrowseAll().click();+ H.entityPickerModalItem(0, "Recent items").click();+ cy.findByRole("dialog", { name: "Pick your starting data" })+ .findByText(METRIC_NAME)+ .should("exist");+ });+ });+});diff --git a/src/metabase/activity_feed/models/recent_views.clj b/src/metabase/activity_feed/models/recent_views.cljindex 357c1328c9e..1d9ecd56227 100644--- a/src/metabase/activity_feed/models/recent_views.clj+++ b/src/metabase/activity_feed/models/recent_views.clj@@ -21,12 +21,7 @@We want to keep track of recents in multiple contexts. e.g. when selecting a value from the data-picker, that shouldlog a recent_view row with context=`selection`. At this time there are only `view` and `selection` contexts.- E.G., if you were to view lots of _cards_, it would not push collections and dashboards out of your recents.-- [Metrics] TODO:- At some point in 2024, there was an attempt to add `metric` to the list of recent-view models. This- was never completed, and the code has not been hooked up. There is no query for metrics, despite there being a- `:metric` model in the `rv-models` list. This is a TODO to complete this work."+ E.G., if you were to view lots of _cards_, it would not push collections and dashboards out of your recents."(:require[clojure.set :as set][colorize.core :as colorize]@@ -78,22 +73,44 @@(into #{} (comp (mapcat (fn [[_ rows]] (drop 1 rows)))(map :id)))))+(def ^:private rv-model->toucan-model+ "Maps each rv-model keyword to the Toucan model backing it. `:card`, `:dataset`, and `:metric` are all stored in+ recent_views as \"card\" and backed by `:model/Card`; a join with report_card is needed to distinguish between+ them — see [[rv-model->card-type]]."+ {:card :model/Card+ :dataset :model/Card+ :metric :model/Card+ :dashboard :model/Dashboard+ :table :model/Table+ :collection :model/Collection+ :document :model/Document})+(def rv-models"Keywords representing entity types that can be returned as recent views."- ;; n.b.: `:card`, `metric` and `:dataset` are stored in recent_views as "card", and a join with report_card is- ;; needed to distinguish between them. `:dataset` is an alias for `:model/Card` with type "model".- [:card :dataset :metric :dashboard :table :collection :document])+ (vec (keys rv-model->toucan-model)))(mu/defn rv-model->model"Given a rv-model, returns the toucan model identifier for it."[rvm :- (into [:enum] rv-models)]- (get {:dataset :model/Card- :card :model/Card- :dashboard :model/Dashboard- :table :model/Table- :collection :model/Collection- :document :model/Document}- rvm))+ (rv-model->toucan-model rvm))++(def ^:private card-type->rv-model+ "Mapping from report_card.type to rv-model keyword."+ {"model" :dataset+ "question" :card+ "metric" :metric})++(def ^:private rv-model->card-type+ "Mapping from rv-model keyword to report_card.type string."+ (set/map-invert card-type->rv-model))++(defn- rv-model->db-model+ "The `recent_views.model` string an rv-model is stored under. `:card`, `:dataset`, and `:metric` are all stored as+ \"card\"; they are told apart by joining report_card.type."+ [model]+ (if (rv-model->card-type model)+ "card"+ (name model)))(defn- ids-to-prune-for-user+model [user-id model context](t2/select-fn-set :id@@ -101,13 +118,11 @@{:select [:rv.id]:from [[:recent_views :rv]]:where [:and- [:= :rv.model (get {:dataset "card"} model (name model))]+ [:= :rv.model (rv-model->db-model model)][:= :rv.user_id user-id][:= :rv.context (h2x/literal (name context))]- (when (#{:card :dataset} model) ;; TODO add metric- [:= :rc.type (cond (= model :card) (h2x/literal "question")- ;; TODO add metric- (= model :dataset) (h2x/literal "model"))])]+ (when-let [card-type (rv-model->card-type model)]+ [:= :rc.type (h2x/literal card-type)])]:left-join [[:report_card :rc][:and[:= :rc.id :rv.model_id]@@ -160,16 +175,6 @@:left-join [[:report_dashboard :d][:= :recent_views.model_id :d.id]]}))-(def ^:private card-type->rv-model- "Mapping from report_card.type to rv-model keyword."- {"model" :dataset- "question" :card- "metric" :metric})--(def ^:private rv-model->card-type- "Mapping from rv-model keyword to report_card.type string."- (set/map-invert card-type->rv-model))-(def Item"The shape of a recent view item, returned from `GET /recent_views`."(mc/schema@@ -479,17 +484,10 @@:selections "selection"})(defn- rv-models->db-models- "Convert rv-model keywords to database model strings.- Note: :card, :dataset, and :metric all map to \"card\" in the database,- distinguished by report_card.type."+ "Convert rv-model keywords to database model strings — see [[rv-model->db-model]]."[models](when (seq models)- (distinct- (map (fn [model]- (case model- (:card :dataset :metric) "card"- (name model)))- models))))+ (distinct (map rv-model->db-model models))))(defn ^:private do-query [user-id context models](when-not (seq context)diff --git a/test/metabase/activity_feed/api_test.clj b/test/metabase/activity_feed/api_test.cljindex 3c8b7eb5046..1ff0561a201 100644--- a/test/metabase/activity_feed/api_test.clj+++ b/test/metabase/activity_feed/api_test.clj@@ -416,6 +416,19 @@(mt/user-http-request :rasta :post 204 "activity/recents"{:model "dashboard" :model_id (:id d) :context "selection"})))))+(deftest post-recents-metric-selection-test+ (testing "POST /api/activity/recents accepts model=metric without HTTP 500 (#79571)"+ (mt/with-model-cleanup [:model/RecentViews]+ (mt/with-temp [:model/Card metric-card {:type "metric"+ :creator_id (mt/user->id :crowberto)}]+ (mt/user-http-request :crowberto :post 204 "activity/recents"+ {:model "metric" :model_id (:id metric-card) :context "selection"})+ (testing "and the selection round-trips through GET /api/activity/recents"+ (is (=? [{:model "metric" :id (:id metric-card)}]+ (->> (mt/user-http-request :crowberto :get 200 "activity/recents?context=selections")+ :recents+ (filter #(= (:id %) (:id metric-card)))))))))))+(deftest card-query-collection-context-excluded-from-recents-test(testing "A card-query event with a non-question context is not recorded as a recent view (#45003)"(mt/with-test-user :crowbertodiff --git a/test/metabase/activity_feed/models/recent_views_test.clj b/test/metabase/activity_feed/models/recent_views_test.cljindex 4baff6a0625..a8d96ea2391 100644--- a/test/metabase/activity_feed/models/recent_views_test.clj+++ b/test/metabase/activity_feed/models/recent_views_test.clj@@ -33,6 +33,25 @@([user-id context] (recent-views user-id context {}))([user-id context options] (:recents (recent-views/get-recents user-id context options))))+(deftest metric-views-are-pruned-to-the-bucket-cap-test+ (testing "metric recents are pruned past the per-model cap without affecting other card buckets (#79571)"+ (binding [recent-views/*recent-views-stored-per-user-per-model* 2]+ (mt/with-model-cleanup [:model/RecentViews]+ (mt/with-temp+ [:model/Database {db-id :id} {}+ :model/Card {question-id :id} {:type "question" :name "q" :database_id db-id}+ :model/Card {metric-1-id :id} {:type "metric" :name "m1" :database_id db-id}+ :model/Card {metric-2-id :id} {:type "metric" :name "m2" :database_id db-id}+ :model/Card {metric-3-id :id} {:type "metric" :name "m3" :database_id db-id}]+ (doseq [id [question-id metric-1-id metric-2-id metric-3-id]]+ (recent-views/update-users-recent-views! (mt/user->id :rasta) :model/Card id :view))+ (let [by-model (mt/with-test-user :rasta+ (group-by :model (recent-views (mt/user->id :rasta))))]+ (is (= #{metric-2-id metric-3-id}+ (into #{} (map :id) (:metric by-model))))+ (is (= [question-id]+ (map :id (:card by-model))))))))))+(deftest simple-get-list-card-test(mt/with-temp[:model/Collection {coll-id :id} {:name "my coll"}