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 4979 manage unsynced content modal (#81226)
Nick Fitzpatrick9ce408d11448
diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.tsindex 995e8c450cb..cd8bfe4e4db 100644--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts@@ -1,6 +1,9 @@import { WRITABLE_DB_ID } from "e2e/support/cypress_data";import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";-import { ORDERS_DASHBOARD_ID } from "e2e/support/cypress_sample_instance_data";+import {+ ADMIN_PERSONAL_COLLECTION_ID,+ ORDERS_DASHBOARD_ID,+} from "e2e/support/cypress_sample_instance_data";import type {Collection,RemoteSyncDependencyErrorResponse,@@ -20,6 +23,12 @@ const SOURCE_COLLECTION_NAME = "Dependency Source";const SOURCE_QUESTION_NAME = "Dependency Source Question";const DEPENDENT_QUESTION_NAME = "Dependent Question";const SECOND_DEPENDENT_QUESTION_NAME = "Second Dependent Question";+const OTHER_SOURCE_QUESTION_NAME = "Other Source Question";+const WEEKLY_DEPENDENT_NAME = "Weekly Summary";+const MONTHLY_DEPENDENT_NAME = "Monthly Summary";+const SNIPPET_NAME = "active_users";+const SNIPPET_QUESTION_NAME = "Snippet Dependent Question";+const PERSONAL_QUESTION_NAME = "Personal Source Question";const setup = (snapshot = "default") => {H.restore(snapshot);@@ -619,7 +628,7 @@ describe("Remote Sync", () => {cy.intercept("PUT", "/api/ee/remote-sync/settings").as("saveSettings");});- it("reports every blocked collection, re-opens after a dismissal, syncs them all, and stays hidden for unrelated errors", () => {+ it("reports every blocked collection and allows to sync from dependency modal", () => {createDependencyFixture().then(({ source, blocked, alsoBlocked }) => {cy.visit("/admin/settings/remote-sync");@@ -633,33 +642,43 @@ describe("Remote Sync", () => {});cy.log("Both collections are refused in a single pass");- saveAndExpectRefusal().then((interception) => {- const body: RemoteSyncDependencyErrorResponse =- interception.response?.body;- expect(- body.errors.collections.map((failure) => failure.collection.name),- ).to.have.members([- BLOCKED_COLLECTION_NAME,- SECOND_BLOCKED_COLLECTION_NAME,- ]);- });+ saveAndExpectRefusal();H.modal().within(() => {- // Every remedy here is a collection we can switch on, so the modal asks rather than refuses.- cy.findByText("Sync collections with dependencies?").should(+ cy.findByText("Couldn’t sync selected collection").should("be.visible",);- // Both failures resolve to the same remedy, so it is offered once.cy.findAllByText(SOURCE_COLLECTION_NAME).should("have.length", 1);- cy.button("Cancel").click();- });- H.modal().should("not.exist");- cy.log("Saving the same selection again brings it back");- saveAndExpectRefusal();+ cy.log(+ "Expanding the row lists every blocking item and what uses it",+ );+ cy.findByText(SOURCE_COLLECTION_NAME).click();+ cy.findByText("Item").should("be.visible");+ cy.findByText("Used By").should("be.visible");++ cy.log("One row per dependency, both under the same remedy");+ cy.findByText(SOURCE_QUESTION_NAME).should("be.visible");+ cy.findByText(OTHER_SOURCE_QUESTION_NAME).should("be.visible");++ // Each dependent reaches the source from a different selected collection, so the cell+ // names both — one per selection, pooled rather than reported from whichever came first.+ cy.findByText(+ new RegExp(+ `^(${DEPENDENT_QUESTION_NAME}, ${SECOND_DEPENDENT_QUESTION_NAME}|${SECOND_DEPENDENT_QUESTION_NAME}, ${DEPENDENT_QUESTION_NAME})$`,+ ),+ ).should("be.visible");- H.modal().within(() => {- cy.button("Sync required collections").click();+ cy.findByText(+ new RegExp(+ `^(${WEEKLY_DEPENDENT_NAME}, ${MONTHLY_DEPENDENT_NAME}|${MONTHLY_DEPENDENT_NAME}, ${WEEKLY_DEPENDENT_NAME})$`,+ ),+ ).should("be.visible");++ cy.findByLabelText(`Sync ${SOURCE_COLLECTION_NAME}`)+ .should("be.enabled")+ .click({ force: true });+ cy.button("Save changes").click();});cy.wait("@saveSettings").then(({ request, response }) => {@@ -694,6 +713,75 @@ describe("Remote Sync", () => {H.modal().should("not.exist");});});++ it("leaves a snippet dependency with nothing to act on when no Library exists", () => {+ createSnippetDependencyFixture().then(({ blocked }) => {+ cy.visit("/admin/settings/remote-sync");++ cy.findByLabelText(`Sync ${BLOCKED_COLLECTION_NAME}`).click({+ force: true,+ });++ saveAndExpectRefusal().then((interception) => {+ const body: RemoteSyncDependencyErrorResponse =+ interception.response?.body;+ const [required] = body.errors.required;++ expect(required.blocks.map((collection) => collection.id)).to.eql([+ blocked.id,+ ]);+ // With no Library there is no collection to name, so the remedy carries only its type.+ expect(required.remedy).to.deep.equal({ type: "library" });+ expect(required.syncable).to.be.false;+ expect(required.dependencies).to.have.length(1);+ expect(required.dependencies[0].model).to.eq("snippet");+ expect(required.dependencies[0].name).to.eq(SNIPPET_NAME);+ });++ H.modal().within(() => {+ cy.findByText("Couldn’t sync selected collection").should(+ "be.visible",+ );+ cy.findByText(/sync with the Library/).should("be.visible");+ cy.findByRole("switch").should("not.exist");++ cy.button("Back").click();+ });++ H.modal().should("not.exist");+ });+ });++ it("lists only the personal collection when a syncable one is blocked behind it", () => {+ createPersonalDependencyFixture().then(({ personal }) => {+ cy.visit("/admin/settings/remote-sync");++ cy.findByLabelText(`Sync ${BLOCKED_COLLECTION_NAME}`).click({+ force: true,+ });++ saveAndExpectRefusal();++ H.modal().within(() => {+ cy.findByText(/saved in a personal collection/).should(+ "be.visible",+ );+ cy.findByText(personal.name).should("be.visible");+ cy.findByText("Can't be synced").should("be.visible");+ // The person icon is how the row shows this is someone's personal collection.+ cy.findByRole("img", { name: "person icon" }).should("be.visible");++ cy.log("The syncable collection is hidden — no save can succeed");+ cy.findByText(SOURCE_COLLECTION_NAME).should("not.exist");+ cy.findByRole("switch").should("not.exist");+ cy.button("Save changes").should("not.exist");++ cy.button("Back").click();+ });++ H.modal().should("not.exist");+ });+ });});});@@ -1154,9 +1242,7 @@ const createCollection = (name: string) =>// Saves, clears the toast and yields the refusal for inspection.const saveAndExpectRefusal = () => {- cy.findByRole("button", { name: "Save changes", timeout: 6000 })- .should("be.enabled")- .click(); // action button text+ cy.findByTestId("remote-sync-submit-button").should("be.enabled").click();return cy.wait("@saveSettings").then((interception) => {expect(interception.response?.statusCode).to.eq(400);H.undoToast()@@ -1178,7 +1264,69 @@ const createDependentQuestion = (collection_id: collectionId,});+const createSnippetDependencyFixture = () =>+ H.createSnippet({ name: SNIPPET_NAME, content: "1 = 1" }).then(+ ({ body: snippet }) =>+ createCollection(BLOCKED_COLLECTION_NAME).then((blocked) =>+ H.createNativeQuestion({+ name: SNIPPET_QUESTION_NAME,+ collection_id: blocked.id,+ native: {+ query: `select 1 where {{snippet: ${SNIPPET_NAME}}}`,+ "template-tags": {+ [`snippet: ${SNIPPET_NAME}`]: {+ id: "6c1b2f34-5d6e-4a7b-8c9d-0e1f2a3b4c5d",+ type: "snippet",+ name: `snippet: ${SNIPPET_NAME}`,+ "display-name": `Snippet: ${SNIPPET_NAME}`,+ "snippet-id": snippet.id,+ "snippet-name": SNIPPET_NAME,+ },+ },+ },+ }).then(() => ({ snippet, blocked })),+ ),+ );++const createPersonalDependencyFixture = () =>+ createCollection(SOURCE_COLLECTION_NAME).then((source) =>+ createCollection(BLOCKED_COLLECTION_NAME).then((blocked) =>+ H.createQuestion({+ name: SOURCE_QUESTION_NAME,+ query: { "source-table": PRODUCTS_ID },+ collection_id: source.id,+ }).then(({ body: sourceQuestion }) =>+ H.createQuestion({+ name: PERSONAL_QUESTION_NAME,+ query: { "source-table": PRODUCTS_ID },+ collection_id: ADMIN_PERSONAL_COLLECTION_ID,+ }).then(({ body: personalQuestion }) =>+ createDependentQuestion(+ DEPENDENT_QUESTION_NAME,+ sourceQuestion.id,+ blocked.id,+ ).then(() =>+ createDependentQuestion(+ SECOND_DEPENDENT_QUESTION_NAME,+ personalQuestion.id,+ blocked.id,+ ).then(() =>+ cy+ .request<Collection>(+ "GET",+ `/api/collection/${ADMIN_PERSONAL_COLLECTION_ID}`,+ )+ .then(({ body: personal }) => ({ source, blocked, personal })),+ ),+ ),+ ),+ ),+ ),+ );+// Two collections that each depend on a question in a third, so syncing either alone is refused.+// A second source question, used twice from the same blocked collection, gives the modal a second+// dependency row and a Used By cell that names more than one thing.const createDependencyFixture = () =>createCollection(SOURCE_COLLECTION_NAME).then((source) =>createCollection(BLOCKED_COLLECTION_NAME).then((blocked) =>@@ -1201,6 +1349,25 @@ const createDependencyFixture = () =>),),)+ .then(() =>+ H.createQuestion({+ name: OTHER_SOURCE_QUESTION_NAME,+ query: { "source-table": PRODUCTS_ID },+ collection_id: source.id,+ }).then(({ body: otherSource }) =>+ createDependentQuestion(+ WEEKLY_DEPENDENT_NAME,+ otherSource.id,+ blocked.id,+ ).then(() =>+ createDependentQuestion(+ MONTHLY_DEPENDENT_NAME,+ otherSource.id,+ blocked.id,+ ),+ ),+ ),+ ).then(() => ({ source, blocked, alsoBlocked })),),),diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.cljindex ca4b9eab04c..12eca1e727e 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.remote-sync.core(:require[java-time.api :as t]+ [medley.core :as m][metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.guards :as guards][metabase-enterprise.remote-sync.settings :as settings]@@ -180,55 +181,82 @@row (remote-sync.db/instance-names (keyword "model" model-name) (map :id group))][[model-name (:id row)] (:name row)])))-(defn- card-item-models- "`{card-id model}` for the Cards in `entities` — only their `type` separates questions from models and- metrics, and the eligibility select doesn't carry it."+(defn- card-item-details+ "`{card-id {:model model :display display}}` for the Cards in `entities`. Their `type` is what separates+ questions from models and metrics, and `display` is what lets clients show a question's visualization+ icon instead of a generic one; the eligibility select carries neither."[entities](when-let [ids (seq (keep #(when (= "Card" (:model %)) (:id %)) entities))](into {}- (map (fn [{:keys [id type]}]- [id (case (keyword type)- :model "dataset"- :metric "metric"- "card")]))+ (map (fn [{:keys [id type display]}]+ [id {:model (case (keyword type)+ :model "dataset"+ :metric "metric"+ "card")+ ;; Named for the wire, as the dirty-changes payload already does for `display`.+ :display (some-> display name)}]));; :card_schema is required alongside :type — selecting it runs Card's schema upgrades.(remote-sync.db/card-types ids))))(defn- describe-entities- "`[{:model :id :name}]` for `entities`, which are `{:model \"Card\" :id 412}` maps, in the order given."+ "`[{:model :id :name}]` for `entities`, which are `{:model \"Card\" :id 412}` maps, in the order given.+ Cards carry `:display` too, so clients can pick the visualization icon."[entities]- (let [names (entity-names entities)- card-models (card-item-models entities)]+ (let [names (entity-names entities)+ card-details (card-item-details entities)](mapv (fn [{:keys [model id]}]- {:model (if (= "Card" model)- (get card-models id "card")- (dependency-item-model model))- :id id- :name (get names [model id])})+ ;; Keyed by id alone, so only consult it once the entity is known to be a Card.+ (let [card (when (= "Card" model) (get card-details id))]+ (cond-> {:model (if (= "Card" model)+ (:model card "card")+ (dependency-item-model model))+ :id id+ :name (get names [model id])}+ (:display card) (assoc :display (:display card)))))entities)))+(defn- remedy-collection+ "The collection a remedy points at, as clients need it: enough to name the row, switch it on, and pick+ the same icon the collection would get anywhere else."+ [collection]+ {:id (:id collection)+ :name (:name collection)+ :type (:type collection)+ :personal (some? (:personal_owner_id collection))})+(defn- sync-remedy- "What an admin would have to sync for `dep` to be covered: a specific top-level collection, or the- Library for models whose eligibility keys on it (snippets) rather than on their own collection.- `:none` when the dependency lives outside any collection."- [{:keys [model instance]} collections top-levels]+ "What an admin would have to sync for `dep` to be covered: a specific top-level collection, or+ `:library` for models whose eligibility keys on the Library (snippets) on an instance that hasn't got+ one yet — there being no collection to name. The Library itself is an ordinary top-level collection,+ so once it exists it is reported as one. `:none` when the dependency lives outside any collection."+ [{:keys [model instance]} collections top-levels library](let [top (some->> (:collection_id instance)(get collections)top-level-ancestor-id(get top-levels))](cond(= :library-synced (get-in (spec/spec-for-model-key (keyword "model" model)) [:eligibility :type]))- {:type :library}+ (if library+ {:type :collection+ :collection (remedy-collection library)}+ {:type :library})top{:type :collection- :collection {:id (:id top)- :name (:name top)- :personal (some? (:personal_owner_id top))}}+ :collection (remedy-collection top)}:else{:type :none})))+(defn- remedy-syncable?+ "Whether an admin can switch this remedy on from the settings list. Personal and instance-analytics+ collections are named so the refusal makes sense, but that list never offers either, so neither is+ something an admin can act on here."+ [{:keys [type collection]}]+ (boolean (and (= :collection type)+ (not (:personal collection))+ (not= collections/instance-analytics-collection-type (:type collection)))))+(defn- dependency-collection"Where the dependency lives, as a map to merge into its description. An explicit `nil` says the rootcollection — a real place, not a missing value — while an absent key says we could not resolve the@@ -239,18 +267,68 @@{:collection (select-keys collection [:id :name])}){:collection nil}))+(defn- referencing-entities+ "`[model-name id]` pairs naming the entities that reference `dep`, in the order the traversal found them.+ Nested models (DashboardCard, DashboardCardSeries, Action) fall away as they do for dependents — they+ have no name of their own, and the parent that does is in the same path."+ [dep]+ (distinct (for [path (:used-by dep)+ [model-name id] path+ :when (contains? model-name->collection-item-model model-name)]+ [model-name id])))++(defn- describe-used-by+ "The rendered `:used-by` of each dependency in `deps`, positionally. Names resolve in a single pass over+ the whole set, so a refusal naming dozens of dependencies costs the same few selects as one naming a+ single dependency."+ [deps]+ (let [entities (vec (distinct (mapcat referencing-entities deps)))+ described (zipmap entities+ (describe-entities (mapv (fn [[model-name id]] {:model model-name :id id})+ entities)))]+ (mapv #(mapv described (referencing-entities %)) deps)))++(defn- dependency-key+ "Identity of a dependency in the traversal's own terms, which is how [[referencing-entities]] names it."+ [{:keys [model id]}]+ [model id])++(defn- subsumed-dependency?+ "Whether reporting `dep` would tell an admin nothing new: everything that reaches it is itself an+ ineligible dependency with the same remedy, and that remedy is a switch covering a whole collection, so+ the row already on screen fixes this one too. Click behaviour pointing at an unsynced dashboard drags in+ every card that dashboard holds, and syncing the dashboard's collection covers them all. Neither a+ referrer with a *different* remedy nor a remedy [[remedy-syncable?]] rejects subsumes: there the fix is+ to move each item, which the parent's move doesn't do, so hiding one refuses the next save for a reason+ never shown."+ [dep remedies]+ (when-let [referrers (seq (referencing-entities dep))]+ (let [remedy (get remedies (dependency-key dep))]+ ;; Referrers outside `remedies` are eligible content, so they never subsume.+ (and (remedy-syncable? remedy)+ (every? #(= remedy (get remedies %)) referrers)))))+(defn- describe-dependencies"Renders [[collections/ineligible-dependencies]] for the API: what each dependency is, the collection it- lives in, and the collection (or the Library) that would have to be synced to cover it."+ lives in, the entities that reference it, and the collection (or the Library) that would have to be+ synced to cover it. Dependencies the traversal only reached through another one with the same remedy+ are dropped — see [[subsumed-dependency?]]."[deps](let [collections (collections-by-id (map (comp :collection_id :instance) deps))- top-levels (collections-by-id (map top-level-ancestor-id (vals collections)))]- (mapv (fn [described {:keys [instance] :as dep}]+ top-levels (collections-by-id (map top-level-ancestor-id (vals collections)))+ ;; Resolved once for the whole refusal rather than per snippet dependency.+ library (collections/library-collection)+ remedies (zipmap (map dependency-key deps)+ (map #(sync-remedy % collections top-levels library) deps))+ reported (into [] (remove #(subsumed-dependency? % remedies)) deps)]+ (mapv (fn [described used-by {:keys [instance] :as dep}](merge described- {:remedy (sync-remedy dep collections top-levels)}+ {:remedy (get remedies (dependency-key dep))+ :used_by used-by}(dependency-collection instance collections)))- (describe-entities deps)- deps)))+ (describe-entities reported)+ (describe-used-by reported)+ reported)))(defn- describe-dependents"Renders [[collections/remote-synced-dependents]] for the API. Each dependent arrives as a path map like@@ -269,7 +347,7 @@Unlike [[collections/check-non-remote-synced-dependencies]] this reports every offending collectionrather than throwing on the first, so an admin sees the whole picture in one pass. Realized eagerly:eligibility only reads correctly against the pending updates, so nothing may be left for- [[describe-dependency-failure]] to force after the transaction rolls back."+ [[describe-required-syncs]] to force after the transaction rolls back."[collections-to-sync](vec(for [collection collections-to-sync@@ -289,10 +367,50 @@:when (seq dependents)]{:collection collection :dependents (vec dependents)})))-(defn- describe-dependency-failure- [{:keys [collection dependencies]}]- {:collection (select-keys collection [:id :name])- :dependencies (describe-dependencies dependencies)})+(defn- group-remedy+ "The remedy an entry is keyed on. A `:none` remedy carries the collection the dependency lives in —+ the only one there is to name — keeping that key's own distinction, where nil is the root collection+ and an absent key is a collection we could not resolve."+ [{:keys [remedy] :as described}]+ (if (= :none (:type remedy))+ (cond-> remedy+ (contains? described :collection) (assoc :collection (:collection described)))+ remedy))++(defn- pooled-dependencies+ "One row per dependency, in first-appearance order, with `:used_by` pooled across the group. Each+ failing selection describes the dependency separately, naming only what reached it from that one, so+ keeping the first row alone would drop every other selection's referrers. Nothing else varies between+ those rows — the rest describes the entity itself."+ [deps]+ (let [used-by (reduce (fn [acc {:keys [model id used_by]}]+ (update acc [model id] (fnil into []) used_by))+ {}+ deps)]+ (into []+ (comp (m/distinct-by (juxt :model :id))+ (map #(assoc % :used_by (vec (distinct (used-by [(:model %) (:id %)]))))))+ deps)))++(defn- describe-required-syncs+ "The refusal as clients render it: one entry per collection an admin would act on, carrying the+ dependencies it covers and the selected collections it unblocks. Grouping by remedy rather than by+ selection is what collapses a dependency that blocks two selected collections into a single entry."+ [failures]+ (let [entries (vec (for [{:keys [collection dependencies]} failures+ described (describe-dependencies dependencies)]+ {:remedy (group-remedy described)+ :blocks (select-keys collection [:id :name])+ :dep (dissoc described :remedy)}))+ by-remedy (group-by :remedy entries)]+ ;; Ordered by first appearance rather than by `group-by`, whose order isn't guaranteed.+ (mapv (fn [remedy]+ (let [group (get by-remedy remedy)]+ {:remedy remedy+ :syncable (remedy-syncable? remedy)+ :blocks (vec (distinct (map :blocks group)))+ :dependencies (pooled-dependencies (map :dep group))}))+ (distinct (map :remedy entries)))))(defn- describe-dependent-failure[{:keys [collection dependents]}]@@ -310,7 +428,7 @@(ex-info (ex-message e){:status-code 400:error_code "unsynced-dependencies"- :errors {:collections (mapv describe-dependency-failure unsynced-dependencies)}})+ :errors {:required (describe-required-syncs unsynced-dependencies)}})remote-synced-dependents(ex-info (ex-message e)diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/db.cljindex f4ff04727b5..a204cffd510 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj@@ -270,9 +270,9 @@:where (path-expr paths true)}))(mu/defn card-types- "The `:id`, `:type`, and `:card_schema` of the Cards with `card-ids`."+ "The `:id`, `:type`, :display, and `:card_schema` of the Cards with `card-ids`."[card-ids :- [:sequential ::lib.schema.id/card]]- (t2/select [:model/Card :id :type :card_schema] :id [:in card-ids]))+ (t2/select [:model/Card :id :type :display :card_schema] :id [:in card-ids]))(mu/defn user-settings-exist-for-table?"Whether the Table with `table-id`, or any of its Fields, has a user-settings row."@@ -304,7 +304,7 @@(mu/defn collections-by-id"A map of ID to the ID, name, location, and personal owner of the Collections with `collection-ids`."[collection-ids :- [:set ::lib.schema.id/collection]]- (t2/select-pk->fn identity [:model/Collection :id :name :location :personal_owner_id] :id [:in collection-ids]))+ (t2/select-pk->fn identity [:model/Collection :id :name :type :location :personal_owner_id] :id [:in collection-ids]))(mu/defn collection-sync-states"The `:id` and `:is_remote_synced` of the Collections with `collection-ids`."diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.cljindex 88f94d2b5c9..bea13912a5e 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj@@ -1189,15 +1189,16 @@(is (= "Uses content that is not remote synced." (:error response)))(testing "the structured failure survives the endpoint's rewrap, keyed by error_code"(is (=? {:error_code "unsynced-dependencies"- :errors {:collections [{:collection {:id remote-synced-coll-id :name "Remote Synced"}- :dependencies [{:model "card"- :id source-card-id- :name "Source Card"- :collection {:id regular-coll-id :name "Regular"}- :remedy {:type "collection"- :collection {:id regular-coll-id- :name "Regular"- :personal false}}}]}]}}+ :errors {:required [{:remedy {:type "collection"+ :collection {:id regular-coll-id+ :name "Regular"+ :personal false}}+ :syncable true+ :blocks [{:id remote-synced-coll-id :name "Remote Synced"}]+ :dependencies [{:model "card"+ :id source-card-id+ :name "Source Card"+ :collection {:id regular-coll-id :name "Regular"}}]}]}}response)))(testing "the body is the ex-data itself, not a stacktrace dump"(is (nil? (:trace response)))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.cljindex 6a93c8e9480..def0e24bd9b 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj@@ -7,7 +7,8 @@[metabase-enterprise.remote-sync.guards :as guards][metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object][metabase-enterprise.remote-sync.test-helpers :as rs.test]- [metabase.collections.test-utils :refer [with-library-synced with-library-not-synced]]+ [metabase.collections.models.collection :as collection]+ [metabase.collections.test-utils :refer [with-library with-library-synced with-library-not-synced]][metabase.events.core :as events][metabase.test :as mt][metabase.test.fixtures :as fixtures]@@ -100,17 +101,57 @@(let [ex (is (thrown? clojure.lang.ExceptionInfo(core/bulk-set-remote-sync {synced-id true})))](is (=? {:status-code 400- :errors {:collections [{:collection {:id synced-id :name "Synced"}- :dependencies [{:model "card"- :id source-card-id- :name "Source Card"- :collection {:id regular-id :name "Regular"}- :remedy {:type :collection- :collection {:id regular-id- :name "Regular"- :personal false}}}]}]}}+ :errors {:required [{:remedy {:type :collection+ :collection {:id regular-id+ :name "Regular"+ :personal false}}+ :syncable true+ :blocks [{:id synced-id :name "Synced"}]+ :dependencies [{:model "card"+ :id source-card-id+ :name "Source Card"+ :collection {:id regular-id :name "Regular"}}]}]}}+ (ex-data ex)))+ (testing "the remedy is the entry's own, not repeated on every dependency under it"+ (is (not (contains? (get-in (ex-data ex) [:errors :required 0 :dependencies 0])+ :remedy))))))))++(deftest bulk-set-remote-sync-dependency-names-what-uses-it-test+ (testing "each dependency names the entity that references it, not only the collection it lives in"+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id regular-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card {dependent-card-id :id} {:name "Dependent Card"+ :collection_id synced-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))]+ (is (=? {:errors {:required [{:dependencies [{:id source-card-id+ :used_by [{:model "card"+ :id dependent-card-id+ :name "Dependent Card"}]}]}]}}(ex-data ex)))))))+(deftest bulk-set-remote-sync-dependency-used-by-drops-nested-models-test+ (testing "a dashboard dependent is reported as the dashboard — the dashcard in the same path has no name to show"+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}+ :model/Card {source-card-id :id} {:name "Source Card"+ :collection_id regular-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Dashboard {dashboard-id :id} {:name "Revenue" :collection_id synced-id}+ :model/DashboardCard _ {:dashboard_id dashboard-id :card_id source-card-id}]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))+ [dep] (get-in (ex-data ex) [:errors :required 0 :dependencies])]+ (is (= source-card-id (:id dep)))+ (is (= [{:model "dashboard" :id dashboard-id :name "Revenue"}] (:used_by dep)))))))+(deftest bulk-set-remote-sync-dependency-model-follows-card-type-test(testing "a Card dependency reports the collection-item model its type implies, not the Toucan name"(doseq [[card-type expected] {:model "dataset"@@ -129,8 +170,8 @@:dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}](let [ex (is (thrown? clojure.lang.ExceptionInfo(core/bulk-set-remote-sync {synced-id true})))]- (is (=? {:errors {:collections [{:dependencies [{:model expected- :id source-card-id}]}]}}+ (is (=? {:errors {:required [{:dependencies [{:model expected+ :id source-card-id}]}]}}(ex-data ex)))))))))(deftest bulk-set-remote-sync-dependency-remedy-is-top-level-ancestor-test@@ -150,10 +191,11 @@:dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}](let [ex (is (thrown? clojure.lang.ExceptionInfo(core/bulk-set-remote-sync {synced-id true})))]- (is (=? {:errors {:collections [{:dependencies [{:id source-card-id- :collection {:id child-id :name "Nested"}- :remedy {:type :collection- :collection {:id root-id :name "Root Regular"}}}]}]}}+ (is (=? {:errors {:required [{:remedy {:type :collection+ :collection {:id root-id :name "Root Regular"}}+ ;; The dependency keeps the sub-collection it actually lives in.+ :dependencies [{:id source-card-id+ :collection {:id child-id :name "Nested"}}]}]}}(ex-data ex)))))))(deftest bulk-set-remote-sync-root-dependency-collection-is-explicit-nil-test@@ -167,42 +209,194 @@:collection_id synced-id:database_id (mt/id):dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]- (let [ex (is (thrown? clojure.lang.ExceptionInfo- (core/bulk-set-remote-sync {synced-id true})))- [dep] (get-in (ex-data ex) [:errors :collections 0 :dependencies])]- (is (= source-card-id (:id dep)))- (is (= {:type :none} (:remedy dep)))+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))+ [required] (get-in (ex-data ex) [:errors :required])]+ (is (= [source-card-id] (map :id (:dependencies required))))+ (is (false? (:syncable required)))+ (testing "the entry is keyed on where the content lives, since there is no remedy to name"+ (is (= {:type :none :collection nil} (:remedy required))))(testing "the key is present and nil, so clients can tell root from unresolvable"- (is (contains? dep :collection))- (is (nil? (:collection dep))))))))+ (is (contains? (:remedy required) :collection)))))))(deftest bulk-set-remote-sync-snippet-dependency-remedy-is-library-test- (testing "a snippet dependency asks for Library sync — its eligibility keys on the Library, not its collection"- (with-library-not-synced+ (testing "a snippet dependency names the Library collection, which an admin switches on like any other"+ (with-library [{:keys [library]}]+ (with-library-not-synced+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/NativeQuerySnippet {snippet-id :id} {:name "active_users" :content "1 = 1"}+ :model/Card _ {:name "Snippet Card"+ :collection_id synced-id+ :database_id (mt/id)+ :dataset_query (mt/native-query+ {:query "SELECT 1 WHERE {{snippet: active_users}}"+ :template-tags {"snippet: active_users"+ {:snippet-id snippet-id+ :snippet-name "active_users"+ :type :snippet+ :name "snippet: active_users"+ :display-name "Snippet: Active Users"+ :id (str (random-uuid))}}})}]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))]+ ;; The collection `type` is what lets clients give the Library its own icon.+ (is (=? {:errors {:required [{:remedy {:type :collection+ :collection {:id (:id library)+ :name (:name library)+ :type "library"+ :personal false}}+ :syncable true+ :dependencies [{:model "snippet"+ :id snippet-id+ :name "active_users"}]}]}}+ (ex-data ex)))))))))++(deftest bulk-set-remote-sync-dependency-remedy-carries-collection-type-test+ (testing "a remedy resolved through the top-level-ancestor lookup still reports the collection's type"+ ;; Distinct from the snippet case above, whose Library is loaded whole. This one goes through+ ;; `collections-by-id`, so it is what proves that select carries `:type`.+ (with-library [{:keys [library]}]+ (with-library-not-synced+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/Card {source-card-id :id} {:name "Library Card"+ :collection_id (:id library)+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id synced-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))]+ (is (=? {:errors {:required [{:remedy {:type :collection+ :collection {:id (:id library)+ :type "library"}}+ :dependencies [{:id source-card-id}]}]}}+ (ex-data ex)))))))))++(deftest bulk-set-remote-sync-analytics-dependency-is-not-syncable-test+ (testing "usage analytics is named so the refusal makes sense, but never offered as something to sync"+ ;; The settings list filters instance-analytics out, so a remedy pointing at it can't be acted on.+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/Collection {analytics-id :id} {:name "Usage analytics"+ :location "/"+ :type "instance-analytics"+ :is_remote_synced false}+ :model/Card {source-card-id :id} {:name "Audit Card"+ :collection_id analytics-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Card _ {:name "Dependent Card"+ :collection_id synced-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))+ [required] (get-in (ex-data ex) [:errors :required])]+ (is (=? {:remedy {:type :collection+ :collection {:id analytics-id+ :name "Usage analytics"+ :type "instance-analytics"+ :personal false}}+ :syncable false+ :dependencies [{:id source-card-id}]}+ required))))))++(defn- link-to-dashboard-dashcard+ "A dashcard on `dashboard-id` that holds no card of its own and links to `target-id` via click behaviour."+ [dashboard-id target-id]+ {:dashboard_id dashboard-id+ :card_id nil+ :visualization_settings {:click_behavior {:type "link"+ :linkType "dashboard"+ :targetId target-id}}})++(defn- reported-dependencies+ "The `[model id]` pairs a refused sync reports, across every required sync it names."+ [ex]+ (set (for [required (get-in (ex-data ex) [:errors :required])+ dep (:dependencies required)]+ [(:model dep) (:id dep)])))++(deftest bulk-set-remote-sync-dependency-prunes-the-contents-of-a-linked-dashboard-test+ (testing "a dashboard reached by click behaviour is reported alone — syncing its collection covers the cards it holds"+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}+ :model/Card {held-card-id :id} {:name "Held Card"+ :collection_id regular-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Dashboard {linked-id :id} {:name "Linked" :collection_id regular-id}+ :model/DashboardCard _ {:dashboard_id linked-id :card_id held-card-id}+ :model/Dashboard {hub-id :id} {:name "Hub" :collection_id synced-id}+ :model/DashboardCard _ (link-to-dashboard-dashcard hub-id linked-id)]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))]+ (is (= #{["dashboard" linked-id]} (reported-dependencies ex)))+ (testing "the card the linked dashboard holds is not reported in its own right"+ (is (not (contains? (reported-dependencies ex) ["card" held-card-id]))))))))++(deftest bulk-set-remote-sync-dependency-keeps-linked-content-needing-its-own-remedy-test+ (testing "a card inside a linked dashboard survives when syncing that dashboard's collection wouldn't cover it"+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}+ :model/Collection {other-id :id} {:name "Other" :location "/" :is_remote_synced false}+ :model/Card {held-card-id :id} {:name "Held Card"+ :collection_id other-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Dashboard {linked-id :id} {:name "Linked" :collection_id regular-id}+ :model/DashboardCard _ {:dashboard_id linked-id :card_id held-card-id}+ :model/Dashboard {hub-id :id} {:name "Hub" :collection_id synced-id}+ :model/DashboardCard _ (link-to-dashboard-dashcard hub-id linked-id)]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))]+ (is (= #{["dashboard" linked-id] ["card" held-card-id]} (reported-dependencies ex)))+ (testing "each gets its own entry, naming the collection that actually covers it"+ (is (= {"Regular" ["dashboard" linked-id]+ "Other" ["card" held-card-id]}+ (into {} (for [{:keys [remedy dependencies]} (get-in (ex-data ex) [:errors :required])]+ [(get-in remedy [:collection :name])+ (first (map (juxt :model :id) dependencies))])))))))))++(deftest bulk-set-remote-sync-dependency-pruning-keeps-a-mutually-linked-pair-reachable-test+ (testing "dashboards that link to each other don't prune each other away, leaving nothing to report"+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}+ :model/Dashboard {first-id :id} {:name "First" :collection_id regular-id}+ :model/Dashboard {second-id :id} {:name "Second" :collection_id regular-id}+ :model/DashboardCard _ (link-to-dashboard-dashcard first-id second-id)+ :model/DashboardCard _ (link-to-dashboard-dashcard second-id first-id)+ :model/Dashboard {hub-id :id} {:name "Hub" :collection_id synced-id}+ :model/DashboardCard _ (link-to-dashboard-dashcard hub-id first-id)]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))]+ ;; Only `First` is reached from the synced collection, so only it survives — but something must.+ (is (= #{["dashboard" first-id]} (reported-dependencies ex)))))))++(deftest bulk-set-remote-sync-dependency-pruning-keeps-items-behind-an-unsyncable-remedy-test+ (testing "content behind a remedy no switch covers is reported item by item — moving the parent leaves the rest"+ ;; The same shape as the pruning test above, with a personal collection standing in for `Regular`.+ ;; There one switch covers the dashboard and its cards; here every item has to be moved on its own.+ (let [personal-id (:id (collection/user->personal-collection (mt/user->id :rasta)))](mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}- :model/NativeQuerySnippet {snippet-id :id} {:name "active_users" :content "1 = 1"}- :model/Card _ {:name "Snippet Card"- :collection_id synced-id- :database_id (mt/id)- :dataset_query (mt/native-query- {:query "SELECT 1 WHERE {{snippet: active_users}}"- :template-tags {"snippet: active_users"- {:snippet-id snippet-id- :snippet-name "active_users"- :type :snippet- :name "snippet: active_users"- :display-name "Snippet: Active Users"- :id (str (random-uuid))}}})}]- (let [ex (is (thrown? clojure.lang.ExceptionInfo- (core/bulk-set-remote-sync {synced-id true})))]- (is (=? {:errors {:collections [{:dependencies [{:model "snippet"- :id snippet-id- :name "active_users"- :remedy {:type :library}}]}]}}- (ex-data ex))))))))--(deftest bulk-set-remote-sync-reports-every-failing-collection-test- (testing "every collection with unsynced dependencies is reported, not just the first to fail"+ :model/Card {held-card-id :id} {:name "Held Card"+ :collection_id personal-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)}+ :model/Dashboard {linked-id :id} {:name "Linked" :collection_id personal-id}+ :model/DashboardCard _ {:dashboard_id linked-id :card_id held-card-id}+ :model/Dashboard {hub-id :id} {:name "Hub" :collection_id synced-id}+ :model/DashboardCard _ (link-to-dashboard-dashcard hub-id linked-id)]+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-id true})))+ [required] (get-in (ex-data ex) [:errors :required])]+ (testing "the remedy is the personal collection, which the settings list never offers"+ (is (false? (:syncable required))))+ (is (= #{["dashboard" linked-id] ["card" held-card-id]} (reported-dependencies ex))))))))++(deftest bulk-set-remote-sync-reports-every-blocked-collection-test+ (testing "one entry covers both selected collections it unblocks, rather than repeating per selection"(mt/with-temp [:model/Collection {synced-a-id :id} {:name "Synced A" :location "/" :is_remote_synced false}:model/Collection {synced-b-id :id} {:name "Synced B" :location "/" :is_remote_synced false}:model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}@@ -218,10 +412,17 @@:collection_id synced-b-id:database_id (mt/id):dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]- (let [ex (is (thrown? clojure.lang.ExceptionInfo- (core/bulk-set-remote-sync {synced-a-id true synced-b-id true})))]- (is (= #{"Synced A" "Synced B"}- (into #{} (map (comp :name :collection)) (get-in (ex-data ex) [:errors :collections]))))))))+ (let [ex (is (thrown? clojure.lang.ExceptionInfo+ (core/bulk-set-remote-sync {synced-a-id true synced-b-id true})))+ [required] (get-in (ex-data ex) [:errors :required])]+ ;; Both selections resolve to the same remedy, so it is offered once and names what it unblocks.+ (is (= 1 (count (get-in (ex-data ex) [:errors :required]))))+ (is (= #{"Synced A" "Synced B"} (into #{} (map :name) (:blocks required))))+ (testing "the shared dependency is listed once, not once per selection"+ (is (= [source-card-id] (map :id (:dependencies required)))))+ (testing "collapsing it keeps what uses it in *both* selections, not just the first"+ (is (= #{"Dependent A" "Dependent B"}+ (into #{} (map :name) (:used_by (first (:dependencies required)))))))))))(deftest bulk-set-remote-sync-dependent-failure-is-structured-test(testing "disabling a collection something still depends on fails with a structured payload, not a bare message"@@ -242,7 +443,9 @@:errors {:collections [{:collection {:id coll1-id :name "Collection 1"}}]}}(ex-data ex)))(testing "the dependents are named, and nested models resolve to something an admin can open"+ ;; Only the identifying keys — dependents also carry display hints this assertion isn't about.(is (contains? (into #{}+ (map #(select-keys % [:model :id :name]))(get-in (ex-data ex) [:errors :collections 0 :dependents])){:model "card" :id dependent-card-id :name "Dependent Card"})))))))diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.module.css b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.module.cssindex 0271d58c3b7..d33928c4846 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.module.css+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.module.css@@ -1,7 +1,49 @@-.collectionRow {+/*+ * Every slot override below is prefixed with `.accordion` to out-specify the single-class theme+ * rules in metabase/ui's Accordion.module.css. The compound selectors are written flat on purpose:+ * nesting them would make postcss-nesting wrap them in `:is()` and change the specificity math.+ */+.accordion .item,+.accordion .item + .item,+.accordion .item[data-active] {+ border: 0;+ border-radius: 0;+}++/* Padding lives on the row around it, which the switch shares. */+.accordion .control {+ flex: 1;+ min-width: 0;+ padding: 0;+}++.accordion .label {+ color: var(--mb-color-text-primary);+ font-size: inherit;+ font-weight: normal;+ line-height: inherit;+ padding: 0.5rem 0;+}++.accordion .chevron {+ border: 0;+ color: var(--mb-color-text-secondary);+ height: auto;+ margin-left: 0;+ width: auto;+}++.accordion .content {+ border-top: none;+ padding-top: 1rem;+ padding-left: 3rem;+}++.contentRow:not(:last-of-type) {border-bottom: 1px solid var(--mb-color-border);+}- &:last-child {- border-bottom: none;- }+.cell {+ flex: 1 1 0;+ min-width: 0;}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.tsxindex 7a76b4e3d02..e01c8ccb041 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.tsx@@ -1,122 +1,224 @@import { useFormikContext } from "formik";import { useState } from "react";-import { t } from "ttag";+import { c, t } from "ttag";-import { Button, Card, Group, Icon, Modal, Stack, Text } from "metabase/ui";-import type { RemoteSyncDependencyFailure } from "metabase-types/api";+import { Link } from "metabase/common/components/Link";+import { useGetIcon } from "metabase/hooks/use-icon";+import {+ Accordion,+ Anchor,+ Button,+ Card,+ Ellipsified,+ Group,+ Icon,+ Modal,+ Stack,+ Switch,+ Text,+} from "metabase/ui";+import { collection as collectionUrl } from "metabase/urls";+import type {+ CollectionSyncPreferences,+ RemoteSyncRequiredSync,+} from "metabase-types/api";import { COLLECTIONS_KEY } from "../../constants";import type { RemoteSyncSettingsFormState } from "../../types";import {- canSyncRequiredCollections,getBlockedMessage,- getRequiredCollectionRows,- getRequiredCollections,+ getListedRequiredSyncs,+ getRequiredSyncRow,} from "../../utils";import S from "./RemoteSyncDependencyModal.module.css";interface RemoteSyncDependencyModalProps {- /** Why the last save was refused, one entry per collection. */- failures?: RemoteSyncDependencyFailure[];+ /** Why the last save was refused, one entry per collection that has to be synced. */+ required?: RemoteSyncRequiredSync[];}export const RemoteSyncDependencyModal = ({- failures,+ required,}: RemoteSyncDependencyModalProps) => {- const { values, setValues, submitForm } =+ const { values, setFieldValue, submitForm, isSubmitting } =useFormikContext<RemoteSyncSettingsFormState>();- // RTK returns a new error object per request, so identity separates fresh from dismissed.- const [dismissedFailures, setDismissedFailures] =- useState<RemoteSyncDependencyFailure[]>();+ const [dismissedRequired, setDismissedRequired] =+ useState<RemoteSyncRequiredSync[]>();- if (!failures?.length || failures === dismissedFailures) {+ if (!required?.length || required === dismissedRequired) {return null;}- // Rows are for display and can include Our analytics; only real remedies are safe to switch on.- const requiredCollections = getRequiredCollections(failures);- const requiredCollectionRows = getRequiredCollectionRows(failures);- const canSync = canSyncRequiredCollections(failures);+ const listedRequiredSyncs = getListedRequiredSyncs(required);+ const syncedCollections = values[COLLECTIONS_KEY] ?? {};+ const canSave = required.every(({ syncable }) => syncable);- const handleDismiss = () => setDismissedFailures(failures);+ const handleDismiss = () => setDismissedRequired(required);- const handleSyncAndSave = async () => {- await setValues({- ...values,- [COLLECTIONS_KEY]: {- ...values[COLLECTIONS_KEY],- ...Object.fromEntries(requiredCollections.map(({ id }) => [id, true])),- },- });- await submitForm();- };+ // Nested path, so the write survives the form reinitializing under the modal.+ const handleToggle = (id: number, checked: boolean) =>+ setFieldValue(`${COLLECTIONS_KEY}.${id}`, checked);return (<ModalopenedonClose={handleDismiss}padding="xxl"- title={- canSync- ? t`Sync collections with dependencies?`- : t`Couldn’t sync selected collection`- }+ title={t`Couldn’t sync selected collection`}+ withCloseButton={false}><Stack gap="xl" pt="lg">- <Text>{getBlockedMessage(failures)}</Text>-- {requiredCollectionRows.length > 0 && (- <Card withBorder p={0} shadow="none">- <Stack gap={0}>- {requiredCollectionRows.map((collection) => (- <Group- key={collection.id}- gap="sm"- className={S.collectionRow}- py="sm"- px="lg"- justify="space-between"- bg={collection.syncable ? undefined : "background-secondary"}- >- <Group>- <Icon- name={collection.personal ? "person" : "collection"}- c="text-secondary"- />- <Text fw="medium">{collection.name}</Text>- </Group>- {collection.syncable ? (- <Group gap="sm">- <Icon name="warning_triangle_filled" c="warning" />- <Text c="feedback-warning-strong">{t`Sync to continue`}</Text>- </Group>- ) : (- <Text c="text-secondary">{t`Can't be synced`}</Text>- )}- </Group>- ))}- </Stack>- </Card>+ <Text>{getBlockedMessage(required)}</Text>++ {listedRequiredSyncs.length > 0 && (+ <Accordion+ multiple+ chevronPosition="left"+ className={S.accordion}+ classNames={{+ item: S.item,+ control: S.control,+ label: S.label,+ chevron: S.chevron,+ content: S.content,+ }}+ >+ {listedRequiredSyncs.map((requiredSync) => (+ <RequiredSyncItem+ key={getRequiredSyncRow(requiredSync).key}+ requiredSync={requiredSync}+ syncedCollections={syncedCollections}+ onToggle={handleToggle}+ />+ ))}+ </Accordion>)}- <Group justify={canSync ? "space-between" : "end"} gap="sm">- <>- {canSync && (- <Button onClick={handleSyncAndSave}>- {t`Sync required collections`}- </Button>- )}+ <Group justify="end" gap="sm">+ <Button onClick={handleDismiss}>{t`Back`}</Button>+ {canSave && (<Buttonvariant="filled"- onClick={handleDismiss}- style={{ justifySelf: "end" }}+ loading={isSubmitting}+ onClick={submitForm}>- {canSync ? t`Cancel` : t`Back`}+ {t`Save changes`}</Button>- </>+ )}</Group></Stack></Modal>);};++interface RequiredSyncItemProps {+ requiredSync: RemoteSyncRequiredSync;+ syncedCollections: CollectionSyncPreferences;+ onToggle: (id: number, checked: boolean) => void;+}++const RequiredSyncItem = ({+ requiredSync,+ syncedCollections,+ onToggle,+}: RequiredSyncItemProps) => {+ const getIcon = useGetIcon();+ const { dependencies } = requiredSync;+ const row = getRequiredSyncRow(requiredSync);+ const { syncableId } = row;+ const isSynced = syncableId != null && !!syncedCollections[syncableId];++ const icon = getIcon({+ model: "collection",+ type: row.type,+ is_personal: row.personal,+ location: "/",+ is_remote_synced: isSynced,+ is_library_root: row.type === "library",+ });++ return (+ <Accordion.Item value={row.key} mt="sm">+ {/* The switch sits outside the control, so flipping it doesn't also toggle the panel. */}+ <Group+ gap="sm"+ px="md"+ wrap="nowrap"+ bg={"background-secondary"}+ bdrs="md"+ >+ <Accordion.Control>+ <Group gap="sm">+ <Icon name={icon.name} c={icon.color ?? "text-secondary"} />+ <Text fw="medium">{row.name}</Text>+ </Group>+ </Accordion.Control>+ {syncableId == null ? (+ <Text c="text-secondary">{t`Can't be synced`}</Text>+ ) : (+ <Group gap="sm" wrap="nowrap">+ <Switch+ checked={isSynced}+ onChange={(event) =>+ onToggle(syncableId, event.currentTarget.checked)+ }+ aria-label={c("{0} is the name of a metabase collection")+ .t`Sync ${row.name}`}+ />+ <Text>{t`Sync`}</Text>+ </Group>+ )}+ </Group>+ <Accordion.Panel>+ <Card withBorder mb="md" p={0} shadow="none">+ <Group+ px="md"+ py="xs"+ bg="background-secondary"+ className={S.contentRow}+ >+ <Text className={S.cell} fz="sm">{t`Item`}</Text>+ <Text className={S.cell} fz="sm">{t`Used By`}</Text>+ </Group>+ {dependencies.map((dependency) => (+ <Group+ px="md"+ py="sm"+ className={S.contentRow}+ key={`${dependency.model}-${dependency.id}`}+ >+ <Group className={S.cell} gap="sm" wrap="nowrap">+ <Icon+ name={+ getIcon({+ model: dependency.model,+ display: dependency.display,+ }).name+ }+ />+ <Ellipsified>{dependency.name}</Ellipsified>+ </Group>+ <Ellipsified className={S.cell}>+ {dependency.used_by.map((used) => used.name).join(", ")}+ </Ellipsified>+ </Group>+ ))}+ </Card>++ {row.collectionId != null && (+ <Anchor+ component={Link}+ to={collectionUrl({ id: row.collectionId, name: row.name })}+ target="_blank"+ >+ <Group gap="xs">+ {t`Go to collection`}+ <Icon name="external" />+ </Group>+ </Anchor>+ )}+ </Accordion.Panel>+ </Accordion.Item>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.unit.spec.tsxindex 10a5f4ebfd1..2042637a05b 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.unit.spec.tsx@@ -6,6 +6,7 @@ import { screen, waitFor, within } from "__support__/ui";import type {RemoteSyncDependencyErrorResponse,RemoteSyncIneligibleDependency,+ RemoteSyncRequiredSync,} from "metabase-types/api";import { createMockCollectionItemFromCollection } from "metabase-types/api/mocks";@@ -14,59 +15,84 @@ import { setup } from "./RemoteSyncSettingsForm.setup.spec";const BLOCKED_COLLECTION = { id: 20, name: "Marketing" };const REQUIRED_COLLECTION = { id: 30, name: "Finance" };+// `used_by` is what an expanded row lists as the dependent; `display` picks the visualization icon.const SYNCABLE_DEPENDENCY: RemoteSyncIneligibleDependency = {model: "card",id: 416,name: "Seats over time",collection: REQUIRED_COLLECTION,- remedy: {- type: "collection",- collection: { ...REQUIRED_COLLECTION, personal: false },- },+ display: "bar",+ used_by: [{ model: "dashboard", id: 7, name: "Q3 Review" }],};-const PERSONAL_DEPENDENCY: RemoteSyncIneligibleDependency = {- model: "card",- id: 417,- name: "Draft",- collection: REQUIRED_COLLECTION,- remedy: {+const requiredSync = (+ remedy: RemoteSyncRequiredSync["remedy"],+ syncable = false,+ dependencies = [SYNCABLE_DEPENDENCY],+): RemoteSyncRequiredSync => ({+ remedy,+ syncable,+ blocks: [BLOCKED_COLLECTION],+ dependencies,+});++const SYNCABLE_REQUIRED = requiredSync(+ {type: "collection",- collection: { id: 5, name: "Nick's stuff", personal: true },+ collection: { ...REQUIRED_COLLECTION, type: null, personal: false },},-};+ true,+);++const PERSONAL_REQUIRED = requiredSync({+ type: "collection",+ collection: { id: 5, name: "Nick's stuff", type: null, personal: true },+});++const ANALYTICS_REQUIRED = requiredSync({+ type: "collection",+ collection: {+ id: 3,+ name: "Usage analytics",+ type: "instance-analytics",+ personal: false,+ },+});// `collection: null` is the root collection-const ROOT_DEPENDENCY: RemoteSyncIneligibleDependency = {- model: "card",- id: 512,- name: "Orphaned",- collection: null,- remedy: { type: "none" },-};+const ROOT_REQUIRED = requiredSync({ type: "none", collection: null });-// The backend sends no id for the Library, so there is nothing to switch on.-const SNIPPET_DEPENDENCY: RemoteSyncIneligibleDependency = {- model: "snippet",- id: 3,- name: "active_users",- remedy: { type: "library" },-};+// The Library is an ordinary collection, so a snippet points at it like any other remedy.+const LIBRARY_COLLECTION = { id: 2, name: "Library" };+const LIBRARY_REQUIRED = requiredSync(+ {+ type: "collection",+ collection: { ...LIBRARY_COLLECTION, type: "library", personal: false },+ },+ true,+ [{ model: "snippet", id: 3, name: "active_users", used_by: [] }],+);++// ...unless the instance has no Library yet, leaving nothing to switch on.+const LIBRARY_MISSING_REQUIRED = requiredSync({ type: "library" }, false, [+ { model: "snippet", id: 4, name: "monthly_cutoff", used_by: [] },+]);const createRefusal = (- ...dependencies: RemoteSyncIneligibleDependency[]+ ...required: RemoteSyncRequiredSync[]): RemoteSyncDependencyErrorResponse => ({error: "Uses content that is not remote synced.",error_code: "unsynced-dependencies",- errors: {- collections: [{ collection: BLOCKED_COLLECTION, dependencies }],- },+ errors: { required },});-// First save is refused with `body`; any retry succeeds, so the second PUT shows what the modal sent.+// The first save is refused with `body`; later ones succeed, so the second PUT+// shows what the modal staged.const setupRefusedSave = async ({- body = createRefusal(SYNCABLE_DEPENDENCY),-}: { body?: RemoteSyncDependencyErrorResponse } = {}) => {+ body = createRefusal(SYNCABLE_REQUIRED),+}: {+ body?: RemoteSyncDependencyErrorResponse;+} = {}) => {setup({remoteSyncType: "read-write",remoteSyncUrl: "https://github.com/test/repo.git",@@ -103,33 +129,20 @@ const setupRefusedSave = async ({await userEvent.click(screen.getByLabelText(`Sync ${BLOCKED_COLLECTION.name}`),);- await userEvent.click(screen.getByRole("button", { name: /Save changes/i }));+ await save();};-// The modal asks a question when it can act, and reports a failure when it can't.-const expectFixOffered = (modal: HTMLElement) => {- expect(- within(modal).getByText("Sync collections with dependencies?"),- ).toBeInTheDocument();- expect(- within(modal).getByRole("button", { name: "Sync required collections" }),- ).toBeInTheDocument();- expect(- within(modal).getByRole("button", { name: "Cancel" }),- ).toBeInTheDocument();-};+// By test id, not label: the button reads "Failed" for several seconds after a rejected submit.+const save = () =>+ userEvent.click(screen.getByTestId("remote-sync-submit-button"));-const expectNoFixOffered = (modal: HTMLElement) => {- expect(- within(modal).getByText(/Couldn.t sync selected collection/),- ).toBeInTheDocument();- expect(- within(modal).queryByRole("button", { name: "Sync required collections" }),- ).not.toBeInTheDocument();- expect(- within(modal).getByRole("button", { name: "Back" }),- ).toBeInTheDocument();-};+const dismiss = (modal: HTMLElement) =>+ userEvent.click(within(modal).getByRole("button", { name: "Back" }));++const expectClosed = () =>+ waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });const getSettingsPuts = async () => {const puts = await findRequests("PUT");@@ -139,17 +152,19 @@ const getSettingsPuts = async () => {};describe("RemoteSyncDependencyModal", () => {- it("opens when a save is refused, naming the collection that must be synced too", async () => {+ it("opens when a save is refused, offering the collection that must be synced too", async () => {await setupRefusedSave();const modal = await screen.findByRole("dialog");- expectFixOffered(modal);expect(- within(modal).getByText(/rely on data saved elsewhere/),+ within(modal).getByText(/Couldn.t sync selected collection/),).toBeInTheDocument();expect(- within(modal).getByText(REQUIRED_COLLECTION.name),+ within(modal).getByText(/rely on data saved elsewhere/),).toBeInTheDocument();+ expect(+ within(modal).getByLabelText(`Sync ${REQUIRED_COLLECTION.name}`),+ ).not.toBeChecked();});it("stays closed until a save is refused", async () => {@@ -165,20 +180,20 @@ describe("RemoteSyncDependencyModal", () => {expect(screen.queryByRole("dialog")).not.toBeInTheDocument();});- it("switches the required collections on and saves them in one action", async () => {+ it("carries a collection switched on in the modal into the next save", async () => {await setupRefusedSave();const modal = await screen.findByRole("dialog");await userEvent.click(- within(modal).getByRole("button", { name: "Sync required collections" }),+ within(modal).getByLabelText(`Sync ${REQUIRED_COLLECTION.name}`),);+ await dismiss(modal);+ await save();await waitFor(async () => {expect(await getSettingsPuts()).toHaveLength(2);});- // The retry carries the collection the admin picked *and* the one the modal added — proof the- // save reads the flipped form state rather than the values that were refused.const [, retry] = await getSettingsPuts();expect(retry.body).toHaveProperty("collections", {[BLOCKED_COLLECTION.id]: true,@@ -186,116 +201,165 @@ describe("RemoteSyncDependencyModal", () => {});});- it("closes once the retry succeeds", async () => {- await setupRefusedSave();+ it.each([+ [+ "personal",+ PERSONAL_REQUIRED,+ "Nick's stuff",+ /saved in a personal collection/,+ ],+ [+ "root",+ ROOT_REQUIRED,+ "Our analytics",+ /can.t be synced where it currently lives/,+ ],+ [+ "usage analytics",+ ANALYTICS_REQUIRED,+ "Usage analytics",+ /rely on content in usage analytics/,+ ],+ ])(+ "explains a %s blocker and lists it alone, not what could otherwise be switched on",+ async (_label, requiredEntry, unsyncableName, message) => {+ await setupRefusedSave({+ body: createRefusal(SYNCABLE_REQUIRED, requiredEntry),+ });++ const modal = await screen.findByRole("dialog");+ expect(within(modal).getByText(message)).toBeInTheDocument();+ expect(within(modal).getByText(unsyncableName)).toBeInTheDocument();+ expect(+ within(modal).queryByLabelText(`Sync ${unsyncableName}`),+ ).not.toBeInTheDocument();+ expect(within(modal).getByText("Can't be synced")).toBeInTheDocument();+ expect(+ within(modal).queryByText(REQUIRED_COLLECTION.name),+ ).not.toBeInTheDocument();+ },+ );++ it("offers the Library as a switchable row, like any other collection", async () => {+ await setupRefusedSave({ body: createRefusal(LIBRARY_REQUIRED) });const modal = await screen.findByRole("dialog");await userEvent.click(- within(modal).getByRole("button", { name: "Sync required collections" }),+ within(modal).getByLabelText(`Sync ${LIBRARY_COLLECTION.name}`),);+ await dismiss(modal);+ await save();- await waitFor(() => {- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ await waitFor(async () => {+ expect(await getSettingsPuts()).toHaveLength(2);+ });++ const [, retry] = await getSettingsPuts();+ expect(retry.body).toHaveProperty("collections", {+ [BLOCKED_COLLECTION.id]: true,+ [LIBRARY_COLLECTION.id]: true,});});- it("stays closed after the admin dismisses it", async () => {+ it("saves from the modal", async () => {await setupRefusedSave();const modal = await screen.findByRole("dialog");await userEvent.click(- within(modal).getByRole("button", { name: "Cancel" }),+ within(modal).getByLabelText(`Sync ${REQUIRED_COLLECTION.name}`),+ );+ await userEvent.click(+ within(modal).getByRole("button", { name: "Save changes" }),);- await waitFor(() => {- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ await waitFor(async () => {+ expect(await getSettingsPuts()).toHaveLength(2);});- expect(await getSettingsPuts()).toHaveLength(1);- });-- it("offers no fix when the blocking content sits in a personal collection", async () => {- await setupRefusedSave({ body: createRefusal(PERSONAL_DEPENDENCY) });- const modal = await screen.findByRole("dialog");- expect(- within(modal).getByText(/saved in a personal collection/),- ).toBeInTheDocument();- expectNoFixOffered(modal);+ const [, retry] = await getSettingsPuts();+ expect(retry.body).toHaveProperty("collections", {+ [BLOCKED_COLLECTION.id]: true,+ [REQUIRED_COLLECTION.id]: true,+ });+ await expectClosed();});- it("offers no fix when the blocking content sits in the root collection", async () => {- await setupRefusedSave({ body: createRefusal(ROOT_DEPENDENCY) });+ it.each([+ ["nothing in the list can be switched on", [ROOT_REQUIRED]],+ ["one entry beside it can't be", [SYNCABLE_REQUIRED, ROOT_REQUIRED]],+ [+ "a Library that doesn't exist blocks it",+ [SYNCABLE_REQUIRED, LIBRARY_MISSING_REQUIRED],+ ],+ ])("offers no save when %s", async (_label, entries) => {+ await setupRefusedSave({ body: createRefusal(...entries) });const modal = await screen.findByRole("dialog");expect(- within(modal).getByText(/can.t be synced where it currently lives/),+ within(modal).queryByRole("button", { name: "Save changes" }),+ ).not.toBeInTheDocument();+ expect(+ within(modal).getByRole("button", { name: "Back" }),).toBeInTheDocument();- expectNoFixOffered(modal);});- it("lists Our analytics as unsyncable, rather than leaving the list empty", async () => {+ it("renders one row per blocker, and none for what can be switched on", async () => {await setupRefusedSave({- body: createRefusal(SYNCABLE_DEPENDENCY, ROOT_DEPENDENCY),+ body: createRefusal(SYNCABLE_REQUIRED, ROOT_REQUIRED, PERSONAL_REQUIRED),});const modal = await screen.findByRole("dialog");- expect(within(modal).getByText("Our analytics")).toBeInTheDocument();- // The syncable remedy is still listed, but nothing here is actionable while the root one stands.- expect(- within(modal).getByText(REQUIRED_COLLECTION.name),- ).toBeInTheDocument();- expect(within(modal).getByText("Can't be synced")).toBeInTheDocument();- });+ const rows = within(modal)+ .getAllByRole("button", { expanded: false })+ .map((row) => row.textContent);- it("offers no fix when the dependency is a snippet, since the Library has no id to switch on", async () => {- await setupRefusedSave({ body: createRefusal(SNIPPET_DEPENDENCY) });-- const modal = await screen.findByRole("dialog");- expect(- within(modal).getByText(/sync with the Library/),- ).toBeInTheDocument();- expectNoFixOffered(modal);+ expect(rows).toHaveLength(2);+ expect(rows[0]).toMatch(/Our analytics/);+ expect(rows[1]).toMatch(/Nick's stuff/);});- it("keeps the admin's selection after a refused save, so it can be retried", async () => {- await setupRefusedSave();+ it.each([+ ["a personal collection", PERSONAL_REQUIRED, /Nick's stuff/, "person icon"],+ [+ "the Library",+ LIBRARY_REQUIRED,+ new RegExp(LIBRARY_COLLECTION.name),+ "repository icon",+ ],+ ])(+ "icons %s by what kind of collection it is",+ async (_label, entry, name, expectedIcon) => {+ await setupRefusedSave({ body: createRefusal(entry) });- const modal = await screen.findByRole("dialog");- await userEvent.click(- within(modal).getByRole("button", { name: "Cancel" }),- );+ const modal = await screen.findByRole("dialog");+ const row = within(modal).getByRole("button", { name });- // A refused save rolls back, so the collection list refetch it triggers must not reset the form.- await waitFor(async () => {- expect(await findRequests("GET")).toEqual(- expect.arrayContaining([- expect.objectContaining({- url: expect.stringContaining("/api/collection/root/items"),- }),- ]),+ expect(within(row).getByRole("img")).toHaveAttribute(+ "aria-label",+ expectedIcon,);- });-- expect(- screen.getByLabelText(`Sync ${BLOCKED_COLLECTION.name}`),- ).toBeChecked();- // Enabled means still dirty; the button relabels to "Failed" after a rejected submit.- expect(screen.getByTestId("remote-sync-submit-button")).toBeEnabled();- });+ },+ );- // Switching Finance on would leave the other dependency behind, so the save is refused again.it.each([- ["personal", PERSONAL_DEPENDENCY],- ["root", ROOT_DEPENDENCY],- ["snippet", SNIPPET_DEPENDENCY],+ ["nothing else is required", [LIBRARY_MISSING_REQUIRED]],+ [+ "a syncable collection waits behind it",+ [SYNCABLE_REQUIRED, LIBRARY_MISSING_REQUIRED],+ ],])(- "offers no fix when a syncable dependency is joined by a %s one",- async (_label, dependency) => {- await setupRefusedSave({- body: createRefusal(SYNCABLE_DEPENDENCY, dependency),- });-- expectNoFixOffered(await screen.findByRole("dialog"));+ "explains a Library blocker with nothing to switch on when %s",+ async (_label, entries) => {+ await setupRefusedSave({ body: createRefusal(...entries) });++ const modal = await screen.findByRole("dialog");+ expect(+ within(modal).getByText(/Create the Library in Data Studio/),+ ).toBeInTheDocument();+ expect(within(modal).queryAllByRole("switch")).toHaveLength(0);+ expect(+ within(modal).queryAllByRole("button", { expanded: false }),+ ).toHaveLength(0);},);});diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsxindex 2ba8b5cdf65..3b9ea8654a2 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx@@ -74,7 +74,7 @@ export const RemoteSyncSettingsForm = ({const { handleDisable, disableModal, isDisabling } = useDisableRemoteSync();const dirtyEntities = dirtyData?.dirty ?? [];- const dependencyFailures = unsyncedDependenciesError?.errors.collections;+ const requiredSyncs = unsyncedDependenciesError?.errors.required;const isModalVariant = variant === "settings-modal";const isSaving = isUpdating || isDisabling;const canDisable =@@ -161,7 +161,7 @@ export const RemoteSyncSettingsForm = ({{/* Inside the form so its fix-and-save can write through formik; Mantine portals it out. */}{!isModalVariant && (- <RemoteSyncDependencyModal failures={dependencyFailures} />+ <RemoteSyncDependencyModal required={requiredSyncs} />)}</Form>);diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.tsindex a1900d42277..068edfacd41 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts@@ -13,19 +13,21 @@ const UNSYNCED_DEPENDENCIES_BODY: RemoteSyncDependencyErrorResponse = {error: "Uses content that is not remote synced.",error_code: "unsynced-dependencies",errors: {- collections: [+ required: [{- collection: { id: 14, name: "New Collection" },+ remedy: {+ type: "collection",+ collection: { id: 7, name: "Regular", type: null, personal: false },+ },+ syncable: true,+ blocks: [{ id: 20, name: "Marketing" }],dependencies: [{model: "card",id: 416,name: "Subscription seats over time",collection: { id: 7, name: "Regular" },- remedy: {- type: "collection",- collection: { id: 7, name: "Regular", personal: false },- },+ used_by: [],},],},diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.tsindex 5627ad18bd0..27e36db1a3b 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts@@ -3,10 +3,10 @@ import { t } from "ttag";import type { ColorName } from "metabase/ui/colors/types";import type {Collection,+ CollectionType,IconName,- RemoteSyncDependencyFailure,RemoteSyncEntityStatus,- RemoteSyncRemedyCollection,+ RemoteSyncRequiredSync,SettingDefinition,} from "metabase-types/api";@@ -168,150 +168,139 @@ export const parseSyncError = (exportError: SyncError | null): ParsedError => {};};-// Deduped because remedies point at top-level collections, so dependencies collapse onto the same one.-export const getRequiredCollections = (- failures: RemoteSyncDependencyFailure[],-): RemoteSyncRemedyCollection[] => {- const collections = failures- .flatMap((failure) => failure.dependencies)- .flatMap((dependency) =>- dependency.remedy.type === "collection"- ? [dependency.remedy.collection]- : [],- );-- const byId = new Map<number, RemoteSyncRemedyCollection>(- collections.map((collection) => [collection.id, collection]),- );-- return [...byId.values()];-};-export const ROOT_COLLECTION_ROW_ID = "root";-export type RequiredCollectionRow = {- id: number | typeof ROOT_COLLECTION_ROW_ID;+export type RequiredSyncRow = {+ key: string;name: string;+ type: CollectionType;personal: boolean;- syncable: boolean;+ syncableId: number | null;+ collectionId: number | typeof ROOT_COLLECTION_ROW_ID | null;};-const getUnsyncableRows = (- failures: RemoteSyncDependencyFailure[],-): RequiredCollectionRow[] => {- const rows = failures- .flatMap((failure) => failure.dependencies)- .filter((dependency) => dependency.remedy.type === "none")- .flatMap((dependency): RequiredCollectionRow[] => {- const { collection } = dependency;-- // Absent means the backend couldn't resolve one, so there is nothing honest to name.- if (collection === undefined) {- return [];- }- return collection === null- ? [- {- id: ROOT_COLLECTION_ROW_ID,- name: t`Our analytics`,- personal: false,- syncable: false,- },- ]- : [{ ...collection, personal: false, syncable: false }];- });+export const getRequiredSyncRow = ({+ remedy,+ syncable,+}: RemoteSyncRequiredSync): RequiredSyncRow => {+ if (remedy.type === "collection") {+ const { id, name, type, personal } = remedy.collection;- return [...new Map(rows.map((row) => [row.id, row])).values()];+ return {+ key: `collection:${id}`,+ name,+ type,+ personal,+ syncableId: syncable ? id : null,+ collectionId: id,+ };+ }++ const unsyncable = { type: null, personal: false, syncableId: null };++ if (remedy.type === "library") {+ return {+ ...unsyncable,+ key: "library",+ name: t`Library`,+ collectionId: null,+ };+ }+ if (remedy.collection === null) {+ return {+ ...unsyncable,+ key: ROOT_COLLECTION_ROW_ID,+ name: t`Our analytics`,+ collectionId: ROOT_COLLECTION_ROW_ID,+ };+ }+ if (remedy.collection === undefined) {+ return {+ ...unsyncable,+ key: "unresolved",+ name: t`Unknown collection`,+ collectionId: null,+ };+ }+ return {+ ...unsyncable,+ key: `none:${remedy.collection.id}`,+ name: remedy.collection.name,+ collectionId: remedy.collection.id,+ };};-export const getRequiredCollectionRows = (- failures: RemoteSyncDependencyFailure[],-): RequiredCollectionRow[] => [- ...getRequiredCollections(failures).map(({ id, name, personal }) => ({- id,- name,- personal,- syncable: !personal,- })),- ...getUnsyncableRows(failures),-];--// `every`, not `some`: one dependency we can't toggle makes this a partial fix, which is refused again.-export const canSyncRequiredCollections = (- failures: RemoteSyncDependencyFailure[],-): boolean =>- getRequiredCollections(failures).length > 0 &&- failures.every((failure) =>- failure.dependencies.every(- (dependency) =>- dependency.remedy.type === "collection" &&- !dependency.remedy.collection.personal,- ),- );+export const getListedRequiredSyncs = (+ required: RemoteSyncRequiredSync[],+): RemoteSyncRequiredSync[] => {+ const blocking = required.filter(({ syncable }) => !syncable);+ const listed = blocking.length > 0 ? blocking : required;++ // Remedy type library means that no library is created to sync, so it blocks+ return listed.filter(({ remedy }) => remedy.type !== "library");+};export type BlockedReason =| "personal-content"+ | "analytics-content"| "unsyncable-content"- | "library"+ | "library-missing"| "linked-collections";// Ordered so content that can't be synced at all outranks content that can.export const getBlockedReason = (- failures: RemoteSyncDependencyFailure[],+ required: RemoteSyncRequiredSync[],): BlockedReason => {- if (isBlockedByPersonalContent(failures)) {+ if (isBlockedByPersonalContent(required)) {return "personal-content";}- if (requiresContentMove(failures)) {+ if (isBlockedByAnalyticsContent(required)) {+ return "analytics-content";+ }+ if (requiresContentMove(required)) {return "unsyncable-content";}- if (requiresLibrarySync(failures)) {- return "library";+ if (isBlockedByMissingLibrary(required)) {+ return "library-missing";}return "linked-collections";};-// `personal` sits on the remedy — the top-level ancestor — not the collection the dependency is in.const isBlockedByPersonalContent = (- failures: RemoteSyncDependencyFailure[],+ required: RemoteSyncRequiredSync[],): boolean =>- failures.some((failure) =>- failure.dependencies.some(- (dependency) =>- dependency.remedy.type === "collection" &&- dependency.remedy.collection.personal,- ),+ required.some(+ ({ remedy }) => remedy.type === "collection" && remedy.collection.personal,);-const requiresLibrarySync = (- failures: RemoteSyncDependencyFailure[],+const isBlockedByAnalyticsContent = (+ required: RemoteSyncRequiredSync[],): boolean =>- failures.some((failure) =>- failure.dependencies.some(- (dependency) => dependency.remedy.type === "library",- ),+ required.some(+ ({ remedy }) =>+ remedy.type === "collection" &&+ remedy.collection.type === "instance-analytics",);-// A `none` remedy leaves nothing to switch on, so the content has to move instead.-const requiresContentMove = (- failures: RemoteSyncDependencyFailure[],-): boolean =>- failures.some((failure) =>- failure.dependencies.some(- (dependency) => dependency.remedy.type === "none",- ),- );+const isBlockedByMissingLibrary = (+ required: RemoteSyncRequiredSync[],+): boolean => required.some(({ remedy }) => remedy.type === "library");++const requiresContentMove = (required: RemoteSyncRequiredSync[]): boolean =>+ required.some(({ remedy }) => remedy.type === "none");export const getBlockedMessage = (- failures: RemoteSyncDependencyFailure[],+ required: RemoteSyncRequiredSync[],): string => {- switch (getBlockedReason(failures)) {+ switch (getBlockedReason(required)) {case "personal-content":return t`Dashboards or questions in this collection rely on content saved in a personal collection, which can’t be synced. Move that content to a shared collection to continue.`;+ case "analytics-content":+ return t`Dashboards or questions in this collection rely on content in usage analytics, which can’t be synced. Update them to use content you can sync to continue.`;case "unsyncable-content":return t`Dashboards or questions in this collection rely on content that can’t be synced where it currently lives. Move that content into a collection you’re syncing to continue.`;- case "library":- return t`Dashboards or questions in this collection rely on snippets, which sync with the Library. Sync the Library as well to continue.`;+ case "library-missing":+ return t`Dashboards or questions in this collection rely on snippets, which sync with the Library. Create the Library in Data Studio, then sync it to continue.`;case "linked-collections":return t`Dashboards or questions in this collection rely on data saved elsewhere. To continue, sync those linked collections as well.`;}diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.tsindex 3415a6d1a6c..0f99c07be9d 100644--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts@@ -1,16 +1,16 @@import type {- RemoteSyncDependencyFailure,+ RemoteSyncDependencyRemedy,RemoteSyncIneligibleDependency,+ RemoteSyncRequiredSync,} from "metabase-types/api";import { createMockCollection } from "metabase-types/api/mocks";import {buildCollectionMap,- canSyncRequiredCollections,getBlockedReason,getCollectionPathSegments,- getRequiredCollectionRows,- getRequiredCollections,+ getListedRequiredSyncs,+ getRequiredSyncRow,isTableChildModel,} from "./utils";@@ -228,269 +228,196 @@ describe("remote_sync utils", () => {});describe("unsynced dependency failures", () => {- // Two blocked collections whose dependencies resolve to the same remedy collection, plus a- // snippet (Library remedy) and a dependency with no actionable remedy.- const FAILURES: RemoteSyncDependencyFailure[] = [- {- collection: { id: 14, name: "Marketing" },- dependencies: [- {- model: "card",- id: 416,- name: "Seats over time",- collection: { id: 7, name: "Finance" },- remedy: {- type: "collection",- collection: { id: 7, name: "Finance", personal: false },- },- },- {- model: "snippet",- id: 3,- name: "active_users",- remedy: { type: "library" },- },- ],- },- {- collection: { id: 22, name: "Ops" },- dependencies: [- {- model: "dashboard",- id: 91,- name: "Weekly review",- collection: { id: 9, name: "Nested" },- // Same top-level remedy as the card above, reached from a different collection.- remedy: {- type: "collection",- collection: { id: 7, name: "Finance", personal: false },- },- },- {- model: "card",- id: 512,- name: "Orphaned",- remedy: { type: "none" },- },- ],- },- ];-- describe("getRequiredCollections", () => {- it("flattens remedies across every failure and dedupes by id", () => {- expect(getRequiredCollections(FAILURES)).toEqual([- { id: 7, name: "Finance", personal: false },- ]);- });-- it("ignores library and non-actionable remedies", () => {- const libraryOnly = [- {- collection: { id: 14, name: "Marketing" },- dependencies: [- {- model: "snippet" as const,- id: 3,- name: "active_users",- remedy: { type: "library" as const },- },- ],- },- ];-- expect(getRequiredCollections(libraryOnly)).toEqual([]);- });-- it("keeps personal collections so callers can flag them as unsyncable", () => {- const personal = [- {- collection: { id: 14, name: "Marketing" },- dependencies: [- {- model: "card" as const,- id: 1,- name: "Draft",- remedy: {- type: "collection" as const,- collection: { id: 5, name: "Nick's stuff", personal: true },- },- },- ],- },- ];-- expect(getRequiredCollections(personal)).toEqual([- { id: 5, name: "Nick's stuff", personal: true },- ]);- });- });-- const SYNCABLE_DEPENDENCY: RemoteSyncIneligibleDependency = {+ const dependency = (+ overrides: Partial<RemoteSyncIneligibleDependency> = {},+ ): RemoteSyncIneligibleDependency => ({model: "card",id: 1,name: "Seats over time",- remedy: {+ used_by: [],+ ...overrides,+ });++ const requiredSync = (+ remedy: RemoteSyncDependencyRemedy,+ syncable = false,+ ): RemoteSyncRequiredSync => ({+ remedy,+ syncable,+ blocks: [{ id: 31, name: "Drafts" }],+ dependencies: [dependency()],+ });++ const SYNCABLE = requiredSync(+ {type: "collection",- collection: { id: 7, name: "Finance", personal: false },+ collection: { id: 7, name: "Finance", type: null, personal: false },},- };- const PERSONAL_DEPENDENCY: RemoteSyncIneligibleDependency = {- model: "card",- id: 2,- name: "Draft",- remedy: {+ true,+ );+ const PERSONAL = requiredSync({+ type: "collection",+ collection: { id: 5, name: "Personal", type: null, personal: true },+ });+ const LIBRARY_COLLECTION = requiredSync(+ {type: "collection",- collection: { id: 5, name: "Personal", personal: true },+ collection: {+ id: 2,+ name: "Library",+ type: "library",+ personal: false,+ },},- };- const ROOT_DEPENDENCY: RemoteSyncIneligibleDependency = {- model: "card",- id: 3,- name: "Orphaned",- collection: null,- remedy: { type: "none" },- };-- // No remedy, but it does live somewhere — the backend couldn't resolve a syncable ancestor.- const UNRESOLVED_DEPENDENCY: RemoteSyncIneligibleDependency = {- model: "card",- id: 6,- name: "Stranded",+ true,+ );+ const ANALYTICS = requiredSync({+ type: "collection",+ collection: {+ id: 3,+ name: "Usage analytics",+ type: "instance-analytics",+ personal: false,+ },+ });+ // No Library exists at all, so the remedy names nothing.+ const LIBRARY_MISSING = requiredSync({ type: "library" });+ const ROOT = requiredSync({ type: "none", collection: null });+ const NAMED_NONE = requiredSync({+ type: "none",collection: { id: 9, name: "Dangling" },- remedy: { type: "none" },- };- const SNIPPET_DEPENDENCY: RemoteSyncIneligibleDependency = {- model: "snippet",- id: 4,- name: "active_users",- remedy: { type: "library" },- };-- const failureWith = (- ...dependencies: RemoteSyncIneligibleDependency[]- ): RemoteSyncDependencyFailure[] => [- { collection: { id: 31, name: "Drafts" }, dependencies },- ];+ });+ const UNRESOLVED = requiredSync({ type: "none" });describe("getBlockedReason", () => {it("is linked-collections when every remedy is a collection the admin can sync", () => {- expect(getBlockedReason(failureWith(SYNCABLE_DEPENDENCY))).toBe(+ expect(getBlockedReason([SYNCABLE])).toBe("linked-collections");+ });++ it("is library-missing when a snippet has no Library to point at", () => {+ expect(getBlockedReason([SYNCABLE, LIBRARY_MISSING])).toBe(+ "library-missing",+ );+ });++ it("is linked-collections when a snippet points at an existing Library", () => {+ expect(getBlockedReason([SYNCABLE, LIBRARY_COLLECTION])).toBe("linked-collections",);});- it("is library when a dependency needs the Library", () => {- expect(- getBlockedReason(- failureWith(SYNCABLE_DEPENDENCY, SNIPPET_DEPENDENCY),- ),- ).toBe("library");+ it("ranks root content above a missing Library, since it can't be synced at all", () => {+ expect(getBlockedReason([LIBRARY_MISSING, ROOT])).toBe(+ "unsyncable-content",+ );});- it("ranks root content above the Library, since it can't be synced at all", () => {- expect(- getBlockedReason(failureWith(SNIPPET_DEPENDENCY, ROOT_DEPENDENCY)),- ).toBe("unsyncable-content");+ it("is analytics-content when a dependency lives in usage analytics", () => {+ expect(getBlockedReason([SYNCABLE, ANALYTICS])).toBe(+ "analytics-content",+ );+ });++ it("ranks usage analytics above root content, which at least names a move", () => {+ expect(getBlockedReason([ROOT, ANALYTICS])).toBe("analytics-content");});it("ranks personal content above every other reason", () => {- expect(- getBlockedReason(- failureWith(- SNIPPET_DEPENDENCY,- ROOT_DEPENDENCY,- PERSONAL_DEPENDENCY,- ),- ),- ).toBe("personal-content");+ expect(getBlockedReason([LIBRARY_MISSING, ROOT, PERSONAL])).toBe(+ "personal-content",+ );});});- describe("getRequiredCollectionRows", () => {- it("marks a syncable remedy as actionable", () => {- expect(- getRequiredCollectionRows(failureWith(SYNCABLE_DEPENDENCY)),- ).toEqual([- { id: 7, name: "Finance", personal: false, syncable: true },+ describe("getListedRequiredSyncs", () => {+ it("lists every entry, in the backend's order, when they can all be synced", () => {+ expect(getListedRequiredSyncs([LIBRARY_COLLECTION, SYNCABLE])).toEqual([+ LIBRARY_COLLECTION,+ SYNCABLE,]);});- it("keeps a personal remedy in the list but not as actionable", () => {+ it("lists only the blockers when one of them can't be synced", () => {expect(- getRequiredCollectionRows(failureWith(PERSONAL_DEPENDENCY)),- ).toEqual([- { id: 5, name: "Personal", personal: true, syncable: false },- ]);+ getListedRequiredSyncs([+ SYNCABLE,+ ROOT,+ LIBRARY_COLLECTION,+ PERSONAL,+ ]),+ ).toEqual([ROOT, PERSONAL]);});- it("names the collection a stranded dependency actually lives in", () => {- expect(- getRequiredCollectionRows(failureWith(UNRESOLVED_DEPENDENCY)),- ).toEqual([- { id: 9, name: "Dangling", personal: false, syncable: false },+ it("has nothing to list when a Library that doesn't exist is the blocker", () => {+ expect(getListedRequiredSyncs([SYNCABLE, LIBRARY_MISSING])).toEqual([]);+ });++ it("treats usage analytics as a blocker, hiding what could be switched on", () => {+ expect(getListedRequiredSyncs([SYNCABLE, ANALYTICS])).toEqual([+ ANALYTICS,]);});+ });- it("adds Our analytics for a root dependency, which carries no remedy of its own", () => {- expect(getRequiredCollectionRows(failureWith(ROOT_DEPENDENCY))).toEqual(- [- {- id: "root",- name: "Our analytics",- personal: false,- syncable: false,- },- ],- );+ describe("getRequiredSyncRow", () => {+ it("offers a syncable collection, keeping the type its icon needs", () => {+ expect(getRequiredSyncRow(LIBRARY_COLLECTION)).toEqual({+ key: "collection:2",+ name: "Library",+ type: "library",+ personal: false,+ syncableId: 2,+ collectionId: 2,+ });});- it("lists the syncable remedy alongside Our analytics", () => {- expect(- getRequiredCollectionRows(- failureWith(SYNCABLE_DEPENDENCY, ROOT_DEPENDENCY),- ),- ).toEqual([- { id: 7, name: "Finance", personal: false, syncable: true },- {- id: "root",- name: "Our analytics",- personal: false,- syncable: false,- },- ]);+ it("names usage analytics but offers nothing to switch on", () => {+ expect(getRequiredSyncRow(ANALYTICS)).toEqual({+ key: "collection:3",+ name: "Usage analytics",+ type: "instance-analytics",+ personal: false,+ syncableId: null,+ collectionId: 3,+ });});- it("is empty when only the Library is implicated", () => {- expect(- getRequiredCollectionRows(failureWith(SNIPPET_DEPENDENCY)),- ).toEqual([]);+ it("names a personal collection but offers nothing to switch on", () => {+ expect(getRequiredSyncRow(PERSONAL)).toEqual({+ key: "collection:5",+ name: "Personal",+ type: null,+ personal: true,+ syncableId: null,+ collectionId: 5,+ });});- });- describe("canSyncRequiredCollections", () => {- it("is true when every dependency points at a collection we can switch on", () => {- expect(- canSyncRequiredCollections(failureWith(SYNCABLE_DEPENDENCY)),- ).toBe(true);+ it("calls the root collection Our analytics", () => {+ expect(getRequiredSyncRow(ROOT)).toMatchObject({+ key: "root",+ name: "Our analytics",+ syncableId: null,+ collectionId: "root",+ });});- it.each([- ["personal", PERSONAL_DEPENDENCY],- ["root", ROOT_DEPENDENCY],- ["library", SNIPPET_DEPENDENCY],- ])(- "is false when a %s dependency rides along, since a half fix is refused again",- (_label, dependency) => {- expect(- canSyncRequiredCollections(- failureWith(SYNCABLE_DEPENDENCY, dependency),- ),- ).toBe(false);- },- );+ it("names the collection unsyncable content actually lives in", () => {+ expect(getRequiredSyncRow(NAMED_NONE)).toMatchObject({+ key: "none:9",+ name: "Dangling",+ syncableId: null,+ collectionId: 9,+ });+ });- it("is false when there is nothing to switch on", () => {- expect(canSyncRequiredCollections([])).toBe(false);+ it("still shows a collection the backend couldn't resolve", () => {+ expect(getRequiredSyncRow(UNRESOLVED)).toMatchObject({+ key: "unresolved",+ name: "Unknown collection",+ syncableId: null,+ collectionId: null,+ });});});});diff --git a/frontend/src/metabase-types/api/remote-sync.ts b/frontend/src/metabase-types/api/remote-sync.tsindex 036d0837a79..af6d4b6349f 100644--- a/frontend/src/metabase-types/api/remote-sync.ts+++ b/frontend/src/metabase-types/api/remote-sync.ts@@ -1,4 +1,4 @@-import type { CollectionItemModel } from "./collection";+import type { CollectionItemModel, CollectionType } from "./collection";import type { EnterpriseSettings } from "./settings";import type { UserId } from "./user";import type { CardDisplayType } from "./visualization";@@ -147,25 +147,41 @@ export type RemoteSyncCollectionRef = {};export type RemoteSyncRemedyCollection = RemoteSyncCollectionRef & {+ type: CollectionType;personal: boolean;};export type RemoteSyncDependencyRemedy =| { type: "collection"; collection: RemoteSyncRemedyCollection }| { type: "library" }- | { type: "none" };+ | { type: "none"; collection?: RemoteSyncCollectionRef | null };++export type RemoteSyncDependentModel =+ | RemoteSyncDependencyModel+ | "collection"+ | "timeline";++export type RemoteSyncDependencyEntity = {+ model: RemoteSyncDependentModel;+ id: number;+ name: string;+ display?: CardDisplayType;+};export type RemoteSyncIneligibleDependency = {model: RemoteSyncDependencyModel;id: number;name: string;- /** `null` is the root collection; absent means the backend couldn't resolve one. */+ /** Where it lives — `null` is the root collection, absent means we couldn't resolve one. */collection?: RemoteSyncCollectionRef | null;- remedy: RemoteSyncDependencyRemedy;+ display?: CardDisplayType;+ used_by: RemoteSyncDependencyEntity[];};-export type RemoteSyncDependencyFailure = {- collection: RemoteSyncCollectionRef;+export type RemoteSyncRequiredSync = {+ remedy: RemoteSyncDependencyRemedy;+ syncable: boolean;+ blocks: RemoteSyncCollectionRef[];dependencies: RemoteSyncIneligibleDependency[];};@@ -175,7 +191,7 @@ export type RemoteSyncDependencyErrorResponse = {error_code: typeof UNSYNCED_DEPENDENCIES_ERROR_CODE;error: string;errors: {- collections: RemoteSyncDependencyFailure[];+ required: RemoteSyncRequiredSync[];};};diff --git a/src/metabase/collections/core.clj b/src/metabase/collections/core.cljindex cea50b3858f..05f5f74420a 100644--- a/src/metabase/collections/core.clj+++ b/src/metabase/collections/core.clj@@ -27,6 +27,7 @@create-library-collection!descendant-idsineligible-dependencies+ instance-analytics-collection-typelibrary-collectionlibrary-collection-typelibrary-data-collection-typediff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex 17b17732b22..078d2c0ecd9 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -1343,14 +1343,16 @@Returns a vector of maps, one per ineligible dependency:- {:model \"Card\", :id 412, :instance <row>}+ {:model \"Card\", :id 412, :instance <row>, :used-by [{\"DashboardCard\" 12 \"Dashboard\" 3}]}`:instance` carries whatever [[select-for-eligibility-check]] loaded for it, notably `:collection_id`.- It falls out of the traversal that [[non-remote-synced-dependencies]] already runs, so reporting it- costs no extra queries."+ `:used-by` carries the [[serdes/descendants]] provenance: one entry per entity that reached this one,+ naming the direct referrer rather than the whole path back to `model`. Both fall out of the traversal+ that [[non-remote-synced-dependencies]] already runs, so reporting them costs no extra queries."[{:keys [id] :as model}](if (collections.db/collection-exists? (if (= (t2/model model) :model/Collection) (:id model) (:collection_id model)))- (let [descendants (u/group-by first second (keys (traverse-descendants [(name (t2/model model)) id] true)))]+ (let [traversed (traverse-descendants [(name (t2/model model)) id] true)+ descendants (u/group-by first second (keys traversed))](into [](for [m (collectable-models):let [model-name (name m)@@ -1363,7 +1365,8 @@:when (not eligible?)]{:model model-name:id inst-id- :instance (get by-id inst-id)})))+ :instance (get by-id inst-id)+ :used-by (vec (get traversed [model-name inst-id]))})))[]))(defn non-remote-synced-dependencies