Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ga4 account explorer #791

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/components/Layout/links.ts
Original file line number Diff line number Diff line change
@@ -36,6 +36,12 @@ export const linkData: LinkData[] = [
type: "link",
versions: [GAVersion.UniversalAnalytics],
},
{
text: "Account Explorer",
href: "/ga4/account-explorer/",
type: "link",
versions: [GAVersion.GoogleAnalytics4],
},
{
text: "Campaign URL Builder",
href: "/campaign-url-builder/",
238 changes: 238 additions & 0 deletions src/components/ga4/AccountExplorer/ExploreTable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
import { CopyIconButton } from "@/components/CopyButton"
import Spinner from "@/components/Spinner"
import {
Box,
makeStyles,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography,
} from "@material-ui/core"
import { Android, Apple, Language } from "@material-ui/icons"
import React from "react"
import { AccountProperty } from "../StreamPicker/useAccountProperty"
import useAllAPS from "./useAllAPS"

interface ExploreTableProps extends AccountProperty {}

const WebCell: React.FC<{
stream: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaWebDataStream
}> = ({ stream }) => {
return (
<>
<Language />
<Box>
<Typography variant="body1">{stream.displayName}</Typography>
<Typography variant="body2">
{stream.name?.substring(stream.name?.lastIndexOf("/") + 1)}
</Typography>
</Box>
</>
)
}

const AndroidCell: React.FC<{
stream: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaAndroidAppDataStream
}> = ({ stream }) => {
return (
<>
<Android />
<Box>
<Typography variant="body1">
{stream.displayName || stream.packageName}
</Typography>
<Typography variant="body2">
{stream.name?.substring(stream.name?.lastIndexOf("/") + 1)}
</Typography>
</Box>
</>
)
}

const IOSCell: React.FC<{
stream: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaIosAppDataStream
}> = ({ stream }) => {
return (
<>
<Apple />
<Box>
<Typography variant="body1">
{stream.displayName || stream.bundleId}
</Typography>
<Typography variant="body2">
{stream.name?.substring(stream.name?.lastIndexOf("/") + 1)}
</Typography>
</Box>
</>
)
}

const useStyles = makeStyles(theme => ({
streamCell: {
display: "flex",
alignItems: "center",
"&> svg": {
marginRight: theme.spacing(1),
},
"&> button": {
marginLeft: "auto",
},
"&> div > p": {
margin: "unset",
padding: "unset",
},
},
}))

const ExploreTable: React.FC<ExploreTableProps> = ({ account, property }) => {
const aps = useAllAPS()
const classes = useStyles()

if (aps === undefined) {
return <Spinner ellipses>Loading accounts</Spinner>
}

return (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Account</TableCell>
<TableCell>Property</TableCell>
<TableCell>Stream</TableCell>
</TableRow>
</TableHead>
<TableBody>
{aps.map(a => (
<React.Fragment key={a.account}>
{a.propertySummaries.flatMap(p => {
const Wrapper: React.FC = ({ children }) => (
<TableRow>
<TableCell>
<Box className={classes.streamCell}>
<Box>
<Typography variant="body1">{a.displayName}</Typography>
<Typography variant="body2">
{a.name?.substring(a.name?.lastIndexOf("/") + 1)}
</Typography>
</Box>
<CopyIconButton
tooltipText="Copy account ID"
toCopy={
a.name?.substring(a.name?.lastIndexOf("/") + 1) || ""
}
/>
</Box>
</TableCell>
<TableCell>
<Box className={classes.streamCell}>
<Box>
<Typography variant="body1">{p.displayName}</Typography>
<Typography variant="body2">
{p.property?.substring(
p.property?.lastIndexOf("/") + 1
)}
</Typography>
</Box>
<CopyIconButton
tooltipText="Copy property ID"
toCopy={
p.property?.substring(
p.property?.lastIndexOf("/") + 1
) || ""
}
/>
</Box>
</TableCell>
<TableCell>
<Box className={classes.streamCell}>{children}</Box>
</TableCell>
</TableRow>
)

const rows: JSX.Element[] = []
const baseKey = `${a.account}-${p.property}`

if (account !== undefined) {
if (a.account !== account.account) {
return null
}
if (property !== undefined) {
if (p.property !== property.property) {
return null
}
}
}
if (p.webStreams === undefined) {
rows.push(
<Wrapper key={`${baseKey}-web-loading`}>Loading...</Wrapper>
)
} else {
p.webStreams.forEach(s =>
rows.push(
<Wrapper key={`${baseKey}-${s.name}`}>
<WebCell stream={s} />
<CopyIconButton
tooltipText="Copy stream ID"
toCopy={
s.name?.substring(s.name?.lastIndexOf("/") + 1) || ""
}
/>
</Wrapper>
)
)
}

if (p.androidStreams === undefined) {
rows.push(
<Wrapper key={`${baseKey}-android-loading`}>
Loading...
</Wrapper>
)
} else {
p.androidStreams.forEach(s =>
rows.push(
<Wrapper key={`${baseKey}-${s.name}`}>
<AndroidCell stream={s} />
<CopyIconButton
tooltipText="Copy stream ID"
toCopy={
s.name?.substring(s.name?.lastIndexOf("/") + 1) || ""
}
/>
</Wrapper>
)
)
}

if (p.iosStreams === undefined) {
rows.push(
<Wrapper key={`${baseKey}-ios-loading`}>Loading...</Wrapper>
)
} else {
p.iosStreams.forEach(s =>
rows.push(
<Wrapper key={`${baseKey}-${s.name}`}>
<IOSCell stream={s} />
<CopyIconButton
tooltipText="Copy stream ID"
toCopy={
s.name?.substring(s.name?.lastIndexOf("/") + 1) || ""
}
/>
</Wrapper>
)
)
}

return rows
})}
</React.Fragment>
))}
</TableBody>
</Table>
)
}

export default ExploreTable
33 changes: 33 additions & 0 deletions src/components/ga4/AccountExplorer/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React from "react"

import { Typography } from "@material-ui/core"
import { StorageKey } from "@/constants"
import StreamPicker from "../StreamPicker"
import ExploreTable from "./ExploreTable"
import useAccountProperty from "../StreamPicker/useAccountProperty"

enum QueryParam {
Account = "a",
Property = "b",
Stream = "c",
}

const AccountExplorer = () => {
const ap = useAccountProperty(StorageKey.ga4AccountExplorerAPS, QueryParam)

return (
<>
<Typography variant="h2">Overview</Typography>
<Typography variant="body1">
Use this tool to browse through your Google Analytics 4 accounts,
properties, and streams, See what accounts you have access to and find
the IDs that you need for APIs or other tools or services that integrate
with Google Analytics 4.
</Typography>
<StreamPicker {...ap} />
<ExploreTable {...ap} />
</>
)
}

export default AccountExplorer
172 changes: 172 additions & 0 deletions src/components/ga4/AccountExplorer/useAllAPS.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { StorageKey } from "@/constants"
import { RequestStatus } from "@/types"
import { AccountSummary, PropertySummary } from "@/types/ga4/StreamPicker"
import moment from "moment"
import { useEffect, useMemo, useRef, useState } from "react"
import { useSelector } from "react-redux"
import useAccountSummaries from "../StreamPicker/useAccounts"

const maxAge = moment.duration(30, "minutes")
type StreamsForProperty = {
webStreams: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaWebDataStream[]
iosStreams: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaIosAppDataStream[]
androidStreams: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaAndroidAppDataStream[]
property: string
timestamp: number
}

const fetchAllStreams = async (
adminAPI: typeof gapi.client.analyticsadmin,
property: string,
key: string
) => {
const [
{
result: { webDataStreams: webStreams = [] },
},
{
result: { iosAppDataStreams: iosStreams = [] },
},
{
result: { androidAppDataStreams: androidStreams = [] },
},
] = await Promise.all([
adminAPI.properties.webDataStreams.list({
parent: property,
}),
adminAPI.properties.iosAppDataStreams.list({
parent: property,
}),
adminAPI.properties.androidAppDataStreams.list({
parent: property,
}),
])
// TODO - consider handling pagination, though it seems very unlikely there
// will be _pages_ of streams for a given property.
const fetchTime = moment.now()
const nu: StreamsForProperty = {
webStreams,
iosStreams,
androidStreams,
property,
timestamp: fetchTime,
}

window.localStorage.setItem(key, JSON.stringify(nu))

return nu
}

interface PropertyWithStreams extends PropertySummary {
webStreams?: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaWebDataStream[]
androidStreams?: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaAndroidAppDataStream[]
iosStreams?: gapi.client.analyticsadmin.GoogleAnalyticsAdminV1alphaIosAppDataStream[]
}

export interface AccountWithStreams extends AccountSummary {
propertySummaries: Array<PropertyWithStreams>
}

const useAllAPS = () => {
const gapi = useSelector((a: AppState) => a.gapi)
const adminAPI = useMemo(() => gapi?.client?.analyticsadmin, [gapi])
const accountSummariesRequest = useAccountSummaries()
const accounts = useMemo(
() =>
accountSummariesRequest.status === RequestStatus.Successful
? accountSummariesRequest.accounts
: undefined,
[accountSummariesRequest]
)
const [allAPS, setAllAPS] = useState<AccountWithStreams[] | undefined>(
accounts as AccountWithStreams[]
)

const shouldRun = useRef(true)

useEffect(() => {
shouldRun.current = true
if (adminAPI === undefined || accounts === undefined) {
return
}
if (accounts.length === 0) {
return
}
;(async () => {
for (let accountIdx = 0; accountIdx < accounts.length; accountIdx++) {
if (shouldRun.current) {
const currentAccount = accounts[accountIdx]
const currentProperties = currentAccount.propertySummaries
if (
currentProperties === undefined ||
currentProperties.length === 0
) {
return
}
for (
let propertyIdx = 0;
propertyIdx < currentProperties.length;
propertyIdx++
) {
if (shouldRun.current) {
const currentProperty = currentProperties[propertyIdx]

const key = StorageKey.ga4Streams + currentProperty.property!
const fromCache = window.localStorage.getItem(key)
let stuff: StreamsForProperty
if (fromCache !== null) {
const parsed: StreamsForProperty = JSON.parse(fromCache)
const now = moment()
const cacheTime = moment(parsed.timestamp)
if (
cacheTime === undefined ||
now.isAfter(moment(cacheTime).add(maxAge))
) {
console.log("should update")
stuff = await fetchAllStreams(
adminAPI,
currentProperty.property!,
key
)
} else {
stuff = parsed
}
} else {
stuff = await fetchAllStreams(
adminAPI,
currentProperty.property!,
key
)
}
const { webStreams, androidStreams, iosStreams } = stuff
setAllAPS((old = []) => {
return old.map((aws, aIdx) =>
aIdx === accountIdx
? {
...aws,
propertySummaries: (
aws.propertySummaries || []
).map((pws, pIdx) =>
pIdx === propertyIdx
? { ...pws, iosStreams, androidStreams, webStreams }
: pws
),
}
: aws
)
})
}
}
}
}
})()

return () => {
shouldRun.current = false
}
}, [accounts, adminAPI, setAllAPS])

return allAPS
}

export default useAllAPS
5 changes: 5 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -248,6 +248,11 @@ export enum StorageKey {
ga4EventBuilderItems = "ga4/event-builder/items",
ga4EventBuilderEventName = "ga4/event-builder/event-name",
ga4EventBuilderUserProperties = "ga4/event-builder/user-properties",

// GA4 Account Explorer
ga4AccountExplorerAPS = "ga4/account-explorer/aps",
allAPS = "ga4/account-explorer/all-aps",
ga4Streams = "ga4/account-explorer/streams-for-property/",
}

export const EventAction = {
10 changes: 10 additions & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -200,6 +200,11 @@ const getRedirectInfo = (
redirectPath: "/",
toast: "Redirecting to the UA home page.",
}
case "/ga4/account-explorer/":
return {
redirectPath: "/account-explorer/",
toast: uaToast("Account Explorer"),
}
default:
return {
redirectPath: "/",
@@ -249,6 +254,11 @@ const getRedirectInfo = (
redirectPath: "/ga4/",
toast: "Redirecting to the GA4 home page.",
}
case "/account-explorer/":
return {
redirectPath: "/ga4/account-explorer/",
toast: ga4Toast("Account Explorer"),
}
default:
return {
redirectPath: "/ga4/",
31 changes: 31 additions & 0 deletions src/pages/ga4/account-explorer/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2020 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as React from "react"

import Layout from "@/components/Layout"
import AccountExplorer from "@/components/ga4/AccountExplorer"

export default ({ location: { pathname } }) => {
return (
<Layout
title="GA4 Account Explorer"
requireLogin
pathname={pathname}
description="Use this tool to search or browse through your Google Analytics 4 accounts, properties, and streams."
>
<AccountExplorer />
</Layout>
)
}