Skip to content

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

GRO-554 update storage upsell (#76052)

Timur Mashara30daa26a7b0b
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..ee0762c5465 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,37 @@
"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."
+ #{"etl-connections"})
+
+(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 +167,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 +178,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 +190,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 +219,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 64224379266..601a9c54b8f 100644
--- a/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveAddDataPanel.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/google_drive/GdriveAddDataPanel.tsx
@@ -4,8 +4,12 @@ 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,
+ StorageSetupView,
+ useStorageSetup,
+} from "metabase/common/components/upsells/StoragePurchaseModal";
+import { useStoreUrl } from "metabase/common/hooks";
import {
CONTENT_MAX_WIDTH,
ContactAdminAlert,
@@ -136,7 +140,7 @@ export const GdriveAddDataPanel = ({
});
const isAdmin = useSelector(getUserIsAdmin);
- const hasStorage = useHasTokenFeature("attached_dwh");
+ const { isSettingUp, hasAttachedDwh } = useStorageSetup();
const storeUrl = useStoreUrl("account/storage");
const showGdrive = useShowGdrive();
@@ -145,6 +149,10 @@ export const GdriveAddDataPanel = ({
{ refetchOnMountOrArgChange: 5 },
);
+ if (isSettingUp) {
+ return <StorageSetupView />;
+ }
+
const status = getStatus({ status: folder?.status, error });
const folderUrl = folder?.url;
@@ -161,10 +169,10 @@ export const GdriveAddDataPanel = ({
);
}
- if (!hasStorage) {
+ if (!hasAttachedDwh) {
return (
<PanelWrapper subtitle={NO_STORAGE_SUBTITLE}>
- <UpsellStorage location="add-data-modal-sheets" />
+ <StoragePurchaseButton location="add-data-modal-sheets" />
</PanelWrapper>
);
}
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..79d0ae64385
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/CSVPanel.unit.spec.tsx
@@ -0,0 +1,236 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseListEndpoint,
+ setupPropertiesEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { CSVPanel } from "metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/Panels/CSVPanel";
+import { createMockState } from "metabase/redux/store/mocks";
+import type { ICloudAddOnProduct, TokenFeatures } from "metabase-types/api";
+import {
+ createMockDatabase,
+ createMockSettings,
+ createMockTokenFeatures,
+ createMockUser,
+} from "metabase-types/api/mocks";
+import { mockStorageCloudAddOn } from "metabase-types/api/mocks/add-ons";
+
+import { StorageSetupProvider } from "./StorageSetupProvider";
+
+interface PanelProps {
+ canUpload: boolean;
+ canManageUploads: boolean;
+ uploadsEnabled: boolean;
+}
+
+const DEFAULT_PANEL_PROPS: PanelProps = {
+ canUpload: false,
+ canManageUploads: true,
+ uploadsEnabled: false,
+};
+
+interface SetupOpts {
+ addOns?: ICloudAddOnProduct[];
+ tokenFeatures?: Partial<TokenFeatures>;
+ hasAttachedDwhDatabase?: boolean;
+ panelProps?: Partial<PanelProps>;
+}
+
+const setup = ({
+ addOns = [mockStorageCloudAddOn],
+ tokenFeatures = {},
+ hasAttachedDwhDatabase = false,
+ panelProps,
+}: SetupOpts = {}) => {
+ const props = { ...DEFAULT_PANEL_PROPS, ...panelProps };
+ const renderPanel = (mounted: boolean) =>
+ mounted ? <CSVPanel {...props} 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: true, is_attached_dwh: true })]
+ : [],
+ );
+ fetchMock.get("path:/api/ee/cloud-add-ons/addons", addOns);
+ fetchMock.post("path:/api/ee/cloud-add-ons/dwh-rent", 200);
+ fetchMock.post("path:/api/premium-features/token/refresh", {});
+
+ 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 };
+};
+
+const openPurchaseModal = async () => {
+ await userEvent.click(
+ await screen.findByRole("button", { name: /Add Metabase Storage/ }),
+ );
+
+ return await screen.findByRole("dialog", { name: "Add Metabase Storage" });
+};
+
+const confirmPurchase = async () => {
+ const modal = await openPurchaseModal();
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Add Metabase Storage" }),
+ );
+};
+
+describe("CSVPanel storage purchase", () => {
+ it("offers to add storage next to the enable uploads CTA", async () => {
+ setup();
+
+ // A plain loader shows while the add-on availability is being 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();
+ // Storage is still offered, but as a link out to the store 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 while provisioning", async () => {
+ // Mid-provisioning the token feature and `uploads-settings` flip before the
+ // DWH database accepts uploads, so `uploadsEnabled` is true while
+ // `canUpload` is still false. The purchasing admin must see the setup view,
+ // not a "contact your administrator" prompt.
+ setup({
+ tokenFeatures: { attached_dwh: true },
+ hasAttachedDwhDatabase: false,
+ panelProps: { uploadsEnabled: true, canUpload: false },
+ });
+
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+ expect(
+ screen.queryByText(/You are not permitted to upload CSV files/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the obtain-permission prompt when uploads are enabled but the user cannot upload", async () => {
+ // Uploads are configured, but this user lacks upload permission and no
+ // provisioning is underway, so they get pointed at their administrator.
+ setup({
+ panelProps: { 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("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();
+ // Numbers are derived from the add-on product: 1M included rows,
+ // $0.000002 per row => $2 per additional 1M rows.
+ 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();
+
+ // Simulate closing the Add data modal (panel content unmounts) and reopening
+ // it. The provider lives above the modal, so the setting-up state survives.
+ remount(false);
+ expect(screen.queryByText("Setting up storage")).not.toBeInTheDocument();
+
+ remount(true);
+ expect(await screen.findByText("Setting up storage")).toBeInTheDocument();
+ });
+});
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..953923fa640
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.tsx
@@ -0,0 +1,98 @@
+import { useDisclosure } from "@mantine/hooks";
+import { useEffect, useMemo } from "react";
+import { usePrevious } from "react-use";
+import { t } from "ttag";
+
+import {
+ StorageSetupContext,
+ type StorageSetupContextValue,
+ type StorageSetupProviderProps,
+} from "metabase/common/components/upsells/StoragePurchaseModal";
+import { useToast } from "metabase/common/hooks";
+
+import { StoragePurchaseModal } from "./StoragePurchaseModal";
+import { usePurchaseStorageAddOn } from "./use-purchase-storage-add-on";
+import { useStorageAddOn } from "./use-storage-add-on";
+
+/**
+ * The real storage setup provider. It owns the cloud-add-ons endpoints, so it
+ * lives in enterprise and is injected into the OSS Add data modal via
+ * `PLUGIN_UPLOAD_MANAGEMENT.StorageSetupProvider` (hosted instances only),
+ * supplying the `StorageSetupContext` that `useStorageSetup` reads.
+ *
+ * Must be mounted outside the modal's `Modal.Root` so its polling keeps running
+ * while the modal is closed, and so the purchase confirmation modal it renders
+ * replaces the host modal instead of stacking on it.
+ */
+export const StorageSetupProvider = ({
+ children,
+ enabled = true,
+}: StorageSetupProviderProps) => {
+ const {
+ isSettingUp,
+ hasAttachedDwh,
+ handlePurchase,
+ resetPurchase,
+ canSetUpStorage,
+ } = usePurchaseStorageAddOn();
+ const { storageAddOn, isLoading: isLoadingStorageAddOn } = useStorageAddOn({
+ skip: !enabled || !canSetUpStorage,
+ });
+ const [
+ isPurchaseModalOpened,
+ { open: openPurchaseModal, close: closePurchaseModal },
+ ] = useDisclosure(false);
+ const [sendToast] = useToast();
+
+ // On the transition out of setting-up, clear the shared purchase state and
+ // toast only if it ended because storage became ready (not on error).
+ const wasSettingUp = usePrevious(isSettingUp);
+ useEffect(() => {
+ if (wasSettingUp && !isSettingUp) {
+ resetPurchase();
+ if (hasAttachedDwh) {
+ 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`,
+ });
+ }
+ }
+ }, [wasSettingUp, isSettingUp, hasAttachedDwh, resetPurchase, sendToast]);
+
+ const value = useMemo<StorageSetupContextValue>(
+ () => ({
+ isSettingUp,
+ storageAddOn,
+ isLoadingStorageAddOn,
+ isPurchaseModalOpened,
+ openPurchaseModal,
+ hasAttachedDwh,
+ canSetUpStorage,
+ }),
+ [
+ isSettingUp,
+ storageAddOn,
+ isLoadingStorageAddOn,
+ isPurchaseModalOpened,
+ openPurchaseModal,
+ hasAttachedDwh,
+ canSetUpStorage,
+ ],
+ );
+
+ return (
+ <StorageSetupContext.Provider value={value}>
+ {children}
+
+ {storageAddOn && canSetUpStorage && (
+ <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..f50319172af
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/StorageSetupProvider.unit.spec.tsx
@@ -0,0 +1,233 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupDatabaseListEndpoint,
+ setupPropertiesEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+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";
+
+const TestConsumer = () => {
+ const { isSettingUp, openPurchaseModal } = useStorageSetup();
+
+ return (
+ <div>
+ <button onClick={openPurchaseModal}>Open purchase modal</button>
+ {isSettingUp && <span>setting up</span>}
+ </div>
+ );
+};
+
+interface SetupOpts {
+ tokenFeatures?: Partial<TokenFeatures>;
+ hasAttachedDwhDatabase?: boolean;
+ isHosted?: boolean;
+ addOns?: ICloudAddOnProduct[];
+}
+
+const setup = ({
+ tokenFeatures = {},
+ hasAttachedDwhDatabase = false,
+ isHosted = true,
+ addOns = [mockStorageCloudAddOn],
+}: 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"] : [],
+ }),
+ }),
+ );
+ // Storage is only "ready" once the provisioned Cloud Storage database
+ // (marked `is_attached_dwh`) surfaces in the databases list and accepts
+ // uploads, so seed it when the provisioned state is expected.
+ setupDatabaseListEndpoint(
+ hasAttachedDwhDatabase
+ ? [
+ createMockDatabase({
+ id: 1,
+ can_upload: true,
+ is_attached_dwh: true,
+ }),
+ ]
+ : [],
+ );
+ fetchMock.get("path:/api/ee/cloud-add-ons/addons", addOns);
+ fetchMock.post("path:/api/ee/cloud-add-ons/dwh-rent", 200);
+ fetchMock.post(
+ "path:/api/premium-features/token/refresh",
+ createMockTokenStatus(),
+ );
+
+ renderWithProviders(
+ <StorageSetupProvider>
+ <TestConsumer />
+ <UndoListing />
+ </StorageSetupProvider>,
+ {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ settings: mockSettings(settingValues),
+ }),
+ },
+ );
+};
+
+const openPurchaseModal = async () => {
+ await userEvent.click(
+ screen.getByRole("button", { name: "Open purchase modal" }),
+ );
+ return screen.findByRole("dialog", { name: "Add Metabase Storage" });
+};
+
+const purchaseStorage = async () => {
+ const modal = await openPurchaseModal();
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Add Metabase Storage" }),
+ );
+};
+
+describe("StorageSetupProvider", () => {
+ it("purchases the add-on on confirm and enters the setting-up state", async () => {
+ setup();
+
+ await purchaseStorage();
+
+ 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 () => {
+ setup();
+
+ await purchaseStorage();
+
+ expect(await screen.findByText("setting up")).toBeInTheDocument();
+
+ // The hook polls the databases list (in addition to settings) so the
+ // surrounding panels can react without a page reload.
+ await waitFor(
+ () => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/database").length,
+ ).toBeGreaterThan(1);
+ },
+ { timeout: 4000 },
+ );
+ });
+
+ it("stays in the setting-up state while the attached DWH database is missing, even when the token feature flipped", async () => {
+ setup({ tokenFeatures: { attached_dwh: true } });
+
+ await purchaseStorage();
+
+ 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 is available", async () => {
+ setup({
+ tokenFeatures: { attached_dwh: true },
+ hasAttachedDwhDatabase: true,
+ });
+
+ await purchaseStorage();
+
+ // Once storage is ready the provider resets back to `initial`, so the
+ // setting-up flag clears and hosting panels reveal their default view.
+ await waitFor(() => {
+ expect(screen.queryByText("setting up")).not.toBeInTheDocument();
+ });
+ expect(
+ await screen.findByText("Metabase Storage is ready"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not flash the setting-up state or toast on load for an instance that already has storage", async () => {
+ // Existing storage admin loading the app, no purchase. The token feature is
+ // synchronous while the databases list is async, so setting-up must not
+ // flash on while the list is still loading.
+ setup({
+ tokenFeatures: { attached_dwh: true },
+ hasAttachedDwhDatabase: true,
+ });
+
+ // Wait for the databases list to resolve — the transition that used to flip
+ // setting-up false → true → false.
+ 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();
+ });
+
+ 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/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..f5a995b10d8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/storage/use-purchase-storage-add-on.ts
@@ -0,0 +1,97 @@
+import { useCallback } from "react";
+import { t } from "ttag";
+
+import { useGetSettingsQuery, useListDatabasesQuery } from "metabase/api";
+import { useTokenRefreshUntil } from "metabase/api/utils";
+import {
+ useHasTokenFeature,
+ useSetting,
+ useToast,
+} from "metabase/common/hooks";
+import { 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";
+
+const POLL_INTERVAL_MS = 2000;
+
+const STORAGE_PURCHASE_CACHE_KEY = "purchase-storage-add-on";
+
+export function usePurchaseStorageAddOn() {
+ const isHosted = useSetting("is-hosted?");
+ const isAdmin = useSelector(getUserIsAdmin);
+ const hasStorageTokenFeature = useHasTokenFeature("attached_dwh");
+ const [sendToast] = useToast();
+
+ const [
+ purchaseCloudAddOn,
+ { isLoading: isPurchasing, isSuccess: isPurchased, reset: resetPurchase },
+ ] = usePurchaseCloudAddOnMutation({
+ fixedCacheKey: STORAGE_PURCHASE_CACHE_KEY,
+ });
+
+ const canSetUpStorage = isHosted && isAdmin;
+
+ const { data: databasesResponse } = useListDatabasesQuery(undefined, {
+ skip: !canSetUpStorage,
+ });
+ // Until loaded, "no attached DWH" is indistinguishable from "not fetched yet".
+ const areDatabasesLoaded = databasesResponse !== undefined;
+ const attachedDwhDatabase = databasesResponse?.data?.find(
+ (db) => db.is_attached_dwh,
+ );
+ const hasAttachedDwh = !!attachedDwhDatabase?.can_upload;
+
+ // Keeps us in setting-up from the POST until storage is ready; collapses on
+ // its own on error (mutation no longer pending or successful).
+ const isPurchaseSettingUp = isPurchasing || (isPurchased && !hasAttachedDwh);
+
+ // Server-derived, so it survives the redeploy that provisioning triggers: the
+ // token flips at purchase time, the DWH database only appears after redeploy.
+ const isProvisioning =
+ canSetUpStorage &&
+ hasStorageTokenFeature &&
+ areDatabasesLoaded &&
+ !hasAttachedDwh;
+
+ const isSettingUp = isPurchaseSettingUp || isProvisioning;
+
+ // Refresh the token (a Store round-trip) until `attached_dwh` shows up.
+ useTokenRefreshUntil("attached-dwh", {
+ skip: !isSettingUp || hasStorageTokenFeature,
+ });
+
+ // While setting up, poll the two sources the surrounding UI reads: session
+ // properties and the databases list.
+ useGetSettingsQuery(undefined, {
+ skip: !isSettingUp,
+ pollingInterval: POLL_INTERVAL_MS,
+ skipPollingIfUnfocused: true,
+ });
+ useListDatabasesQuery(undefined, {
+ skip: !isSettingUp,
+ pollingInterval: POLL_INTERVAL_MS,
+ skipPollingIfUnfocused: true,
+ });
+
+ const handlePurchase = useCallback(async () => {
+ try {
+ await purchaseCloudAddOn({ product_type: STORAGE_PRODUCT_TYPE }).unwrap();
+ } catch {
+ sendToast({
+ icon: "warning_triangle_filled",
+ iconColor: "warning",
+ message: t`It looks like something went wrong. Please refresh the page and try again.`,
+ });
+ }
+ }, [purchaseCloudAddOn, sendToast]);
+
+ return {
+ isSettingUp,
+ hasAttachedDwh,
+ handlePurchase,
+ resetPurchase,
+ canSetUpStorage,
+ };
+}
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 b494e4b49dd..d76e36712a9 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 9e68da6675f..5cd322938bb 100644
--- a/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.tsx
+++ b/frontend/src/metabase/admin/settings/components/UploadSettings/UploadSettingsForm.tsx
@@ -173,6 +173,7 @@ export function UploadSettingsFormView({
<Group align="flex-start">
<Select
label={t`Database to use for uploads`}
+ description={t`PostgreSQL, MySQL, Redshift, and ClickHouse databases are supported for file storage.`}
value={dbId ? String(dbId) : null}
placeholder={t`Select a database`}
disabled={!hasValidDatabases}
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..a200207baba 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,15 @@ describe("Admin > Settings > UploadSettingsFormView", () => {
).toBeInTheDocument();
});
+ it("should render the supported-databases helper text under the dropdown", async () => {
+ setup();
+ expect(
+ screen.getByText(
+ "PostgreSQL, MySQL, Redshift, and ClickHouse 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..1db3dea38f2 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);
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..1ae0a1b2d3d
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StoragePurchaseButton.tsx
@@ -0,0 +1,56 @@
+import { useMount } from "react-use";
+import { t } from "ttag";
+
+import { useStoreUrl } from "metabase/common/hooks/use-store-url/use-store-url";
+import { Button } from "metabase/ui";
+
+import { UpsellGem } from "../components/UpsellGem";
+import { trackUpsellClicked, trackUpsellViewed } from "../components/analytics";
+
+import { useStorageSetup } from "./storage-setup-context";
+
+const CAMPAIGN = "storage";
+
+export const StoragePurchaseButton = ({ location }: { location: string }) => {
+ const { canSetUpStorage, openPurchaseModal, storageAddOn } =
+ useStorageSetup();
+ const storeUrl = useStoreUrl("account/storage");
+
+ useMount(() => {
+ if (canSetUpStorage) {
+ trackUpsellViewed({ location, campaign: CAMPAIGN });
+ }
+ });
+
+ if (!canSetUpStorage) {
+ return null;
+ }
+
+ const handleClick = () => {
+ trackUpsellClicked({ location, campaign: CAMPAIGN });
+ if (storageAddOn) {
+ openPurchaseModal();
+ }
+ };
+
+ const linkProps = storageAddOn
+ ? null
+ : {
+ component: "a" as const,
+ href: storeUrl,
+ target: "_blank",
+ rel: "noopener noreferrer",
+ };
+
+ return (
+ <Button
+ variant="default"
+ leftSection={<UpsellGem />}
+ onClick={handleClick}
+ {...linkProps}
+ >
+ {/* 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/StorageSetupView.tsx b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupView.tsx
new file mode 100644
index 00000000000..5134824f55c
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/StorageSetupView.tsx
@@ -0,0 +1,47 @@
+import { t } from "ttag";
+
+import { Box, Flex, Loader, Stack, Text, Title } from "metabase/ui";
+
+import databaseAdd from "./database-add.svg?component";
+
+const StorageIcon = () => (
+ <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)`,
+ }}
+ >
+ <Loader size="xs" ml={1} mt={1} />
+ </Flex>
+ </Box>
+);
+
+export const StorageSetupView = () => (
+ <Stack align="center" justify="center" gap="lg" h="100%">
+ <StorageIcon />
+
+ <Box ta="center">
+ <Title c="text-primary" fz="lg">
+ {t`Setting up storage`}
+ </Title>
+ <Text c="text-secondary" fz="md" lh={1.43}>
+ {t`This can take a few minutes.`}
+ </Text>
+ </Box>
+ </Stack>
+);
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..84833e6966d
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/index.ts
@@ -0,0 +1,9 @@
+export {
+ StorageSetupContext,
+ StorageSetupProvider,
+ useStorageSetup,
+ type StorageSetupContextValue,
+ type StorageSetupProviderProps,
+} from "./storage-setup-context";
+export { StorageSetupView } from "./StorageSetupView";
+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..1dd5275482c
--- /dev/null
+++ b/frontend/src/metabase/common/components/upsells/StoragePurchaseModal/storage-setup-context.tsx
@@ -0,0 +1,57 @@
+import type { ReactNode } from "react";
+import { createContext, useContext } from "react";
+
+import type { ICloudAddOnProduct } from "metabase-types/api";
+
+export interface StorageSetupContextValue {
+ isSettingUp: boolean;
+ storageAddOn: ICloudAddOnProduct | undefined;
+ isLoadingStorageAddOn: boolean;
+ isPurchaseModalOpened: boolean;
+ openPurchaseModal: () => void;
+ hasAttachedDwh: boolean;
+ canSetUpStorage: boolean;
+}
+
+export const StorageSetupContext =
+ createContext<StorageSetupContextValue | null>(null);
+
+export interface StorageSetupProviderProps {
+ children: ReactNode;
+ /**
+ * Pass `false` while the hosting UI is hidden to avoid fetching the add-ons
+ * list (a Store API round-trip) eagerly. Purchase/setup state and its
+ * polling keep running regardless.
+ */
+ enabled?: boolean;
+}
+
+const INERT_STORAGE_SETUP_VALUE: StorageSetupContextValue = {
+ isSettingUp: false,
+ storageAddOn: undefined,
+ isLoadingStorageAddOn: false,
+ isPurchaseModalOpened: false,
+ openPurchaseModal: () => {},
+ hasAttachedDwh: false,
+ canSetUpStorage: 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/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/AddDataModal.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/AddDataModal/AddDataModal.tsx
index 67adcdc2f52..21ba8a8f82e 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";
@@ -14,11 +14,7 @@ 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 { type AddDataTab, isValidTab } from "./utils";
interface AddDataModalProps {
opened: boolean;
@@ -35,29 +31,36 @@ interface Tabs {
iconName: IconName;
}
-export const AddDataModal = ({
+export const AddDataModal = (props: AddDataModalProps) => (
+ // The provider sits outside `Modal.Root` so the storage setup state and its
+ // polling survive the modal being closed and reopened, and so the purchase
+ // confirmation modal it hosts can replace this modal instead of stacking.
+ // `enabled` defers the add-ons fetch until the modal is actually 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 { data: databasesResponse } = useListDatabasesQuery();
- const { data: uploadableDatabasesResponse } = useListDatabasesQuery({
- include_only_uploadable: true,
- });
-
- const hasUploadableDatabases = hasMeaningfulUploadableDatabases({
- allDatabases: databasesResponse?.data,
- allUploadableDatabases: uploadableDatabasesResponse?.data,
- });
-
- const shouldShowUploadsPanel = hasUploadableDatabases || canUploadToDatabase;
+ const {
+ areUploadsEnabled,
+ canUploadToDatabase,
+ canManageUploads,
+ isAdmin,
+ canPerformMeaningfulActions,
+ hasUploadableDatabases,
+ } = useAddDataPermissions();
+ const { isPurchaseModalOpened, canSetUpStorage } = useStorageSetup();
+
+ const shouldShowUploadsTab =
+ hasUploadableDatabases || canPerformMeaningfulActions || canSetUpStorage;
const [activeTab, setActiveTab] = useState<Tabs["value"] | null>(null);
-
const isHosted = useSetting("is-hosted?");
const handleTabChange = (tabValue: string | null) => {
@@ -77,11 +80,16 @@ export const AddDataModal = ({
const tabs = useMemo(() => {
return [
- { name: t`Database`, value: "db", isVisible: true, iconName: "database" },
+ {
+ name: t`Database`,
+ value: "db",
+ isVisible: true,
+ iconName: "database",
+ },
{
name: t`CSV`,
value: "csv",
- isVisible: shouldShowUploadsPanel,
+ isVisible: shouldShowUploadsTab,
iconName: "table2",
},
{
@@ -91,7 +99,7 @@ export const AddDataModal = ({
iconName: "document",
},
] satisfies Tabs[];
- }, [shouldShowUploadsPanel, isHosted]);
+ }, [shouldShowUploadsTab, isHosted]);
useEffect(() => {
if (initialTab) {
@@ -106,7 +114,14 @@ export const AddDataModal = ({
}, [tabs, initialTab]);
return (
- <Modal.Root opened={opened} onClose={onClose} size="auto">
+ // The modal hides itself (stays mounted) while the storage purchase
+ // confirmation is shown, 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
@@ -142,10 +157,20 @@ export const AddDataModal = ({
<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 && areUploadsEnabled
+ }
onAddDataModalClose={onClose}
/>
+ <Tabs.Panel value="db" className={S.panel}>
+ <DatabasesPanel
+ canSeeContent={isAdmin}
+ fromEmbeddingSetupGuide={fromEmbeddingSetupGuide}
+ />
+ </Tabs.Panel>
<Tabs.Panel value="csv" className={S.panel}>
<CSVPanel
onCloseAddDataModal={onClose}
@@ -154,12 +179,6 @@ export const AddDataModal = ({
canManageUploads={canManageUploads}
/>
</Tabs.Panel>
- <Tabs.Panel value="db" className={S.panel}>
- <DatabasesPanel
- canSeeContent={isAdmin}
- fromEmbeddingSetupGuide={fromEmbeddingSetupGuide}
- />
- </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 432bb6fdee2..edf7fdfc58e 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
@@ -10,11 +10,11 @@ import {
Box,
Button,
Center,
+ Group,
Icon,
Stack,
Text,
Title,
- Tooltip,
} from "metabase/ui";
import { getSubpathSafeUrl } from "metabase/urls";
@@ -109,7 +109,7 @@ interface EmptyStateProps {
illustration: ReactNode;
ctaLink?: CTALink;
contactAdminReason?: ContactReason;
- upsell?: ReactNode;
+ secondaryAction?: ReactNode;
}
const AddDataEmptyState = ({
@@ -118,7 +118,7 @@ const AddDataEmptyState = ({
illustration,
ctaLink,
contactAdminReason,
- upsell,
+ secondaryAction,
}: EmptyStateProps) => {
return (
<Stack gap="lg" align="center" justify="center" pt="2.5rem">
@@ -130,17 +130,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,35 +165,25 @@ export const DatabasePanelEmptyState = () => {
export const CSVPanelEmptyState = ({
ctaLink,
contactAdminReason,
- upsell,
+ secondaryAction,
}:
| {
ctaLink: CTALink;
contactAdminReason?: never;
- upsell?: ReactNode;
+ secondaryAction?: ReactNode;
}
| {
ctaLink?: never;
contactAdminReason: ContactReason;
- upsell?: never;
+ secondaryAction?: 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 storageSubtitle =
+ // 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.`;
+
+ const ctaSubtitle = secondaryAction
+ ? storageSubtitle
+ : t`To work with CSVs, enable file uploads in your database.`;
const subtitle = ctaLink
? ctaSubtitle
@@ -201,10 +193,10 @@ export const CSVPanelEmptyState = ({
<AddDataEmptyState
title={t`Upload CSV files`}
subtitle={subtitle}
- illustration={<Box component={IconCSV} c="core-brand" h={66} />}
+ illustration={<Box component={IconCSV} c="core-brand" h={48} />}
contactAdminReason={contactAdminReason}
ctaLink={ctaLink}
- upsell={upsell}
+ secondaryAction={secondaryAction}
/>
);
};
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..f1f2ede18e7 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,6 +1,11 @@
import { t } from "ttag";
-import { UpsellStorage } from "metabase/common/components/upsells/UpsellStorage";
+import {
+ StoragePurchaseButton,
+ StorageSetupView,
+ useStorageSetup,
+} from "metabase/common/components/upsells/StoragePurchaseModal";
+import { Center, Loader } from "metabase/ui";
import * as Urls from "metabase/urls";
import { CSVPanelEmptyState } from "./AddDataModalEmptyStates";
@@ -19,11 +24,17 @@ export const CSVPanel = ({
onCloseAddDataModal,
uploadsEnabled,
}: CSVPanelProps) => {
- const showObtainPermissionPrompt = uploadsEnabled && !canUpload;
+ const { isSettingUp, isLoadingStorageAddOn, canSetUpStorage } =
+ useStorageSetup();
+ const showObtainPermissionPrompt = uploadsEnabled && !canUpload;
const showEnableUploadsCTA = !uploadsEnabled && canManageUploads;
const showEnableUploadsPrompt = !uploadsEnabled && !canManageUploads;
+ if (isSettingUp) {
+ return <StorageSetupView />;
+ }
+
if (showEnableUploadsPrompt) {
return <CSVPanelEmptyState contactAdminReason="enable-csv-upload" />;
}
@@ -35,13 +46,25 @@ export const CSVPanel = ({
}
if (showEnableUploadsCTA) {
+ if (isLoadingStorageAddOn) {
+ return (
+ <Center h="100%">
+ <Loader data-testid="loading-indicator" />
+ </Center>
+ );
+ }
+
return (
<CSVPanelEmptyState
ctaLink={{
text: t`Enable uploads`,
to: Urls.uploadsSettings(),
}}
- upsell={<UpsellStorage location="add-data-modal-csv" />}
+ secondaryAction={
+ canSetUpStorage ? (
+ <StoragePurchaseButton location="add-data-modal-csv" />
+ ) : undefined
+ }
/>
);
}
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..1cf30ae3b76 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(
+ 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.findByText("Add Metabase Storage"),
+ 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,29 +249,15 @@ describe("AddDataModal", () => {
).toBeInTheDocument();
});
- it("regular user should be instructed to contact their admin in order to gain upload permissions", async () => {
+ it("does not offer the CSV tab to a regular user who cannot upload to any database", async () => {
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" }),
+ await screen.findByRole("tab", { name: /Database$/ }),
).toBeInTheDocument();
expect(
- screen.getByText(
- "Work with CSVs, just like with any other data source.",
- ),
- ).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();
- expect(
- within(alert).getByText("[email protected]"),
- ).toBeInTheDocument();
+ screen.queryByRole("tab", { name: /CSV$/ }),
+ ).not.toBeInTheDocument();
});
it("should show CSV panel for a regular user with sufficient permissions", async () => {
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..c25d3da19a5 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,57 @@
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";
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.",
});
+ // The upsell is 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/,
+ });
+ expect(upsellLink).toHaveAttribute(
+ "href",
+ "https://store.metabase.com/account/storage",
+ );
+ });
+
+ 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.",
+ });
+
+ // When purchasable in-app, the button opens the purchase confirmation
+ // instead of linking to the store.
+ 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 () => {
@@ -187,16 +216,19 @@ describe("Add data modal (Pro: hosted instance with the attached DWH)", () => {
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..5997e8b22ae 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,7 @@ import {
setupGdriveGetFolderEndpoint,
setupGdrivePostFolderEndpoint,
setupGdriveServiceAccountEndpoint,
+ setupPropertiesEndpoints,
setupTokenStatusEndpoint,
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
@@ -12,10 +15,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 +42,7 @@ interface SetupOpts {
enableGoogleSheets?: boolean;
status?: GdrivePayload["status"];
adminEmail?: string | null;
+ addOns?: ICloudAddOnProduct[];
}
export const setup = ({
@@ -48,6 +57,7 @@ export const setup = ({
enableGoogleSheets = false,
status,
adminEmail = "[email protected]",
+ addOns = [],
}: SetupOpts = {}) => {
const user = createMockUser({
is_superuser: isAdmin,
@@ -71,8 +81,36 @@ export const setup = ({
can_upload: isAdmin || canUpload,
});
+ // Once Storage is provisioned the attached DWH database surfaces in the
+ // databases list (with `is_attached_dwh` + uploads enabled). This is the
+ // signal the storage UI actually keys off — the `attached_dwh` token feature
+ // flips earlier — so faithful mocks must include it whenever it is set.
+ const attachedDwhDatabase = tokenFeatures.attached_dwh
+ ? createMockDatabase({
+ id: 2,
+ name: "Metabase Storage",
+ is_attached_dwh: true,
+ can_upload: true,
+ })
+ : 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 +118,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 +132,8 @@ 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);
if (enableGoogleSheets) {
setupGdrivePostFolderEndpoint();
@@ -139,6 +170,9 @@ export const setupHostedInstance = (opts: Partial<SetupOpts>) => {
export const setupProUpload = (opts: Partial<SetupOpts>) =>
setupHostedInstance({
+ // A provisioned attached DWH enables uploads by default, so the imports
+ // settings link (gated on uploads being enabled) is available to admins.
+ 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
index 2ab62cc8c40..c6ec7a2b45d 100644
--- 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
@@ -10,6 +10,7 @@ export function useAddDataPermissions() {
const databases = databasesResponse?.data;
const uploadDbId = useSetting("uploads-settings")?.db_id;
const uploadDB = databases?.find((db) => db.id === uploadDbId);
+ const hasUploadableDatabases = !!databases?.some((db) => db.can_upload);
/**
* This covers the case where instance has the attached dwh. In such cases
@@ -26,6 +27,7 @@ export function useAddDataPermissions() {
canUploadToDatabase,
canManageUploads,
canPerformMeaningfulActions,
+ hasUploadableDatabases,
isAdmin,
};
}
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/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();