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 more customer columns (Paid, Canceled) (#3380)

Steven Teydab4876d7328
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-table.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-table.tsx
index 3888def01b..ceb5c7fe8d 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-table.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/partners-table.tsx
@@ -280,6 +280,14 @@ export function PartnersTable() {
id: "location",
header: "Location",
minSize: 150,
+ meta: {
+ filterParams: ({ getValue }) =>
+ getValue()
+ ? {
+ country: getValue(),
+ }
+ : undefined,
+ },
cell: ({ row }) => {
const country = row.original.country;
return (
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index 8d8da87707..54e3c3508c 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -140,7 +140,23 @@ export const CustomerSchema = z.object({
.number()
.nullish()
.describe("Total amount of sales for the customer."),
- createdAt: z.date().describe("The date the customer was created."),
+ createdAt: z
+ .date()
+ .describe(
+ "The date the customer was created (usually the signup date or trial start date).",
+ ),
+ firstSaleAt: z
+ .date()
+ .nullish()
+ .describe(
+ "The date the customer made their first sale. Useful for calculating the time to first sale and LTV.",
+ ),
+ subscriptionCanceledAt: z
+ .date()
+ .nullish()
+ .describe(
+ "The date the customer canceled their subscription. Useful for calculating LTV and churn rate.",
+ ),
});
// An extended schema that includes the customer's link, partner, and discount.
diff --git a/apps/web/scripts/migrations/backfill-customer-first-sale.ts b/apps/web/scripts/migrations/backfill-customer-first-sale.ts
new file mode 100644
index 0000000000..bf50c2554e
--- /dev/null
+++ b/apps/web/scripts/migrations/backfill-customer-first-sale.ts
@@ -0,0 +1,60 @@
+import { prisma } from "@dub/prisma";
+import { chunk } from "@dub/utils";
+import "dotenv-flow/config";
+import * as z from "zod/v4";
+import { tb } from "../../lib/tinybird/client";
+
+export const getFirstSaleEvents = tb.buildPipe({
+ pipe: "get_first_sale_events",
+ parameters: z.object({
+ customerIds: z.string().array(),
+ }),
+ data: z.object({
+ customerId: z.string(),
+ firstSaleAt: z.string(),
+ }),
+});
+
+async function main() {
+ const customerWithSales = await prisma.customer.findMany({
+ where: {
+ sales: {
+ gt: 0,
+ },
+ firstSaleAt: null,
+ },
+ take: 5000,
+ });
+
+ let updated = 0;
+
+ const chunks = chunk(customerWithSales, 50);
+
+ for (const chunk of chunks) {
+ const firstSaleEvents = await getFirstSaleEvents({
+ customerIds: chunk.map((customer) => customer.id),
+ }).then((res) => res.data);
+
+ await Promise.all(
+ firstSaleEvents.map(async (event) => {
+ const res = await prisma.customer.update({
+ where: { id: event.customerId },
+ data: {
+ firstSaleAt: new Date(event.firstSaleAt),
+ },
+ });
+ console.log({
+ id: res.id,
+ firstSaleAt: res.firstSaleAt,
+ });
+ updated++;
+ }),
+ );
+ }
+
+ console.log(
+ `Updated ${updated}/${customerWithSales.length} customers (${(updated / customerWithSales.length) * 100}%)`,
+ );
+}
+
+main();
diff --git a/apps/web/scripts/migrations/backfill-customer-subscription-cancellation.ts b/apps/web/scripts/migrations/backfill-customer-subscription-cancellation.ts
index 21269b4b63..22152b8b63 100644
--- a/apps/web/scripts/migrations/backfill-customer-subscription-cancellation.ts
+++ b/apps/web/scripts/migrations/backfill-customer-subscription-cancellation.ts
@@ -1,76 +1,80 @@
import { prisma } from "@dub/prisma";
+import { chunk } from "@dub/utils";
import "dotenv-flow/config";
import { stripeAppClient } from "../../lib/stripe";
async function main() {
- const stripeCustomers = await prisma.customer.findMany({
- where: {
- AND: [
- {
- stripeCustomerId: {
- not: null,
- },
- },
- {
- stripeCustomerId: {
- notIn: [],
- },
- },
- {
- firstSaleAt: null,
- },
- ],
- },
- take: 20,
- });
+ let page = 0;
+ const pageSize = 5000;
- let testModeCustomerIds: string[] = [];
-
- await Promise.all(
- stripeCustomers.map(async (customer) => {
- try {
- const customerSubscriptions = await stripeAppClient({
- mode: "live",
- }).subscriptions.list(
- {
- customer: customer.stripeCustomerId!,
- status: "all",
- },
- {
- stripeAccount: customer.projectConnectId!,
- },
- );
+ while (true) {
+ const stripeCustomers = await prisma.customer.findMany({
+ where: {
+ stripeCustomerId: {
+ not: null,
+ },
+ firstSaleAt: null,
+ },
+ take: pageSize,
+ skip: page * pageSize,
+ });
- if (customerSubscriptions.data.length === 0) {
- console.log(`No subscriptions found for customer ${customer.email}`);
- return;
- }
+ if (stripeCustomers.length === 0) {
+ console.log("No customers left to backfill");
+ break;
+ }
- const subscription = customerSubscriptions.data[0];
+ const chunks = chunk(stripeCustomers, 20);
+ for (const chunk of chunks) {
+ await Promise.all(
+ chunk.map(async (customer) => {
+ try {
+ const customerSubscriptions = await stripeAppClient({
+ mode: "live",
+ }).subscriptions.list(
+ {
+ customer: customer.stripeCustomerId!,
+ status: "all",
+ },
+ {
+ stripeAccount: customer.projectConnectId!,
+ },
+ );
- const data = {
- startDate: new Date(subscription.created * 1000),
- subscriptionCanceledAt: subscription.canceled_at
- ? new Date(subscription.canceled_at * 1000)
- : null,
- };
+ if (customerSubscriptions.data.length === 0) {
+ console.log(
+ `No subscriptions found for customer ${customer.email}`,
+ );
+ return;
+ }
- console.log({
- email: customer.email,
- ...data,
- });
+ const subscription = customerSubscriptions.data[0];
- await prisma.customer.update({
- where: { id: customer.id },
- data,
- });
- } catch (error) {
- testModeCustomerIds.push(customer.id);
- }
- }),
- );
+ const updatedCustomer = await prisma.customer.update({
+ where: { id: customer.id },
+ data: {
+ firstSaleAt: new Date(subscription.created * 1000),
+ subscriptionCanceledAt: subscription.canceled_at
+ ? new Date(subscription.canceled_at * 1000)
+ : null,
+ },
+ });
+ console.log({
+ email: updatedCustomer.email,
+ firstSaleAt: updatedCustomer.firstSaleAt,
+ subscriptionCanceledAt: updatedCustomer.subscriptionCanceledAt,
+ });
+ } catch (error) {
+ console.log(
+ `Test mode customer detected: ${customer.stripeCustomerId}`,
+ );
+ }
+ }),
+ );
+ }
- console.log(`Test mode customer ids: "${testModeCustomerIds.join('", "')}"`);
+ page++;
+ }
}
main();
diff --git a/apps/web/tests/customers/index.test.ts b/apps/web/tests/customers/index.test.ts
index 4189344ac0..673fc2c344 100644
--- a/apps/web/tests/customers/index.test.ts
+++ b/apps/web/tests/customers/index.test.ts
@@ -14,6 +14,8 @@ const expectedCustomer = {
saleAmount: 0,
sales: 0,
createdAt: expect.any(String),
+ firstSaleAt: null,
+ subscriptionCanceledAt: null,
};
describe.sequential("/customers/**", async () => {
diff --git a/apps/web/ui/customers/customer-table/customer-table.tsx b/apps/web/ui/customers/customer-table/customer-table.tsx
index 52f4f9f1d0..426f767f54 100644
--- a/apps/web/ui/customers/customer-table/customer-table.tsx
+++ b/apps/web/ui/customers/customer-table/customer-table.tsx
@@ -42,6 +42,7 @@ import { Cell, Row } from "@tanstack/react-table";
import { Command } from "cmdk";
import Image from "next/image";
import Link from "next/link";
+import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { toast } from "sonner";
import useSWR from "swr";
@@ -63,9 +64,9 @@ export function CustomerTable({
isProgramPage?: boolean;
}) {
const { id: workspaceId, slug: workspaceSlug, plan } = useWorkspace();
-
const { canManageCustomers } = getPlanCapabilities(plan);
+ const router = useRouter();
const { queryParams, searchParams, getQueryString } = useRouterStuff();
const sortBy = searchParams.get("sortBy") || "createdAt";
@@ -115,6 +116,8 @@ export function CustomerTable({
"link",
"saleAmount",
"createdAt",
+ "firstSaleAt",
+ "subscriptionCanceledAt",
"externalId",
],
defaultVisible: [
@@ -123,6 +126,8 @@ export function CustomerTable({
...(isProgramPage ? ["partner"] : ["link"]),
"saleAmount",
"createdAt",
+ "firstSaleAt",
+ "subscriptionCanceledAt",
],
};
@@ -149,11 +154,6 @@ export function CustomerTable({
return (
<CustomerRowItem
customer={row.original}
- href={
- isProgramPage
- ? `/${workspaceSlug}/program/customers/${row.original.id}`
- : `/${workspaceSlug}/customers/${row.original.id}`
- }
chartActivityIconMode="visible"
/>
);
@@ -239,7 +239,11 @@ export function CustomerTable({
},
{
id: "saleAmount",
- header: "Lifetime value",
+ header: "LTV",
+ meta: {
+ headerTooltip:
+ "The total amount of revenue the customer has generated over time (lifetime value).",
+ },
accessorKey: "saleAmount",
cell: ({ getValue }) => (
<div className="flex items-center gap-2">
@@ -255,6 +259,10 @@ export function CustomerTable({
{
id: "createdAt",
header: "Created",
+ meta: {
+ headerTooltip:
+ "The date the customer was created (usually the signup date or trial start date).",
+ },
cell: ({ row }) => (
<TimestampTooltip
timestamp={row.original.createdAt}
@@ -268,6 +276,52 @@ export function CustomerTable({
</TimestampTooltip>
),
},
+ {
+ id: "firstSaleAt",
+ header: "Paid",
+ meta: {
+ headerTooltip: "The date the customer made their first sale.",
+ },
+ cell: ({ row }) =>
+ row.original.firstSaleAt ? (
+ <TimestampTooltip
+ timestamp={row.original.firstSaleAt}
+ rows={["local"]}
+ side="left"
+ delayDuration={150}
+ >
+ <span>
+ {formatDate(row.original.firstSaleAt, { month: "short" })}
+ </span>
+ </TimestampTooltip>
+ ) : (
+ "-"
+ ),
+ },
+ {
+ id: "subscriptionCanceledAt",
+ header: "Canceled",
+ meta: {
+ headerTooltip: "The date the customer canceled their subscription.",
+ },
+ cell: ({ row }) =>
+ row.original.subscriptionCanceledAt ? (
+ <TimestampTooltip
+ timestamp={row.original.subscriptionCanceledAt}
+ rows={["local"]}
+ side="left"
+ delayDuration={150}
+ >
+ <span>
+ {formatDate(row.original.subscriptionCanceledAt, {
+ month: "short",
+ })}
+ </span>
+ </TimestampTooltip>
+ ) : (
+ "-"
+ ),
+ },
{
id: "externalId",
header: "External ID",
@@ -299,9 +353,27 @@ export function CustomerTable({
[isProgramPage, workspaceSlug],
);
+ const getCustomerUrl = (row: Row<CustomerProps>) =>
+ isProgramPage
+ ? `/${workspaceSlug}/program/customers/${row.original.id}`
+ : `/${workspaceSlug}/customers/${row.original.id}`;
+
const { table, ...tableProps } = useTable({
data: canManageCustomers ? customers || [] : EXAMPLE_CUSTOMER_DATA,
columns,
+ columnPinning: { right: ["menu"] },
+ onRowClick: (row, e) => {
+ const url = getCustomerUrl(row);
+
+ if (e.metaKey || e.ctrlKey) window.open(url, "_blank");
+ else router.push(url);
+ },
+ onRowAuxClick: (row) => window.open(getCustomerUrl(row), "_blank"),
+ rowProps: (row) => ({
+ onPointerEnter: () => {
+ router.prefetch(getCustomerUrl(row));
+ },
+ }),
pagination,
onPaginationChange: setPagination,
columnVisibility,
@@ -318,7 +390,6 @@ export function CustomerTable({
del: "page",
scroll: false,
}),
- columnPinning: { right: ["menu"] },
cellRight: (cell) => {
const meta = cell.column.columnDef.meta as ColumnMeta | undefined;
return (
diff --git a/apps/web/ui/layout/toolbar/onboarding/onboarding-button.tsx b/apps/web/ui/layout/toolbar/onboarding/onboarding-button.tsx
index 1441f16e82..c73d55ce64 100644
--- a/apps/web/ui/layout/toolbar/onboarding/onboarding-button.tsx
+++ b/apps/web/ui/layout/toolbar/onboarding/onboarding-button.tsx
@@ -1,8 +1,7 @@
"use client";
-import { DIRECT_DEBIT_PAYMENT_METHOD_TYPES } from "@/lib/constants/payouts";
import useDomainsCount from "@/lib/swr/use-domains-count";
-import usePaymentMethods from "@/lib/swr/use-payment-methods";
+import usePartnersCount from "@/lib/swr/use-partners-count";
import useWorkspace from "@/lib/swr/use-workspace";
import useWorkspaceUsers from "@/lib/swr/use-workspace-users";
import { useAnalyticsConnectedStatus } from "@/ui/analytics/use-analytics-connected-status";
@@ -46,14 +45,14 @@ function OnboardingButtonInner({
const { users, loading: usersLoading } = useWorkspaceUsers();
const { isConnected: connectedAnalytics } = useAnalyticsConnectedStatus();
- const { paymentMethods, loading: paymentMethodsLoading } = usePaymentMethods({
- enabled: Boolean(defaultProgramId),
- });
- const connectedBankAccount = paymentMethods?.some((pm) =>
- DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(pm.type),
- );
- const loading = domainsLoading || usersLoading || paymentMethodsLoading;
+ const { partnersCount, loading: partnersCountLoading } =
+ usePartnersCount<number>({
+ ignoreParams: true,
+ enabled: Boolean(defaultProgramId),
+ });
+
+ const loading = domainsLoading || usersLoading || partnersCountLoading;
const tasks = useMemo(() => {
return [
@@ -78,9 +77,9 @@ function OnboardingButtonInner({
recommended: true,
},
{
- display: "Connect bank account for payouts",
- cta: `/${slug}/program/payouts`,
- checked: connectedBankAccount,
+ display: "Invite your partners",
+ cta: `/${slug}/program/partners`,
+ checked: partnersCount && partnersCount > 0,
recommended: true,
},
]
@@ -88,7 +87,7 @@ function OnboardingButtonInner({
{
display: "Create a short link",
cta: `/${slug}/links`,
- checked: totalLinks === 0 ? false : true,
+ checked: totalLinks && totalLinks > 0,
recommended: true,
},
{
@@ -102,9 +101,9 @@ function OnboardingButtonInner({
}, [
slug,
defaultProgramId,
- connectedAnalytics,
- paymentMethods,
domainsCount,
+ connectedAnalytics,
+ partnersCount,
totalLinks,
users,
]);
@@ -128,7 +127,8 @@ function OnboardingButtonInner({
<div>
<span className="text-base font-medium">Complete setup</span>
<p className="mt-1 text-sm text-neutral-300">
- Finish setting up your workspace
+ Finish setting up your{" "}
+ {defaultProgramId ? "program" : "workspace"}
<br className="hidden sm:block" />
to get the most out of Dub
</p>