The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Fix purchase page for paid Metabase AI add-on for non-store users (#66086)
Dennis Schriddea7f3165348e6
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.tsxindex dd96d244166..c4abbbbd72b 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.tsx@@ -1,181 +1,27 @@-import { useDisclosure } from "@mantine/hooks";-import { type ReactElement, useCallback } from "react";-import { P, match } from "ts-pattern";+import type { ReactElement } from "react";import { t } from "ttag";-import * as Yup from "yup";-import {- SettingsPageWrapper,- SettingsSection,-} from "metabase/admin/components/SettingsSection";-import ExternalLink from "metabase/common/components/ExternalLink";-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import {- Form,- FormCheckbox,- FormProvider,- FormSubmitButton,-} from "metabase/forms";+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";import { useSelector } from "metabase/lib/redux";import { getStoreUsers } from "metabase/selectors/store-users";-import { Card, Stack, Text } from "metabase/ui";-import { usePurchaseCloudAddOnMutation } from "metabase-enterprise/api";+import { Text } from "metabase/ui";-import { MetabotSettingUpModal } from "../MetabotSettingUpModal";-import { handleFieldError, isFetchBaseQueryError } from "../utils";--import { MetabotRadios } from "./MetabotRadios";-import { useAddOnsBilling } from "./hooks";-import type { IMetabotPurchaseFormFields } from "./types";+import { MetabotPurchasePageForNonStoreUser } from "./MetabotPurchasePageForNonStoreUser";+import { MetabotPurchasePageForStoreUser } from "./MetabotPurchasePageForStoreUser";export function MetabotPurchasePage(): ReactElement {const { isStoreUser, anyStoreUserEmailAddress } = useSelector(getStoreUsers);- const { isLoading, error, billingPeriodMonths, tiers, defaultQuantity } =- useAddOnsBilling();- const hasData =- billingPeriodMonths !== undefined &&- defaultQuantity !== undefined &&- tiers.length > 0;-- const [settingUpModalOpened, settingUpModalHandlers] = useDisclosure(false);- const [purchaseCloudAddOn] = usePurchaseCloudAddOnMutation();- const onSubmit = useCallback(- async ({ quantity, terms_of_service }: IMetabotPurchaseFormFields) => {- settingUpModalHandlers.open();- await purchaseCloudAddOn({- product_type: "metabase-ai-tiered",- quantity: parseInt(quantity, 10),- terms_of_service,- })- .unwrap()- .catch((error: unknown) => {- settingUpModalHandlers.close();- if (isFetchBaseQueryError(error)) {- handleFieldError<IMetabotPurchaseFormFields>(- error.data,- "terms_of_service",- );- }- throw error;- });- },- [purchaseCloudAddOn, settingUpModalHandlers],- );-- if (error || !hasData || isLoading) {- return (- <LoadingAndErrorWrapper- loading={isLoading}- error={match({- isLoading,- hasData,- error,- })- .with(- { isLoading: false, hasData: P.any, error: P.nonNullable },- { isLoading: false, hasData: false, error: P.any },- () => t`Error fetching information about available add-ons.`,- )- .otherwise(() => null)}- />- );- }-- const validationSchema = Yup.object({- quantity: Yup.string()- .required()- .test(- "quantity-is-int",- t`Quantity must be a positive integer`,- (v) => !!v && parseInt(v, 10) > 0,- ),- terms_of_service: Yup.boolean()- .required()- .isTrue(t`Terms of Service must be accepted`),- });-return (<SettingsPageWrapper title={t`Metabot AI`}><Text maw="26rem">{t`Metabot helps you move faster and understand your data better. You can ask it to generate SQL, and build or explain queries.`}</Text>{isStoreUser ? (- <SettingsSection- title={t`Monthly usage limit`}- description={- <Text- maw="35rem"- mt="sm"- >{t`Usage is measured in Metabot requests. If a chat has multiple questions, they are counted as separate Metabot requests. Usage limit applies to your whole organization.`}</Text>- }- >- <FormProvider- initialValues={{- quantity: `${defaultQuantity}`,- terms_of_service: false,- }}- onSubmit={onSubmit}- validationSchema={validationSchema}- >- {({ values }) => (- <Form>- <Stack gap="xl" w="100%">- <MetabotRadios- quantity={values.quantity}- tiers={tiers}- billingPeriodMonths={billingPeriodMonths}- />-- <Stack gap="md">- {/* eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins. */}- <Text maw="35rem">{t`Additional amount for the add-on will be added to your next billing period invoice. You can cancel the add-on anytime in Metabase Store.`}</Text>-- <Card- bg="var(--mb-color-bg-light)"- p={12}- radius="md"- shadow="none"- w="100%"- >- <FormCheckbox- name="terms_of_service"- label={- <Text>- {t`I agree with the Metabot AI add-on`}{" "}- <ExternalLink href="https://www.metabase.com/license/hosting">{t`Terms of Service`}</ExternalLink>- </Text>- }- />- </Card>-- <FormSubmitButton- disabled={!values.terms_of_service}- label={t`Confirm purchase`}- failedLabel={t`Failed to purchase Metabot AI`}- variant="filled"- w="100%"- />- </Stack>- </Stack>- </Form>- )}- </FormProvider>- </SettingsSection>+ <MetabotPurchasePageForStoreUser />) : (- <Text fw="bold">- {- /* eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins. */- t`Please ask a Metabase Store Admin${anyStoreUserEmailAddress && ` (${anyStoreUserEmailAddress})`} of your organization to enable this for you.`- }- </Text>+ <MetabotPurchasePageForNonStoreUser+ anyStoreUserEmailAddress={anyStoreUserEmailAddress}+ />)}-- <MetabotSettingUpModal- opened={settingUpModalOpened}- onClose={() => {- settingUpModalHandlers.close();- window.location.reload();- }}- /></SettingsPageWrapper>);}diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.unit.spec.tsxindex 91e9c085903..dd574c5b9a3 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePage.unit.spec.tsx@@ -18,6 +18,40 @@ import { createMockSettingsState } from "metabase-types/store/mocks";import { MetabotPurchasePage } from ".";+const expectNonStoreUserPage = async () => {+ expect(+ await screen.findByText(/Please ask a Metabase Store Admin/),+ ).toBeVisible();+ expect(+ screen.queryByText(/Additional amount for the add-on/),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(/Error fetching information/),+ ).not.toBeInTheDocument();+};++const expectStoreUserPage = async () => {+ expect(+ screen.queryByText(/Please ask a Metabase Store Admin/),+ ).not.toBeInTheDocument();+ expect(+ await screen.findByText(/Additional amount for the add-on/),+ ).toBeVisible();+ expect(+ screen.queryByText(/Error fetching information/),+ ).not.toBeInTheDocument();+};++const expectErrorPage = async () => {+ expect(+ screen.queryByText(/Please ask a Metabase Store Admin/),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(/Additional amount for the add-on/),+ ).not.toBeInTheDocument();+ expect(await screen.findByText(/Error fetching information/)).toBeVisible();+};+const setupRefreshableProperties = ({current_user_matches_store_user,has_metabot_v3 = false,@@ -72,6 +106,8 @@ const setup = async ({currentUser: user,},});++ await screen.findByText(/Metabot helps you move faster/);};describe("MetabotPurchasePage", () => {@@ -82,12 +118,8 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: false,simulate_http_post_error: false,});- expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();- expect(- screen.getByText(/Please ask a Metabase Store Admin/),- ).toBeInTheDocument();++ await expectNonStoreUserPage();});it("shows an error message when retrieving billing or add-on information fails", async () => {@@ -97,13 +129,19 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: true,simulate_http_post_error: false,});- expect(await screen.findByText(/Error fetching information/)).toBeVisible();- expect(- screen.queryByText(/Metabot helps you move faster/),- ).not.toBeInTheDocument();- expect(- screen.queryByText(/Please ask a Metabase Store Admin/),- ).not.toBeInTheDocument();++ await expectErrorPage();+ });++ it("does not show an error message when when current user is not a store user", async () => {+ await setup({+ current_user_matches_store_user: false,+ billing_period_months: 12,+ simulate_http_get_error: true,+ simulate_http_post_error: false,+ });++ await expectNonStoreUserPage();});it("shows monthly tiers according to own billing period", async () => {@@ -113,12 +151,9 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: false,simulate_http_post_error: false,});- expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();- expect(- screen.queryByText(/Please ask a Metabase Store Admin/),- ).not.toBeInTheDocument();++ await expectStoreUserPage();+const metabase_ai_tier1 = screen.getByRole("radio", {name: /up to 1234 requests\/month/,});@@ -138,12 +173,9 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: false,simulate_http_post_error: false,});- expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();- expect(- screen.queryByText(/Please ask a Metabase Store Admin/),- ).not.toBeInTheDocument();++ await expectStoreUserPage();+const metabase_ai_tier3 = screen.getByRole("radio", {name: /up to 3456 requests\/month/,});@@ -163,46 +195,30 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: false,simulate_http_post_error: false,});++ await expectStoreUserPage();++ // This add-on product tier has `is_default = true`:expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();- expect(- screen.queryByText(/Please ask a Metabase Store Admin/),- ).not.toBeInTheDocument();+ screen.getByRole("radio", { name: /up to 4567 requests/ }),+ ).toBeChecked();expect(screen.getByRole("checkbox", { name: /Terms of Service/ }),).not.toBeChecked();expect(screen.getByRole("button", { name: /Confirm purchase/ }),).toBeDisabled();+await userEvent.click(screen.getByRole("checkbox", { name: /Terms of Service/ }),);+expect(screen.getByRole("checkbox", { name: /Terms of Service/ }),).toBeChecked();expect(screen.getByRole("button", { name: /Confirm purchase/ }),).toBeEnabled();- });-- it("submits a HTTP request", async () => {- await setup({- current_user_matches_store_user: true,- billing_period_months: 12,- simulate_http_get_error: false,- simulate_http_post_error: false,- });- expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();- // This add-on product tier has `is_default = true`:- expect(- screen.getByRole("radio", { name: /up to 4567 requests/ }),- ).toBeChecked();- await userEvent.click(- screen.getByRole("checkbox", { name: /Terms of Service/ }),- );await userEvent.click(screen.getByRole("button", { name: /Confirm purchase/ }),@@ -240,9 +256,9 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: false,simulate_http_post_error: false,});- expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();++ await expectStoreUserPage();+await userEvent.click(screen.getByRole("radio", { name: /up to 3456 requests/ }),);@@ -272,9 +288,9 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: false,simulate_http_post_error: "error-no-quantity",});- expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();++ await expectStoreUserPage();+await userEvent.click(screen.getByRole("checkbox", { name: /Terms of Service/ }),);@@ -299,9 +315,9 @@ describe("MetabotPurchasePage", () => {simulate_http_get_error: false,simulate_http_post_error: "error-no-connection",});- expect(- await screen.findByText(/Metabot helps you move faster/),- ).toBeVisible();++ await expectStoreUserPage();+await userEvent.click(screen.getByRole("checkbox", { name: /Terms of Service/ }),);diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePageForNonStoreUser.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePageForNonStoreUser.tsxnew file mode 100644index 00000000000..c800308ed6e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePageForNonStoreUser.tsx@@ -0,0 +1,16 @@+import { t } from "ttag";++import { Text } from "metabase/ui";++import type { IPageForNonStoreUserProps } from "./types";++export const MetabotPurchasePageForNonStoreUser = ({+ anyStoreUserEmailAddress,+}: IPageForNonStoreUserProps) => (+ <Text fw="bold">+ {+ /* eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins. */+ t`Please ask a Metabase Store Admin${anyStoreUserEmailAddress && ` (${anyStoreUserEmailAddress})`} of your organization to enable this for you.`+ }+ </Text>+);diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePageForStoreUser.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePageForStoreUser.tsxnew file mode 100644index 00000000000..a8e3730533f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/MetabotPurchasePageForStoreUser.tsx@@ -0,0 +1,164 @@+import { useDisclosure } from "@mantine/hooks";+import { useCallback } from "react";+import { P, match } from "ts-pattern";+import { t } from "ttag";+import * as Yup from "yup";++import { SettingsSection } from "metabase/admin/components/SettingsSection";+import ExternalLink from "metabase/common/components/ExternalLink";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import {+ Form,+ FormCheckbox,+ FormProvider,+ FormSubmitButton,+} from "metabase/forms";+import { Card, Stack, Text } from "metabase/ui";+import { usePurchaseCloudAddOnMutation } from "metabase-enterprise/api";++import { MetabotSettingUpModal } from "../MetabotSettingUpModal";+import { handleFieldError, isFetchBaseQueryError } from "../utils";++import { MetabotRadios } from "./MetabotRadios";+import { useAddOnsBilling } from "./hooks";+import type { IMetabotPurchaseFormFields } from "./types";++export const MetabotPurchasePageForStoreUser = () => {+ const { isLoading, error, billingPeriodMonths, tiers, defaultQuantity } =+ useAddOnsBilling();+ const hasData =+ billingPeriodMonths !== undefined &&+ defaultQuantity !== undefined &&+ tiers.length > 0;++ const [settingUpModalOpened, settingUpModalHandlers] = useDisclosure(false);+ const [purchaseCloudAddOn] = usePurchaseCloudAddOnMutation();+ const onSubmit = useCallback(+ async ({ quantity, terms_of_service }: IMetabotPurchaseFormFields) => {+ settingUpModalHandlers.open();+ await purchaseCloudAddOn({+ product_type: "metabase-ai-tiered",+ quantity: parseInt(quantity, 10),+ terms_of_service,+ })+ .unwrap()+ .catch((error: unknown) => {+ settingUpModalHandlers.close();+ if (isFetchBaseQueryError(error)) {+ handleFieldError<IMetabotPurchaseFormFields>(+ error.data,+ "terms_of_service",+ );+ }+ throw error;+ });+ },+ [purchaseCloudAddOn, settingUpModalHandlers],+ );++ if (error || !hasData || isLoading) {+ return (+ <LoadingAndErrorWrapper+ loading={isLoading}+ error={match({+ isLoading,+ hasData,+ error,+ })+ .with(+ { isLoading: false, hasData: P.any, error: P.nonNullable },+ { isLoading: false, hasData: false, error: P.any },+ () => t`Error fetching information about available add-ons.`,+ )+ .otherwise(() => null)}+ />+ );+ }++ const validationSchema = Yup.object({+ quantity: Yup.string()+ .required()+ .test(+ "quantity-is-int",+ t`Quantity must be a positive integer`,+ (v) => !!v && parseInt(v, 10) > 0,+ ),+ terms_of_service: Yup.boolean()+ .required()+ .isTrue(t`Terms of Service must be accepted`),+ });++ return (+ <>+ <SettingsSection+ title={t`Monthly usage limit`}+ description={+ <Text+ maw="35rem"+ mt="sm"+ >{t`Usage is measured in Metabot requests. If a chat has multiple questions, they are counted as separate Metabot requests. Usage limit applies to your whole organization.`}</Text>+ }+ >+ <FormProvider+ initialValues={{+ quantity: `${defaultQuantity}`,+ terms_of_service: false,+ }}+ onSubmit={onSubmit}+ validationSchema={validationSchema}+ >+ {({ values }) => (+ <Form>+ <Stack gap="xl" w="100%">+ <MetabotRadios+ quantity={values.quantity}+ tiers={tiers}+ billingPeriodMonths={billingPeriodMonths}+ />++ <Stack gap="md">+ {/* eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins. */}+ <Text maw="35rem">{t`Additional amount for the add-on will be added to your next billing period invoice. You can cancel the add-on anytime in Metabase Store.`}</Text>++ <Card+ bg="var(--mb-color-bg-light)"+ p={12}+ radius="md"+ shadow="none"+ w="100%"+ >+ <FormCheckbox+ name="terms_of_service"+ label={+ <Text>+ {t`I agree with the Metabot AI add-on`}{" "}+ <ExternalLink href="https://www.metabase.com/license/hosting">{t`Terms of Service`}</ExternalLink>+ </Text>+ }+ />+ </Card>++ <FormSubmitButton+ disabled={!values.terms_of_service}+ label={t`Confirm purchase`}+ failedLabel={t`Failed to purchase Metabot AI`}+ variant="filled"+ w="100%"+ />+ </Stack>+ </Stack>+ </Form>+ )}+ </FormProvider>+ </SettingsSection>++ <MetabotSettingUpModal+ opened={settingUpModalOpened}+ onClose={() => {+ settingUpModalHandlers.close();+ window.location.reload();+ }}+ />+ </>+ );+};diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/types.ts b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/types.tsindex 317ab0723e3..a96dea38034 100644--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/types.ts+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage/types.ts@@ -5,6 +5,10 @@ export interface IMetabotPurchaseFormFields {terms_of_service: boolean;}+export interface IPageForNonStoreUserProps {+ anyStoreUserEmailAddress?: string;+}+export interface IMetabotRadioProps {selected?: boolean;value: string;