Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add "Sales by type" block to program overview

Tim Wilson38879194b7dd
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx
index 75a6ecf739..f021bb7bf7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/page-client.tsx
@@ -10,6 +10,7 @@ import { ConversionBlock } from "@/ui/partners/overview/blocks/conversion-block"
import { CountriesBlock } from "@/ui/partners/overview/blocks/countries-block";
import { LinksBlock } from "@/ui/partners/overview/blocks/links-block";
import { PartnersBlock } from "@/ui/partners/overview/blocks/partners-block";
+import { SaleTypeBlock } from "@/ui/partners/overview/blocks/sale-type-block";
import { TrafficSourcesBlock } from "@/ui/partners/overview/blocks/traffic-sources-block";
import { ProgramOverviewCard } from "@/ui/partners/overview/program-overview-card";
import SimpleDateRangePicker from "@/ui/shared/simple-date-range-picker";
@@ -28,6 +29,7 @@ const BLOCKS = [
ConversionBlock,
CountriesBlock,
LinksBlock,
+ SaleTypeBlock,
];
export default function ProgramOverviewPageClient() {
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index 6635c0d7cd..dc6b1863b2 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -114,6 +114,7 @@ export const INTERVAL_DATA: Record<
export const VALID_ANALYTICS_ENDPOINTS = [
"count",
+ "count_new",
"timeseries",
"continents",
"regions",
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index c3ca94f3d6..08967cfbc6 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -44,7 +44,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
// 5. no other dimensional filters are applied
if (
linkId &&
- groupBy === "count" &&
+ ["count", "count_new"].includes(groupBy) &&
interval === "all" &&
!start &&
!end &&
@@ -121,7 +121,9 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
region,
});
- if (groupBy === "count") {
+ console.log("RESPONSE!!!", response);
+
+ if (["count", "count_new"].includes(groupBy)) {
// Return the count value for deprecated endpoints
if (isDeprecatedClicksEndpoint) {
return response.data[0][event];
diff --git a/apps/web/lib/zod/schemas/analytics-response.ts b/apps/web/lib/zod/schemas/analytics-response.ts
index 86f4a9ccbe..23058ec68b 100644
--- a/apps/web/lib/zod/schemas/analytics-response.ts
+++ b/apps/web/lib/zod/schemas/analytics-response.ts
@@ -38,6 +38,17 @@ export const analyticsResponse = {
.default(0),
})
.openapi({ ref: "AnalyticsCount", title: "AnalyticsCount" }),
+ count_new: z
+ .object({
+ clicks: z.number().describe("The total number of clicks").default(0),
+ leads: z.number().describe("The total number of leads").default(0),
+ sales: z.number().describe("The total number of sales").default(0),
+ saleAmount: z
+ .number()
+ .describe("The total amount of sales, in cents")
+ .default(0),
+ })
+ .openapi({ ref: "AnalyticsCount", title: "AnalyticsCount" }),
timeseries: z
.object({
start: z.string().describe("The starting timestamp of the interval"),
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 2098ad20d7..6b2cae352b 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -137,6 +137,10 @@ export const analyticsQuerySchema = z
"The IANA time zone code for aligning timeseries granularity (e.g. America/New_York). Defaults to UTC.",
)
.openapi({ example: "America/New_York", default: "UTC" }),
+ saleType: z
+ .enum(["new", "recurring"])
+ .optional()
+ .describe("The sale type to retrieve analytics for."),
country: z
.enum(COUNTRY_CODES)
.optional()
@@ -238,6 +242,7 @@ export const analyticsFilterTB = z
.optional()
.transform((v) => (v ? prefixWorkspaceId(v) : undefined)),
customerId: z.string().optional(),
+ saleType: z.string().optional(),
root: z.boolean().optional(),
qr: z.boolean().optional(),
start: z.string(),
diff --git a/apps/web/ui/partners/overview/blocks/sale-type-block.tsx b/apps/web/ui/partners/overview/blocks/sale-type-block.tsx
new file mode 100644
index 0000000000..cd92904977
--- /dev/null
+++ b/apps/web/ui/partners/overview/blocks/sale-type-block.tsx
@@ -0,0 +1,163 @@
+import { AnalyticsResponseOptions } from "@/lib/analytics/types";
+import { editQueryString } from "@/lib/analytics/utils";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { AnalyticsContext } from "@/ui/analytics/analytics-provider";
+import { LoadingSpinner, useRouterStuff } from "@dub/ui";
+import { cn, fetcher, nFormatter } from "@dub/utils";
+import { useContext, useMemo, useState } from "react";
+import useSWR from "swr";
+import { ProgramOverviewBlock } from "../program-overview-block";
+
+export function SaleTypeBlock() {
+ const { slug: workspaceSlug } = useWorkspace();
+
+ const { getQueryString } = useRouterStuff();
+ const { queryString, totalEvents } = useContext(AnalyticsContext);
+
+ const [hoveredItem, setHoveredItem] = useState<string | null>(null);
+
+ const {
+ data: recurringEvents,
+ isLoading: isLoadingRecurring,
+ error,
+ } = useSWR<{
+ [key in AnalyticsResponseOptions]: number;
+ }>(
+ `/api/analytics?${editQueryString(queryString, {
+ event: "sales",
+ groupBy: "count_new",
+ saleType: "recurring",
+ })}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ const isLoading = isLoadingRecurring || !totalEvents;
+
+ const maxAmount = useMemo(
+ () =>
+ Math.max(totalEvents?.saleAmount ?? 0, recurringEvents?.saleAmount ?? 0),
+ [totalEvents, recurringEvents],
+ );
+
+ const items = useMemo(
+ () =>
+ [
+ {
+ label: "First",
+ count: (totalEvents?.sales ?? 0) - (recurringEvents?.sales ?? 0),
+ amount:
+ (totalEvents?.saleAmount ?? 0) - (recurringEvents?.saleAmount ?? 0),
+ fraction:
+ ((totalEvents?.saleAmount ?? 0) -
+ (recurringEvents?.saleAmount ?? 0)) /
+ maxAmount,
+ colorClassName: "text-violet-500",
+ },
+ {
+ label: "Recurring",
+ count: recurringEvents?.sales ?? 0,
+ amount: recurringEvents?.saleAmount ?? 0,
+ fraction: (recurringEvents?.saleAmount ?? 0) / maxAmount,
+ colorClassName: "text-violet-200",
+ },
+ ].filter(({ fraction }) => fraction > 0),
+ [totalEvents, recurringEvents, maxAmount],
+ );
+
+ return (
+ <ProgramOverviewBlock
+ title="Sales by type"
+ viewAllHref={`/${workspaceSlug}/program/analytics${getQueryString(
+ { tab: "sales" },
+ {
+ include: ["interval", "start", "end"],
+ },
+ )}`}
+ className="pb-0"
+ contentClassName="px-0 mt-1"
+ >
+ <div className="h-full min-h-48">
+ {isLoading ? (
+ <div className="flex size-full items-center justify-center py-4">
+ <LoadingSpinner />
+ </div>
+ ) : error ? (
+ <div className="text-content-subtle flex size-full items-center justify-center py-4 text-xs">
+ Failed to load data
+ </div>
+ ) : (
+ <div className="flex size-full flex-col gap-6 px-6 pb-6">
+ <span className="text-content-emphasis block text-xl font-medium">
+ {nFormatter(totalEvents?.sales, {
+ full: totalEvents?.sales < 99999,
+ })}
+ </span>
+ <div className="flex grow flex-col justify-end gap-9">
+ {/* Bars */}
+ <div className="flex h-20 gap-4">
+ {items.map((item) => (
+ <div
+ key={item.label}
+ className={cn(
+ "h-full rounded-md bg-current transition-transform",
+ hoveredItem === item.label && "scale-105",
+ item.colorClassName,
+ )}
+ style={{ width: `${Math.max(item.fraction * 100, 1)}%` }}
+ onPointerEnter={() => setHoveredItem(item.label)}
+ onPointerLeave={() =>
+ setHoveredItem((i) => (i === item.label ? null : i))
+ }
+ />
+ ))}
+ </div>
+
+ {/* List */}
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,max-content)_minmax(0,max-content)] items-center gap-x-4 gap-y-2">
+ {items.map((item) => (
+ <div
+ key={item.label}
+ className={cn(
+ "text-content-default contents text-xs font-medium tabular-nums transition-colors [&>*]:transition-opacity",
+ item.label === hoveredItem && "text-content-emphasis",
+ hoveredItem &&
+ item.label !== hoveredItem &&
+ "[&>*]:opacity-60",
+ )}
+ onPointerEnter={() => setHoveredItem(item.label)}
+ onPointerLeave={() =>
+ setHoveredItem((i) => (i === item.label ? null : i))
+ }
+ >
+ <div className="flex items-center gap-2 py-1">
+ <div
+ className={cn(
+ "h-5 w-1 rounded-full bg-current",
+ item.colorClassName,
+ )}
+ />
+ <span>{item.label}</span>
+ </div>
+ <span>{formatPercentage(item.fraction * 100)}%</span>
+ <span className="text-content-muted">
+ {nFormatter(item.count, { full: item.count < 99999 })}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </ProgramOverviewBlock>
+ );
+}
+
+const formatPercentage = (value: number) => {
+ return value > 0 && value < 0.01
+ ? "< 0.01"
+ : nFormatter(value, { digits: 2 });
+};
diff --git a/packages/tinybird/pipes/v2_count_new.pipe b/packages/tinybird/pipes/v2_count_new.pipe
new file mode 100644
index 0000000000..0fdae48d16
--- /dev/null
+++ b/packages/tinybird/pipes/v2_count_new.pipe
@@ -0,0 +1,216 @@
+DESCRIPTION >
+ Top countries
+
+
+TAGS "Dub Endpoints"
+
+NODE workspace_links
+SQL >
+
+ %
+ SELECT link_id
+ FROM
+ {% if defined(isMegaFolder) and Boolean(isMegaFolder) == 1 %} dub_links_metadata_latest
+ {% else %} dub_regular_links_metadata_latest
+ {% end %} FINAL
+ WHERE
+ deleted == 0
+ {% if defined(workspaceId) %} AND workspace_id = {{ workspaceId }} {% end %}
+ {% if defined(programId) %} AND program_id = {{ programId }} {% end %}
+ {% if defined(partnerId) %} AND partner_id = {{ partnerId }} {% end %}
+ {% if defined(tenantId) %} AND tenant_id = {{ tenantId }} {% end %}
+ {% if defined(folderIds) %} AND folder_id IN {{ Array(folderIds, 'String') }}
+ {% elif defined(folderId) %} AND folder_id = {{ folderId }}
+ {% end %}
+ {% if defined(domain) %} AND domain IN {{ Array(domain, 'String') }} {% end %}
+ {% if defined(tagIds) %}
+ AND arrayIntersect(tag_ids, {{ Array(tagIds, 'String') }}) != []
+ {% end %}
+ {% if defined(root) %}
+ {% if Boolean(root) == 1 %} AND key = '_root' {% else %} AND key != '_root' {% end %}
+ {% end %}
+
+
+
+NODE count_clicks
+SQL >
+
+ %
+ SELECT COUNT(*) as clicks
+ FROM
+ {% if defined(customerId) %} dub_click_events_id
+ {% else %} dub_click_events_mv
+ {% end %}
+ {% if defined(customerId) %}
+ PREWHERE click_id IN (
+ SELECT DISTINCT click_id
+ FROM dub_lead_events_mv
+ WHERE customer_id = {{ String(customerId) }}
+ )
+ {% elif not defined(linkId) and (
+ defined(workspaceId) or defined(partnerId) or defined(programId)
+ ) %} PREWHERE link_id in (SELECT link_id from workspace_links)
+ {% end %}
+ WHERE
+ true
+ {% if defined(linkId) %} AND link_id = {{ String(linkId) }} {% end %}
+ {% if defined(qr) %} AND qr = {{ Boolean(qr) }} {% end %}
+ {% if defined(continent) %} AND continent = {{ continent }} {% end %}
+ {% if defined(country) %} AND country = {{ country }} {% end %}
+ {% if defined(region) %} AND region = {{ region }} {% end %}
+ {% if defined(city) %} AND city = {{ city }} {% end %}
+ {% if defined(device) %} AND device = {{ device }} {% end %}
+ {% if defined(browser) %} AND browser = {{ browser }} {% end %}
+ {% if defined(os) %} AND os = {{ os }} {% end %}
+ {% if defined(referer) %} AND referer = {{ referer }} {% end %}
+ {% if defined(refererUrl) %} AND splitByString('?', referer_url)[1] = {{ refererUrl }} {% end %}
+ {% if defined(utm_source) %}
+ AND url LIKE concat('%utm_source=', encodeURLFormComponent({{ String(utm_source) }}), '%')
+ {% end %}
+ {% if defined(utm_medium) %}
+ AND url LIKE concat('%utm_medium=', encodeURLFormComponent({{ String(utm_medium) }}), '%')
+ {% end %}
+ {% if defined(utm_campaign) %}
+ AND url
+ LIKE concat('%utm_campaign=', encodeURLFormComponent({{ String(utm_campaign) }}), '%')
+ {% end %}
+ {% if defined(utm_term) %}
+ AND url LIKE concat('%utm_term=', encodeURLFormComponent({{ String(utm_term) }}), '%')
+ {% end %}
+ {% if defined(utm_content) %}
+ AND url LIKE concat('%utm_content=', encodeURLFormComponent({{ String(utm_content) }}), '%')
+ {% end %}
+ {% if defined(url) %} AND url = {{ url }} {% end %}
+ {% if defined(start) %} AND timestamp >= {{ DateTime64(start) }} {% end %}
+ {% if defined(end) %} AND timestamp <= {{ DateTime64(end) }} {% end %}
+
+
+
+NODE count_leads
+SQL >
+
+ %
+ SELECT COUNT(*) as leads
+ FROM
+ dub_lead_events_mv
+ {% if not defined(linkId) and (defined(workspaceId) or defined(partnerId) or defined(programId)) %}
+ PREWHERE link_id in (SELECT link_id from workspace_links)
+ {% end %}
+ WHERE
+ true
+ {% if defined(linkId) %} AND link_id = {{ String(linkId) }} {% end %}
+ {% if defined(customerId) %} AND customer_id = {{ String(customerId) }} {% end %}
+ {% if defined(qr) %} AND qr = {{ Boolean(qr) }} {% end %}
+ {% if defined(continent) %} AND continent = {{ continent }} {% end %}
+ {% if defined(country) %} AND country = {{ country }} {% end %}
+ {% if defined(region) %} AND region = {{ region }} {% end %}
+ {% if defined(city) %} AND city = {{ city }} {% end %}
+ {% if defined(device) %} AND device = {{ device }} {% end %}
+ {% if defined(browser) %} AND browser = {{ browser }} {% end %}
+ {% if defined(os) %} AND os = {{ os }} {% end %}
+ {% if defined(referer) %} AND referer = {{ referer }} {% end %}
+ {% if defined(refererUrl) %} AND splitByString('?', referer_url)[1] = {{ refererUrl }} {% end %}
+ {% if defined(utm_source) %} AND url LIKE concat('%utm_source=', encodeURLFormComponent({{ String(utm_source) }}), '%') {% end %}
+ {% if defined(utm_medium) %} AND url LIKE concat('%utm_medium=', encodeURLFormComponent({{ String(utm_medium) }}), '%') {% end %}
+ {% if defined(utm_campaign) %} AND url LIKE concat('%utm_campaign=', encodeURLFormComponent({{ String(utm_campaign) }}), '%') {% end %}
+ {% if defined(utm_term) %} AND url LIKE concat('%utm_term=', encodeURLFormComponent({{ String(utm_term) }}), '%') {% end %}
+ {% if defined(utm_content) %} AND url LIKE concat('%utm_content=', encodeURLFormComponent({{ String(utm_content) }}), '%') {% end %}
+ {% if defined(url) %} AND url = {{ url }} {% end %}
+ {% if defined(start) %} AND timestamp >= {{ DateTime(start) }} {% end %}
+ {% if defined(end) %} AND timestamp <= {{ DateTime(end) }} {% end %}
+
+
+
+NODE count_sales
+SQL >
+
+ %
+ WITH
+ sale_rankings AS (
+ SELECT
+ *,
+ ROW_NUMBER() OVER (
+ PARTITION BY customer_id, link_id ORDER BY timestamp ASC
+ ) as sale_rank
+ FROM
+ dub_sale_events_mv
+ {% if not defined(linkId) and (
+ defined(workspaceId) or defined(partnerId) or defined(programId)
+ ) %} PREWHERE link_id in (SELECT link_id from workspace_links) {% end %}
+ WHERE
+ true
+ {% if defined(linkId) %} AND link_id = {{ String(linkId) }} {% end %}
+ {% if defined(customerId) %} AND customer_id = {{ String(customerId) }} {% end %}
+ {% if defined(qr) %} AND qr = {{ Boolean(qr) }} {% end %}
+ {% if defined(continent) %} AND continent = {{ continent }} {% end %}
+ {% if defined(country) %} AND country = {{ country }} {% end %}
+ {% if defined(region) %} AND region = {{ region }} {% end %}
+ {% if defined(city) %} AND city = {{ city }} {% end %}
+ {% if defined(device) %} AND device = {{ device }} {% end %}
+ {% if defined(browser) %} AND browser = {{ browser }} {% end %}
+ {% if defined(os) %} AND os = {{ os }} {% end %}
+ {% if defined(referer) %} AND referer = {{ referer }} {% end %}
+ {% if defined(refererUrl) %}
+ AND splitByString('?', referer_url)[1] = {{ refererUrl }}
+ {% end %}
+ {% if defined(utm_source) %}
+ AND url
+ LIKE concat('%utm_source=', encodeURLFormComponent({{ String(utm_source) }}), '%')
+ {% end %}
+ {% if defined(utm_medium) %}
+ AND url
+ LIKE concat('%utm_medium=', encodeURLFormComponent({{ String(utm_medium) }}), '%')
+ {% end %}
+ {% if defined(utm_campaign) %}
+ AND url LIKE concat(
+ '%utm_campaign=', encodeURLFormComponent({{ String(utm_campaign) }}), '%'
+ )
+ {% end %}
+ {% if defined(utm_term) %}
+ AND url
+ LIKE concat('%utm_term=', encodeURLFormComponent({{ String(utm_term) }}), '%')
+ {% end %}
+ {% if defined(utm_content) %}
+ AND url
+ LIKE concat('%utm_content=', encodeURLFormComponent({{ String(utm_content) }}), '%')
+ {% end %}
+ {% if defined(url) %} AND url = {{ url }} {% end %}
+ {% if defined(start) %} AND timestamp >= {{ DateTime(start) }} {% end %}
+ {% if defined(end) %} AND timestamp <= {{ DateTime(end) }} {% end %}
+ )
+ SELECT sales, amount, amount AS saleAmount
+ FROM
+ (
+ SELECT COUNT(*) as sales, sum(amount) as amount
+ FROM sale_rankings
+ WHERE
+ 1 = 1
+ {% if defined(saleType) %}
+ {% if saleType == 'new' %} AND sale_rank = 1
+ {% elif saleType == 'recurring' %} AND sale_rank > 1
+ {% end %}
+ {% end %}
+ ) AS subquery
+
+
+
+NODE count_composite
+SQL >
+
+ SELECT clicks, leads, sales, amount, saleAmount FROM count_clicks, count_leads, count_sales
+
+
+
+NODE endpoint
+SQL >
+
+ %
+ SELECT *
+ FROM
+ {% if eventType == 'clicks' %} count_clicks
+ {% elif eventType == 'leads' %} count_leads
+ {% elif eventType == 'sales' %} count_sales
+ {% else %} count_composite
+ {% end %}
+
+