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.

8.7 KB
Raw Blame
import * as z from "zod/v4";
import { LinkSchema } from "./links";
import {
  booleanQuerySchema,
  getCursorPaginationQuerySchema,
  getPaginationQuerySchema,
} from "./misc";
import { centsSchema, parseDateSchema } from "./utils";

export const CUSTOMERS_MAX_PAGE_SIZE = 100;

export const getCustomersQuerySchema = z
  .object({
    email: z
      .string()
      .optional()
      .describe(
        "A case-sensitive filter on the list based on the customer's `email` field. The value must be a string. Takes precedence over `externalId`.",
      ),
    externalId: z
      .string()
      .optional()
      .describe(
        "A case-sensitive filter on the list based on the customer's `externalId` field. The value must be a string. Takes precedence over `search`.",
      ),
    search: z
      .string()
      .optional()
      .describe(
        "A search query to filter customers by email, name, or customer ID (`cus_...`). If `email` or `externalId` is provided, this will be ignored.",
      ),
    country: z
      .string()
      .optional()
      .describe(
        "A filter on the list based on the customer's `country` field.",
      ),
    linkId: z
      .string()
      .optional()
      .describe(
        "A filter on the list based on the customer's `linkId` field (the referral link ID).",
      ),
    includeExpandedFields: booleanQuerySchema
      .optional()
      .describe("Whether to include expanded fields on the customer (`link`)."),
    sortBy: z
      .enum([
        "createdAt",
        "saleAmount",
        "firstSaleAt",
        "subscriptionCanceledAt",
      ])
      .optional()
      .default("createdAt")
      .describe(
        "The field to sort the customers by. The default is `createdAt`.",
      ),
    sortOrder: z
      .enum(["asc", "desc"])
      .optional()
      .default("desc")
      .describe("The sort order. The default is `desc`."),
  })
  .extend({
    ...getCursorPaginationQuerySchema({
      example: "cus_1KAP4CDPBSVMMBMH9XX3YZZ0Z",
    }),
    ...getPaginationQuerySchema({
      pageSize: CUSTOMERS_MAX_PAGE_SIZE,
      deprecated: true,
    }),
  });

export const getCustomersQuerySchemaExtended = getCustomersQuerySchema.extend({
  customerIds: z
    .union([z.string(), z.array(z.string())])
    .transform((v) => (Array.isArray(v) ? v : v.split(",")))
    .nullish()
    .describe("Customer IDs to filter by."),
});

export const getCustomersCountQuerySchema = getCustomersQuerySchema
  .omit({
    includeExpandedFields: true,
    page: true,
    pageSize: true,
    sortBy: true,
    sortOrder: true,
    startingAfter: true,
    endingBefore: true,
  })
  .extend({ groupBy: z.enum(["country", "linkId"]).optional() });

export const createCustomerBodySchema = z.object({
  email: z.email().nullish().describe("The customer's email address."),
  name: z
    .string()
    .nullish()
    .describe(
      "The customer's name. If not provided, the email address will be used, and if email is not provided, a random name will be generated.",
    ),
  avatar: z
    .url()
    .nullish()
    .describe(
      "The customer's avatar URL. If not provided, a random avatar will be generated.",
    ),
  externalId: z
    .string("External ID is required")
    .describe(
      "The customer's unique identifier your database. This is useful for associating subsequent conversion events from Dub's API to your internal systems.",
    ),
  stripeCustomerId: z
    .string()
    .nullish()
    .describe(
      "The customer's Stripe customer ID. This is useful for attributing recurring sale events to the customer.",
    ),
  country: z
    .string()
    .describe(
      "The customer's country in ISO 3166-1 alpha-2 format. Updating this field will only affect the customer's country in Dub's system (and has no effect on existing conversion events).",
    ),
});

export const updateCustomerBodySchema = createCustomerBodySchema
  .partial()
  .extend({
    subscriptionCanceledAt: parseDateSchema
      .nullish()
      .describe(
        "The date the customer canceled their subscription. Set to a timestamp to mark the subscription as canceled, or `null` to clear it (e.g. if they resubscribe).",
      ),
  });

