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
analytics events for documents (#62447)
Nick Fitzpatrick0d677e4f5183
diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.tsindex 42c8376ccd8..5d45ed8a79e 100644--- a/e2e/test/scenarios/documents/documents.cy.spec.ts+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts@@ -11,11 +11,12 @@ import {const { H } = cy;-describe("documents", () => {+H.describeWithSnowplowEE("documents", () => {beforeEach(() => {H.restore();cy.signInAsAdmin();H.activateToken("bleeding-edge");+ H.resetSnowplow();});it("should allow you to create a new document from the new button and save", () => {@@ -42,6 +43,8 @@ describe("documents", () => {H.entityPickerModal().findByRole("button", { name: "Select" }).click();cy.title().should("eq", "Test Document · Metabase");+ H.expectUnstructuredSnowplowEvent({ event: "document_created" });+H.appBar().findByRole("link", { name: /First collection/ }).click();@@ -181,6 +184,27 @@ describe("documents", () => {cy.findByText("The page you asked for couldn't be found.");});});++ it("should allow you to print", () => {+ cy.get("@documentId").then((id) => cy.visit(`/document/${id}`));+ cy.findByRole("button", { name: "More options" }).click();++ // This needs to be *after* the page load to work+ cy.window().then((win: Window) => {+ cy.stub(win, "print").as("printStub");+ });++ H.popover().findByText("Print Document").click();++ cy.get("@printStub").should("have.been.calledOnce");++ cy.get("@documentId").then((id) => {+ H.expectUnstructuredSnowplowEvent({+ event: "document_print",+ target_id: id,+ });+ });+ });});});@@ -369,6 +393,13 @@ describe("documents", () => {cy.realPress("{downarrow}");H.addToDocument("\n", false);+ cy.get("@documentId").then((id) => {+ H.expectUnstructuredSnowplowEvent({+ event: "document_add_card",+ target_id: id,+ });+ });+H.getDocumentCard(ACCOUNTS_COUNT_BY_CREATED_AT.name).should("exist");cy.realPress("{downarrow}");@@ -458,6 +489,13 @@ describe("documents", () => {cy.findAllByTestId("result-item").findByText("Orders").click();});+ cy.get("@documentId").then((id) => {+ H.expectUnstructuredSnowplowEvent({+ event: "document_replace_card",+ target_id: id,+ });+ });+H.getDocumentCard(ORDERS_COUNT_BY_PRODUCT_CATEGORY.name).should("not.exist",);@@ -494,6 +532,7 @@ describe("documents", () => {H.addToDocument("");H.addToDocument("Adding a static link: /", false);H.commandSuggestionItem("Link").click();+H.addToDocument("Ord", false);H.commandSuggestionItem(/Orders, Count$/).click();H.addToDocument(" And continue typing", false);@@ -515,6 +554,17 @@ describe("documents", () => {cy.wait("@documentGet");+ cy.get("@documentId").then((id) => {+ H.expectUnstructuredSnowplowEvent({+ event: "document_saved",+ target_id: id,+ });+ H.expectUnstructuredSnowplowEvent({+ event: "document_add_smart_link",+ target_id: id,+ });+ });+cy.findByTestId("toast-undo").findByText("Document saved").should("be.visible");diff --git a/enterprise/frontend/src/metabase-enterprise/documents/analytics.ts b/enterprise/frontend/src/metabase-enterprise/documents/analytics.tsnew file mode 100644index 00000000000..1a48ce02a6e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/documents/analytics.ts@@ -0,0 +1,51 @@+import { trackSimpleEvent } from "metabase/lib/analytics";+import type { Document } from "metabase-types/api";++export const trackDocumentCreated = (document: Document) => {+ trackSimpleEvent({+ event: "document_created",+ target_id: document.id,+ });+};++export const trackDocumentUpdated = (document: Document) => {+ trackSimpleEvent({+ event: "document_saved",+ target_id: document.id,+ });+};++export const trackDocumentAddCard = (document?: Document | null) => {+ trackSimpleEvent({+ event: "document_add_card",+ target_id: document?.id || null,+ });+};++export const trackDocumentAddSmartLink = (document?: Document | null) => {+ trackSimpleEvent({+ event: "document_add_smart_link",+ target_id: document?.id || null,+ });+};++export const trackDocumentReplaceCard = (document?: Document | null) => {+ trackSimpleEvent({+ event: "document_replace_card",+ target_id: document?.id || null,+ });+};++export const trackDocumentAskMetabot = (document?: Document | null) => {+ trackSimpleEvent({+ event: "document_ask_metabot",+ target_id: document?.id || null,+ });+};++export const trackDocumentPrint = (document?: Document | null) => {+ trackSimpleEvent({+ event: "document_print",+ target_id: document?.id || null,+ });+};diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsxindex d64b4889c21..f42dd1e99d2 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentHeader.tsx@@ -19,6 +19,7 @@ import {} from "metabase/ui";import type { Document } from "metabase-types/api";+import { trackDocumentPrint } from "../analytics";import { DOCUMENT_TITLE_MAX_LENGTH } from "../constants";import S from "./DocumentHeader.module.css";@@ -58,7 +59,8 @@ export const DocumentHeader = ({}: DocumentHeaderProps) => {const handlePrint = useCallback(() => {window.print();- }, []);+ trackDocumentPrint(document);+ }, [document]);return (<Flexdiff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsxindex 3be372502e7..ac0ac36f5b2 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/DocumentPage.tsx@@ -41,6 +41,7 @@ import type {RegularCollectionId,} from "metabase-types/api";+import { trackDocumentCreated, trackDocumentUpdated } from "../analytics";import {clearDraftCards,openVizSettingsSidebar,@@ -284,8 +285,10 @@ export const DocumentPage = ({? updateDocument({ ...newDocumentData, id: documentData.id }).then((response) => {if (response.data) {+ const _document = response.data;+ trackDocumentUpdated(_document);scheduleNavigation(() => {- dispatch(push(`/document/${response.data.id}`));+ dispatch(push(`/document/${_document.id}`));});}return response.data;@@ -296,8 +299,10 @@ export const DocumentPage = ({collection_id: collectionId || undefined,}).then((response) => {if (response.data) {+ const _document = response.data;+ trackDocumentCreated(_document);scheduleNavigation(() => {- dispatch(replace(`/document/${response.data.id}`));+ dispatch(replace(`/document/${_document.id}`));});}return response.data;diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.tsxindex 5303a7aa677..ab715423d4a 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/CardEmbed/CardEmbedNode.tsx@@ -17,6 +17,8 @@ import { Box, Flex, Icon, Loader, Menu, Text, TextInput } from "metabase/ui";import Visualization from "metabase/visualizations/components/Visualization";import ChartSkeleton from "metabase/visualizations/components/skeletons/ChartSkeleton";import { getGenericErrorMessage } from "metabase/visualizations/lib/errors";+import { trackDocumentReplaceCard } from "metabase-enterprise/documents/analytics";+import { getCurrentDocument } from "metabase-enterprise/documents/selectors";import Question from "metabase-lib/v1/Question";import { getUrl } from "metabase-lib/v1/urls";import type { Card, CardDisplayType, Dataset } from "metabase-types/api";@@ -144,6 +146,7 @@ export const CardEmbedComponent = memo(const { card, dataset, isLoading, series, error } = useCardData({ id });const metadata = useSelector(getMetadata);+ const document = useSelector(getCurrentDocument);const datasetError = dataset && getDatasetError(dataset);const [isEditingTitle, setIsEditingTitle] = useState(false);const [editedTitle, setEditedTitle] = useState(name || "");@@ -222,9 +225,13 @@ export const CardEmbedComponent = memo(id: item.id,name: null,});+ if (document) {+ trackDocumentReplaceCard(document);+ }+setIsReplaceModalOpen(false);},- [updateAttributes],+ [updateAttributes, document],);// Handle drill-through navigationdiff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandExtension.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandExtension.tsindex f3a36d52632..97236eeb369 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandExtension.ts+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandExtension.ts@@ -2,19 +2,27 @@ import { type Editor, Extension, type Range } from "@tiptap/core";import { PluginKey } from "@tiptap/pm/state";import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion";+import {+ trackDocumentAddCard,+ trackDocumentAddSmartLink,+ trackDocumentAskMetabot,+} from "metabase-enterprise/documents/analytics";+import type { Document } from "metabase-types/api";+export interface CommandOptions {suggestion: Partial<SuggestionOptions>;}-interface CommandProps {+export interface CommandProps {command?: string;clearQuery?: boolean;switchToLinkMode?: boolean;switchToEmbedMode?: boolean;selectItem?: boolean;embedItem?: boolean;- entityId?: number;+ entityId?: number | string;model?: string;+ document?: Document | null;}export const CommandPluginKey = new PluginKey("command");@@ -63,6 +71,10 @@ export const CommandExtension = Extension.create<CommandOptions>({}).setTextSelection(range.from + 1).run();+ if (props.document) {+ trackDocumentAddCard(props.document);+ }+return;}if (props.selectItem && props.entityId && props.model) {@@ -78,6 +90,9 @@ export const CommandExtension = Extension.create<CommandOptions>({},}).run();+ if (props.document) {+ trackDocumentAddSmartLink(props.document);+ }return;}@@ -95,6 +110,9 @@ export const CommandExtension = Extension.create<CommandOptions>({attrs: {},}).run();+ if (props.document) {+ trackDocumentAskMetabot(props.document);+ }return;}diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.tsxindex 0295bd72e9f..58466251927 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.tsx@@ -10,6 +10,7 @@ import {} from "react";import { t } from "ttag";+import { useSelector } from "metabase/lib/redux";import { PLUGIN_METABOT } from "metabase/plugins";import {Box,@@ -21,6 +22,7 @@ import {Text,UnstyledButton,} from "metabase/ui";+import { getCurrentDocument } from "metabase-enterprise/documents/selectors";import type { SearchResult } from "metabase-types/api";import {@@ -36,26 +38,28 @@ import { EntitySearchSection } from "../shared/EntitySearchSection";import { EMBED_SEARCH_MODELS, LINK_SEARCH_MODELS } from "../shared/constants";import { useEntitySuggestions } from "../shared/useEntitySuggestions";+import type { CommandProps } from "./CommandExtension";import CommandS from "./CommandSuggestion.module.css";export interface CommandSuggestionProps {items: SearchResult[];- command: (item: CommandItem) => void;+ command: (item: CommandProps) => void;editor: Editor;range: Range;query: string;}-interface CommandItem {- command?: string;- clearQuery?: boolean;- switchToLinkMode?: boolean;- switchToEmbedMode?: boolean;- selectItem?: boolean;- embedItem?: boolean;- entityId?: number | string;- model?: string;-}+// interface CommandItem {+// command?: string;+// clearQuery?: boolean;+// switchToLinkMode?: boolean;+// switchToEmbedMode?: boolean;+// selectItem?: boolean;+// embedItem?: boolean;+// entityId?: number | string;+// model?: string;+// document?: Document | null;+// }interface SuggestionRef {onKeyDown: (props: { event: KeyboardEvent }) => boolean;@@ -114,6 +118,7 @@ export const CommandSuggestion = forwardRef<SuggestionRef,CommandSuggestionProps>(function CommandSuggestionComponent({ command, editor, query }, ref) {+ const document = useSelector(getCurrentDocument);const [selectedIndex, setSelectedIndex] = useState(0);const [showLinkSearch, setShowLinkSearch] = useState(false);const [showEmbedSearch, setShowEmbedSearch] = useState(false);@@ -216,16 +221,18 @@ export const CommandSuggestion = forwardRef<selectItem: true,entityId: item.id,model: item.model,+ document,});} else {command({embedItem: true,entityId: item.id,model: item.model,+ document,});}},- [command, showLinkSearch],+ [command, showLinkSearch, document],);const executeCommand = (commandName: string) => {@@ -250,6 +257,7 @@ export const CommandSuggestion = forwardRef<if (commandName === "metabot") {command({command: "metabot",+ document,});return;}diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.unit.spec.tsxindex 75e2035c664..609c582003a 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Command/CommandSuggestion.unit.spec.tsx@@ -170,6 +170,7 @@ describe("CommandSuggestion", () => {embedItem: true,entityId: 2,model: "card",+ document: null,});});@@ -201,6 +202,7 @@ describe("CommandSuggestion", () => {selectItem: true,entityId: 4,model: "document",+ document: null,});});@@ -240,6 +242,7 @@ describe("CommandSuggestion", () => {embedItem: true,entityId: 5,model: "card",+ document: null,});});@@ -274,6 +277,7 @@ describe("CommandSuggestion", () => {embedItem: true,entityId: 6,model: "card",+ document: null,});});@@ -308,6 +312,7 @@ describe("CommandSuggestion", () => {selectItem: true,entityId: 8,model: "table",+ document: null,});});diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionExtension.ts b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionExtension.tsindex 4c9648cd4cd..446ddc53f80 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionExtension.ts+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionExtension.ts@@ -3,6 +3,9 @@ import type { Node as ProseMirrorNode } from "@tiptap/pm/model";import { PluginKey } from "@tiptap/pm/state";import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion";+import { trackDocumentAddSmartLink } from "metabase-enterprise/documents/analytics";+import type { Document } from "metabase-types/api";+export interface MentionOptions {HTMLAttributes: Record<string, unknown>;renderText: (props: {@@ -12,10 +15,11 @@ export interface MentionOptions {suggestion: Partial<SuggestionOptions>;}-interface MentionProps {+export interface MentionCommandProps {type?: string;id?: number | string;model?: string;+ document?: Document | null;}export const MentionPluginKey = new PluginKey("mention");@@ -41,7 +45,7 @@ export const MentionExtension = Extension.create<MentionOptions>({}: {editor: Editor;range: Range;- props: MentionProps;+ props: MentionCommandProps;}) => {if (props.id && props.model) {editor@@ -56,6 +60,9 @@ export const MentionExtension = Extension.create<MentionOptions>({},}).run();+ if (props.document) {+ trackDocumentAddSmartLink(props.document);+ }}},},diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionSuggestion.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionSuggestion.tsxindex 5cd7a60f6c5..de30cb9501c 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionSuggestion.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/Mention/MentionSuggestion.tsx@@ -2,6 +2,8 @@ import type { Editor, Range } from "@tiptap/core";import { forwardRef, useCallback, useImperativeHandle } from "react";import { t } from "ttag";+import { useSelector } from "metabase/lib/redux";+import { getCurrentDocument } from "metabase-enterprise/documents/selectors";import type { SearchResult } from "metabase-types/api";import {@@ -11,20 +13,16 @@ import {import { EntitySearchSection } from "../shared/EntitySearchSection";import { useEntitySuggestions } from "../shared/useEntitySuggestions";+import type { MentionCommandProps } from "./MentionExtension";+interface MentionSuggestionProps {items: SearchResult[];- command: (item: MentionCommandItem) => void;+ command: (item: MentionCommandProps) => void;editor: Editor;range: Range;query: string;}-interface MentionCommandItem {- type?: string;- id?: number | string;- model?: string;-}-interface SuggestionRef {onKeyDown: (props: { event: KeyboardEvent }) => boolean;}@@ -36,14 +34,16 @@ const MentionSuggestionComponent = forwardRef<{ items: _items, command, editor, range: _range, query },ref,) {+ const document = useSelector(getCurrentDocument);const onSelectEntity = useCallback((item: { id: number | string; model: string }) => {command({id: item.id,model: item.model,+ document,});},- [command],+ [command, document],);const {diff --git a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.tsx b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.tsxindex c88fdc56e3b..ac7cd09bd41 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.tsx+++ b/enterprise/frontend/src/metabase-enterprise/documents/components/Editor/extensions/MetabotEmbed/MetabotEmbed.tsx@@ -12,15 +12,17 @@ import { useLatest } from "react-use";import { t } from "ttag";import CS from "metabase/css/core/index.css";-import { useDispatch } from "metabase/lib/redux";+import { useDispatch, useSelector } from "metabase/lib/redux";import { PLUGIN_METABOT } from "metabase/plugins";import { Box, Button, Flex, Icon, Text, Tooltip } from "metabase/ui";import { useLazyMetabotGenerateContentQuery } from "metabase-enterprise/api/metabot";+import { trackDocumentAskMetabot } from "metabase-enterprise/documents/analytics";import {createDraftCard,generateDraftCardId,loadMetadataForDocumentCard,} from "metabase-enterprise/documents/documents.slice";+import { getCurrentDocument } from "metabase-enterprise/documents/selectors";import MetabotThinkingStyles from "metabase-enterprise/metabot/components/MetabotChat/MetabotThinking.module.css";import type { Card, MetabotGenerateContentRequest } from "metabase-types/api";@@ -145,6 +147,7 @@ export const MetabotNode = Node.create<{export const MetabotComponent = memo(({ editor, getPos, deleteNode, node, extension }: NodeViewProps) => {const dispatch = useDispatch();+ const document = useSelector(getCurrentDocument);const controllerRef = useRef<AbortController | null>(null);const [isLoading, setIsLoading] = useState(false);const [errorText, setErrorText] = useState("");@@ -218,6 +221,7 @@ export const MetabotComponent = memo(archived: false,};+ trackDocumentAskMetabot(document);await dispatch(loadMetadataForDocumentCard(card));dispatch(diff --git a/enterprise/frontend/src/metabase-enterprise/documents/selectors.ts b/enterprise/frontend/src/metabase-enterprise/documents/selectors.tsindex b509cf3c128..588438a9d25 100644--- a/enterprise/frontend/src/metabase-enterprise/documents/selectors.ts+++ b/enterprise/frontend/src/metabase-enterprise/documents/selectors.ts@@ -31,7 +31,7 @@ export const getSelectedEmbedIndex = createSelector(export const getCurrentDocument = createSelector(getDocumentsState,- (documents) => documents?.currentDocument,+ (documents) => documents?.currentDocument || null,);export const getShowNavigateBackToDocumentButton = createSelector(diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.tsindex a063b6063bb..9b5b6b39f85 100644--- a/frontend/src/metabase-types/analytics/event.ts+++ b/frontend/src/metabase-types/analytics/event.ts@@ -280,6 +280,41 @@ export type TransformCreatedEvent = ValidateEvent<{target_id: number;}>;+export type DocumentCreatedEvent = ValidateEvent<{+ event: "document_created";+ target_id: number;+}>;++export type DocumentUpdatedEvent = ValidateEvent<{+ event: "document_saved";+ target_id: number;+}>;++export type DocumentAddCardEvent = ValidateEvent<{+ event: "document_add_card";+ target_id: number | null;+}>;++export type DocumentAddSmartLinkEvent = ValidateEvent<{+ event: "document_add_smart_link";+ target_id: number | null;+}>;++export type DocumentReplaceCardEvent = ValidateEvent<{+ event: "document_replace_card";+ target_id: number | null;+}>;++export type DocumentAskMetabotEvent = ValidateEvent<{+ event: "document_ask_metabot";+ target_id: number | null;+}>;++export type DocumentPrintEvent = ValidateEvent<{+ event: "document_print";+ target_id: number | null;+}>;+export type EmbedWizardEvent =| EmbedWizardExperienceSelectedEvent| EmbedWizardResourceSelectedEvent@@ -322,4 +357,11 @@ export type SimpleEvent =| TransformTriggerManualRunEvent| TransformJobTriggerManualRunEvent| TransformCreatedEvent- | TransformCreateEvent;+ | TransformCreateEvent+ | DocumentAddCardEvent+ | DocumentAddSmartLinkEvent+ | DocumentAskMetabotEvent+ | DocumentCreatedEvent+ | DocumentReplaceCardEvent+ | DocumentUpdatedEvent+ | DocumentPrintEvent;