Skip to content

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

New storage upsell 2 (#78162)

Timur Masharaf07aac4b8827
diff --git a/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj b/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj
index f20c786d164..898679c604f 100644
--- a/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/cloud_add_ons/api.clj
@@ -31,6 +31,10 @@
(deferred-tru "Need to accept terms of service."))
(def ^:private error-no-quantity
(deferred-tru "Purchase of add-on requires quantity."))
+(def ^:private error-quantity-not-supported
+ (deferred-tru "This add-on does not support a quantity."))
+(def ^:private error-bundle-only
+ (deferred-tru "This add-on can only be purchased as part of a bundle."))
(def ^:private response-not-hosted
{:status 400 :body error-not-hosted})
@@ -40,6 +44,10 @@
{:status 400 :body {:errors {:terms_of_service error-terms-not-accepted}}})
(def ^:private response-no-quantity
{:status 400 :body {:errors {:quantity error-no-quantity}}})
+(def ^:private response-quantity-not-supported
+ {:status 400 :body {:errors {:quantity error-quantity-not-supported}}})
+(def ^:private response-bundle-only
+ {:status 400 :body error-bundle-only})
(def ^:private response-success-empty
{:status 200 :body {}})
@@ -53,7 +61,41 @@
"transforms-basic"
"transforms-advanced"
"transforms-basic-metered"
- "transforms-advanced-metered"])
+ "transforms-advanced-metered"
+ "dwh-rent"
+ "etl-connections"])
+
+(def ^:private add-on-bundles
+ "Product types whose purchase provisions additional add-ons in the same upsert call. Purchasing
+ Storage (`dwh-rent`) also provisions `etl-connections`, mirroring the store's storage purchase flow."
+ {"dwh-rent" [{:product-type "dwh-rent" :prepaid-units 0}
+ {:product-type "etl-connections" :prepaid-units 1}]})
+
+(def ^:private bundle-only-product-types
+ "Product types that are only ever provisioned as part of a bundle (see `add-on-bundles`) and can
+ never be purchased directly. The Store rejects them anyway (`etl-connections` depends on a DWH
+ product), so fail fast with a clear error instead of a confusing Store 400."
+ (into #{}
+ (comp (mapcat val)
+ (map :product-type)
+ (remove (set (keys add-on-bundles))))
+ add-on-bundles))
+
+(defn- add-ons-for-purchase
+ "Add-ons to upsert for a given `product-type`. Bundled product types (see `add-on-bundles`) expand
+ into multiple add-ons; everything else is a single add-on carrying the requested `quantity`."
+ [product-type quantity]
+ (or (add-on-bundles product-type)
+ [(cond-> {:product-type product-type}
+ quantity (assoc :prepaid-units quantity))]))
+
+(defn- add-ons-for-removal
+ "Add-ons to remove for a given `product-type`. Bundled product types (see `add-on-bundles`) expand
+ into all their members; everything else is a single add-on."
+ [product-type]
+ (if-let [bundle (add-on-bundles product-type)]
+ (mapv #(select-keys % [:product-type]) bundle)
+ [{:product-type product-type}]))
(defn- handle-store-api-error
"Handle exceptions from Store API calls and return appropriate error response."
@@ -129,6 +171,9 @@
(not (premium-features/is-hosted?))
response-not-hosted
+ (bundle-only-product-types product-type)
+ response-bundle-only
+
(and (requires-terms-of-service? product-type)
(not terms-of-service))
response-terms-not-accepted
@@ -137,6 +182,10 @@
(not quantity))
response-no-quantity
+ (and (contains? add-on-bundles product-type)
+ quantity)
+ response-quantity-not-supported
+
(and (#{"transforms" "transforms-basic" "transforms-basic-metered"} product-type)
(premium-features/enable-basic-transforms?))
response-not-eligible
@@ -145,12 +194,18 @@
(premium-features/enable-python-transforms?))
response-not-eligible
+ (and (= product-type "dwh-rent")
+ (premium-features/has-attached-dwh?))
+ response-not-eligible
+
:else
(try
- (let [add-on (cond-> {:product-type product-type}
- quantity (assoc :prepaid-units quantity))]
- (events/publish-event! :event/cloud-add-on-purchase {:details {:add-on add-on}, :user-id api/*current-user-id*})
- (hm.client/call :change-add-ons :upsert-add-ons [add-on]))
+ (let [add-ons (add-ons-for-purchase product-type quantity)
+ ;; Single-product purchases keep the original `{:add-on {...}}` audit shape; bundled
+ ;; purchases (Storage) record the full vector.
+ audit-add-on (if (= (count add-ons) 1) (first add-ons) add-ons)]
+ (events/publish-event! :event/cloud-add-on-purchase {:details {:add-on audit-add-on}, :user-id api/*current-user-id*})
+ (hm.client/call :change-add-ons :upsert-add-ons add-ons))
(premium-features/clear-cache!)
response-success-empty
(catch Exception e
@@ -168,9 +223,12 @@
(not (premium-features/is-hosted?))
response-not-hosted
+ (bundle-only-product-types product-type)
+ response-bundle-only
+
:else
(try
- (hm.client/call :change-add-ons :remove-add-ons [{:product-type product-type}])
+ (hm.client/call :change-add-ons :remove-add-ons (add-ons-for-removal product-type))
(premium-features/clear-cache!)
response-success-empty
(catch Exception e
diff --git a/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj b/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj
index 55b30e8e0b1..2371b51cd3b 100644
--- a/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/cloud_add_ons/api_test.clj
@@ -83,6 +83,62 @@
(is (=? {}
(mt/user-http-request :crowberto :post 200 (str "ee/cloud-add-ons/" product-type) {})))))))))
+(deftest ^:sequential post-dwh-rent-test
+ (testing "POST /api/ee/cloud-add-ons/dwh-rent"
+ (testing "requires superuser"
+ (mt/with-premium-features #{}
+ (is (=? "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "ee/cloud-add-ons/dwh-rent" {})))))
+ (testing "requires token feature 'hosting'"
+ (mt/with-premium-features #{}
+ (is (=? "Can only access Store API for Metabase Cloud instances."
+ (mt/user-http-request :crowberto :post 400 "ee/cloud-add-ons/dwh-rent" {})))))
+ (testing "not eligible if storage is already attached"
+ (mt/with-premium-features #{:hosting :attached-dwh}
+ (is (=? "Can only purchase add-ons for eligible subscriptions."
+ (mt/user-http-request :crowberto :post 400 "ee/cloud-add-ons/dwh-rent" {})))))
+ (testing "rejects an explicit quantity for the bundled product type"
+ (mt/with-premium-features #{:hosting}
+ (is (=? {:errors {:quantity "This add-on does not support a quantity."}}
+ (mt/user-http-request :crowberto :post 400 "ee/cloud-add-ons/dwh-rent" {:quantity 2})))))
+ (testing "succeeds, provisioning dwh-rent and etl-connections together"
+ (mt/with-premium-features #{:hosting :audit-app}
+ (let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))
+ {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]
+ (with-redefs [hm.client/call store-api-proxy
+ premium-features/clear-cache! clear-token-cache-proxy]
+ (is (=? {}
+ (mt/user-http-request :crowberto :post 200 "ee/cloud-add-ons/dwh-rent" {})))
+ (is (= [{:args [:change-add-ons
+ :upsert-add-ons
+ [{:product-type "dwh-rent" :prepaid-units 0}
+ {:product-type "etl-connections" :prepaid-units 1}]]
+ :ret nil}]
+ @store-api-calls))
+ (is (not-empty @clear-token-cache-calls)
+ "Token cache was cleared")
+ (testing "audit log records both provisioned add-ons"
+ (let [{:keys [details user_id]} (mt/latest-audit-log-entry "cloud-add-on-purchase")]
+ (is (= (mt/user->id :crowberto) user_id))
+ (is (= {:add-on [{:product-type "dwh-rent" :prepaid-units 0}
+ {:product-type "etl-connections" :prepaid-units 1}]}
+ details))))))))))
+
+(deftest ^:sequential post-etl-connections-test
+ (testing "POST /api/ee/cloud-add-ons/etl-connections"
+ (testing "requires superuser"
+ (mt/with-premium-features #{}
+ (is (=? "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "ee/cloud-add-ons/etl-connections" {})))))
+ (testing "is rejected as a bundle-only product type without calling the Store"
+ (mt/with-premium-features #{:hosting}
+ (let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))]
+ (with-redefs [hm.client/call store-api-proxy]
+ (is (=? "This add-on can only be purchased as part of a bundle."
+ (mt/user-http-request :crowberto :post 400 "ee/cloud-add-ons/etl-connections" {})))
+ (is (empty? @store-api-calls)
+ "Store API was not called")))))))
+
(deftest ^:sequential delete-product-type-test
(testing "DELETE /api/ee/cloud-add-ons/metabase-ai-managed"
(testing "requires superuser"
@@ -122,6 +178,48 @@
(is (not-empty @clear-token-cache-calls)
"Token cache was cleared"))))))))
+(deftest ^:sequential delete-dwh-rent-test
+ (testing "DELETE /api/ee/cloud-add-ons/dwh-rent"
+ (testing "requires superuser"
+ (mt/with-premium-features #{}
+ (is (=? "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 "ee/cloud-add-ons/dwh-rent")))))
+ (testing "requires token feature 'hosting'"
+ (mt/with-premium-features #{}
+ (is (=? "Can only access Store API for Metabase Cloud instances."
+ (mt/user-http-request :crowberto :delete 400 "ee/cloud-add-ons/dwh-rent")))))
+ (testing "succeeds, removing dwh-rent and etl-connections together"
+ (mt/with-premium-features #{:hosting}
+ (let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))
+ {clear-token-cache-proxy :proxy clear-token-cache-calls :calls} (semantic.tu/spy premium-features/clear-cache!)]
+ (with-redefs [hm.client/call store-api-proxy
+ premium-features/clear-cache! clear-token-cache-proxy]
+ (is (=? {}
+ (mt/user-http-request :crowberto :delete 200 "ee/cloud-add-ons/dwh-rent")))
+ (is (= [{:args [:change-add-ons
+ :remove-add-ons
+ [{:product-type "dwh-rent"}
+ {:product-type "etl-connections"}]]
+ :ret nil}]
+ @store-api-calls))
+ (is (not-empty @clear-token-cache-calls)
+ "Token cache was cleared")))))))
+
+(deftest ^:sequential delete-etl-connections-test
+ (testing "DELETE /api/ee/cloud-add-ons/etl-connections"
+ (testing "requires superuser"
+ (mt/with-premium-features #{}
+ (is (=? "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 "ee/cloud-add-ons/etl-connections")))))
+ (testing "is rejected as a bundle-only product type without calling the Store"
+ (mt/with-premium-features #{:hosting}
+ (let [{store-api-proxy :proxy store-api-calls :calls} (semantic.tu/spy (constantly nil))]
+ (with-redefs [hm.client/call store-api-proxy]
+ (is (=? "This add-on can only be purchased as part of a bundle."
+ (mt/user-http-request :crowberto :delete 400 "ee/cloud-add-ons/etl-connections")))
+ (is (empty? @store-api-calls)
+ "Store API was not called")))))))
+
(deftest ^:sequential get-plans-test
(testing "GET /api/ee/cloud-add-ons/plans"
(testing "requires superuser"
diff --git a/enterprise/frontend/src/metabase-enterprise/api/cloud-add-ons.ts b/enterprise/frontend/src/metabase-enterprise/api/cloud-add-ons.ts
index 18a016f3113..ab79b724d8c 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/cloud-add-ons.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/cloud-add-ons.ts
@@ -29,6 +29,7 @@ export const cloudAddOnApi = EnterpriseApi.injectEndpoints({
}),
}),
});
+
export const {
useListAddOnsQuery,
usePurchaseCloudAddOnMutation,
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveAddDataPanel.tsx b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveAddDataPanel.tsx
index c1e2d8197a7..f5d1297f1fe 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveAddDataPanel.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveAddDataPanel.tsx
@@ -4,12 +4,23 @@ import { match } from "ts-pattern";
import { t } from "ttag";
import { skipToken } from "metabase/api";
-import { UpsellStorage } from "metabase/common/components/upsells/UpsellStorage";
-import { useHasTokenFeature, useStoreUrl } from "metabase/common/hooks";
+import {
+ StoragePurchaseButton,
+ StorageSetupErrorView,
+ StorageSetupView,
+ useStorageSetup,
+} from "metabase/common/components/upsells/StoragePurchaseModal";
+import {
+ useAttachedDwh,
+ useHasTokenFeature,
+ useStoreUrl,
+} from "metabase/common/hooks";
import {
CONTENT_MAX_WIDTH,
ContactAdminAlert,
INNER_WIDTH,
+ PanelLoadingState,
+ getStorageNotProvisionedSubtitle,
} from "metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/AddDataModalEmptyStates";
import { useSelector } from "metabase/redux";
import { getUserIsAdmin } from "metabase/selectors/user";
@@ -34,6 +45,7 @@ import {
import { getDisconnectModalStrings } from "./GdriveConnectionModal.strings";
import { trackSheetConnectionClick } from "./analytics";
+import { getSheetsPanelState } from "./sheets-panel-state";
import { getStatus, useDeleteGdriveFolderLink, useShowGdrive } from "./utils";
const PanelWrapper = ({
@@ -136,82 +148,79 @@ export const GdriveAddDataPanel = ({
});
const isAdmin = useSelector(getUserIsAdmin);
- const hasStorage = useHasTokenFeature("attached_dwh");
+ const { isSettingUp, hasSetupFailed, isLoadingStorageAddOn } =
+ useStorageSetup();
+ const { hasAttachedDwh, areDatabasesLoading } = useAttachedDwh();
+ const hasStorageTokenFeature = useHasTokenFeature("attached_dwh");
const storeUrl = useStoreUrl("account/storage");
- const showGdrive = useShowGdrive();
+ const { showGdrive, isLoading: isLoadingServiceAccount } = useShowGdrive();
const { data: folder, error } = useGetGsheetsFolderQuery(
!showGdrive ? skipToken : undefined,
{ refetchOnMountOrArgChange: 5 },
);
- const status = getStatus({ status: folder?.status, error });
-
const folderUrl = folder?.url;
const NO_STORAGE_SUBTITLE = t`To work with spreadsheets, you can add storage to your instance.`;
// eslint-disable-next-line metabase/no-literal-metabase-strings -- admin only
const ERROR_MESSAGE = t`Please check that the folder is shared with the Metabase Service Account.`;
- if (!isAdmin) {
- return (
+ const state = getSheetsPanelState({
+ isSettingUp,
+ hasSetupFailed,
+ isAdmin,
+ isLoading: areDatabasesLoading || isLoadingServiceAccount,
+ isLoadingStorageAddOn,
+ hasAttachedDwh,
+ hasStorageTokenFeature,
+ showGdrive,
+ areConnectionDetailsShown,
+ status: getStatus({ status: folder?.status, error }),
+ });
+
+ return match(state)
+ .with("provisioning-storage", () => <StorageSetupView />)
+ .with("storage-setup-failed", () => <StorageSetupErrorView />)
+ .with("loading", () => <PanelLoadingState />)
+ .with("ask-admin", () => (
<PanelWrapper>
<ContactAdminAlert reason="enable-google-sheets" />
</PanelWrapper>
- );
- }
-
- if (!hasStorage) {
- return (
+ ))
+ .with("needs-storage", () => (
<PanelWrapper subtitle={NO_STORAGE_SUBTITLE}>
- <UpsellStorage location="add-data-modal-sheets" />
+ <StoragePurchaseButton location="add-data-modal-sheets" />
</PanelWrapper>
- );
- }
-
- // If a user is an admin of a hosted instance with storage but for some reason
- // any other condition from the `showGdrive` hook is not met, we show the general error
- if (!showGdrive) {
- return (
+ ))
+ .with("storage-not-provisioned", () => (
+ <PanelWrapper subtitle={getStorageNotProvisionedSubtitle()} />
+ ))
+ .with("unavailable", () => (
<PanelWrapper>
<ErrorAlert error={ERROR_MESSAGE} />
</PanelWrapper>
- );
- }
-
- if (areConnectionDetailsShown) {
- return (
+ ))
+ .with("connection-details", () => (
<ConnectionDetails
onClose={closeConnectionDetails}
isDeleteInProgress={isDeletingFolderLink}
onDelete={onDelete}
deleteError={deleteError}
/>
- );
- }
-
- // Finally, all conditions have been met, and all screens below this line depend only
- // on the status of the attempted connection
-
- if (status === "active" || status === "syncing") {
- return (
+ ))
+ .with("connected", () => (
<PanelWrapper title={t`Import Google Sheets`}>
<DriveConnectionDisplay />
- <Button
+ <ConnectionDetailsButton
+ label={t`Add new`}
variant="subtle"
- onClick={() => {
- trackSheetConnectionClick({ from: "add-data-modal" });
- showConnectionDetails();
- }}
- >
- {t`Add new`}
- </Button>
+ w="auto"
+ onClick={showConnectionDetails}
+ />
</PanelWrapper>
- );
- }
-
- if (status === "paused") {
- return (
+ ))
+ .with("storage-full", () => (
<PanelWrapper subtitle={NO_STORAGE_SUBTITLE}>
<ErrorAlert
// eslint-disable-next-line metabase/no-literal-metabase-strings -- admin only
@@ -223,11 +232,8 @@ export const GdriveAddDataPanel = ({
</Group>
</ErrorAlert>
</PanelWrapper>
- );
- }
-
- if (status === "not-connected") {
- return (
+ ))
+ .with("not-connected", () => (
<>
<PanelWrapper>
<Button
@@ -258,32 +264,50 @@ export const GdriveAddDataPanel = ({
reconnect={false}
/>
</>
- );
- }
-
- const buttonText = match(status)
- .with("initializing", () => t`Connecting...`)
- .with("error", () => t`Something went wrong`)
+ ))
+ .with("connecting", () => (
+ <PanelWrapper>
+ <ConnectionDetailsButton
+ label={t`Connecting...`}
+ onClick={showConnectionDetails}
+ />
+ </PanelWrapper>
+ ))
+ .with("connection-error", () => (
+ <PanelWrapper>
+ <ConnectionDetailsButton
+ label={t`Something went wrong`}
+ onClick={showConnectionDetails}
+ />
+ <ErrorAlert error={ERROR_MESSAGE} />
+ </PanelWrapper>
+ ))
.exhaustive();
-
- return (
- <PanelWrapper>
- <Button
- variant="filled"
- w={INNER_WIDTH}
- onClick={() => {
- trackSheetConnectionClick({ from: "add-data-modal" });
- showConnectionDetails();
- }}
- >
- {buttonText}
- </Button>
-
- {status === "error" && <ErrorAlert error={ERROR_MESSAGE} />}
- </PanelWrapper>
- );
};
+const ConnectionDetailsButton = ({
+ label,
+ onClick,
+ variant = "filled",
+ w = INNER_WIDTH,
+}: {
+ label: string;
+ onClick: () => void;
+ variant?: string;
+ w?: string | number;
+}) => (
+ <Button
+ variant={variant}
+ w={w}
+ onClick={() => {
+ trackSheetConnectionClick({ from: "add-data-modal" });
+ onClick();
+ }}
+ >
+ {label}
+ </Button>
+);
+
const ErrorAlert = ({
error,
children,
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx
index cdc48f42f4d..4b1f30e9b0e 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveConnectionModal.tsx
@@ -43,7 +43,7 @@ export function GdriveConnectionModal({
onClose: (success?: boolean) => void;
reconnect: boolean;
}) {
- const shouldShow = useShowGdrive();
+ const { showGdrive: shouldShow } = useShowGdrive();
const { data: { email: serviceAccountEmail } = {} } =
useGetServiceAccountQuery(shouldShow ? undefined : skipToken);
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveDbMenu.tsx b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveDbMenu.tsx
index 4cc9f481900..1144c581a86 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveDbMenu.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveDbMenu.tsx
@@ -29,7 +29,7 @@ export function GdriveDbMenu() {
);
const isDwh = databaseInfo?.is_attached_dwh;
- const showGdrive = useShowGdrive();
+ const { showGdrive } = useShowGdrive();
const showMenu = showGdrive && isDwh;
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.tsx b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.tsx
index 641a069ed6e..5cf89a4a8d9 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveSyncStatus.tsx
@@ -20,7 +20,7 @@ type GsheetsStatus = GdrivePayload["status"];
export const GdriveSyncStatus = () => {
const dispatch = useDispatch();
- const showGdrive = useShowGdrive();
+ const { showGdrive } = useShowGdrive();
const [forceHide, setForceHide] = useState(true);
const [dbId, setDbId] = useState<DatabaseId | undefined>();
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/sheets-panel-state.ts b/enterprise/frontend/src/metabase-enterprise/google_drive/sheets-panel-state.ts
new file mode 100644
index 00000000000..4aa4ba86cf4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/sheets-panel-state.ts
@@ -0,0 +1,108 @@
+import { match } from "ts-pattern";
+
+import type { GdrivePayload } from "metabase-types/api";
+
+/**
+ * Everything the Google Sheets panel can show, as one value — the counterpart
+ * to `CsvPanelState`. Plain strings rather than tagged objects, since no Sheets
+ * state carries data.
+ */
+export type SheetsPanelState =
+ | "provisioning-storage"
+ | "storage-setup-failed"
+ | "ask-admin"
+ | "loading"
+ | "needs-storage"
+ | "storage-not-provisioned"
+ | "unavailable"
+ | "connection-details"
+ | "connected"
+ | "storage-full"
+ | "not-connected"
+ | "connecting"
+ | "connection-error";
+
+export interface SheetsPanelStateInput {
+ isSettingUp: boolean;
+ hasSetupFailed: boolean;
+ isAdmin: boolean;
+ isLoading: boolean;
+ isLoadingStorageAddOn: boolean;
+ hasAttachedDwh: boolean;
+ hasStorageTokenFeature: boolean;
+ showGdrive: boolean;
+ areConnectionDetailsShown: boolean;
+ status: GdrivePayload["status"];
+}
+
+export function getSheetsPanelState({
+ isSettingUp,
+ hasSetupFailed,
+ isAdmin,
+ isLoading,
+ isLoadingStorageAddOn,
+ hasAttachedDwh,
+ hasStorageTokenFeature,
+ showGdrive,
+ areConnectionDetailsShown,
+ status,
+}: SheetsPanelStateInput): SheetsPanelState {
+ if (isSettingUp) {
+ return "provisioning-storage";
+ }
+
+ // `hasSetupFailed` can be a stale, session-cached verdict: setup may have timed
+ // out locally yet completed in the background. Once the DWH is actually attached,
+ // trust that over the cached failure rather than showing an error state.
+ if (hasSetupFailed && !hasAttachedDwh) {
+ return "storage-setup-failed";
+ }
+
+ if (!isAdmin) {
+ return "ask-admin";
+ }
+
+ // Not first, unlike `getCsvPanelState`: the gates above answer without
+ // waiting on a request. Below this line, storage and the service account both
+ // read as absent until their queries land, which would flash an "add storage"
+ // upsell at an admin who already has it.
+ if (isLoading) {
+ return "loading";
+ }
+
+ // Sheets only needs the DWH to exist, not to be the uploads target.
+ if (!hasAttachedDwh) {
+ // Already entitled to storage (token present) but the DWH database has not
+ // shown up yet — provisioning, or a token that runs ahead of the data.
+ // Offering to buy it again would be wrong; point at a refresh instead.
+ if (hasStorageTokenFeature) {
+ return "storage-not-provisioned";
+ }
+
+ // Until the add-on lands, `StoragePurchaseButton` cannot tell whether it is
+ // the in-app purchase or the link out to the store, and would swap one for
+ // the other mid-render.
+ if (isLoadingStorageAddOn) {
+ return "loading";
+ }
+
+ return "needs-storage";
+ }
+
+ // Some other `useShowGdrive` condition is unmet — nothing specific to say.
+ if (!showGdrive) {
+ return "unavailable";
+ }
+
+ if (areConnectionDetailsShown) {
+ return "connection-details";
+ }
+
+ return match<GdrivePayload["status"], SheetsPanelState>(status)
+ .with("active", "syncing", () => "connected")
+ .with("paused", () => "storage-full")
+ .with("not-connected", () => "not-connected")
+ .with("initializing", () => "connecting")
+ .with("error", () => "connection-error")
+ .exhaustive();
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/sheets-panel-state.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/google_drive/sheets-panel-state.unit.spec.ts
new file mode 100644
index 00000000000..d00ed53a55d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/sheets-panel-state.unit.spec.ts
@@ -0,0 +1,140 @@
+import {
+ type SheetsPanelState,
+ type SheetsPanelStateInput,
+ getSheetsPanelState,
+} from "./sheets-panel-state";
+
+// A hosted admin with storage, nothing connected yet: status alone decides.
+const BASE: SheetsPanelStateInput = {
+ isSettingUp: false,
+ hasSetupFailed: false,
+ isAdmin: true,
+ isLoading: false,
+ isLoadingStorageAddOn: false,
+ hasAttachedDwh: true,
+ hasStorageTokenFeature: false,
+ showGdrive: true,
+ areConnectionDetailsShown: false,
+ status: "not-connected",
+};
+
+const state = (overrides: Partial<SheetsPanelStateInput>): SheetsPanelState =>
+ getSheetsPanelState({ ...BASE, ...overrides });
+
+describe("getSheetsPanelState", () => {
+ describe("gating, in precedence order", () => {
+ it("shows provisioning ahead of every other gate", () => {
+ // Storage is absent mid-provisioning, which alone reads as "buy storage".
+ expect(
+ state({ isSettingUp: true, hasAttachedDwh: false, isAdmin: false }),
+ ).toBe("provisioning-storage");
+ });
+
+ it("shows the setup failure ahead of the remaining gates", () => {
+ expect(
+ state({ hasSetupFailed: true, hasAttachedDwh: false, isAdmin: false }),
+ ).toBe("storage-setup-failed");
+ });
+
+ it("points a non-admin at their admin rather than at the store", () => {
+ expect(state({ isAdmin: false, hasAttachedDwh: false })).toBe(
+ "ask-admin",
+ );
+ });
+
+ it("waits rather than offering storage to an admin whose databases have not arrived", () => {
+ // Owning storage and owning none look identical until the list lands.
+ expect(state({ isLoading: true, hasAttachedDwh: false })).toBe("loading");
+ });
+
+ it("waits rather than blaming Sheets while the service account is still loading", () => {
+ expect(state({ isLoading: true, showGdrive: false })).toBe("loading");
+ });
+
+ it("answers a non-admin without making them wait", () => {
+ // Nothing below the `ask-admin` gate can change their answer.
+ expect(state({ isLoading: true, isAdmin: false })).toBe("ask-admin");
+ });
+
+ it("keeps showing setup ahead of the loading state", () => {
+ expect(state({ isLoading: true, isSettingUp: true })).toBe(
+ "provisioning-storage",
+ );
+ expect(
+ state({ isLoading: true, hasSetupFailed: true, hasAttachedDwh: false }),
+ ).toBe("storage-setup-failed");
+ });
+
+ it("trusts an attached DWH over a stale cached setup failure", () => {
+ // Setup can time out locally yet finish in the background; once the DWH is
+ // present, the failure gate must yield to the normal status path.
+ expect(state({ hasSetupFailed: true, hasAttachedDwh: true })).toBe(
+ "not-connected",
+ );
+ });
+
+ it("offers storage to an admin who has none", () => {
+ expect(state({ hasAttachedDwh: false })).toBe("needs-storage");
+ });
+
+ it("tells an entitled admin to refresh instead of re-offering storage", () => {
+ // The token says storage is theirs, but the database has not landed yet.
+ expect(
+ state({ hasAttachedDwh: false, hasStorageTokenFeature: true }),
+ ).toBe("storage-not-provisioned");
+ });
+
+ it("does not wait on the add-on for an entitled admin without a DWH", () => {
+ // Ownership is already known from the token, so there is nothing to buy.
+ expect(
+ state({
+ hasAttachedDwh: false,
+ hasStorageTokenFeature: true,
+ isLoadingStorageAddOn: true,
+ }),
+ ).toBe("storage-not-provisioned");
+ });
+
+ it("waits for the add-on before offering storage", () => {
+ // Until it lands the CTA can't tell purchase modal from store link.
+ expect(
+ state({ hasAttachedDwh: false, isLoadingStorageAddOn: true }),
+ ).toBe("loading");
+ });
+
+ it("does not wait on the add-on once storage is there", () => {
+ // The add-ons query is skipped for anyone who cannot buy storage.
+ expect(state({ isLoadingStorageAddOn: true })).toBe("not-connected");
+ });
+
+ it("falls back to the generic error when Sheets is unavailable for some other reason", () => {
+ expect(state({ showGdrive: false })).toBe("unavailable");
+ });
+
+ it("prefers the connection details over anything the status would show", () => {
+ expect(state({ areConnectionDetailsShown: true, status: "active" })).toBe(
+ "connection-details",
+ );
+ });
+
+ it("does not show connection details to an admin without storage", () => {
+ expect(
+ state({ areConnectionDetailsShown: true, hasAttachedDwh: false }),
+ ).toBe("needs-storage");
+ });
+ });
+
+ describe("connection status, once every gate is passed", () => {
+ it.each([
+ { status: "active", expected: "connected" },
+ // Syncing is still a working connection, so it shares the connected view.
+ { status: "syncing", expected: "connected" },
+ { status: "paused", expected: "storage-full" },
+ { status: "not-connected", expected: "not-connected" },
+ { status: "initializing", expected: "connecting" },
+ { status: "error", expected: "connection-error" },
+ ] as const)("maps $status to $expected", ({ status, expected }) => {
+ expect(state({ status })).toBe(expected);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/google_drive/utils.tsx b/enterprise/frontend/src/metabase-enterprise/google_drive/utils.tsx
index 88430e94eef..af80c292463 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/utils.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/utils.tsx
@@ -20,13 +20,18 @@ export type ErrorPayload =
| { message: string }
| { error_message: string };
-export function useShowGdrive() {
+/**
+ * `isLoading` is reported alongside the flag because a `showGdrive` of `false`
+ * that is only waiting on the service account looks the same as a settled
+ * "Sheets is unavailable here", and callers would flash the wrong one.
+ */
+export function useShowGdrive(): { showGdrive: boolean; isLoading: boolean } {
const gSheetsEnabled = useSetting("show-google-sheets-integration");
const hasDwh = useHasTokenFeature("attached_dwh");
const userIsAdmin = useSelector(getUserIsAdmin);
const shouldGetServiceAccount = gSheetsEnabled && userIsAdmin && hasDwh;
- const { data: serviceAccount } = useGetServiceAccountQuery(
+ const { data: serviceAccount, isLoading } = useGetServiceAccountQuery(
shouldGetServiceAccount ? undefined : skipToken,
);
@@ -34,7 +39,7 @@ export function useShowGdrive() {
hasDwh && gSheetsEnabled && userIsAdmin && serviceAccount?.email,
);
- return showGdrive;
+ return { showGdrive, isLoading };
}
export const getStatus = ({
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/AddDataModalPanels.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/storage/AddDataModalPanels.unit.spec.tsx
new file mode 100644
index 00000000000..5ff3cfbcb52
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/AddDataModalPanels.unit.spec.tsx
@@ -0,0 +1,81 @@
+import userEvent from "@testing-library/user-event";
+
+import { act, screen } from "__support__/ui";
+import { setupHostedInstance } from "metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup";
+import { mockStorageCloudAddOn } from "metabase-types/api/mocks/add-ons";
+
+import { type Clicker, confirmPurchaseModal } from "./test-utils";
+import { STORAGE_SETUP_TIMEOUT_MS } from "./use-purchase-storage-add-on";
+
+/**
+ * Both panels derive their state separately from the same provider, so a
+ * purchase started on the CSV tab has to be visible on the Google Sheets tab.
+ *
+ * Lives here rather than with the modal's own tests to keep the enterprise
+ * timeout constant and test helpers out of the OSS tree.
+ */
+const setup = () =>
+ setupHostedInstance({
+ isAdmin: true,
+ addOns: [mockStorageCloudAddOn],
+ enableGoogleSheets: true,
+ });
+
+const openTab = async (user: Clicker, name: RegExp) =>
+ user.click(await screen.findByRole("tab", { name }));
+
+/** Buys storage through the CSV panel's own upsell button, not a test harness. */
+const buyStorageFromCsvPanel = async (user: Clicker) => {
+ await user.click(
+ await screen.findByRole("button", { name: /Add Metabase Storage/ }),
+ );
+ await confirmPurchaseModal(user);
+};
+
+describe("Add data modal (storage bought from one tab, seen from the other)", () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it("shows the setting-up view on the Sheets tab after buying from the CSV tab", async () => {
+ setup();
+
+ await openTab(userEvent, /CSV$/);
+ await buyStorageFromCsvPanel(userEvent);
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+
+ await openTab(userEvent, /Google Sheets$/);
+
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("link", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the failure view on the Sheets tab once setup passes its deadline", async () => {
+ // Fake timers must be installed before render and drive the click, or the
+ // setup deadline stays on the real clock.
+ jest.useFakeTimers();
+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
+
+ setup();
+
+ await openTab(user, /CSV$/);
+ await buyStorageFromCsvPanel(user);
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+
+ await act(async () => {
+ jest.advanceTimersByTime(STORAGE_SETUP_TIMEOUT_MS);
+ });
+
+ await openTab(user, /Google Sheets$/);
+
+ expect(
+ await screen.findByText("Storage setup didn't finish"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/CSVPanel.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/storage/CSVPanel.unit.spec.tsx
new file mode 100644
index 00000000000..062b5d4594e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/CSVPanel.unit.spec.tsx
@@ -0,0 +1,461 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupCollectionByIdEndpoint,
+ setupCollectionsEndpoints,
+ setupDatabaseListEndpoint,
+ setupPropertiesEndpoints,
+ setupTokenRefreshEndpoint,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import {
+ act,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { useListDatabasesQuery } from "metabase/api";
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import { CSVPanel } from "metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVPanel";
+import { createMockState } from "metabase/redux/store/mocks";
+import type {
+ Database,
+ ICloudAddOnProduct,
+ TokenFeatures,
+} from "metabase-types/api";
+import {
+ createMockCollection,
+ createMockDatabase,
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { mockStorageCloudAddOn } from "metabase-types/api/mocks/add-ons";
+
+import { StorageSetupProvider } from "./StorageSetupProvider";
+import {
+ PurchaseTrigger,
+ confirmPurchase,
+ invalidatedTagsInclude,
+ openPurchaseModal,
+} from "./test-utils";
+import {
+ POLL_INTERVAL_MS,
+ STORAGE_SETUP_TIMEOUT_MS,
+} from "./use-purchase-storage-add-on";
+
+/** Renders the real panel, so these cases cover databases list → state → view. */
+interface SetupOpts {
+ addOns?: ICloudAddOnProduct[];
+ tokenFeatures?: Partial<TokenFeatures>;
+ hasAttachedDwhDatabase?: boolean;
+ /** False before the redeploy that makes storage the upload target. */
+ dwhCanUpload?: boolean;
+ /** Adds an ordinary database that is the instance's upload target. */
+ uploadsEnabled?: boolean;
+ /** Whether the current user may upload to that database. */
+ canUpload?: boolean;
+}
+
+const setup = ({
+ addOns = [mockStorageCloudAddOn],
+ tokenFeatures = {},
+ hasAttachedDwhDatabase = false,
+ dwhCanUpload = true,
+ uploadsEnabled = false,
+ canUpload = false,
+}: SetupOpts = {}) => {
+ const renderPanel = (mounted: boolean) => (
+ <>
+ <PurchaseTrigger />
+ {mounted ? <CSVPanel onCloseAddDataModal={jest.fn()} /> : null}
+ </>
+ );
+
+ const settingValues = {
+ "is-hosted?": true,
+ "store-url": "https://store.metabase.com",
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ };
+
+ setupPropertiesEndpoints(createMockSettings(settingValues));
+ setupDatabaseListEndpoint([
+ ...(hasAttachedDwhDatabase
+ ? [
+ createMockDatabase({
+ id: 1,
+ can_upload: dwhCanUpload,
+ is_attached_dwh: true,
+ }),
+ ]
+ : []),
+ ...(uploadsEnabled
+ ? [
+ createMockDatabase({
+ id: 2,
+ uploads_enabled: true,
+ can_upload: canUpload,
+ }),
+ ]
+ : []),
+ ]);
+ // The uploader picks a target collection as soon as it renders.
+ const collections = [
+ createMockCollection({ ...ROOT_COLLECTION, can_write: true }),
+ ];
+ setupCollectionsEndpoints({ collections });
+ setupCollectionByIdEndpoint({ collections });
+
+ fetchMock.get("path:/api/ee/cloud-add-ons/addons", addOns);
+ fetchMock.post("path:/api/ee/cloud-add-ons/dwh-rent", 200);
+ setupTokenRefreshEndpoint();
+
+ const { rerender } = renderWithProviders(
+ <StorageSetupProvider>{renderPanel(true)}</StorageSetupProvider>,
+ {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ settings: mockSettings(settingValues),
+ }),
+ },
+ );
+
+ const remount = (mounted: boolean) =>
+ rerender(
+ <StorageSetupProvider>{renderPanel(mounted)}</StorageSetupProvider>,
+ );
+
+ return { remount };
+};
+
+describe("CSVPanel storage purchase", () => {
+ it("offers to add storage next to the enable uploads CTA", async () => {
+ setup();
+
+ // Loader while add-on availability is fetched.
+ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();
+
+ expect(
+ await screen.findByRole("button", { name: /Add Metabase Storage/ }),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();
+ expect(screen.getByText("Enable uploads")).toBeInTheDocument();
+ expect(
+ screen.getByText(/either enable file uploads in/),
+ ).toBeInTheDocument();
+ expect(screen.getByText(/, or add Metabase Storage\./)).toBeInTheDocument();
+ });
+
+ it("falls back to a store link when no purchasable add-on is available", async () => {
+ setup({ addOns: [] });
+
+ expect(await screen.findByText("Enable uploads")).toBeInTheDocument();
+ // Still offered, but as a store link rather than the in-app purchase modal.
+ const storeLink = await screen.findByRole("link", {
+ name: /Add Metabase Storage/,
+ });
+ expect(storeLink).toHaveAttribute(
+ "href",
+ expect.stringContaining("/account/storage"),
+ );
+ expect(screen.getByText(/, or add Metabase Storage\./)).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the setting-up view instead of the obtain-permission prompt after a purchase", async () => {
+ // Mid-setup `uploads-settings` flips before the DWH accepts uploads, which
+ // on its own reads as a permissions problem.
+ setup({ uploadsEnabled: true, canUpload: false });
+
+ await confirmPurchase();
+
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+ expect(
+ screen.queryByText(/You are not permitted to upload CSV files/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not offer storage again on a reload mid-setup", async () => {
+ // The token flips well before the database appears. Losing the setting-up
+ // state on reload is fine; re-offering the purchase is not.
+ setup({ tokenFeatures: { attached_dwh: true } });
+
+ expect(
+ await screen.findByText(
+ "You don't have storage provisioned yet. Refresh this page after 1-2 minutes.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("link", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ // No setup was started, so nothing polls.
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+ });
+
+ it("shows the obtain-permission prompt when uploads are enabled but the user cannot upload", async () => {
+ setup({ uploadsEnabled: true, canUpload: false });
+
+ expect(
+ await screen.findByText(/You are not permitted to upload CSV files/),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Enable uploads")).not.toBeInTheDocument();
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+ });
+
+ it("does not offer to buy storage to an admin who already has it", async () => {
+ // Storage exists but uploads point elsewhere, so the CTA still shows.
+ setup({
+ tokenFeatures: { attached_dwh: true },
+ hasAttachedDwhDatabase: true,
+ dwhCanUpload: false,
+ uploadsEnabled: true,
+ canUpload: false,
+ });
+
+ expect(
+ await screen.findByText(/You are not permitted to upload CSV files/),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("link", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("offers the enable-uploads CTA when uploads are off on an instance with storage", async () => {
+ // Storage exists but is not the upload target, so the admin can turn uploads on.
+ setup({
+ tokenFeatures: { attached_dwh: true },
+ hasAttachedDwhDatabase: true,
+ dwhCanUpload: false,
+ uploadsEnabled: false,
+ });
+
+ expect(await screen.findByText("Enable uploads")).toBeInTheDocument();
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps the uploader while a purchase is still landing", async () => {
+ // Setup must not take away an upload target that already works.
+ setup({ uploadsEnabled: true, canUpload: true });
+
+ await confirmPurchase();
+
+ expect(
+ await screen.findByText("Drag and drop a file here"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+ });
+
+ it("shows the failure view when setup exceeds its deadline", async () => {
+ // Fake timers must be installed before render and drive the click, or the
+ // setup deadline stays on the real clock.
+ jest.useFakeTimers();
+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
+
+ try {
+ setup();
+
+ await confirmPurchase(user);
+
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+
+ await act(async () => {
+ jest.advanceTimersByTime(STORAGE_SETUP_TIMEOUT_MS);
+ });
+
+ expect(
+ screen.getByText("Storage setup didn't finish"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+
+ // The failure is terminal for the session — it used to collapse back to
+ // the upsell, re-offering storage to someone who had just bought it.
+ await act(async () => {
+ jest.advanceTimersByTime(STORAGE_SETUP_TIMEOUT_MS);
+ });
+
+ expect(
+ screen.getByText("Storage setup didn't finish"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it("shows the confirmation modal with the pricing terms", async () => {
+ setup();
+
+ const modal = await openPurchaseModal();
+
+ expect(
+ within(modal).getByText(
+ /Get secure, fully managed data storage where you can upload your CSVs and sync data from Google Sheets\./,
+ ),
+ ).toBeInTheDocument();
+ // From the add-on product: 1M included rows at $0.000002/row => $2 per 1M.
+ expect(
+ within(modal).getByText(
+ /You will not be charged until you reach 1M stored rows, after which it's \$2\/mo\. for each additional 1M rows\./,
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("does not purchase when the confirmation modal is cancelled", async () => {
+ setup();
+
+ const modal = await openPurchaseModal();
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Cancel" }),
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("dialog", { name: "Add Metabase Storage" }),
+ ).not.toBeInTheDocument();
+ });
+ expect(
+ fetchMock.callHistory.called("path:/api/ee/cloud-add-ons/dwh-rent"),
+ ).toBe(false);
+ });
+
+ it("shows the in-panel setting-up view after confirming the purchase", async () => {
+ setup();
+
+ await confirmPurchase();
+
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called("path:/api/ee/cloud-add-ons/dwh-rent", {
+ method: "POST",
+ }),
+ ).toBe(true);
+ });
+ });
+
+ it("keeps the setting-up state when the panel is unmounted and remounted", async () => {
+ const { remount } = setup();
+
+ await confirmPurchase();
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+
+ // Closing and reopening the Add data modal. The provider lives above it.
+ remount(false);
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+
+ remount(true);
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+ });
+
+ it("refetches the uploadable-databases list once storage is provisioned", async () => {
+ // The admin Uploads form reads its target list from a different databases
+ // query arg (`include_only_uploadable`) than the one setup polls, so the new
+ // Storage DB must be surfaced by invalidating the shared list tag, not by the
+ // poll alone. The probe stands in for that form.
+ const UploadableDatabasesProbe = () => {
+ const { data } = useListDatabasesQuery({ include_only_uploadable: true });
+ return (
+ <div data-testid="uploadable-databases">
+ {(data?.data ?? []).map((db) => db.name).join(",")}
+ </div>
+ );
+ };
+
+ jest.useFakeTimers();
+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
+
+ try {
+ // Storage does not exist yet; it materializes mid-setup.
+ let databases: Database[] = [];
+ const settingValues = {
+ "is-hosted?": true,
+ "store-url": "https://store.metabase.com",
+ "token-features": createMockTokenFeatures({}),
+ };
+
+ setupPropertiesEndpoints(createMockSettings(settingValues));
+ // Query-string-agnostic, so the polled `undefined` variant and the probe's
+ // `include_only_uploadable` variant read the same evolving list.
+ fetchMock.get(
+ "path:/api/database",
+ () => ({ data: databases, total: databases.length }),
+ { name: "database-list" },
+ );
+ const collections = [
+ createMockCollection({ ...ROOT_COLLECTION, can_write: true }),
+ ];
+ setupCollectionsEndpoints({ collections });
+ setupCollectionByIdEndpoint({ collections });
+ fetchMock.get("path:/api/ee/cloud-add-ons/addons", [
+ mockStorageCloudAddOn,
+ ]);
+ fetchMock.post("path:/api/ee/cloud-add-ons/dwh-rent", 200);
+ setupTokenRefreshEndpoint();
+
+ const { store } = renderWithProviders(
+ <StorageSetupProvider>
+ <PurchaseTrigger />
+ <CSVPanel onCloseAddDataModal={jest.fn()} />
+ <UploadableDatabasesProbe />
+ </StorageSetupProvider>,
+ {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ settings: mockSettings(settingValues),
+ }),
+ },
+ );
+ const dispatchSpy = jest.spyOn(store, "dispatch");
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+ expect(screen.getByTestId("uploadable-databases")).toHaveTextContent("");
+
+ // Storage lands: the DWH database now appears in the list.
+ databases = [
+ createMockDatabase({
+ id: 1,
+ name: "Metabase Storage",
+ is_attached_dwh: true,
+ can_upload: true,
+ }),
+ ];
+
+ // Polling picks up the DWH, flips setup to done, and invalidates the list
+ // tag so every variant — including the probe's — refetches.
+ await act(async () => {
+ await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS);
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("uploadable-databases")).toHaveTextContent(
+ "Metabase Storage",
+ );
+ });
+
+ // Session properties refetch too, so the admin Uploads form picks up the
+ // new upload target from `uploads-settings`.
+ expect(
+ invalidatedTagsInclude(dispatchSpy, ["database", "session-properties"]),
+ ).toBe(true);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/StoragePurchaseModal.tsx b/enterprise/frontend/src/metabase-enterprise/storage/StoragePurchaseModal.tsx
new file mode 100644
index 00000000000..562236cf6cf
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/StoragePurchaseModal.tsx
@@ -0,0 +1,85 @@
+import { c, t } from "ttag";
+
+import {
+ Button,
+ Group,
+ Modal,
+ type ModalProps,
+ Stack,
+ Text,
+} from "metabase/ui";
+import { formatNumber } from "metabase/utils/formatting";
+import type { ICloudAddOnProduct } from "metabase-types/api";
+
+const ROWS_BLOCK = 1_000_000;
+
+type StoragePurchaseModalProps = Pick<ModalProps, "opened" | "onClose"> & {
+ storageAddOn: ICloudAddOnProduct;
+ onConfirm: () => void;
+};
+
+export const StoragePurchaseModal = ({
+ opened,
+ onClose,
+ onConfirm,
+ storageAddOn,
+}: StoragePurchaseModalProps) => {
+ const includedRows = formatNumber(storageAddOn.default_included_units, {
+ compact: true,
+ decimals: 0,
+ });
+ const additionalRows = formatNumber(ROWS_BLOCK, {
+ compact: true,
+ decimals: 0,
+ });
+ const pricePerBlock = formatNumber(
+ storageAddOn.default_price_per_unit * ROWS_BLOCK,
+ {
+ number_style: "currency",
+ currency: "USD",
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 2,
+ },
+ );
+
+ const handleConfirm = () => {
+ onClose();
+ onConfirm();
+ };
+
+ return (
+ <Modal
+ opened={opened}
+ onClose={onClose}
+ size="35rem"
+ padding="2.5rem"
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Upsell for Metabase Storage, only visible to admins
+ title={t`Add Metabase Storage`}
+ >
+ <Stack gap="md" mt="md">
+ <Text>
+ {t`Get secure, fully managed data storage where you can upload your CSVs and sync data from Google Sheets.`}
+ </Text>
+
+ <Text c="text-secondary" size="sm" lh={1.4}>
+ {c(
+ "{0} and {2} are numbers of database rows, {1} is a monthly price, e.g. '$40'",
+ )
+ /* prettier-ignore */
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Upsell for Metabase Storage, only visible to admins
+ .t`By clicking "Add Metabase Storage," you agree to be charged in accordance with our terms of service. You will not be charged until you reach ${includedRows} stored rows, after which it's ${pricePerBlock}/mo. for each additional ${additionalRows} rows.`}
+ </Text>
+
+ <Group justify="flex-end" mt="sm">
+ <Button variant="subtle" onClick={onClose}>
+ {t`Cancel`}
+ </Button>
+ <Button variant="filled" onClick={handleConfirm}>
+ {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Upsell for Metabase Storage, only visible to admins */}
+ {t`Add Metabase Storage`}
+ </Button>
+ </Group>
+ </Stack>
+ </Modal>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.tsx b/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.tsx
new file mode 100644
index 00000000000..02a6c6921c6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.tsx
@@ -0,0 +1,71 @@
+import { useDisclosure } from "@mantine/hooks";
+import { useMemo } from "react";
+
+import {
+ StorageSetupContext,
+ type StorageSetupContextValue,
+ type StorageSetupProviderProps,
+} from "metabase/common/components/upsells/StoragePurchaseModal";
+
+import { StoragePurchaseModal } from "./StoragePurchaseModal";
+import { usePurchaseStorageAddOn } from "./use-purchase-storage-add-on";
+import { useStorageAddOn } from "./use-storage-add-on";
+
+/**
+ * The real storage setup provider, injected into the OSS Add data modal via
+ * `PLUGIN_UPLOAD_MANAGEMENT.StorageSetupProvider` on hosted instances.
+ *
+ * Must be mounted outside the modal's `Modal.Root`, so its polling survives the
+ * modal closing and its purchase modal replaces the host modal rather than
+ * stacking on it.
+ */
+export const StorageSetupProvider = ({
+ children,
+ enabled = true,
+}: StorageSetupProviderProps) => {
+ const { isSettingUp, hasSetupFailed, handlePurchase, canPurchaseStorage } =
+ usePurchaseStorageAddOn();
+ const { storageAddOn, isLoading: isLoadingStorageAddOn } = useStorageAddOn({
+ skip: !enabled || !canPurchaseStorage,
+ });
+ const [
+ isPurchaseModalOpened,
+ { open: openPurchaseModal, close: closePurchaseModal },
+ ] = useDisclosure(false);
+
+ const value = useMemo<StorageSetupContextValue>(
+ () => ({
+ isSettingUp,
+ hasSetupFailed,
+ storageAddOn,
+ isLoadingStorageAddOn,
+ isPurchaseModalOpened,
+ openPurchaseModal,
+ canPurchaseStorage,
+ }),
+ [
+ isSettingUp,
+ hasSetupFailed,
+ storageAddOn,
+ isLoadingStorageAddOn,
+ isPurchaseModalOpened,
+ openPurchaseModal,
+ canPurchaseStorage,
+ ],
+ );
+
+ return (
+ <StorageSetupContext.Provider value={value}>
+ {children}
+
+ {storageAddOn && canPurchaseStorage && (
+ <StoragePurchaseModal
+ opened={isPurchaseModalOpened}
+ onClose={closePurchaseModal}
+ onConfirm={handlePurchase}
+ storageAddOn={storageAddOn}
+ />
+ )}
+ </StorageSetupContext.Provider>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.unit.spec.tsx
new file mode 100644
index 00000000000..e9de7b9c57f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.unit.spec.tsx
@@ -0,0 +1,490 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseListEndpoint,
+ setupPropertiesEndpoints,
+ setupTokenRefreshEndpoint,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import {
+ act,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { Api } from "metabase/api";
+import { listTag } from "metabase/api/tags";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import { useStorageSetup } from "metabase/common/components/upsells/StoragePurchaseModal";
+import { createMockState } from "metabase/redux/store/mocks";
+import type { ICloudAddOnProduct, TokenFeatures } from "metabase-types/api";
+import {
+ createMockDatabase,
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockTokenStatus,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { mockStorageCloudAddOn } from "metabase-types/api/mocks/add-ons";
+
+import { StorageSetupProvider } from "./StorageSetupProvider";
+import {
+ PurchaseTrigger,
+ confirmPurchase,
+ invalidatedTagsInclude,
+ openPurchaseModal,
+} from "./test-utils";
+import {
+ POLL_INTERVAL_MS,
+ STORAGE_SETUP_TIMEOUT_MS,
+} from "./use-purchase-storage-add-on";
+
+/**
+ * What RTK Query's `setupListeners` dispatches when the document loses focus.
+ * Dispatched by hand because nothing in the app calls `setupListeners`.
+ */
+const RTK_QUERY_UNFOCUSED = { type: "__rtkq/unfocused" };
+
+const TestConsumer = () => {
+ const { isSettingUp, hasSetupFailed } = useStorageSetup();
+
+ return (
+ <div>
+ <PurchaseTrigger />
+ {isSettingUp && <span>setting up</span>}
+ {hasSetupFailed && <span>setup failed</span>}
+ </div>
+ );
+};
+
+interface SetupOpts {
+ tokenFeatures?: Partial<TokenFeatures>;
+ hasAttachedDwhDatabase?: boolean;
+ isHosted?: boolean;
+ addOns?: ICloudAddOnProduct[];
+ /** Mirrors `enabled={opened}` from the Add data modal. */
+ enabled?: boolean;
+ /** The purchase request itself fails, as opposed to provisioning never landing. */
+ purchaseFails?: boolean;
+}
+
+const setup = ({
+ tokenFeatures = {},
+ hasAttachedDwhDatabase = false,
+ isHosted = true,
+ addOns = [mockStorageCloudAddOn],
+ enabled = true,
+ purchaseFails = false,
+}: SetupOpts = {}) => {
+ const settingValues = {
+ "is-hosted?": isHosted,
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ "uploads-settings": {
+ db_id: hasAttachedDwhDatabase ? 1 : null,
+ schema_name: null,
+ table_prefix: null,
+ },
+ };
+
+ setupPropertiesEndpoints(
+ createMockSettings({
+ ...settingValues,
+ "token-status": createMockTokenStatus({
+ features: tokenFeatures.attached_dwh ? ["attached-dwh"] : [],
+ }),
+ }),
+ );
+ // Setup finishes once the `is_attached_dwh` database surfaces here. Whether it
+ // accepts uploads is a separate question that must not feed back into setup.
+ setupDatabaseListEndpoint(
+ hasAttachedDwhDatabase
+ ? [
+ createMockDatabase({
+ id: 1,
+ is_attached_dwh: true,
+ }),
+ ]
+ : [],
+ );
+ fetchMock.get("path:/api/ee/cloud-add-ons/addons", addOns);
+ fetchMock.post(
+ "path:/api/ee/cloud-add-ons/dwh-rent",
+ purchaseFails ? 500 : 200,
+ );
+ setupTokenRefreshEndpoint();
+
+ // The consumer stands in for the modal contents, which unmount on close.
+ // `UndoListing` is a sibling so toasts still render while it is gone.
+ const renderTree = (opts: {
+ isConsumerMounted: boolean;
+ enabled: boolean;
+ }) => (
+ <StorageSetupProvider enabled={opts.enabled}>
+ {opts.isConsumerMounted ? <TestConsumer /> : null}
+ <UndoListing />
+ </StorageSetupProvider>
+ );
+
+ const { rerender, store } = renderWithProviders(
+ renderTree({ isConsumerMounted: true, enabled }),
+ {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ settings: mockSettings(settingValues),
+ }),
+ },
+ );
+
+ /** Stands in for the Add data modal closing (`enabled={opened}`) and reopening. */
+ const remount = ({
+ isConsumerMounted = true,
+ enabled: nextEnabled = enabled,
+ }: { isConsumerMounted?: boolean; enabled?: boolean } = {}) =>
+ rerender(renderTree({ isConsumerMounted, enabled: nextEnabled }));
+
+ return { remount, store };
+};
+
+/**
+ * Setup polls on a short interval and gives up minutes later, so tests drive a
+ * fake clock rather than waiting it out. The click that starts setup has to
+ * advance that clock too, hence binding `userEvent` to it.
+ */
+const setupFakeClock = () => {
+ jest.useFakeTimers();
+ return userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
+};
+
+/** One poll tick, plus a wait for the refetch it issues to settle. */
+const advanceToNextPoll = async () => {
+ await act(async () => {
+ jest.advanceTimersByTime(POLL_INTERVAL_MS);
+ });
+ // Waited on directly rather than flushed by a second tick, which would leave
+ // the number of ticks it takes to land as an unspoken assumption.
+ await act(async () => {
+ await fetchMock.callHistory.flush(true);
+ });
+};
+
+describe("StorageSetupProvider", () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it("purchases the add-on on confirm and enters the setting-up state", async () => {
+ setup();
+
+ await confirmPurchase();
+
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.called("path:/api/ee/cloud-add-ons/dwh-rent", {
+ method: "POST",
+ }),
+ ).toBe(true);
+ });
+ });
+
+ it("reloads the databases list while setting up", async () => {
+ const user = setupFakeClock();
+ setup();
+
+ await confirmPurchase(user);
+
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ const callsBeforePoll =
+ fetchMock.callHistory.calls("path:/api/database").length;
+ await advanceToNextPoll();
+
+ expect(
+ fetchMock.callHistory.calls("path:/api/database").length,
+ ).toBeGreaterThan(callsBeforePoll);
+ });
+
+ it("stays in the setting-up state while the attached DWH database is missing", async () => {
+ setup();
+
+ await confirmPurchase();
+
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Metabase Storage is ready"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("leaves the setting-up state once the attached DWH database appears", async () => {
+ const user = setupFakeClock();
+ setup();
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ // The databases list, not the token feature, is what ends setup.
+ const storage = [createMockDatabase({ id: 1, is_attached_dwh: true })];
+ fetchMock.modifyRoute("database-list", {
+ response: () => ({ data: storage, total: storage.length }),
+ });
+
+ await advanceToNextPoll();
+
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+ expect(
+ await screen.findByText("Metabase Storage is ready"),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps polling for the attached DWH while the document is unfocused", async () => {
+ // RTK Query gates polling on `config.focused`, which is fixed at whatever
+ // `document.visibilityState` said when the store was built — only
+ // `setupListeners`, which this app never calls, can change it afterwards. A
+ // page first opened in a background tab is therefore unfocused for its whole
+ // life, so setup must not be gated on focus or it would never finish.
+ const user = setupFakeClock();
+ const { store } = setup();
+
+ store.dispatch(RTK_QUERY_UNFOCUSED);
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ const storage = [createMockDatabase({ id: 1, is_attached_dwh: true })];
+ fetchMock.modifyRoute("database-list", {
+ response: () => ({ data: storage, total: storage.length }),
+ });
+
+ await advanceToNextPoll();
+
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+ expect(
+ await screen.findByText("Metabase Storage is ready"),
+ ).toBeInTheDocument();
+ });
+
+ it("invalidates the databases list and session properties together when storage lands", async () => {
+ // Session properties carry `uploads-settings`, which the admin Uploads form
+ // reads, so it must refetch alongside the databases list.
+ const user = setupFakeClock();
+ const { store } = setup();
+ const dispatchSpy = jest.spyOn(store, "dispatch");
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ const storage = [createMockDatabase({ id: 1, is_attached_dwh: true })];
+ fetchMock.modifyRoute("database-list", {
+ response: () => ({ data: storage, total: storage.length }),
+ });
+
+ await advanceToNextPoll();
+
+ expect(
+ invalidatedTagsInclude(dispatchSpy, ["database", "session-properties"]),
+ ).toBe(true);
+ });
+
+ it("gives up on setup once it exceeds its deadline, and stays given up", async () => {
+ // Fake timers must be installed before render or the deadline stays real.
+ const user = setupFakeClock();
+ setup();
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ await act(async () => {
+ jest.advanceTimersByTime(STORAGE_SETUP_TIMEOUT_MS);
+ });
+
+ expect(screen.getByText("setup failed")).toBeInTheDocument();
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("Metabase Storage is ready"),
+ ).not.toBeInTheDocument();
+
+ // Terminal for the session — it used to collapse straight back to the upsell.
+ await act(async () => {
+ jest.advanceTimersByTime(STORAGE_SETUP_TIMEOUT_MS);
+ });
+ expect(screen.getByText("setup failed")).toBeInTheDocument();
+ });
+
+ it("clears a failed setup once the attached DWH database surfaces", async () => {
+ const user = setupFakeClock();
+ const { store } = setup();
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ await act(async () => {
+ jest.advanceTimersByTime(STORAGE_SETUP_TIMEOUT_MS);
+ });
+ expect(screen.getByText("setup failed")).toBeInTheDocument();
+
+ // Setup timed out locally, but the DWH lands in the background. A later
+ // databases-list refetch (e.g. a page refresh) must clear the stale failure.
+ const storage = [createMockDatabase({ id: 1, is_attached_dwh: true })];
+ fetchMock.modifyRoute("database-list", {
+ response: () => ({ data: storage, total: storage.length }),
+ });
+ await act(async () => {
+ store.dispatch(Api.util.invalidateTags([listTag("database")]));
+ });
+ await act(async () => {
+ await fetchMock.callHistory.flush(true);
+ });
+
+ expect(screen.queryByText("setup failed")).not.toBeInTheDocument();
+ expect(
+ await screen.findByText("Metabase Storage is ready"),
+ ).toBeInTheDocument();
+ });
+
+ it("never enters setup on its own, however the instance looks on load", async () => {
+ // A token with no matching database looks like mid-provisioning, and used to
+ // be read as exactly that. Only a purchase enters setup now.
+ setup({ tokenFeatures: { attached_dwh: true } });
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("path:/api/database")).toBe(true);
+ });
+
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+ expect(screen.queryByText("setup failed")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("Metabase Storage is ready"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not flash the setting-up state or toast on load for an instance that already has storage", async () => {
+ setup({
+ tokenFeatures: { attached_dwh: true },
+ hasAttachedDwhDatabase: true,
+ });
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("path:/api/database")).toBe(true);
+ });
+
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("Metabase Storage is ready"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("recovers and lets the admin retry when the purchase request fails", async () => {
+ // Unlike the deadline case, this leaves no setup running.
+ setup({ purchaseFails: true });
+
+ await confirmPurchase();
+
+ expect(
+ await screen.findByText(
+ "It looks like something went wrong. Please refresh the page and try again.",
+ ),
+ ).toBeInTheDocument();
+
+ // `setting-up` is entered before the request is awaited, so it flashes.
+ await waitFor(() => {
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+ });
+ expect(screen.queryByText("setup failed")).not.toBeInTheDocument();
+
+ // Nothing was bought, so the offer has to still be there.
+ expect(await openPurchaseModal()).toBeInTheDocument();
+ });
+
+ it("finishes setup and toasts while the modal that started it is closed", async () => {
+ // This is why the provider sits outside `Modal.Root`.
+ const user = setupFakeClock();
+ const { remount } = setup();
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ remount({ isConsumerMounted: false, enabled: false });
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+
+ const storage = [createMockDatabase({ id: 1, is_attached_dwh: true })];
+ fetchMock.modifyRoute("database-list", {
+ response: () => ({ data: storage, total: storage.length }),
+ });
+
+ await advanceToNextPoll();
+
+ expect(
+ await screen.findByText("Metabase Storage is ready"),
+ ).toBeInTheDocument();
+ });
+
+ describe("enabled", () => {
+ it("does not fetch the add-ons list while the hosting UI is hidden", async () => {
+ // The provider is app-wide, so an ungated fetch means a Store round-trip
+ // on every page load.
+ setup({ enabled: false });
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("path:/api/database")).toBe(true);
+ });
+ expect(
+ fetchMock.callHistory.called("path:/api/ee/cloud-add-ons/addons"),
+ ).toBe(false);
+ });
+
+ it("keeps setup running and polling after the modal that started it closes", async () => {
+ const user = setupFakeClock();
+ const { remount } = setup();
+
+ await confirmPurchase(user);
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ remount({ enabled: false });
+
+ expect(screen.getByText("setting up")).toBeInTheDocument();
+
+ const callsBeforeClose =
+ fetchMock.callHistory.calls("path:/api/database").length;
+ await advanceToNextPoll();
+
+ expect(
+ fetchMock.callHistory.calls("path:/api/database").length,
+ ).toBeGreaterThan(callsBeforeClose);
+ });
+ });
+
+ describe("purchase confirmation modal", () => {
+ it("does not purchase when the confirmation modal is cancelled", async () => {
+ setup();
+
+ const modal = await openPurchaseModal();
+
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Cancel" }),
+ );
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("dialog", { name: "Add Metabase Storage" }),
+ ).not.toBeInTheDocument();
+ });
+ expect(
+ fetchMock.callHistory.called("path:/api/ee/cloud-add-ons/dwh-rent"),
+ ).toBe(false);
+ });
+
+ it("does not render the confirmation modal without a purchasable add-on", async () => {
+ setup({ isHosted: false, addOns: [] });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Open purchase modal" }),
+ );
+
+ expect(
+ screen.queryByRole("dialog", { name: "Add Metabase Storage" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/test-utils.tsx b/enterprise/frontend/src/metabase-enterprise/storage/test-utils.tsx
new file mode 100644
index 00000000000..6905c1c2515
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/test-utils.tsx
@@ -0,0 +1,66 @@
+import userEvent from "@testing-library/user-event";
+
+import { screen, within } from "__support__/ui";
+import { useStorageSetup } from "metabase/common/components/upsells/StoragePurchaseModal";
+
+/** Either the bare `userEvent` or an instance bound to jest fake timers. */
+export type Clicker = Pick<ReturnType<typeof userEvent.setup>, "click">;
+
+const TRIGGER_NAME = "Open purchase modal";
+
+/**
+ * Starts setup from any state — the panels only render their own purchase button
+ * in one of them. Uses the same entry point that button does.
+ */
+export const PurchaseTrigger = () => {
+ const { openPurchaseModal } = useStorageSetup();
+
+ return <button onClick={openPurchaseModal}>{TRIGGER_NAME}</button>;
+};
+
+/** Takes the clicker because fake-clock tests need a bound `userEvent`. */
+export const openPurchaseModal = async (user: Clicker = userEvent) => {
+ await user.click(screen.getByRole("button", { name: TRIGGER_NAME }));
+
+ return await findPurchaseModal();
+};
+
+/** The modal can also be opened by a panel's own upsell button, not just `PurchaseTrigger`. */
+export const findPurchaseModal = async () =>
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Test assertion against admin-only upsell copy
+ await screen.findByRole("dialog", { name: "Add Metabase Storage" });
+
+/** Confirms an already-open purchase modal, however it was opened. */
+export const confirmPurchaseModal = async (user: Clicker = userEvent) => {
+ const modal = await findPurchaseModal();
+ await user.click(
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Test assertion against admin-only upsell copy
+ within(modal).getByRole("button", { name: "Add Metabase Storage" }),
+ );
+};
+
+export const confirmPurchase = async (user: Clicker = userEvent) => {
+ await openPurchaseModal(user);
+ await confirmPurchaseModal(user);
+};
+
+type DispatchSpy = { mock: { calls: unknown[][] } };
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null;
+
+export const invalidatedTagsInclude = (
+ dispatchSpy: DispatchSpy,
+ types: string[],
+): boolean =>
+ dispatchSpy.mock.calls.some(([action]) => {
+ if (!isRecord(action) || action.type !== "metabase-api/invalidateTags") {
+ return false;
+ }
+
+ const tagTypes = (Array.isArray(action.payload) ? action.payload : []).map(
+ (entry) => (isRecord(entry) ? entry.type : entry),
+ );
+
+ return types.every((type) => tagTypes.includes(type));
+ });
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/use-purchase-storage-add-on.ts b/enterprise/frontend/src/metabase-enterprise/storage/use-purchase-storage-add-on.ts
new file mode 100644
index 00000000000..fe345efa9fc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/use-purchase-storage-add-on.ts
@@ -0,0 +1,128 @@
+import { useCallback, useEffect, useState } from "react";
+import { t } from "ttag";
+
+import { Api, useListDatabasesQuery } from "metabase/api";
+import { listTag, tag } from "metabase/api/tags";
+import { useTokenRefreshUntil } from "metabase/api/utils";
+import {
+ useAttachedDwh,
+ useHasTokenFeature,
+ useSetting,
+ useToast,
+} from "metabase/common/hooks";
+import { useDispatch, useSelector } from "metabase/redux";
+import { getUserIsAdmin } from "metabase/selectors/user";
+import { usePurchaseCloudAddOnMutation } from "metabase-enterprise/api";
+
+import { STORAGE_PRODUCT_TYPE } from "./use-storage-add-on";
+
+export const POLL_INTERVAL_MS = 4000;
+
+/** Setup lives only in this tab, so it needs its own deadline to stop spinning. */
+export const STORAGE_SETUP_TIMEOUT_MS = 6 * 60 * 1000;
+
+/** `failed` is terminal for the session; only another purchase or a reload clears it. */
+type StorageSetupPhase = "idle" | "setting-up" | "failed";
+
+/**
+ * Storage setup as a session-local state machine.
+ *
+ * Deliberately not inferred from server state: an `attached_dwh` token with no
+ * matching database is indistinguishable from a local hosted build or a plan
+ * whose token runs ahead of the data, so inferring it put those admins in a
+ * ten-minute polling spinner on every page load.
+ *
+ * A reload mid-setup therefore loses the spinner, but `canPurchaseStorage` keys
+ * off the token feature so it can't re-offer storage they already bought.
+ */
+export function usePurchaseStorageAddOn() {
+ const isHosted = useSetting("is-hosted?");
+ const isAdmin = useSelector(getUserIsAdmin);
+ const hasStorageTokenFeature = useHasTokenFeature("attached_dwh");
+ const [sendToast] = useToast();
+ const dispatch = useDispatch();
+
+ const [purchaseCloudAddOn] = usePurchaseCloudAddOnMutation();
+
+ const canPurchaseStorage = isHosted && isAdmin && !hasStorageTokenFeature;
+
+ // Presence, not readiness: waiting for storage to accept uploads would never
+ // finish for an admin who points uploads at a different database.
+ const { hasAttachedDwh } = useAttachedDwh();
+
+ const [phase, setPhase] = useState<StorageSetupPhase>("idle");
+
+ const isSettingUp = phase === "setting-up";
+ const hasSetupFailed = phase === "failed";
+
+ useEffect(() => {
+ if (!isSettingUp) {
+ return;
+ }
+
+ const timer = setTimeout(
+ () => setPhase("failed"),
+ STORAGE_SETUP_TIMEOUT_MS,
+ );
+ return () => clearTimeout(timer);
+ }, [isSettingUp]);
+
+ // A condition rather than a transition, so it also covers storage that was
+ // already there when setup started, and a background success that lands after
+ // setup has locally timed out into `failed`.
+ useEffect(() => {
+ if (phase !== "idle" && hasAttachedDwh) {
+ setPhase("idle");
+ // Refetch every databases-list variant (the poll only refreshes the
+ // `undefined` one) so the new Storage database surfaces as an upload
+ // target, and `session-properties` so the admin Uploads form picks up the
+ // flipped `uploads-settings`.
+ dispatch(
+ Api.util.invalidateTags([
+ listTag("database"),
+ tag("session-properties"),
+ ]),
+ );
+ sendToast({
+ icon: "check",
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Storage setup outcome, only visible to admins
+ message: t`Metabase Storage is ready`,
+ });
+ }
+ }, [phase, hasAttachedDwh, sendToast, dispatch]);
+
+ // Refresh the token (a Store round-trip) until `attached_dwh` shows up, so the
+ // rest of the app picks up the new plan without a reload.
+ useTokenRefreshUntil("attached-dwh", {
+ skip: !isSettingUp || hasStorageTokenFeature,
+ });
+
+ // A second subscription to the query `useAttachedDwh` makes, not a second
+ // request. It exists only to attach polling while setup is in progress.
+ useListDatabasesQuery(undefined, {
+ skip: !isSettingUp,
+ pollingInterval: POLL_INTERVAL_MS,
+ });
+
+ const handlePurchase = useCallback(async () => {
+ setPhase("setting-up");
+
+ try {
+ await purchaseCloudAddOn({ product_type: STORAGE_PRODUCT_TYPE }).unwrap();
+ } catch {
+ setPhase("idle");
+ sendToast({
+ icon: "warning_triangle_filled",
+ iconColor: "feedback-warning",
+ message: t`It looks like something went wrong. Please refresh the page and try again.`,
+ });
+ }
+ }, [purchaseCloudAddOn, sendToast]);
+
+ return {
+ isSettingUp,
+ hasSetupFailed,
+ handlePurchase,
+ canPurchaseStorage,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/storage/use-storage-add-on.ts b/enterprise/frontend/src/metabase-enterprise/storage/use-storage-add-on.ts
new file mode 100644
index 00000000000..f04f54a9edc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/use-storage-add-on.ts
@@ -0,0 +1,16 @@
+import { useListAddOnsQuery } from "metabase-enterprise/api";
+
+export const STORAGE_PRODUCT_TYPE = "dwh-rent";
+
+export function useStorageAddOn({ skip = false }: { skip?: boolean } = {}) {
+ const { data: addOns, isLoading } = useListAddOnsQuery(undefined, {
+ skip,
+ });
+
+ const storageAddOn = addOns?.find(
+ ({ active, self_service, product_type }) =>
+ active && self_service && product_type === STORAGE_PRODUCT_TYPE,
+ );
+
+ return { storageAddOn, isLoading };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts b/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts
index 51fd7c91bba..bdb9c042af2 100644
--- a/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/upload_management/index.ts
@@ -1,5 +1,6 @@
import { PLUGIN_UPLOAD_MANAGEMENT } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
+import { StorageSetupProvider } from "metabase-enterprise/storage/StorageSetupProvider";
import {
FileUploadErrorModal,
@@ -23,6 +24,9 @@ export function initializePlugin() {
// The reason we're showing this panel even to instances without the dwh
// is because we want to show them the storage upsell.
PLUGIN_UPLOAD_MANAGEMENT.GdriveAddDataPanel = GdriveAddDataPanel;
+ // The real storage-setup provider owns the cloud-add-ons purchase
+ // endpoints, so it only activates on hosted instances.
+ PLUGIN_UPLOAD_MANAGEMENT.StorageSetupProvider = StorageSetupProvider;
}
if (hasPremiumFeature("hosting") && hasPremiumFeature("attached_dwh")) {
diff --git a/frontend/src/metabase-types/api/mocks/add-ons.ts b/frontend/src/metabase-types/api/mocks/add-ons.ts
index db5d30cb9a5..488e1591914 100644
--- a/frontend/src/metabase-types/api/mocks/add-ons.ts
+++ b/frontend/src/metabase-types/api/mocks/add-ons.ts
@@ -44,6 +44,30 @@ export const mockAdvancedTransformsCloudAddOn: ICloudAddOnProduct = {
trial_days: 0,
};
+export const mockStorageCloudAddOn: ICloudAddOnProduct = {
+ active: true,
+ billing_period_months: 1,
+ default_base_fee: 0,
+ default_included_units: 1_000_000,
+ default_prepaid_units: 0,
+ default_price_per_unit: 0.000002,
+ default_total_units: 1_000_000,
+ deployment: "hosting",
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- test mock fixture
+ description: "Metabase Storage (Monthly) - metered",
+ free_units: 0,
+ id: 200,
+ is_metered: true,
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- test mock fixture
+ name: "Metabase Storage metered",
+ product_tiers: [],
+ product_type: "dwh-rent",
+ self_service: true,
+ short_name: "Storage - metered",
+ token_features: ["attached_dwh", "upload_management"],
+ trial_days: 0,
+};
+
export function createMockCloudAddOns(
opts?: Partial<ICloudAddOnProduct>,
): Partial<ICloudAddOnProduct>[] {
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index bf4bb9aac15..64fc15435db 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -255,6 +255,7 @@ export type GdrivePayload = {
const tokenStatusFeatures = [
"advanced-config",
"advanced-permissions",
+ "attached-dwh",
"audit-app",
"cache-granular-controls",
"collection-cleanup",
diff --git a/frontend/src/metabase-types/api/store.ts b/frontend/src/metabase-types/api/store.ts
index cd9d9ddf381..43537c671e9 100644
--- a/frontend/src/metabase-types/api/store.ts
+++ b/frontend/src/metabase-types/api/store.ts
@@ -43,7 +43,9 @@ export type AddOnProductType =
| "transforms-basic"
| "transforms-basic-metered"
| "transforms-advanced"
- | "transforms-advanced-metered";
+ | "transforms-advanced-metered"
+ | "dwh-rent"
+ | "etl-connections";
interface IBillingInfoData {
billing_period_months?: number | null;
diff --git a/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.tsx b/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.tsx
index 954357a669b..72e78ab9412 100644
--- a/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.tsx
+++ b/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.tsx
@@ -172,7 +172,21 @@ export function UploadSettingsFormView({
{isH2db && <H2PersistenceWarning isHosted={isHosted} />}
<Group align="flex-start">
<Select
- label={t`Database to use for uploads`}
+ label={
+ <Group gap="xs" wrap="nowrap" align="center">
+ {t`Database to use for uploads`}
+ <Tooltip
+ label={t`PostgreSQL, MySQL, Redshift, ClickHouse, and Snowflake databases are supported for file storage.`}
+ >
+ <Icon
+ name="info"
+ size={14}
+ c="text-secondary"
+ data-testid="uploads-db-info-icon"
+ />
+ </Tooltip>
+ </Group>
+ }
value={dbId ? String(dbId) : null}
placeholder={t`Select a database`}
disabled={!hasValidDatabases}
@@ -287,7 +301,7 @@ export function UploadSettingsFormView({
const H2PersistenceWarning = ({ isHosted }: { isHosted: boolean }) => (
<Alert my="md" maw={620} icon={<Icon name="warning" />} color="warning">
<Stack gap="sm">
- {t`Warning: uploads to the Sample Database are for testing only and may disappear. If you want your data to stick around, you should upload to a PostgreSQL, MySQL, Redshift or Clickhouse database.`}
+ {t`Warning: uploads to the Sample Database are for testing only and may disappear. If you want your data to stick around, you should upload to a PostgreSQL, MySQL, Redshift, ClickHouse, or Snowflake database.`}
{isHosted && (
<Tooltip
label={
diff --git a/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.unit.spec.tsx
index 13d5b5215e1..62395d259ea 100644
--- a/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.unit.spec.tsx
@@ -150,6 +150,16 @@ describe("Admin > Settings > UploadSettingsFormView", () => {
).toBeInTheDocument();
});
+ it("should show the supported databases in a tooltip on the dropdown label", async () => {
+ setup();
+ await userEvent.hover(screen.getByTestId("uploads-db-info-icon"));
+ expect(
+ await screen.findByText(
+ "PostgreSQL, MySQL, Redshift, ClickHouse, and Snowflake databases are supported for file storage.",
+ ),
+ ).toBeInTheDocument();
+ });
+
it("should show an empty state if there are no databases", async () => {
setup({ databases: [] });
expect(
diff --git a/frontend/src/metabase/api/utils/use-token-refresh.ts b/frontend/src/metabase/api/utils/use-token-refresh.ts
index 0b12127ed89..4034bb54d9b 100644
--- a/frontend/src/metabase/api/utils/use-token-refresh.ts
+++ b/frontend/src/metabase/api/utils/use-token-refresh.ts
@@ -54,7 +54,7 @@ export function useTokenRefreshUntil(
},
) {
/* in order to force this hook to re-run on every request, even if the response data is the same, we can't destructure only the data prop from this hook, as is the pattern in many components */
- const res = useGetSettingsQuery();
+ const res = useGetSettingsQuery(undefined, { skip });
const dispatch = useDispatch();
const [refreshTokenStatus] = useRefreshTokenStatusMutation();
const hasCalledOnSatisfied = useRef(false);
@@ -64,9 +64,6 @@ export function useTokenRefreshUntil(
}
const refreshToken = useCallback(async () => {
- // Bust the server-side cache first; the mutation's invalidatesTags will
- // also invalidate session-properties on success, but we do it in finally
- // too so the UI updates even if the request fails.
try {
const status = await refreshTokenStatus().unwrap();
@@ -78,7 +75,9 @@ export function useTokenRefreshUntil(
hasCalledOnSatisfied.current = true;
onSatisfied();
}
- } finally {
+ } catch {
+ // The mutation only invalidates session-properties when it succeeds, so
+ // the failure path has to do it here for the UI to move on.
dispatch(Api.util.invalidateTags(["session-properties"]));
}
}, [dispatch, onSatisfied, refreshTokenStatus, tokenFeature]);
diff --git a/frontend/src/metabase/api/utils/use-token-refresh.unit.spec.tsx b/frontend/src/metabase/api/utils/use-token-refresh.unit.spec.tsx
index fb1397e16b2..09bba3adcc1 100644
--- a/frontend/src/metabase/api/utils/use-token-refresh.unit.spec.tsx
+++ b/frontend/src/metabase/api/utils/use-token-refresh.unit.spec.tsx
@@ -1,13 +1,20 @@
+import fetchMock from "fetch-mock";
+
import {
findRequests,
setupPropertiesEndpoints,
+ setupTokenRefreshEndpoint,
} from "__support__/server-mocks";
import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
-import { createMockSettings } from "metabase-types/api/mocks";
+import type { TokenStatusFeature } from "metabase-types/api";
+import {
+ createMockSettings,
+ createMockTokenStatus,
+} from "metabase-types/api/mocks";
import { useGetSettingsQuery } from "../session";
-import { useTokenRefresh } from "./use-token-refresh";
+import { useTokenRefresh, useTokenRefreshUntil } from "./use-token-refresh";
const TestComponent = () => {
useTokenRefresh();
@@ -58,11 +65,15 @@ const waitForGets = async (count: number) => {
});
};
-describe("useTokenRefresh", () => {
- beforeAll(() => {
- jest.useFakeTimers({ advanceTimers: true });
- });
+beforeAll(() => {
+ jest.useFakeTimers({ advanceTimers: true });
+});
+
+afterAll(() => {
+ jest.useRealTimers();
+});
+describe("useTokenRefresh", () => {
it("should refetch every 10 seconds", async () => {
await setup(true); // always start with 1 request
await waitForElevenSeconds(); // 2
@@ -99,3 +110,205 @@ describe("useTokenRefresh", () => {
expect(gets.length).toBe(3);
});
});
+
+const TOKEN_FEATURE: TokenStatusFeature = "attached-dwh";
+const UNTIL_INTERVAL_MS = 1000;
+
+const UntilTestComponent = ({
+ skip,
+ onSatisfied,
+}: {
+ skip: boolean;
+ onSatisfied: () => void;
+}) => {
+ useTokenRefreshUntil(TOKEN_FEATURE, {
+ intervalMs: UNTIL_INTERVAL_MS,
+ skip,
+ onSatisfied,
+ });
+
+ return <div>Test</div>;
+};
+
+const settingsGets = () =>
+ fetchMock.callHistory.calls("path:/api/session/properties").length;
+const tokenRefreshPosts = () =>
+ fetchMock.callHistory.calls("path:/api/premium-features/token/refresh")
+ .length;
+
+const advancePastInterval = async (intervals = 1) => {
+ await act(async () => {
+ jest.advanceTimersByTime(intervals * UNTIL_INTERVAL_MS + 100);
+ });
+};
+
+const setupUntil = ({
+ skip = false,
+ /** Whether the *settings* payload already reports the awaited feature. */
+ hasFeature = false,
+ /** What the token refresh responds with, i.e. whether provisioning landed. */
+ refreshFeatures = [] as TokenStatusFeature[],
+ refreshFails = false,
+}: {
+ skip?: boolean;
+ hasFeature?: boolean;
+ refreshFeatures?: TokenStatusFeature[];
+ refreshFails?: boolean;
+} = {}) => {
+ setupPropertiesEndpoints(
+ createMockSettings({
+ "token-status": createMockTokenStatus({
+ features: hasFeature ? [TOKEN_FEATURE] : [],
+ }),
+ }),
+ );
+
+ setupTokenRefreshEndpoint(
+ refreshFails ? 500 : createMockTokenStatus({ features: refreshFeatures }),
+ );
+
+ const onSatisfied = jest.fn();
+
+ const { rerender } = renderWithProviders(
+ <UntilTestComponent skip={skip} onSatisfied={onSatisfied} />,
+ );
+
+ return {
+ onSatisfied,
+ setSkip: (nextSkip: boolean) =>
+ rerender(
+ <UntilTestComponent skip={nextSkip} onSatisfied={onSatisfied} />,
+ ),
+ };
+};
+
+describe("useTokenRefreshUntil", () => {
+ describe("skip", () => {
+ it("fetches nothing at all while skipped", async () => {
+ // The storage flow mounts this app-wide and skips it until a purchase, so
+ // a skipped hook has to be completely inert.
+ setupUntil({ skip: true });
+
+ await advancePastInterval(3);
+
+ expect(settingsGets()).toBe(0);
+ expect(tokenRefreshPosts()).toBe(0);
+ });
+
+ it("starts polling once it is no longer skipped", async () => {
+ const { setSkip } = setupUntil({ skip: true });
+
+ await advancePastInterval();
+ expect(tokenRefreshPosts()).toBe(0);
+
+ setSkip(false);
+
+ await waitFor(() => {
+ expect(settingsGets()).toBeGreaterThan(0);
+ });
+ await advancePastInterval();
+ expect(tokenRefreshPosts()).toBeGreaterThan(0);
+ });
+ });
+
+ describe("polling", () => {
+ it("keeps refreshing the token while the feature is missing", async () => {
+ setupUntil();
+
+ await advancePastInterval();
+ expect(tokenRefreshPosts()).toBe(1);
+
+ await advancePastInterval();
+ expect(tokenRefreshPosts()).toBeGreaterThan(1);
+ });
+
+ it("does not refresh at all once the token already has the feature", async () => {
+ setupUntil({ hasFeature: true });
+
+ await waitFor(() => {
+ expect(settingsGets()).toBeGreaterThan(0);
+ });
+ await advancePastInterval(3);
+
+ expect(tokenRefreshPosts()).toBe(0);
+ });
+
+ it("invalidates session properties when the refresh request succeeds", async () => {
+ // The mutation's own `invalidatesTags` does this, not the hook. Pinned
+ // because the hook only invalidates itself in the failure case.
+ setupUntil();
+
+ await waitFor(() => {
+ expect(settingsGets()).toBeGreaterThan(0);
+ });
+ const getsBeforeRefresh = settingsGets();
+
+ await advancePastInterval();
+ expect(tokenRefreshPosts()).toBeGreaterThan(0);
+
+ await waitFor(() => {
+ expect(settingsGets()).toBeGreaterThan(getsBeforeRefresh);
+ });
+ });
+
+ it("invalidates session properties even when the refresh request fails", async () => {
+ // The `catch` invalidates so a failed refresh still lets the UI move on.
+ setupUntil({ refreshFails: true });
+
+ await waitFor(() => {
+ expect(settingsGets()).toBeGreaterThan(0);
+ });
+ const getsBeforeRefresh = settingsGets();
+
+ await advancePastInterval();
+ expect(tokenRefreshPosts()).toBeGreaterThan(0);
+
+ // The invalidation's refetch is a fresh request, so it needs retrying.
+ await waitFor(() => {
+ expect(settingsGets()).toBeGreaterThan(getsBeforeRefresh);
+ });
+ });
+ });
+
+ describe("onSatisfied", () => {
+ it("fires once when the refresh reports the awaited feature", async () => {
+ const { onSatisfied } = setupUntil({
+ refreshFeatures: [TOKEN_FEATURE],
+ });
+
+ await advancePastInterval();
+ expect(onSatisfied).toHaveBeenCalledTimes(1);
+
+ // The loop keeps going, but the callback must not fire on every tick.
+ await advancePastInterval(3);
+ expect(onSatisfied).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not fire while the refresh still lacks the feature", async () => {
+ const { onSatisfied } = setupUntil();
+
+ await advancePastInterval(2);
+ expect(tokenRefreshPosts()).toBeGreaterThan(0);
+ expect(onSatisfied).not.toHaveBeenCalled();
+ });
+
+ it("can fire again for a second run after being skipped", async () => {
+ // Skipping resets the guard, so the next purchase gets its callback too.
+ const { onSatisfied, setSkip } = setupUntil({
+ refreshFeatures: [TOKEN_FEATURE],
+ });
+
+ await advancePastInterval();
+ expect(onSatisfied).toHaveBeenCalledTimes(1);
+
+ setSkip(true);
+ await advancePastInterval();
+ setSkip(false);
+
+ await advancePastInterval();
+ await waitFor(() => {
+ expect(onSatisfied).toHaveBeenCalledTimes(2);
+ });
+ });
+ });
+});
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StoragePurchaseButton.tsx b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StoragePurchaseButton.tsx
new file mode 100644
index 00000000000..c28f27a74ac
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StoragePurchaseButton.tsx
@@ -0,0 +1,61 @@
+import type { MouseEvent } from "react";
+import { useMount } from "react-use";
+import { t } from "ttag";
+
+import { ExternalLink } from "metabase/common/components/ExternalLink";
+import { useStoreUrl } from "metabase/common/hooks";
+import { Button } from "metabase/ui";
+
+import { UpsellGem } from "../components/UpsellGem";
+import { trackUpsellClicked, trackUpsellViewed } from "../components/analytics";
+import { useUpsellLink } from "../components/use-upsell-link";
+
+import { useStorageSetup } from "./storage-setup-context";
+
+const CAMPAIGN = "storage";
+
+export const StoragePurchaseButton = ({ location }: { location: string }) => {
+ const { canPurchaseStorage, openPurchaseModal, storageAddOn } =
+ useStorageSetup();
+ const storeUrl = useUpsellLink({
+ url: useStoreUrl("account/storage"),
+ campaign: CAMPAIGN,
+ location,
+ });
+
+ useMount(() => {
+ if (canPurchaseStorage) {
+ trackUpsellViewed({ location, campaign: CAMPAIGN });
+ }
+ });
+
+ if (!canPurchaseStorage) {
+ return null;
+ }
+
+ const props = storageAddOn
+ ? {
+ onClick() {
+ trackUpsellClicked({ location, campaign: CAMPAIGN });
+ openPurchaseModal();
+ },
+ }
+ : {
+ component: ExternalLink,
+ href: storeUrl,
+ // `ExternalLink` stops propagation in the capture phase, killing any
+ // `onClick` we pass. Override its capture handler instead, re-doing the
+ // stopPropagation it would have done.
+ onClickCapture(event: MouseEvent<HTMLElement>) {
+ event.stopPropagation();
+ trackUpsellClicked({ location, campaign: CAMPAIGN });
+ },
+ };
+
+ return (
+ <Button variant="default" leftSection={<UpsellGem />} {...props}>
+ {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Upsell for Metabase Storage, only visible to admins */}
+ {t`Add Metabase Storage`}
+ </Button>
+ );
+};
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StoragePurchaseButton.unit.spec.tsx b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StoragePurchaseButton.unit.spec.tsx
new file mode 100644
index 00000000000..eeecea8460b
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StoragePurchaseButton.unit.spec.tsx
@@ -0,0 +1,124 @@
+import userEvent from "@testing-library/user-event";
+
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import { mockStorageCloudAddOn } from "metabase-types/api/mocks/add-ons";
+
+import { StoragePurchaseButton } from "./StoragePurchaseButton";
+import {
+ StorageSetupContext,
+ type StorageSetupContextValue,
+} from "./storage-setup-context";
+
+// `metabase/analytics` is auto-mocked for every test (see `__support__/mocks`).
+// Reached via requireMock because the lint rule forbids importing
+// `trackSchemaEvent` outside analytics files.
+const { trackSchemaEvent: mockTrackSchemaEvent } = jest.requireMock<{
+ trackSchemaEvent: jest.Mock;
+}>("metabase/analytics");
+
+const LOCATION = "add-data-modal-csv";
+const STORE_URL = "https://store.metabase.com";
+
+/**
+ * The button is a leaf that reads nothing but `useStorageSetup`, so the context
+ * is supplied directly. That keeps every case reachable — including ones the
+ * real provider only reaches mid-flight, like an offer with no add-on yet.
+ */
+const setup = ({
+ canPurchaseStorage = true,
+ hasAddOn = true,
+}: { canPurchaseStorage?: boolean; hasAddOn?: boolean } = {}) => {
+ const openPurchaseModal = jest.fn();
+
+ const value: StorageSetupContextValue = {
+ isSettingUp: false,
+ hasSetupFailed: false,
+ storageAddOn: hasAddOn ? mockStorageCloudAddOn : undefined,
+ isLoadingStorageAddOn: false,
+ isPurchaseModalOpened: false,
+ openPurchaseModal,
+ canPurchaseStorage,
+ };
+
+ renderWithProviders(
+ <StorageSetupContext.Provider value={value}>
+ <StoragePurchaseButton location={LOCATION} />
+ </StorageSetupContext.Provider>,
+ {
+ storeInitialState: createMockState({
+ settings: mockSettings({ "store-url": STORE_URL }),
+ }),
+ },
+ );
+
+ return { openPurchaseModal };
+};
+
+const getUpsellEvents = (event: string) =>
+ mockTrackSchemaEvent.mock.calls.filter(
+ ([schema, data]) => schema === "upsell" && data?.event === event,
+ );
+
+describe("StoragePurchaseButton", () => {
+ beforeEach(() => {
+ mockTrackSchemaEvent.mockClear();
+ });
+
+ it("renders nothing, and reports no view, to someone who cannot buy storage", () => {
+ setup({ canPurchaseStorage: false });
+
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("link", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ // An upsell nobody was shown must not be counted as viewed.
+ expect(getUpsellEvents("upsell_viewed")).toHaveLength(0);
+ });
+
+ it("reports the view once, tagged with its campaign and location", () => {
+ setup();
+
+ const viewed = getUpsellEvents("upsell_viewed");
+ expect(viewed).toHaveLength(1);
+ expect(viewed[0][1]).toMatchObject({
+ promoted_feature: "storage",
+ upsell_location: LOCATION,
+ });
+ });
+
+ it("opens the purchase modal, and reports the click, when the add-on is purchasable in-app", async () => {
+ const { openPurchaseModal } = setup();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: /Add Metabase Storage/ }),
+ );
+
+ expect(openPurchaseModal).toHaveBeenCalledTimes(1);
+ const clicked = getUpsellEvents("upsell_clicked");
+ expect(clicked).toHaveLength(1);
+ expect(clicked[0][1]).toMatchObject({
+ promoted_feature: "storage",
+ upsell_location: LOCATION,
+ });
+ });
+
+ it("links out to the store, and still reports the click, without a purchasable add-on", async () => {
+ const { openPurchaseModal } = setup({ hasAddOn: false });
+
+ const link = screen.getByRole("link", { name: /Add Metabase Storage/ });
+ const href = new URL(link.getAttribute("href") ?? "");
+ expect(href.origin + href.pathname).toBe(`${STORE_URL}/account/storage`);
+ expect(href.searchParams.get("utm_campaign")).toBe("storage");
+ expect(href.searchParams.get("utm_content")).toBe(LOCATION);
+
+ await userEvent.click(link);
+
+ expect(getUpsellEvents("upsell_clicked")).toHaveLength(1);
+ // Nothing to confirm, so no modal on top of the navigation.
+ expect(openPurchaseModal).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupErrorView.tsx b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupErrorView.tsx
new file mode 100644
index 00000000000..9a22bbd8eec
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupErrorView.tsx
@@ -0,0 +1,28 @@
+import { c, t } from "ttag";
+
+import { ExternalLink } from "metabase/common/components/ExternalLink";
+import { useHelpLink } from "metabase/nav/components/AppSwitcher/useHelpLink";
+import { Icon } from "metabase/ui";
+
+import { StorageSetupStatusView } from "./StorageSetupStatusView";
+
+export const StorageSetupErrorView = () => {
+ const { href } = useHelpLink();
+
+ const supportLink = (
+ <ExternalLink key="support" href={href}>
+ {t`contact support`}
+ </ExternalLink>
+ );
+
+ const description = c("{0} is a 'contact support' link")
+ .jt`Refresh the page after 1-2 minutes or ${supportLink} if the issue persists.`;
+
+ return (
+ <StorageSetupStatusView
+ badge={<Icon name="warning_triangle_filled" size={12} color="warning" />}
+ title={t`Storage setup didn't finish`}
+ description={description}
+ />
+ );
+};
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupStatusView.tsx b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupStatusView.tsx
new file mode 100644
index 00000000000..8082033c2b1
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupStatusView.tsx
@@ -0,0 +1,54 @@
+import type { ReactNode } from "react";
+
+import { Box, Flex, Stack, Text, Title } from "metabase/ui";
+
+import databaseAdd from "./database-add.svg?component";
+
+interface StorageSetupStatusViewProps {
+ /** Rendered inside the circular badge overlaying the illustration. */
+ badge: ReactNode;
+ title: string;
+ description: ReactNode;
+}
+
+export const StorageSetupStatusView = ({
+ badge,
+ title,
+ description,
+}: StorageSetupStatusViewProps) => (
+ <Stack pt="40" align="center" gap="lg">
+ <Box h={96} pos="relative" w={96}>
+ <Box component={databaseAdd} />
+
+ <Flex
+ bottom={0}
+ align="center"
+ direction="row"
+ gap={0}
+ justify="center"
+ pos="absolute"
+ right={0}
+ wrap="nowrap"
+ bg="white"
+ fz={0}
+ p="sm"
+ ta="center"
+ style={{
+ borderRadius: "100%",
+ boxShadow: `0 1px 6px 0 var(--mb-color-shadow)`,
+ }}
+ >
+ {badge}
+ </Flex>
+ </Box>
+
+ <Box ta="center">
+ <Title c="text-primary" fz="lg">
+ {title}
+ </Title>
+ <Text c="text-secondary" fz="md" lh={1.43}>
+ {description}
+ </Text>
+ </Box>
+ </Stack>
+);
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupView.tsx b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupView.tsx
new file mode 100644
index 00000000000..b2dce31d6fc
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupView.tsx
@@ -0,0 +1,13 @@
+import { t } from "ttag";
+
+import { Loader } from "metabase/ui";
+
+import { StorageSetupStatusView } from "./StorageSetupStatusView";
+
+export const StorageSetupView = () => (
+ <StorageSetupStatusView
+ badge={<Loader size="xs" ml={1} mt={1} />}
+ title={t`Setting up storage`}
+ description={t`This can take a few minutes.`}
+ />
+);
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/database-add.svg b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/database-add.svg
new file mode 100644
index 00000000000..cc32f3fcf1f
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/database-add.svg
@@ -0,0 +1,10 @@
+<svg width="96" height="96" viewBox="0 0 96 96" fill="none" xmlns="http://www.w3.org/2000/svg">
+<rect width="96" height="96" rx="48" fill="#F3F3F4"/>
+<path d="M48 63C54.6274 63 60 61.9152 60 60.5769V54.5C60 53.3954 59.1046 52.5 58 52.5H38C36.8954 52.5 36 53.3954 36 54.5V60.5769C36 61.9152 41.3726 63 48 63Z" fill="white" stroke="#92999E" stroke-width="1.25"/>
+<path d="M48 54C54.6274 54 60 52.9152 60 51.5769V45.5C60 44.3954 59.1046 43.5 58 43.5H38C36.8954 43.5 36 44.3954 36 45.5V51.5769C36 52.9152 41.3726 54 48 54Z" fill="white" stroke="#92999E" stroke-width="1.25"/>
+<path d="M48 45C54.6274 45 60 43.9152 60 42.5769V34.65C60 34.5672 59.9328 34.5 59.85 34.5H36.15C36.0672 34.5 36 34.5672 36 34.65V42.5769C36 43.9152 41.3726 45 48 45Z" fill="white" stroke="#92999E" stroke-width="1.25"/>
+<ellipse cx="48" cy="34.5" rx="12" ry="1.5" fill="white" stroke="#92999E" stroke-width="1.25"/>
+<circle cx="60" cy="57" r="10" fill="#74A73C"/>
+<path d="M56 57H64" stroke="white" stroke-width="1.25" stroke-linecap="round"/>
+<path d="M60 53L60 61" stroke="white" stroke-width="1.25" stroke-linecap="round"/>
+</svg>
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/index.ts b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/index.ts
new file mode 100644
index 00000000000..c30c2c8dd22
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/index.ts
@@ -0,0 +1,10 @@
+export {
+ StorageSetupContext,
+ StorageSetupProvider,
+ useStorageSetup,
+ type StorageSetupContextValue,
+ type StorageSetupProviderProps,
+} from "./storage-setup-context";
+export { StorageSetupView } from "./StorageSetupView";
+export { StorageSetupErrorView } from "./StorageSetupErrorView";
+export { StoragePurchaseButton } from "./StoragePurchaseButton";
diff --git a/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/storage-setup-context.tsx b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/storage-setup-context.tsx
new file mode 100644
index 00000000000..48fb718138a
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/storage-setup-context.tsx
@@ -0,0 +1,66 @@
+import type { ReactNode } from "react";
+import { createContext, useContext } from "react";
+
+import type { ICloudAddOnProduct } from "metabase-types/api";
+
+export interface StorageSetupContextValue {
+ /** This admin bought storage in this tab and it has not shown up yet. */
+ isSettingUp: boolean;
+ /** Setup ran past its deadline; the panels offer a way out instead of spinning. */
+ hasSetupFailed: boolean;
+ storageAddOn: ICloudAddOnProduct | undefined;
+ isLoadingStorageAddOn: boolean;
+ isPurchaseModalOpened: boolean;
+ openPurchaseModal: () => void;
+ /**
+ * A hosted admin without the `attached_dwh` token. The token flips at purchase
+ * time, so a reload mid-setup can't re-offer storage they already bought.
+ */
+ canPurchaseStorage: boolean;
+}
+
+// Whether the instance *has* storage is deliberately absent: consumers read it
+// from `useAttachedDwh`, since this context is inert in OSS and would answer
+// `false` there.
+
+export const StorageSetupContext =
+ createContext<StorageSetupContextValue | null>(null);
+
+export interface StorageSetupProviderProps {
+ children: ReactNode;
+ /**
+ * Pass `false` while the hosting UI is hidden to skip the add-ons Store
+ * round-trip. Purchase state and its polling keep running regardless.
+ */
+ enabled?: boolean;
+}
+
+const INERT_STORAGE_SETUP_VALUE: StorageSetupContextValue = {
+ isSettingUp: false,
+ hasSetupFailed: false,
+ storageAddOn: undefined,
+ isLoadingStorageAddOn: false,
+ isPurchaseModalOpened: false,
+ openPurchaseModal: () => {},
+ canPurchaseStorage: false,
+};
+
+export const StorageSetupProvider = ({
+ children,
+}: StorageSetupProviderProps) => (
+ <StorageSetupContext.Provider value={INERT_STORAGE_SETUP_VALUE}>
+ {children}
+ </StorageSetupContext.Provider>
+);
+
+export const useStorageSetup = (): StorageSetupContextValue => {
+ const context = useContext(StorageSetupContext);
+
+ if (!context) {
+ throw new Error(
+ "useStorageSetup must be used within a StorageSetupProvider",
+ );
+ }
+
+ return context;
+};
diff --git a/frontend/src/metabase/common/components/upsells/UpsellStorage.tsx b/frontend/src/metabase/common/components/upsells/UpsellStorage.tsx
deleted file mode 100644
index 25fa081cecc..00000000000
--- a/frontend/src/metabase/common/components/upsells/UpsellStorage.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { t } from "ttag";
-
-import {
- useHasTokenFeature,
- useSetting,
- useStoreUrl,
-} from "metabase/common/hooks";
-import { List } from "metabase/ui";
-
-import { UpsellBanner } from "./components";
-
-export const UpsellStorage = ({ location }: { location: string }) => {
- const campaign = "storage";
- /**
- * @link https://linear.app/metabase/issue/CLO-4190/create-url-for-buy-storage-page-without-purchase-id
- */
- const storeUrl = useStoreUrl("account/storage");
-
- const isHosted = useSetting("is-hosted?");
- const hasStorage = useHasTokenFeature("attached_dwh");
-
- if (!isHosted || hasStorage || storeUrl === undefined) {
- return null;
- }
-
- return (
- <UpsellBanner
- campaign={campaign}
- buttonText={t`Add`}
- buttonLink={storeUrl}
- location={location}
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- Upsell for Metabase Storage, only visible to admins
- title={t`Add Metabase Storage`}
- large
- >
- <List
- mt="xs"
- withPadding
- size="sm"
- styles={{ root: { paddingInlineStart: "var(--mantine-spacing-sm)" } }}
- >
- {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Upsell for Metabase Storage, only visible to admins */}
- <List.Item>{t`Secure, fully managed by Metabase`}</List.Item>
- <List.Item>{t`Upload CSV files`}</List.Item>
- <List.Item>{t`Sync with Google Sheets`}</List.Item>
- </List>
- </UpsellBanner>
- );
-};
diff --git a/frontend/src/metabase/common/hooks/index.ts b/frontend/src/metabase/common/hooks/index.ts
index de81bc88a7c..1ae8abf28ae 100644
--- a/frontend/src/metabase/common/hooks/index.ts
+++ b/frontend/src/metabase/common/hooks/index.ts
@@ -1,4 +1,5 @@
export * from "./entity-framework";
+export * from "./use-attached-dwh";
export * from "./use-abortable-query";
export * from "./use-confirmation";
export * from "./use-dnd-sensors";
diff --git a/frontend/src/metabase/common/hooks/use-attached-dwh.ts b/frontend/src/metabase/common/hooks/use-attached-dwh.ts
new file mode 100644
index 00000000000..b62457ba6d4
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-attached-dwh.ts
@@ -0,0 +1,39 @@
+import { useMemo } from "react";
+
+import { useListDatabasesQuery } from "metabase/api";
+import type { Database } from "metabase-types/api";
+
+export interface AttachedDwhInfo {
+ /** Storage exists on this instance. */
+ hasAttachedDwh: boolean;
+}
+
+export interface AttachedDwhState extends AttachedDwhInfo {
+ /** While true, the flag above reads `false` because nothing was fetched yet. */
+ areDatabasesLoading: boolean;
+}
+
+export const getHasAttachedDwh = (databases: Database[] | undefined) =>
+ !!databases?.some((db) => db.is_attached_dwh);
+
+/**
+ * Whether this instance has Metabase Storage, derived from the databases list.
+ *
+ * Deliberately ungated on admin/hosted: non-admins such as settings managers
+ * also need the answer, and the databases list is already fetched on every page.
+ */
+export function useAttachedDwh(): AttachedDwhState {
+ const { data: databasesResponse, isLoading: areDatabasesLoading } =
+ useListDatabasesQuery();
+ const databases = databasesResponse?.data;
+
+ // Mounted in always-present spots and re-run on every poll tick while storage
+ // provisions, so keep the scan off the render path (as `useAddDataState` does).
+ return useMemo(
+ () => ({
+ hasAttachedDwh: getHasAttachedDwh(databases),
+ areDatabasesLoading,
+ }),
+ [databases, areDatabasesLoading],
+ );
+}
diff --git a/frontend/src/metabase/common/hooks/use-attached-dwh.unit.spec.ts b/frontend/src/metabase/common/hooks/use-attached-dwh.unit.spec.ts
new file mode 100644
index 00000000000..70f7bc1cd70
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-attached-dwh.unit.spec.ts
@@ -0,0 +1,49 @@
+import fetchMock from "fetch-mock";
+
+import { setupDatabaseListEndpoint } from "__support__/server-mocks";
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import { createMockDatabase, createMockUser } from "metabase-types/api/mocks";
+
+import { useAttachedDwh } from "./use-attached-dwh";
+
+function setup({
+ hasAttachedDwhDatabase = true,
+ isAdmin = false,
+}: {
+ hasAttachedDwhDatabase?: boolean;
+ isAdmin?: boolean;
+} = {}) {
+ setupDatabaseListEndpoint(
+ hasAttachedDwhDatabase
+ ? [createMockDatabase({ id: 1, is_attached_dwh: true })]
+ : [],
+ );
+
+ return renderHookWithProviders(() => useAttachedDwh(), {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: isAdmin }),
+ }),
+ });
+}
+
+describe("useAttachedDwh", () => {
+ it("reports storage for a non-admin", async () => {
+ // This used to come from a query skipped for anyone who couldn't buy
+ // storage, so non-admins saw an instance with storage as one without.
+ const { result } = setup({ isAdmin: false });
+
+ await waitFor(() => {
+ expect(result.current.hasAttachedDwh).toBe(true);
+ });
+ });
+
+ it("reports no storage when the databases list has no attached DWH", async () => {
+ const { result } = setup({ hasAttachedDwhDatabase: false });
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("path:/api/database")).toBe(true);
+ });
+ expect(result.current.hasAttachedDwh).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/AddDataModal.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/AddDataModal.tsx
index 67adcdc2f52..220f406b274 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/AddDataModal.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/AddDataModal.tsx
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { t } from "ttag";
-import { useListDatabasesQuery } from "metabase/api";
+import { useStorageSetup } from "metabase/common/components/upsells/StoragePurchaseModal";
import { useSetting } from "metabase/common/hooks";
import CS from "metabase/css/core/index.css";
import { PLUGIN_UPLOAD_MANAGEMENT } from "metabase/plugins";
@@ -13,12 +13,8 @@ import { CSVPanel } from "./Panels/CSVPanel";
import { DatabasesPanel } from "./Panels/DatabasesPanel";
import { PanelsHeader } from "./Panels/PanelsHeader";
import { trackAddDataEvent } from "./analytics";
-import { useAddDataPermissions } from "./use-add-data-permission";
-import {
- type AddDataTab,
- hasMeaningfulUploadableDatabases,
- isValidTab,
-} from "./utils";
+import { useAddDataState } from "./use-add-data-state";
+import { type AddDataTab, isValidTab } from "./utils";
interface AddDataModalProps {
opened: boolean;
@@ -30,83 +26,90 @@ interface AddDataModalProps {
interface Tabs {
name: string;
- value: "csv" | "db" | "gsheets";
- isVisible: boolean;
+ value: AddDataTab;
iconName: IconName;
}
-export const AddDataModal = ({
+const DEFAULT_TAB = "db" satisfies AddDataTab;
+
+const EVENT_MAPPING = {
+ db: "database_tab_clicked",
+ csv: "csv_tab_clicked",
+ gsheets: "sheets_tab_clicked",
+} as const satisfies Record<AddDataTab, string>;
+
+export const AddDataModal = (props: AddDataModalProps) => (
+ // Outside `Modal.Root` so setup state and its polling survive the modal
+ // closing, and so the purchase modal it hosts replaces this one rather than
+ // stacking. `enabled` defers the add-ons fetch until the modal is shown.
+ <PLUGIN_UPLOAD_MANAGEMENT.StorageSetupProvider enabled={props.opened}>
+ <AddDataModalContent {...props} />
+ </PLUGIN_UPLOAD_MANAGEMENT.StorageSetupProvider>
+);
+
+const AddDataModalContent = ({
opened,
onClose,
initialTab,
fromEmbeddingSetupGuide,
}: AddDataModalProps) => {
- const { areUploadsEnabled, canUploadToDatabase, canManageUploads, isAdmin } =
- useAddDataPermissions();
+ const { areUploadsEnabled, canManageUploads, isAdmin, hasAttachedDwh } =
+ useAddDataState();
+ const { isPurchaseModalOpened } = useStorageSetup();
- const { data: databasesResponse } = useListDatabasesQuery();
- const { data: uploadableDatabasesResponse } = useListDatabasesQuery({
- include_only_uploadable: true,
- });
-
- const hasUploadableDatabases = hasMeaningfulUploadableDatabases({
- allDatabases: databasesResponse?.data,
- allUploadableDatabases: uploadableDatabasesResponse?.data,
- });
+ const [activeTab, setActiveTab] = useState<AddDataTab | null>(null);
+ const isHosted = useSetting("is-hosted?");
- const shouldShowUploadsPanel = hasUploadableDatabases || canUploadToDatabase;
+ // Both CSV and Google Sheets stay visible even when the panel can only say
+ // "contact an admin" — the tabs advertise what Metabase can do. Google Sheets
+ // is conditional only on the instance being hosted.
+ const tabs = useMemo(() => {
+ const result: Tabs[] = [
+ {
+ name: t`Database`,
+ value: "db",
+ iconName: "database",
+ },
+ {
+ name: t`CSV`,
+ value: "csv",
+ iconName: "table2",
+ },
+ ] satisfies Tabs[];
- const [activeTab, setActiveTab] = useState<Tabs["value"] | null>(null);
+ if (isHosted) {
+ result.push({
+ name: t`Google Sheets`,
+ value: "gsheets",
+ iconName: "document",
+ } satisfies Tabs);
+ }
- const isHosted = useSetting("is-hosted?");
+ return result;
+ }, [isHosted]);
const handleTabChange = (tabValue: string | null) => {
if (tabValue === activeTab || !isValidTab(tabValue)) {
return;
}
- const eventMapping = {
- db: "database_tab_clicked",
- csv: "csv_tab_clicked",
- gsheets: "sheets_tab_clicked",
- } as const satisfies Record<AddDataTab, string>;
+ trackAddDataEvent(EVENT_MAPPING[tabValue]);
- trackAddDataEvent(eventMapping[tabValue]);
setActiveTab(tabValue);
};
- const tabs = useMemo(() => {
- return [
- { name: t`Database`, value: "db", isVisible: true, iconName: "database" },
- {
- name: t`CSV`,
- value: "csv",
- isVisible: shouldShowUploadsPanel,
- iconName: "table2",
- },
- {
- name: t`Google Sheets`,
- value: "gsheets",
- isVisible: isHosted,
- iconName: "document",
- },
- ] satisfies Tabs[];
- }, [shouldShowUploadsPanel, isHosted]);
-
useEffect(() => {
- if (initialTab) {
- setActiveTab(initialTab);
- } else {
- const firstVisibleTab = tabs.find((tab) => tab.isVisible);
-
- if (firstVisibleTab) {
- setActiveTab(firstVisibleTab.value);
- }
- }
- }, [tabs, initialTab]);
+ setActiveTab(initialTab ?? DEFAULT_TAB);
+ }, [initialTab]);
return (
- <Modal.Root opened={opened} onClose={onClose} size="auto">
+ // Hides itself, but stays mounted, while the purchase confirmation is up,
+ // so the confirmation replaces it instead of stacking on top of it.
+ <Modal.Root
+ opened={opened && !isPurchaseModalOpened}
+ onClose={onClose}
+ size="auto"
+ >
<Modal.Overlay />
<Modal.Content h="30rem">
<Tabs
@@ -126,40 +129,37 @@ export const AddDataModal = ({
<Modal.Title fz="lg">{t`Add data`}</Modal.Title>
</Box>
<Tabs.List px="md" pb="lg">
- {tabs
- .filter((tab) => tab.isVisible)
- .map((tab) => (
- <Tabs.Tab
- key={tab.value}
- value={tab.value}
- leftSection={<Icon name={tab.iconName} />}
- >
- {tab.name}
- </Tabs.Tab>
- ))}
+ {tabs.map((tab) => (
+ <Tabs.Tab
+ key={tab.value}
+ value={tab.value}
+ leftSection={<Icon name={tab.iconName} />}
+ >
+ {tab.name}
+ </Tabs.Tab>
+ ))}
</Tabs.List>
</Box>
<Box component="main" w="30rem" className={S.panelContainer}>
<PanelsHeader
showDatabasesLink={activeTab === "db" && isAdmin}
- showUploadsLink={activeTab === "csv" && canManageUploads}
- showManageImports={activeTab === "gsheets" && isAdmin}
+ showUploadsLink={
+ activeTab === "csv" && canManageUploads && areUploadsEnabled
+ }
+ showManageImports={
+ activeTab === "gsheets" && isAdmin && hasAttachedDwh
+ }
onAddDataModalClose={onClose}
/>
- <Tabs.Panel value="csv" className={S.panel}>
- <CSVPanel
- onCloseAddDataModal={onClose}
- uploadsEnabled={areUploadsEnabled}
- canUpload={canUploadToDatabase}
- canManageUploads={canManageUploads}
- />
- </Tabs.Panel>
<Tabs.Panel value="db" className={S.panel}>
<DatabasesPanel
canSeeContent={isAdmin}
fromEmbeddingSetupGuide={fromEmbeddingSetupGuide}
/>
</Tabs.Panel>
+ <Tabs.Panel value="csv" className={S.panel}>
+ <CSVPanel onCloseAddDataModal={onClose} />
+ </Tabs.Panel>
<Tabs.Panel value="gsheets" className={S.panel}>
<PLUGIN_UPLOAD_MANAGEMENT.GdriveAddDataPanel
onAddDataModalClose={onClose}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/AddDataModalEmptyStates.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/AddDataModalEmptyStates.tsx
index cf9b8a507e1..2348bad3d56 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/AddDataModalEmptyStates.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/AddDataModalEmptyStates.tsx
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import { match } from "ts-pattern";
import { c, t } from "ttag";
+import { StoragePurchaseButton } from "metabase/common/components/upsells/StoragePurchaseModal";
import { useSelector } from "metabase/redux";
import { Link } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
@@ -10,11 +11,12 @@ import {
Box,
Button,
Center,
+ Group,
Icon,
+ Loader,
Stack,
Text,
Title,
- Tooltip,
} from "metabase/ui";
import { getSubpathSafeUrl } from "metabase/urls";
@@ -23,6 +25,13 @@ import IconCSV from "./illustrations/csv.svg?component";
export const CONTENT_MAX_WIDTH = "22.5rem";
export const INNER_WIDTH = "12.5rem";
+/** Shared by both tabs so their loading states can't drift apart visually. */
+export const PanelLoadingState = () => (
+ <Center h="100%">
+ <Loader data-testid="loading-indicator" />
+ </Center>
+);
+
type ContactReason =
| "add-database"
| "enable-csv-upload"
@@ -112,7 +121,7 @@ interface EmptyStateProps {
illustration: ReactNode;
ctaLink?: CTALink;
contactAdminReason?: ContactReason;
- upsell?: ReactNode;
+ secondaryAction?: ReactNode;
}
const AddDataEmptyState = ({
@@ -121,7 +130,7 @@ const AddDataEmptyState = ({
illustration,
ctaLink,
contactAdminReason,
- upsell,
+ secondaryAction,
}: EmptyStateProps) => {
return (
<Stack gap="lg" align="center" justify="center" pt="2.5rem">
@@ -133,17 +142,19 @@ const AddDataEmptyState = ({
<Text c="text-secondary">{subtitle}</Text>
</Box>
{ctaLink && (
- <Button
- variant="filled"
- w={INNER_WIDTH}
- component={Link}
- to={ctaLink.to}
- >
- {ctaLink.text}
- </Button>
+ <Group gap="sm" justify="center">
+ <Button
+ variant="filled"
+ w={secondaryAction ? undefined : INNER_WIDTH}
+ component={Link}
+ to={ctaLink.to}
+ >
+ {ctaLink.text}
+ </Button>
+ {secondaryAction}
+ </Group>
)}
{contactAdminReason && <ContactAdminAlert reason={contactAdminReason} />}
- {upsell}
</Stack>
);
};
@@ -163,38 +174,44 @@ export const DatabasePanelEmptyState = () => {
);
};
+const CSVIllustration = () => <Box component={IconCSV} c="core-brand" h={48} />;
+
+/**
+ * Shared by the CSV and Sheets panels: the instance is entitled to storage (the
+ * `attached_dwh` token is present) but the DWH database has not shown up yet —
+ * either it is still provisioning, or the token runs ahead of the data. A reload
+ * re-fetches the databases list, so pointing at a refresh is the honest hint.
+ */
+export const getStorageNotProvisionedSubtitle = () =>
+ t`You don't have storage provisioned yet. Refresh this page after 1-2 minutes.`;
+
+export const CSVStorageNotProvisionedEmptyState = () => (
+ <AddDataEmptyState
+ title={t`Upload CSV files`}
+ subtitle={getStorageNotProvisionedSubtitle()}
+ illustration={<CSVIllustration />}
+ />
+);
+
export const CSVPanelEmptyState = ({
ctaLink,
contactAdminReason,
- upsell,
+ canOfferStorage,
}:
| {
ctaLink: CTALink;
contactAdminReason?: never;
- upsell?: ReactNode;
+ canOfferStorage?: boolean;
}
| {
ctaLink?: never;
contactAdminReason: ContactReason;
- upsell?: never;
+ canOfferStorage?: never;
}) => {
- const text = (
- <Text component="span" td="underline">{c(
- "in the sentence 'To work with CSVs, enable file uploads in your database.'",
- ).t`your database`}</Text>
- );
- const ctaSubtitle = c("{0} refers to the string 'your database'")
- .jt`To work with CSVs, enable file uploads in ${(
- <Tooltip
- inline
- maw={INNER_WIDTH}
- multiline
- label={t`PostgreSQL, MySQL, Redshift, and ClickHouse databases are supported for file storage.`}
- key="database-tooltip"
- >
- {text}
- </Tooltip>
- )}.`;
+ const ctaSubtitle = canOfferStorage
+ ? // eslint-disable-next-line metabase/no-literal-metabase-strings -- Upsell for Metabase Storage, only visible to admins
+ t`To work with CSVs, either enable file uploads in your database, or add Metabase Storage.`
+ : t`To work with CSVs, enable file uploads in your database.`;
const subtitle = ctaLink
? ctaSubtitle
@@ -204,10 +221,14 @@ export const CSVPanelEmptyState = ({
<AddDataEmptyState
title={t`Upload CSV files`}
subtitle={subtitle}
- illustration={<Box component={IconCSV} c="core-brand" h={66} />}
+ illustration={<CSVIllustration />}
contactAdminReason={contactAdminReason}
ctaLink={ctaLink}
- upsell={upsell}
+ secondaryAction={
+ canOfferStorage ? (
+ <StoragePurchaseButton location="add-data-modal-csv" />
+ ) : undefined
+ }
/>
);
};
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVPanel.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVPanel.tsx
index c3199a6ac66..70983ca3ff5 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVPanel.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVPanel.tsx
@@ -1,50 +1,52 @@
+import { match } from "ts-pattern";
import { t } from "ttag";
-import { UpsellStorage } from "metabase/common/components/upsells/UpsellStorage";
+import {
+ StorageSetupErrorView,
+ StorageSetupView,
+} from "metabase/common/components/upsells/StoragePurchaseModal";
import * as Urls from "metabase/urls";
-import { CSVPanelEmptyState } from "./AddDataModalEmptyStates";
+import { useCsvPanelState } from "../csv-panel-state";
+
+import {
+ CSVPanelEmptyState,
+ CSVStorageNotProvisionedEmptyState,
+ PanelLoadingState,
+} from "./AddDataModalEmptyStates";
import { CSVUpload } from "./CSVUpload";
interface CSVPanelProps {
- canUpload: boolean;
- canManageUploads: boolean;
onCloseAddDataModal: () => void;
- uploadsEnabled: boolean;
}
-export const CSVPanel = ({
- canUpload,
- canManageUploads,
- onCloseAddDataModal,
- uploadsEnabled,
-}: CSVPanelProps) => {
- const showObtainPermissionPrompt = uploadsEnabled && !canUpload;
-
- const showEnableUploadsCTA = !uploadsEnabled && canManageUploads;
- const showEnableUploadsPrompt = !uploadsEnabled && !canManageUploads;
-
- if (showEnableUploadsPrompt) {
- return <CSVPanelEmptyState contactAdminReason="enable-csv-upload" />;
- }
-
- if (showObtainPermissionPrompt) {
- return (
+export const CSVPanel = ({ onCloseAddDataModal }: CSVPanelProps) => {
+ const state = useCsvPanelState();
+
+ return match(state)
+ .with({ type: "loading" }, () => <PanelLoadingState />)
+ .with({ type: "provisioning-storage" }, () => <StorageSetupView />)
+ .with({ type: "storage-setup-failed" }, () => <StorageSetupErrorView />)
+ .with({ type: "storage-not-provisioned" }, () => (
+ <CSVStorageNotProvisionedEmptyState />
+ ))
+ .with({ type: "ask-admin" }, () => (
+ <CSVPanelEmptyState contactAdminReason="enable-csv-upload" />
+ ))
+ .with({ type: "no-upload-permission" }, () => (
<CSVPanelEmptyState contactAdminReason="obtain-csv-upload-permission" />
- );
- }
-
- if (showEnableUploadsCTA) {
- return (
+ ))
+ .with({ type: "needs-uploads-setup" }, ({ canOfferStorage }) => (
<CSVPanelEmptyState
ctaLink={{
text: t`Enable uploads`,
to: Urls.uploadsSettings(),
}}
- upsell={<UpsellStorage location="add-data-modal-csv" />}
+ canOfferStorage={canOfferStorage}
/>
- );
- }
-
- return <CSVUpload onCloseAddDataModal={onCloseAddDataModal} />;
+ ))
+ .with({ type: "ready" }, () => (
+ <CSVUpload onCloseAddDataModal={onCloseAddDataModal} />
+ ))
+ .exhaustive();
};
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/csv-panel-state.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/csv-panel-state.ts
new file mode 100644
index 00000000000..2640a05d8f6
--- /dev/null
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/csv-panel-state.ts
@@ -0,0 +1,127 @@
+import { useStorageSetup } from "metabase/common/components/upsells/StoragePurchaseModal";
+import { useHasTokenFeature } from "metabase/common/hooks";
+
+import { useAddDataState } from "./use-add-data-state";
+
+/**
+ * Everything the CSV panel can show, as one value. These cases overlap heavily,
+ * so their precedence lives in one pure function rather than in independent
+ * booleans that can contradict each other.
+ */
+export type CsvPanelState =
+ | { type: "loading" }
+ | { type: "provisioning-storage" }
+ | { type: "storage-setup-failed" }
+ | { type: "storage-not-provisioned" }
+ | { type: "ask-admin" }
+ | { type: "no-upload-permission" }
+ | { type: "needs-uploads-setup"; canOfferStorage: boolean }
+ | { type: "ready" };
+
+export interface CsvPanelStateInput {
+ areDatabasesLoading: boolean;
+ areUploadsEnabled: boolean;
+ canUploadToDatabase: boolean;
+ canManageUploads: boolean;
+ isSettingUp: boolean;
+ hasSetupFailed: boolean;
+ isLoadingStorageAddOn: boolean;
+ hasAttachedDwh: boolean;
+ hasStorageTokenFeature: boolean;
+ canPurchaseStorage: boolean;
+}
+
+export function getCsvPanelState({
+ areDatabasesLoading,
+ areUploadsEnabled,
+ canUploadToDatabase,
+ canManageUploads,
+ isSettingUp,
+ hasSetupFailed,
+ isLoadingStorageAddOn,
+ hasAttachedDwh,
+ hasStorageTokenFeature,
+ canPurchaseStorage,
+}: CsvPanelStateInput): CsvPanelState {
+ // Before the list arrives, "cannot upload anywhere" is indistinguishable from
+ // "not fetched yet", and guessing shows an answer that then flips.
+ if (areDatabasesLoading) {
+ return { type: "loading" };
+ }
+
+ // A working uploader outranks anything storage is doing — an in-flight
+ // purchase must not take the uploader away for the minutes it takes to land.
+ if (areUploadsEnabled && canUploadToDatabase) {
+ return { type: "ready" };
+ }
+
+ if (isSettingUp) {
+ return { type: "provisioning-storage" };
+ }
+
+ if (hasSetupFailed) {
+ return { type: "storage-setup-failed" };
+ }
+
+ if (!areUploadsEnabled) {
+ if (!canManageUploads) {
+ return { type: "ask-admin" };
+ }
+
+ if (isLoadingStorageAddOn) {
+ return { type: "loading" };
+ }
+
+ // Entitled to storage but the DWH database has not appeared yet (still
+ // provisioning, or a token that runs ahead of the data). "Enable uploads"
+ // would be a dead end, so point at a refresh instead.
+ if (hasStorageTokenFeature && !hasAttachedDwh) {
+ return { type: "storage-not-provisioned" };
+ }
+
+ return {
+ type: "needs-uploads-setup",
+ canOfferStorage: canPurchaseStorage && !hasAttachedDwh,
+ };
+ }
+
+ // Uploads are enabled and the "ready" case above did not fire, so the upload
+ // target exists but this user may not write to it.
+ return { type: "no-upload-permission" };
+}
+
+/**
+ * Gathered where the panel is rendered rather than threaded down from the
+ * modal, the same way the Sheets panel does it.
+ */
+export function useCsvPanelState(): CsvPanelState {
+ const {
+ areDatabasesLoading,
+ areUploadsEnabled,
+ canUploadToDatabase,
+ canManageUploads,
+ hasAttachedDwh,
+ } = useAddDataState();
+ const {
+ isSettingUp,
+ hasSetupFailed,
+ isLoadingStorageAddOn,
+ canPurchaseStorage,
+ } = useStorageSetup();
+ const hasStorageTokenFeature = useHasTokenFeature("attached_dwh");
+
+ // Listed field by field rather than spread: both hooks carry extra keys, and
+ // a spread would let a rename here silently bind to the wrong hook's key.
+ return getCsvPanelState({
+ areDatabasesLoading,
+ areUploadsEnabled,
+ canUploadToDatabase,
+ canManageUploads,
+ hasAttachedDwh,
+ hasStorageTokenFeature,
+ isSettingUp,
+ hasSetupFailed,
+ isLoadingStorageAddOn,
+ canPurchaseStorage,
+ });
+}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/csv-panel-state.unit.spec.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/csv-panel-state.unit.spec.ts
new file mode 100644
index 00000000000..1ec0fac344e
--- /dev/null
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/csv-panel-state.unit.spec.ts
@@ -0,0 +1,160 @@
+import {
+ type CsvPanelState,
+ type CsvPanelStateInput,
+ getCsvPanelState,
+} from "./csv-panel-state";
+
+// A settled OSS instance where the user can upload, with no storage flags set.
+const BASE: CsvPanelStateInput = {
+ areDatabasesLoading: false,
+ areUploadsEnabled: true,
+ canUploadToDatabase: true,
+ canManageUploads: false,
+ isSettingUp: false,
+ hasSetupFailed: false,
+ isLoadingStorageAddOn: false,
+ hasAttachedDwh: false,
+ hasStorageTokenFeature: false,
+ canPurchaseStorage: false,
+};
+
+const state = (overrides: Partial<CsvPanelStateInput>): CsvPanelState =>
+ getCsvPanelState({ ...BASE, ...overrides });
+
+describe("getCsvPanelState", () => {
+ it("waits for the databases list before committing to an answer", () => {
+ // Every other input says "you cannot upload"; none of it is knowable yet.
+ expect(
+ state({
+ areDatabasesLoading: true,
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ }),
+ ).toEqual({ type: "loading" });
+ });
+
+ it("lets the user upload once uploads are enabled and permitted", () => {
+ expect(state({})).toEqual({ type: "ready" });
+ });
+
+ it("points a user without upload permission at their admin", () => {
+ expect(state({ canUploadToDatabase: false })).toEqual({
+ type: "no-upload-permission",
+ });
+ });
+
+ it("points a user who cannot manage uploads at their admin", () => {
+ expect(
+ state({ areUploadsEnabled: false, canUploadToDatabase: false }),
+ ).toEqual({ type: "ask-admin" });
+ });
+
+ it("offers storage alongside the CTA to an admin who could buy it", () => {
+ expect(
+ state({
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ canManageUploads: true,
+ canPurchaseStorage: true,
+ }),
+ ).toEqual({ type: "needs-uploads-setup", canOfferStorage: true });
+ });
+
+ it("does not offer a second copy of storage to an admin who owns it", () => {
+ expect(
+ state({
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ canManageUploads: true,
+ canPurchaseStorage: true,
+ hasAttachedDwh: true,
+ }),
+ ).toEqual({ type: "needs-uploads-setup", canOfferStorage: false });
+ });
+
+ describe("storage setup", () => {
+ it("shows provisioning ahead of any permission prompt", () => {
+ // Mid-provisioning the flags briefly look like a permissions problem.
+ expect(state({ isSettingUp: true, canUploadToDatabase: false })).toEqual({
+ type: "provisioning-storage",
+ });
+ });
+
+ it("shows the failure once setup passes its deadline", () => {
+ expect(
+ state({ hasSetupFailed: true, canUploadToDatabase: false }),
+ ).toEqual({ type: "storage-setup-failed" });
+ });
+
+ it("offers the enable-uploads CTA to an admin whose storage has uploads off", () => {
+ // Storage exists but uploads are off, so the admin can just turn them on.
+ expect(
+ state({
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ canManageUploads: true,
+ canPurchaseStorage: true,
+ hasAttachedDwh: true,
+ }),
+ ).toEqual({ type: "needs-uploads-setup", canOfferStorage: false });
+ });
+
+ it("points a user who cannot enable uploads at their admin instead", () => {
+ expect(
+ state({
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ canManageUploads: false,
+ hasAttachedDwh: true,
+ }),
+ ).toEqual({ type: "ask-admin" });
+ });
+
+ it("tells an entitled admin to refresh when the DWH has not appeared yet", () => {
+ // Token says storage is theirs, but the database has not shown up — still
+ // provisioning, or a token that runs ahead of the data.
+ expect(
+ state({
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ canManageUploads: true,
+ hasStorageTokenFeature: true,
+ hasAttachedDwh: false,
+ }),
+ ).toEqual({ type: "storage-not-provisioned" });
+ });
+
+ it("prefers the enable-uploads CTA once the entitled admin's DWH exists", () => {
+ expect(
+ state({
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ canManageUploads: true,
+ hasStorageTokenFeature: true,
+ hasAttachedDwh: true,
+ }),
+ ).toEqual({ type: "needs-uploads-setup", canOfferStorage: false });
+ });
+
+ it("keeps a working uploader while storage is still provisioning", () => {
+ // Setup that never lands must not hide an upload target that works.
+ expect(state({ isSettingUp: true })).toEqual({ type: "ready" });
+ });
+
+ it("keeps a working uploader after storage setup gives up", () => {
+ expect(state({ hasSetupFailed: true })).toEqual({ type: "ready" });
+ });
+
+ it("waits for the add-on before offering to buy storage", () => {
+ expect(
+ state({
+ areUploadsEnabled: false,
+ canUploadToDatabase: false,
+ canManageUploads: true,
+ canPurchaseStorage: true,
+ isLoadingStorageAddOn: true,
+ }),
+ ).toEqual({ type: "loading" });
+ });
+ });
+});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/common.unit.spec.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/common.unit.spec.tsx
index c0f501cf2df..a7b663e5976 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/common.unit.spec.tsx
@@ -1,8 +1,9 @@
import userEvent from "@testing-library/user-event";
-import { fireEvent, screen, within } from "__support__/ui";
+import { fireEvent, screen, waitFor, within } from "__support__/ui";
+import { mockStorageCloudAddOn } from "metabase-types/api/mocks/add-ons";
-import { setup } from "./setup";
+import { setup, setupHostedInstance } from "./setup";
const csvFile = new File(["test,data"], "bank-statement.csv", {
type: "text/csv",
@@ -156,29 +157,71 @@ describe("AddDataModal", () => {
setup({ isAdmin: true, uploadsEnabled: false });
await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
- expect(await screen.findByText("Manage uploads")).toBeInTheDocument();
expect(
- screen.getByRole("heading", { name: "Upload CSV files" }),
+ await screen.findByRole("heading", { name: "Upload CSV files" }),
).toBeInTheDocument();
expect(
screen.getByText(/^To work with CSVs, enable file uploads/),
).toBeInTheDocument();
expect(screen.getByText("Enable uploads")).toBeInTheDocument();
+ // The uploads settings link only shows once uploads are enabled.
+ expect(screen.queryByText("Manage uploads")).not.toBeInTheDocument();
// Upsell banner should not show for self-hosted instances.
expect(
screen.queryByText("Add Metabase Storage"),
).not.toBeInTheDocument();
});
- it("should prompt the admin to enable uploads with an upsell on a hosted instance", async () => {
- setup({ isAdmin: true, uploadsEnabled: false, isHosted: true });
+ it("should offer the admin to either enable uploads or add storage on a hosted instance", async () => {
+ setupHostedInstance({
+ isAdmin: true,
+ uploadsEnabled: false,
+ addOns: [mockStorageCloudAddOn],
+ });
await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
- expect(await screen.findByText("Manage uploads")).toBeInTheDocument();
expect(await screen.findByText("Enable uploads")).toBeInTheDocument();
+ expect(screen.queryByText("Manage uploads")).not.toBeInTheDocument();
+
+ const storageButton = await screen.findByRole("button", {
+ name: /Add Metabase Storage/,
+ });
expect(
- await screen.findByText("Add Metabase Storage"),
+ screen.getByText(/either enable file uploads in/),
).toBeInTheDocument();
+
+ await userEvent.click(storageButton);
+ const purchaseModal = await screen.findByRole("dialog", {
+ name: "Add Metabase Storage",
+ });
+
+ // The confirmation replaces the Add data modal instead of stacking on it.
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("dialog", { name: "Add data" }),
+ ).not.toBeInTheDocument();
+ });
+
+ // Cancelling brings the Add data modal back on the same tab.
+ await userEvent.click(
+ within(purchaseModal).getByRole("button", { name: "Cancel" }),
+ );
+ expect(
+ await screen.findByRole("dialog", { name: "Add data" }),
+ ).toBeInTheDocument();
+ expect(await screen.findByText("Enable uploads")).toBeInTheDocument();
+ });
+
+ it("falls back to a store link on a hosted instance without a purchasable add-on", async () => {
+ setupHostedInstance({ isAdmin: true, uploadsEnabled: false });
+
+ await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
+ expect(await screen.findByText("Enable uploads")).toBeInTheDocument();
+ // The in-app purchase isn't available, but storage is still offered as a
+ // link out to the store.
+ expect(
+ await screen.findByRole("link", { name: /Add Metabase Storage/ }),
+ ).toHaveAttribute("href", expect.stringContaining("/account/storage"));
});
it("regular user should be instructed to contact their admin in order to enable uploads", async () => {
@@ -206,28 +249,18 @@ describe("AddDataModal", () => {
).toBeInTheDocument();
});
- it("regular user should be instructed to contact their admin in order to gain upload permissions", async () => {
+ it("still offers the CSV tab to a regular user who cannot upload to any database", async () => {
+ // The tabs advertise what Metabase can do, so CSV stays visible and the
+ // panel explains what is missing, the same way Google Sheets does.
setup({ isAdmin: false, uploadsEnabled: true, canUpload: false });
- await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
- expect(screen.queryByText("Manage uploads")).not.toBeInTheDocument();
expect(
- await screen.findByRole("heading", { name: "Upload CSV files" }),
- ).toBeInTheDocument();
- expect(
- screen.getByText(
- "Work with CSVs, just like with any other data source.",
- ),
+ await screen.findByRole("tab", { name: /Database$/ }),
).toBeInTheDocument();
- const alert = screen.getByRole("alert");
- expect(
- within(alert).getByText(
- /^You are not permitted to upload CSV files. To get proper permissions, please contact your administrator at/,
- ),
- ).toBeInTheDocument();
+ await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
expect(
- within(alert).getByText("[email protected]"),
+ await screen.findByText(/You are not permitted to upload CSV files/),
).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-advanced-permissions.unit.spec.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-advanced-permissions.unit.spec.tsx
index 3b046d63033..6e957057801 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-advanced-permissions.unit.spec.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-advanced-permissions.unit.spec.tsx
@@ -26,8 +26,9 @@ describe("Add data modal (EE with token)", () => {
});
await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
- expect(await screen.findByText("Manage uploads")).toBeInTheDocument();
expect(await screen.findByText("Enable uploads")).toBeInTheDocument();
+ // The uploads settings link only shows once uploads are enabled.
+ expect(screen.queryByText("Manage uploads")).not.toBeInTheDocument();
});
it("should offer a setting manager to manage (csv) uploads", async () => {
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-hosting-upload.unit.spec.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-hosting-upload.unit.spec.tsx
index a33ff733b0a..c44ffef67ec 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-hosting-upload.unit.spec.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/premium-hosting-upload.unit.spec.tsx
@@ -1,28 +1,60 @@
import userEvent from "@testing-library/user-event";
import { screen, within } from "__support__/ui";
+import { mockStorageCloudAddOn } from "metabase-types/api/mocks/add-ons";
-import { setupHostedInstance, setupProUpload } from "./setup";
+import { setup, setupHostedInstance, setupProUpload } from "./setup";
describe("Add data modal (Starter: hosted instance without the attached DWH)", () => {
describe("Google Sheets", () => {
- it("should render a storage upsell for an admin", async () => {
+ it("should render a storage upsell for an admin when the add-on is not purchasable in-app", async () => {
setupHostedInstance({ isAdmin: true });
await assertSheetsOpened({
+ hasStorage: false,
subtitle:
"To work with spreadsheets, you can add storage to your instance.",
});
+ // A single button matching the CSV tab, not the old bulleted banner. With
+ // no in-app add-on it links to the store.
+ const upsellLink = await screen.findByRole("link", {
+ name: /Add Metabase Storage/,
+ });
+ const href = new URL(upsellLink.getAttribute("href") ?? "");
+ expect(href.origin + href.pathname).toBe(
+ "https://store.metabase.com/account/storage",
+ );
+ expect(href.searchParams.get("utm_campaign")).toBe("storage");
+ expect(href.searchParams.get("utm_content")).toBe(
+ "add-data-modal-sheets",
+ );
+ });
+
+ it("should offer the purchasable storage add-on to an admin through the upsell button", async () => {
+ setupHostedInstance({
+ isAdmin: true,
+ addOns: [mockStorageCloudAddOn],
+ });
+ await assertSheetsOpened({
+ hasStorage: false,
+ subtitle:
+ "To work with spreadsheets, you can add storage to your instance.",
+ });
+
+ // Purchasable in-app: opens the confirmation instead of linking out.
+ const addButton = await screen.findByRole("button", {
+ name: /Add Metabase Storage/,
+ });
+ await userEvent.click(addButton);
+
+ const modal = await screen.findByRole("dialog", {
+ name: "Add Metabase Storage",
+ });
expect(
- screen.getByRole("heading", { name: "Add Metabase Storage" }),
- ).toBeInTheDocument();
- expect(
- screen.getByText("Secure, fully managed by Metabase"),
+ within(modal).getByText(
+ /You will not be charged until you reach 1M stored rows/,
+ ),
).toBeInTheDocument();
- expect(screen.getByText("Upload CSV files")).toBeInTheDocument();
- expect(screen.getByText("Sync with Google Sheets")).toBeInTheDocument();
- const upsellLink = screen.getByRole("link", { name: "Add" });
- expect(upsellLink).toBeInTheDocument();
});
it("should render a 'contact admin prompt' for non-admin", async () => {
@@ -185,18 +217,98 @@ describe("Add data modal (Pro: hosted instance with the attached DWH)", () => {
});
});
+describe("Add data modal (hosted instance whose storage never materialized)", () => {
+ // The token flips at purchase but the database only appears once provisioning
+ // finishes, and on a local hosted build it never does. Reading that gap as
+ // "provisioning" spun and polled on every page load, so only a purchase made
+ // in this tab enters setup.
+ const setupTokenWithoutStorage = (opts: { uploadsEnabled: boolean }) =>
+ setupProUpload({
+ isAdmin: true,
+ hasAttachedDwhDatabase: false,
+ ...opts,
+ });
+
+ it("should tell the admin to refresh on the CSV tab rather than spin", async () => {
+ setupTokenWithoutStorage({ uploadsEnabled: false });
+
+ await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
+
+ expect(
+ await screen.findByText(
+ "You don't have storage provisioned yet. Refresh this page after 1-2 minutes.",
+ ),
+ ).toBeInTheDocument();
+ // "Enable uploads" would be a dead end while the DWH is still absent.
+ expect(screen.queryByText("Enable uploads")).not.toBeInTheDocument();
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("Storage setup didn't finish"),
+ ).not.toBeInTheDocument();
+ // Already bought, so it must be offered neither as button nor store link.
+ expect(
+ screen.queryByRole("button", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("link", { name: /Add Metabase Storage/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should keep the uploader on the CSV tab when another database accepts uploads", async () => {
+ setupTokenWithoutStorage({ uploadsEnabled: true });
+
+ await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
+
+ expect(
+ await screen.findByText("Drag and drop a file here"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+ });
+});
+
+/** A settings manager needs both plugins: one to gate uploads, one to be one. */
+const setupSettingsManager = () =>
+ setup({
+ isAdmin: false,
+ canManageSettings: true,
+ isHosted: true,
+ enterprisePlugins: ["upload_management", "application_permissions"],
+ tokenFeatures: {
+ hosting: true,
+ attached_dwh: true,
+ advanced_permissions: true,
+ },
+ uploadsEnabled: false,
+ dwhCanUpload: false,
+ });
+
+describe("Add data modal (Pro: uploads turned off by an admin)", () => {
+ it("should offer the settings manager the enable-uploads CTA", async () => {
+ // Storage presence comes from the databases list, so a settings manager
+ // sees it too. Uploads being off is a choice they can undo.
+ setupSettingsManager();
+
+ await userEvent.click(await screen.findByRole("tab", { name: /CSV$/ }));
+
+ expect(await screen.findByText("Enable uploads")).toBeInTheDocument();
+ });
+});
+
async function assertSheetsOpened({
isAdmin = true,
+ hasStorage = true,
title = "Connect Google Sheets",
subtitle = "Sync a spreadsheet or an entire Google Drive folder with your instance.",
}: {
isAdmin?: boolean;
+ hasStorage?: boolean;
title?: string;
subtitle?: string;
} = {}) {
await userEvent.click(screen.getByRole("tab", { name: /Google Sheets$/ }));
- if (isAdmin) {
+ // The imports settings link only shows for admins once storage is enabled.
+ if (isAdmin && hasStorage) {
expect(await screen.findByText("Manage imports")).toBeInTheDocument();
} else {
expect(screen.queryByText("Manage imports")).not.toBeInTheDocument();
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx
index 80f6a197d1f..e7c898f2b39 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/tests/setup.tsx
@@ -1,3 +1,5 @@
+import fetchMock from "fetch-mock";
+
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
setupCollectionByIdEndpoint,
@@ -5,6 +7,8 @@ import {
setupGdriveGetFolderEndpoint,
setupGdrivePostFolderEndpoint,
setupGdriveServiceAccountEndpoint,
+ setupPropertiesEndpoints,
+ setupTokenRefreshEndpoint,
setupTokenStatusEndpoint,
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
@@ -12,10 +16,15 @@ import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders } from "__support__/ui";
import { ROOT_COLLECTION } from "metabase/common/collections/constants";
import { createMockState } from "metabase/redux/store/mocks";
-import type { GdrivePayload, TokenFeatures } from "metabase-types/api";
+import type {
+ GdrivePayload,
+ ICloudAddOnProduct,
+ TokenFeatures,
+} from "metabase-types/api";
import {
createMockCollection,
createMockDatabase,
+ createMockSettings,
createMockTokenFeatures,
createMockUser,
} from "metabase-types/api/mocks";
@@ -34,6 +43,14 @@ interface SetupOpts {
enableGoogleSheets?: boolean;
status?: GdrivePayload["status"];
adminEmail?: string | null;
+ addOns?: ICloudAddOnProduct[];
+ /**
+ * Defaults to following the token feature. Set `false` for the window between
+ * purchase and redeploy, or storage that never materialized.
+ */
+ hasAttachedDwhDatabase?: boolean;
+ /** False in the window before the redeploy makes storage the upload target. */
+ dwhCanUpload?: boolean;
}
export const setup = ({
@@ -48,6 +65,9 @@ export const setup = ({
enableGoogleSheets = false,
status,
adminEmail = "[email protected]",
+ addOns = [],
+ hasAttachedDwhDatabase = !!tokenFeatures.attached_dwh,
+ dwhCanUpload = true,
}: SetupOpts = {}) => {
const user = createMockUser({
is_superuser: isAdmin,
@@ -71,8 +91,34 @@ export const setup = ({
can_upload: isAdmin || canUpload,
});
+ // The storage UI keys off the attached DWH appearing in the databases list,
+ // not the `attached_dwh` token, which flips earlier — hence two controls.
+ const attachedDwhDatabase = hasAttachedDwhDatabase
+ ? createMockDatabase({
+ id: 2,
+ name: "Metabase Storage",
+ is_attached_dwh: true,
+ can_upload: dwhCanUpload,
+ })
+ : null;
+
const collections = [rootCollection];
- const databases = [database];
+ const databases = attachedDwhDatabase
+ ? [database, attachedDwhDatabase]
+ : [database];
+
+ const settingValues = {
+ "admin-email": adminEmail,
+ "is-hosted?": isHosted,
+ "show-google-sheets-integration": enableGoogleSheets,
+ "token-features": createMockTokenFeatures(tokenFeatures),
+ "uploads-settings": {
+ db_id: uploadsEnabled ? database.id : null,
+ schema_name: "uploads",
+ table_prefix: "uploaded_",
+ },
+ "store-url": "https://store.metabase.com",
+ };
const state = createMockState({
currentUser: createMockUser(user),
@@ -80,20 +126,11 @@ export const setup = ({
databases,
collections,
}),
- settings: mockSettings({
- "admin-email": adminEmail,
- "is-hosted?": isHosted,
- "show-google-sheets-integration": enableGoogleSheets,
- "token-features": createMockTokenFeatures(tokenFeatures),
- "uploads-settings": {
- db_id: uploadsEnabled ? database.id : null,
- schema_name: "uploads",
- table_prefix: "uploaded_",
- },
- "store-url": "https://store.metabase.com",
- }),
+ settings: mockSettings(settingValues),
});
+ setupPropertiesEndpoints(createMockSettings(settingValues));
+
if (enterprisePlugins) {
enterprisePlugins.forEach((plugin) => {
setupEnterpriseOnlyPlugin(plugin);
@@ -103,6 +140,11 @@ export const setup = ({
setupDatabaseListEndpoint(databases);
setupCollectionByIdEndpoint({ collections });
+ // The storage offer (shown on hosted instances) checks add-on availability.
+ fetchMock.get("path:/api/ee/cloud-add-ons/addons", addOns);
+ // A purchase posts and then refreshes the token until the new plan lands.
+ fetchMock.post("path:/api/ee/cloud-add-ons/dwh-rent", 200);
+ setupTokenRefreshEndpoint();
if (enableGoogleSheets) {
setupGdrivePostFolderEndpoint();
@@ -139,6 +181,8 @@ export const setupHostedInstance = (opts: Partial<SetupOpts>) => {
export const setupProUpload = (opts: Partial<SetupOpts>) =>
setupHostedInstance({
+ // A provisioned DWH enables uploads, which is what gates the imports link.
+ uploadsEnabled: true,
...opts,
tokenFeatures: { attached_dwh: true },
});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.ts
deleted file mode 100644
index 2ab62cc8c40..00000000000
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { useListDatabasesQuery } from "metabase/api";
-import { useSetting } from "metabase/common/hooks";
-import { useSelector } from "metabase/redux";
-import { canAccessSettings, getUserIsAdmin } from "metabase/selectors/user";
-
-export function useAddDataPermissions() {
- const { data: databasesResponse } = useListDatabasesQuery();
- const userCanAccessSettings = useSelector(canAccessSettings);
- const isAdmin = useSelector(getUserIsAdmin);
- const databases = databasesResponse?.data;
- const uploadDbId = useSetting("uploads-settings")?.db_id;
- const uploadDB = databases?.find((db) => db.id === uploadDbId);
-
- /**
- * This covers the case where instance has the attached dwh. In such cases
- * uploads are enabled by default.
- */
- const areUploadsEnabled = !!uploadDbId;
- const canUploadToDatabase = !!uploadDB?.can_upload;
- const canManageUploads = userCanAccessSettings;
- const canPerformMeaningfulActions =
- canUploadToDatabase || canManageUploads || isAdmin;
-
- return {
- areUploadsEnabled,
- canUploadToDatabase,
- canManageUploads,
- canPerformMeaningfulActions,
- isAdmin,
- };
-}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-state.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-state.ts
new file mode 100644
index 00000000000..e6c6957a0de
--- /dev/null
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-state.ts
@@ -0,0 +1,45 @@
+import { useMemo } from "react";
+
+import { useListDatabasesQuery } from "metabase/api";
+import { type AttachedDwhInfo, getHasAttachedDwh } from "metabase/common/hooks";
+import { useSelector } from "metabase/redux";
+import { canAccessSettings, getUserIsAdmin } from "metabase/selectors/user";
+
+interface AddDataState extends AttachedDwhInfo {
+ areDatabasesLoading: boolean;
+ areUploadsEnabled: boolean;
+ canUploadToDatabase: boolean;
+ canManageUploads: boolean;
+ isAdmin: boolean;
+}
+
+/**
+ * The upload facts the Add data modal derives from, in one place so the tabs,
+ * the header links and the CSV panel cannot disagree about them.
+ *
+ * They come from the databases list rather than the `uploads-settings` setting,
+ * which only updates when session properties are refetched and so goes stale as
+ * soon as the upload target changes.
+ */
+export function useAddDataState(): AddDataState {
+ const { data: databasesResponse, isLoading: areDatabasesLoading } =
+ useListDatabasesQuery();
+ const canManageUploads = useSelector(canAccessSettings);
+ const isAdmin = useSelector(getUserIsAdmin);
+
+ const databases = databasesResponse?.data;
+
+ // Mounted on every page through `useCanAddData` and re-run on every poll tick
+ // while storage provisions, so keep the scans off the render path.
+ return useMemo(
+ () => ({
+ areDatabasesLoading,
+ areUploadsEnabled: !!databases?.some((db) => db.uploads_enabled),
+ canUploadToDatabase: !!databases?.some((db) => db.can_upload),
+ hasAttachedDwh: getHasAttachedDwh(databases),
+ canManageUploads,
+ isAdmin,
+ }),
+ [databases, areDatabasesLoading, canManageUploads, isAdmin],
+ );
+}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-state.unit.spec.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-state.unit.spec.ts
new file mode 100644
index 00000000000..5841cb40e07
--- /dev/null
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-state.unit.spec.ts
@@ -0,0 +1,91 @@
+import { setupDatabaseListEndpoint } from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { createMockEntitiesState } from "__support__/store";
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import { createMockDatabase, createMockUser } from "metabase-types/api/mocks";
+
+import { useAddDataState } from "./use-add-data-state";
+
+function setup({
+ canUpload = false,
+ uploadsEnabled = canUpload,
+ staleUploadsSettingDbId = null,
+}: {
+ canUpload?: boolean;
+ uploadsEnabled?: boolean;
+ staleUploadsSettingDbId?: number | null;
+}) {
+ const database = createMockDatabase({
+ uploads_enabled: uploadsEnabled,
+ can_upload: canUpload,
+ });
+
+ const storeInitialState = createMockState({
+ currentUser: createMockUser({ is_superuser: false }),
+ entities: createMockEntitiesState({
+ databases: [database],
+ collections: [],
+ }),
+ settings: mockSettings({
+ // Deliberately out of sync: the hook must ignore this stale setting.
+ "uploads-settings": {
+ db_id: staleUploadsSettingDbId,
+ schema_name: "uploads",
+ table_prefix: "uploaded_",
+ },
+ }),
+ });
+
+ setupDatabaseListEndpoint([database]);
+
+ return renderHookWithProviders(() => useAddDataState(), {
+ storeInitialState,
+ });
+}
+
+describe("useAddDataState", () => {
+ it("reports the list as loading before it arrives", () => {
+ // Callers must tell "cannot upload anywhere" apart from "not fetched yet".
+ const { result } = setup({ canUpload: true });
+
+ expect(result.current.areDatabasesLoading).toBe(true);
+ expect(result.current.canUploadToDatabase).toBe(false);
+ });
+
+ it("reports uploads as enabled even when the cached setting says otherwise", async () => {
+ const { result } = setup({
+ canUpload: true,
+ uploadsEnabled: true,
+ staleUploadsSettingDbId: null,
+ });
+
+ await waitFor(() => {
+ expect(result.current.areUploadsEnabled).toBe(true);
+ });
+ expect(result.current.canUploadToDatabase).toBe(true);
+ });
+
+ it("reports uploads as disabled even when the cached setting points at a database", async () => {
+ const { result } = setup({
+ canUpload: false,
+ uploadsEnabled: false,
+ staleUploadsSettingDbId: 1,
+ });
+
+ await waitFor(() => {
+ expect(result.current.areDatabasesLoading).toBe(false);
+ });
+ expect(result.current.areUploadsEnabled).toBe(false);
+ expect(result.current.canUploadToDatabase).toBe(false);
+ });
+
+ it("separates uploads being enabled from the user being allowed to upload", async () => {
+ const { result } = setup({ canUpload: false, uploadsEnabled: true });
+
+ await waitFor(() => {
+ expect(result.current.areUploadsEnabled).toBe(true);
+ });
+ expect(result.current.canUploadToDatabase).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/utils.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/utils.ts
index 5f9bff3d6f5..a1f64e367fb 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/utils.ts
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/utils.ts
@@ -1,5 +1,3 @@
-import type { Database } from "metabase-types/api";
-
const validTabArray = ["db", "csv", "gsheets"] as const;
const validTabs = new Set<string>(validTabArray);
@@ -7,28 +5,3 @@ export type AddDataTab = (typeof validTabArray)[number];
export const isValidTab = (v: string | null): v is AddDataTab =>
typeof v === "string" && validTabs.has(v);
-
-export function hasMeaningfulUploadableDatabases({
- allDatabases = [],
- allUploadableDatabases = [],
-}: {
- allDatabases: Database[] | undefined;
- allUploadableDatabases: Database[] | undefined;
-}) {
- // if there are no uploadable databases or no databases, return false
- if (!allUploadableDatabases?.length || !allDatabases) {
- return false;
- }
-
- // if we have more than one database and the only uploadable database is h2, return false
- if (
- allUploadableDatabases.length === 1 &&
- allDatabases.length > 1 &&
- allUploadableDatabases[0]?.engine === "h2"
- ) {
- return false;
- }
-
- // we have some meaningful uploadable databases, return true
- return true;
-}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/utils.unit.spec.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/utils.unit.spec.ts
deleted file mode 100644
index 4582e155f6f..00000000000
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/utils.unit.spec.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { createMockDatabase } from "metabase-types/api/mocks";
-
-import { hasMeaningfulUploadableDatabases } from "./utils";
-
-const h2 = createMockDatabase({
- id: 1,
- name: "Db Uno",
- engine: "h2",
-});
-
-const postgres = createMockDatabase({
- id: 2,
- name: "Db Dos",
- engine: "postgres",
-});
-
-const athena = createMockDatabase({
- id: 3,
- name: "Db Tres",
- engine: "athena",
-});
-
-const testCases = [
- {
- description: "there are no uploadable databases",
- result: false,
- data: {
- allDatabases: [],
- allUploadableDatabases: [],
- },
- },
- {
- description: "there is only one uploadable database and it is h2",
- result: true,
- data: {
- allDatabases: [h2],
- allUploadableDatabases: [h2],
- },
- },
- {
- description: "multiple databases but h2 is only uploadable",
- result: false,
- data: {
- allDatabases: [h2, athena],
- allUploadableDatabases: [h2],
- },
- },
- {
- description: "with non-h2 uploadable databases",
- result: true,
- data: {
- allDatabases: [postgres, athena],
- allUploadableDatabases: [postgres],
- },
- },
-];
-
-describe("hasMeaningfulUploadableDatabases", () => {
- it.each(testCases)(
- "should return $result when $description",
- ({ result, data }) => {
- expect(hasMeaningfulUploadableDatabases(data)).toBe(result);
- },
- );
-});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/BrowseNavSection.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/BrowseNavSection.tsx
index 5264d43e77a..6fac39ef178 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/BrowseNavSection.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/BrowseNavSection.tsx
@@ -11,7 +11,7 @@ import { PaddedSidebarLink, SidebarHeading } from "../MainNavbar.styled";
import { trackAddDataModalOpened } from "../analytics";
import type { SelectedItem } from "../types";
-import { useAddDataPermissions } from "./AddDataModal/use-add-data-permission";
+import { useCanAddData } from "./use-can-add-data";
export const BrowseNavSection = ({
nonEntityItem,
@@ -32,11 +32,11 @@ export const BrowseNavSection = ({
"expand-browse-in-nav",
);
- const { canPerformMeaningfulActions } = useAddDataPermissions();
+ const canAddData = useCanAddData();
const entityTypes = useSelector(getEntityTypes);
const isEmbeddingIframe = useSelector(getIsEmbeddingIframe);
- const showAddDataButton = canPerformMeaningfulActions && !isEmbeddingIframe;
+ const showAddDataButton = canAddData && !isEmbeddingIframe;
return (
<CollapseSection
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/GettingStartedSection.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/GettingStartedSection.tsx
index d6826146a85..c289cf545c6 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/GettingStartedSection.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/GettingStartedSection.tsx
@@ -9,7 +9,7 @@ import { PaddedSidebarLink, SidebarHeading } from "../MainNavbar.styled";
import { trackOnboardingChecklistOpened } from "../analytics";
import type { SelectedItem } from "../types";
-import { useAddDataPermissions } from "./AddDataModal/use-add-data-permission";
+import { useCanAddData } from "./use-can-add-data";
export const GettingStartedSection = ({
nonEntityItem,
@@ -19,7 +19,7 @@ export const GettingStartedSection = ({
nonEntityItem: SelectedItem;
onAddDataModalOpen: () => void;
}>) => {
- const { canPerformMeaningfulActions } = useAddDataPermissions();
+ const canAddData = useCanAddData();
const [opened, { toggle }] = useDisclosure(true);
const ONBOARDING_URL = "/getting-started";
@@ -46,7 +46,7 @@ export const GettingStartedSection = ({
role="tabpanel"
aria-expanded={opened}
>
- {canPerformMeaningfulActions && (
+ {canAddData && (
<PaddedSidebarLink icon="add_data" onClick={onAddDataModalOpen}>
{t`Add your data`}
</PaddedSidebarLink>
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/use-can-add-data.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/use-can-add-data.ts
new file mode 100644
index 00000000000..9f752dafa71
--- /dev/null
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/use-can-add-data.ts
@@ -0,0 +1,13 @@
+import { useAddDataState } from "./AddDataModal/use-add-data-state";
+
+/**
+ * Whether to offer the "Add data" entry points in the navbar. Shares
+ * `useAddDataState` with the modal it opens so the two cannot disagree.
+ */
+export function useCanAddData() {
+ // No separate admin term: `canManageUploads` is `canAccessSettings`, which
+ // admins always pass.
+ const { canUploadToDatabase, canManageUploads } = useAddDataState();
+
+ return canUploadToDatabase || canManageUploads;
+}
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.unit.spec.ts b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/use-can-add-data.unit.spec.ts
similarity index 58%
rename from frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.unit.spec.ts
rename to frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/use-can-add-data.unit.spec.ts
index 429d70af41e..953f89f068e 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/use-add-data-permission.unit.spec.ts
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/use-can-add-data.unit.spec.ts
@@ -13,20 +13,22 @@ import {
createMockUser,
} from "metabase-types/api/mocks";
-import { useAddDataPermissions } from "./use-add-data-permission";
+import { useCanAddData } from "./use-can-add-data";
function setup({
isSuperUser = false,
canUpload = false,
canAccessSettings = false,
+}: {
+ isSuperUser?: boolean;
+ canUpload?: boolean;
+ canAccessSettings?: boolean;
}) {
const database = createMockDatabase({
uploads_enabled: canUpload,
can_upload: canUpload,
});
- const currentUser = createMockUser({
- is_superuser: isSuperUser,
- });
+ const currentUser = createMockUser({ is_superuser: isSuperUser });
if (canAccessSettings) {
currentUser.permissions = {
@@ -34,14 +36,12 @@ function setup({
can_access_monitoring: false,
can_access_subscription: false,
};
- }
- setupTokenStatusEndpoint({ valid: true });
-
- if (canAccessSettings) {
// enterprise plugin is needed for advanced permissions to be returned
setupEnterprisePlugins();
}
+ setupTokenStatusEndpoint({ valid: true });
+
const storeInitialState = createMockState({
currentUser,
entities: createMockEntitiesState({
@@ -49,47 +49,38 @@ function setup({
collections: [],
}),
settings: mockSettings({
- "token-features": createMockTokenFeatures({
- advanced_permissions: true,
- }),
- "uploads-settings": {
- db_id: database.id,
- schema_name: "uploads",
- table_prefix: "uploaded_",
- },
+ "token-features": createMockTokenFeatures({ advanced_permissions: true }),
}),
});
setupDatabaseListEndpoint([database]);
- return renderHookWithProviders(() => useAddDataPermissions(), {
- storeInitialState,
- });
+ return renderHookWithProviders(() => useCanAddData(), { storeInitialState });
}
-describe("correctly sets canPerformMeaningfulActions", () => {
+describe("useCanAddData", () => {
const testCases = [
+ { description: "an admin", data: { isSuperUser: true } },
+ { description: "a user who can upload", data: { canUpload: true } },
{
- description: "admin user can perform meaningful actions",
- data: { isSuperUser: true },
- },
- {
- description: "user who can upload can perform meaningful actions",
- data: { canUpload: true },
- },
- {
- description: "user with settings access can perform meaningful actions",
+ description: "a user with settings access",
data: { canAccessSettings: true },
},
];
- it.each(testCases)("$description", async (testCase) => {
+ it.each(testCases)("offers Add data to $description", async (testCase) => {
const { result } = setup(testCase.data);
await waitFor(() => {
- expect(result.current).toEqual(
- expect.objectContaining({ canPerformMeaningfulActions: true }),
- );
+ expect(result.current).toBe(true);
+ });
+ });
+
+ it("does not offer Add data to a user who can neither upload nor manage settings", async () => {
+ const { result } = setup({});
+
+ await waitFor(() => {
+ expect(result.current).toBe(false);
});
});
});
diff --git a/frontend/src/metabase/plugins/oss/upload-management.ts b/frontend/src/metabase/plugins/oss/upload-management.ts
index fdc1bc451cd..4a172a29395 100644
--- a/frontend/src/metabase/plugins/oss/upload-management.ts
+++ b/frontend/src/metabase/plugins/oss/upload-management.ts
@@ -1,5 +1,6 @@
import type { ComponentType } from "react";
+import { StorageSetupProvider } from "metabase/common/components/upsells/StoragePurchaseModal/storage-setup-context";
import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";
import { _FileUploadErrorModal } from "metabase/status/components/FileUploadStatusLarge/FileUploadErrorModal";
@@ -24,6 +25,7 @@ const getDefaultPluginUploadManagement = () => ({
GdriveAddDataPanel:
// Unjustified type cast. FIXME
PluginPlaceholder as ComponentType<GdriveAddDataPanelProps>,
+ StorageSetupProvider,
});
export const PLUGIN_UPLOAD_MANAGEMENT = getDefaultPluginUploadManagement();
diff --git a/frontend/test/__support__/server-mocks/premium-features.ts b/frontend/test/__support__/server-mocks/premium-features.ts
index 9343e172d5a..fb74f1e9344 100644
--- a/frontend/test/__support__/server-mocks/premium-features.ts
+++ b/frontend/test/__support__/server-mocks/premium-features.ts
@@ -1,4 +1,6 @@
-import fetchMock from "fetch-mock";
+import fetchMock, { type RouteResponse } from "fetch-mock";
+
+import { createMockTokenStatus } from "metabase-types/api/mocks";
export const setupTokenStatusEndpoint = ({
valid,
@@ -26,9 +28,18 @@ export const setupTokenStatusEndpointEmpty = () => {
});
};
-export const setupTokenRefreshEndpoint = () => {
- fetchMock.post("path:/api/premium-features/token/refresh", 200, {
- name: "premium-token-refresh",
+/**
+ * Defaults to a plausible `TokenStatus` body, which is what callers of
+ * `useTokenRefreshUntil` read. Pass `response` a status code for failure cases
+ * or a `TokenStatus` carrying the features a test waits on.
+ */
+export const setupTokenRefreshEndpoint = (
+ response: RouteResponse = createMockTokenStatus(),
+) => {
+ const name = "premium-token-refresh";
+ fetchMock.removeRoute(name);
+ fetchMock.post("path:/api/premium-features/token/refresh", response, {
+ name,
});
};