// used in webhook responses + regular /customers endpoints (without expanded fields)
export const CustomerSchema = z.object({
  id: z
    .string()
    .describe(
      "The unique ID of the customer. You may use either the customer's `id` on Dub (obtained via `/customers` endpoint) or their `externalId` (unique ID within your system, prefixed with `ext_`, e.g. `ext_123`).",
    ),
  name: z.string().nullish().describe("Name of the customer."),
  email: z.string().nullish().describe("Email of the customer."),
  avatar: z.string().nullish().describe("Avatar URL of the customer."),
  externalId: z
    .string()
    .describe("Unique identifier for the customer in the client's app."),
  stripeCustomerId: z
    .string()
    .nullish()
    .describe(
      "The customer's Stripe customer ID. This is useful for attributing recurring sale events to the customer.",
    ),
  country: z.string().nullish().describe("Country of the customer."),
  sales: z
    .number()
    .nullish()
    .describe("Total number of sales for the customer."),
  saleAmount: centsSchema
    .nullish()
    .describe("Total amount of sales for the customer."),
  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.
export const CustomerEnrichedSchema = CustomerSchema.extend({
  link: LinkSchema.pick({
    id: true,
    domain: true,
    key: true,
    shortLink: true,
    url: true,
  }).nullish(),
});

export const StripeCustomerSchema = z.object({
  id: z.string(),
  email: z.string().nullable(),
  name: z.string().nullable(),
  country: z.string().nullable(),
  subscriptions: z.number(),
  dubCustomerId: z.string().nullable(),
});

export const CUSTOMER_EXPORT_COLUMNS = [
  {
    id: "id",
    label: "ID",
    type: "string",
    default: true,
    order: 1,
  },
  {
    id: "name",
    label: "Name",
    type: "string",
    default: true,
    order: 2,
  },
  {
    id: "email",
    label: "Email",
    type: "string",
    default: true,
    order: 3,
  },
  {
    id: "avatar",
    label: "Avatar",
    type: "string",
    default: true,
    order: 4,
  },
  {
    id: "externalId",
    label: "External ID",
    type: "string",
    default: true,
    order: 5,
  },
  {
    id: "stripeCustomerId",
    label: "Stripe customer ID",
    type: "string",
    default: true,
    order: 6,
  },
  {
    id: "country",
    label: "Country",
    type: "string",
    default: true,
    order: 7,
  },
  {
    id: "sales",
    label: "Sales",
    type: "number",
    default: true,
    order: 8,
  },
  {
    id: "saleAmount",
    label: "Sale amount",
    type: "number",
    default: true,
    order: 9,
  },
  {
    id: "createdAt",
    label: "Created at",
    type: "date",
    default: true,
    order: 10,
  },
  {
    id: "firstSaleAt",
    label: "First sale at",
    type: "date",
    default: true,
    order: 11,
  },
  {
    id: "subscriptionCanceledAt",
    label: "Subscription canceled",
    type: "date",
    default: true,
    order: 12,
  },
  {
    id: "link",
    label: "Link",
    type: "string",
    default: false,
    order: 13,
  },
] as const;

type CustomerExportColumnId = (typeof CUSTOMER_EXPORT_COLUMNS)[number]["id"];

export const CUSTOMER_EXPORT_DEFAULT_COLUMNS = CUSTOMER_EXPORT_COLUMNS.filter(
  (column) => column.default,
).map((column) => column.id);

export const customersExportQuerySchema = getCustomersQuerySchema
  .omit({
    page: true,
    pageSize: true,
    includeExpandedFields: true,
  })
  .extend({
    columns: z
      .string()
      .optional()
      .default(CUSTOMER_EXPORT_DEFAULT_COLUMNS.join(","))
      .transform((v) =>
        v
          .split(",")
          .map((s) => s.trim())
          .filter(Boolean),
      )
      .refine(
        (columns) => {
          const validColumnIds = CUSTOMER_EXPORT_COLUMNS.map((col) => col.id);

          return columns.every((column: CustomerExportColumnId) =>
            validColumnIds.includes(column),
          );
        },
        {
          message:
            "Invalid column IDs provided. Please check the available columns.",
        },
      ),
  });

export const customersExportCronInputSchema = customersExportQuerySchema.extend(
  {
    workspaceId: z.string(),
    userId: z.string(),
  },
);