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.

update to useCustomers only

Steven Tey5f54dce19ba2
diff --git a/apps/web/app/api/customers/route.ts b/apps/web/app/api/customers/route.ts
index 58dc14a5b6..54ac60c337 100644
--- a/apps/web/app/api/customers/route.ts
+++ b/apps/web/app/api/customers/route.ts
@@ -11,7 +11,7 @@ import {
createCustomerBodySchema,
CustomerEnrichedSchema,
CustomerSchema,
- getCustomersQuerySchema,
+ getCustomersQuerySchemaExtended,
} from "@/lib/zod/schemas/customers";
import { DiscountSchemaWithDeprecatedFields } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
@@ -42,28 +42,43 @@ interface CustomerResponse extends Customer {
// GET /api/customers – Get all customers
export const GET = withWorkspace(
async ({ workspace, searchParams }) => {
- const { email, externalId, search, includeExpandedFields } =
- getCustomersQuerySchema.parse(searchParams);
+ const {
+ email,
+ externalId,
+ search,
+ includeExpandedFields,
+ page,
+ pageSize,
+ customerIds,
+ } = getCustomersQuerySchemaExtended.parse(searchParams);
const customers = (await prisma.customer.findMany({
where: {
- projectId: workspace.id,
- ...(email ? { email } : {}),
- ...(externalId ? { externalId } : {}),
- ...(search
+ ...(customerIds
? {
- OR: [
- { email: { contains: search } },
- { name: { contains: search } },
- { externalId: { contains: search } },
- ],
+ id: { in: customerIds },
}
: {}),
+ projectId: workspace.id,
+ ...(email
+ ? { email }
+ : externalId
+ ? { externalId }
+ : search
+ ? {
+ OR: [
+ { email: { startsWith: search } },
+ { externalId: { startsWith: search } },
+ { name: { startsWith: search } },
+ ],
+ }
+ : {}),
},
- take: 100,
orderBy: {
createdAt: "desc",
},
+ skip: (page - 1) * pageSize,
+ take: pageSize,
...(includeExpandedFields
? {
include: {
diff --git a/apps/web/app/api/programs/[programId]/customers/count/route.ts b/apps/web/app/api/programs/[programId]/customers/count/route.ts
deleted file mode 100644
index 9e17a1482f..0000000000
--- a/apps/web/app/api/programs/[programId]/customers/count/route.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
-import { withWorkspace } from "@/lib/auth";
-import { prisma } from "@dub/prisma";
-import { NextResponse } from "next/server";
-
-// GET /api/programs/[programId]/customers/count
-export const GET = withWorkspace(async ({ workspace, params }) => {
- const { programId } = params;
-
- await getProgramOrThrow({
- workspaceId: workspace.id,
- programId,
- });
-
- const count = await prisma.customer.count({
- where: {
- commissions: {
- some: {
- programId,
- },
- },
- },
- });
-
- return NextResponse.json(count);
-});
diff --git a/apps/web/app/api/programs/[programId]/customers/route.ts b/apps/web/app/api/programs/[programId]/customers/route.ts
deleted file mode 100644
index 1c81345500..0000000000
--- a/apps/web/app/api/programs/[programId]/customers/route.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
-import { withWorkspace } from "@/lib/auth";
-import {
- CustomerSchema,
- customersQuerySchema,
-} from "@/lib/zod/schemas/customers";
-import { PartnerSchema } from "@/lib/zod/schemas/partners";
-import { prisma } from "@dub/prisma";
-import { NextResponse } from "next/server";
-import { z } from "zod";
-
-const responseSchema = CustomerSchema.and(
- z.object({
- partner: PartnerSchema,
- }),
-);
-
-// GET /api/programs/[programId]/customers - get all customers for a program
-export const GET = withWorkspace(
- async ({ workspace, params, searchParams }) => {
- const { programId } = params;
- const { search, ids, page, pageSize } =
- customersQuerySchema.parse(searchParams);
-
- await getProgramOrThrow({
- workspaceId: workspace.id,
- programId,
- });
-
- const customers = await prisma.customer.findMany({
- where: {
- commissions: {
- some: {
- programId,
- },
- },
- ...(search && { name: { contains: search } }),
- ...(ids && { id: { in: ids } }),
- },
- select: {
- id: true,
- name: true,
- email: true,
- avatar: true,
- externalId: true,
- createdAt: true,
- updatedAt: true,
- commissions: {
- select: {
- partner: true,
- },
- },
- },
- orderBy: {
- createdAt: "desc",
- },
- skip: (page - 1) * pageSize,
- take: pageSize,
- });
-
- const customersWithPartner = customers.map((customer) => {
- return responseSchema.parse({
- ...customer,
- partner: customer.commissions[0]?.partner,
- });
- });
-
- return NextResponse.json(customersWithPartner);
- },
-);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx
index beecc8215d..e66bd0e21b 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/create-commission-sheet.tsx
@@ -341,7 +341,7 @@ function CreateCommissionSheetContent({
Invoice ID
</h2>
</label>
- <div className="mt-2">
+ <div className="mt-2 p-px">
<input
type="text"
id="invoiceId"
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/use-commission-filters.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/use-commission-filters.tsx
index 6cc10fb92b..6c3f1f6fb1 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/use-commission-filters.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/programs/[programId]/commissions/use-commission-filters.tsx
@@ -1,8 +1,8 @@
import useCommissionsCount from "@/lib/swr/use-commissions-count";
+import useCustomers from "@/lib/swr/use-customers";
+import useCustomersCount from "@/lib/swr/use-customers-count";
import usePartners from "@/lib/swr/use-partners";
import usePartnersCount from "@/lib/swr/use-partners-count";
-import useProgramCustomers from "@/lib/swr/use-program-customers";
-import useProgramCustomersCount from "@/lib/swr/use-program-customers-count";
import { CustomerProps, EnrolledPartnerProps } from "@/lib/types";
import { CUSTOMERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/customers";
import { PARTNERS_MAX_PAGE_SIZE } from "@/lib/zod/schemas/partners";
@@ -218,18 +218,18 @@ function usePartnerFilterOptions(search: string) {
function useCustomerFilterOptions(search: string) {
const { searchParamsObj } = useRouterStuff();
- const { customersCount } = useProgramCustomersCount();
+ const { data: customersCount } = useCustomersCount();
const customersAsync = Boolean(
customersCount && customersCount > CUSTOMERS_MAX_PAGE_SIZE,
);
- const { data: customers, loading: customersLoading } = useProgramCustomers({
+ const { customers, loading: customersLoading } = useCustomers({
query: { search: customersAsync ? search : "" },
});
- const { data: selectedCustomers } = useProgramCustomers({
+ const { customers: selectedCustomers } = useCustomers({
query: {
- ids: searchParamsObj.customerId
+ customerIds: searchParamsObj.customerId
? [searchParamsObj.customerId]
: undefined,
},
diff --git a/apps/web/lib/swr/use-customers.ts b/apps/web/lib/swr/use-customers.ts
index 805a7374c4..68ccb755a1 100644
--- a/apps/web/lib/swr/use-customers.ts
+++ b/apps/web/lib/swr/use-customers.ts
@@ -2,10 +2,10 @@ import { fetcher } from "@dub/utils";
import useSWR from "swr";
import { z } from "zod";
import { CustomerProps } from "../types";
-import { customersQuerySchema } from "../zod/schemas/customers";
+import { getCustomersQuerySchemaExtended } from "../zod/schemas/customers";
import useWorkspace from "./use-workspace";
-const partialQuerySchema = customersQuerySchema.partial();
+const partialQuerySchema = getCustomersQuerySchemaExtended.partial();
export default function useCustomers({
query,
diff --git a/apps/web/lib/swr/use-program-customers-count.ts b/apps/web/lib/swr/use-program-customers-count.ts
deleted file mode 100644
index 1b44e33267..0000000000
--- a/apps/web/lib/swr/use-program-customers-count.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { fetcher } from "@dub/utils";
-import { useParams } from "next/navigation";
-import useSWR from "swr";
-import useWorkspace from "./use-workspace";
-
-export default function useProgramCustomersCount() {
- const { programId } = useParams();
- const { id: workspaceId } = useWorkspace();
-
- const { data: customersCount, error } = useSWR<number>(
- `/api/programs/${programId}/customers/count?workspaceId=${workspaceId}`,
- fetcher,
- );
-
- return {
- customersCount,
- error,
- };
-}
diff --git a/apps/web/lib/swr/use-program-customers.ts b/apps/web/lib/swr/use-program-customers.ts
deleted file mode 100644
index 3a419e2f38..0000000000
--- a/apps/web/lib/swr/use-program-customers.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { fetcher } from "@dub/utils";
-import { useParams } from "next/navigation";
-import useSWR from "swr";
-import { z } from "zod";
-import { CustomerProps } from "../types";
-import { customersQuerySchema } from "../zod/schemas/customers";
-import useWorkspace from "./use-workspace";
-
-const partialQuerySchema = customersQuerySchema.partial();
-
-export default function useProgramCustomers({
- query,
- enabled = true,
-}: {
- query?: z.infer<typeof partialQuerySchema>;
- enabled?: boolean;
-} = {}) {
- const { programId } = useParams();
- const { id: workspaceId } = useWorkspace();
-
- const { data, error } = useSWR<CustomerProps[]>(
- enabled && workspaceId
- ? `/api/programs/${programId}/customers?${new URLSearchParams({
- workspaceId: workspaceId,
- ...query,
- } as Record<string, any>).toString()}`
- : undefined,
- fetcher,
- );
-
- return {
- data,
- loading: !data && !error,
- error,
- };
-}
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index 161b874479..66fd65a9b4 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -4,31 +4,45 @@ import { LinkSchema } from "./links";
import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
import { PartnerSchema } from "./partners";
-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.",
- ),
- 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.",
- ),
- search: z
- .string()
- .optional()
- .describe(
- "A search query to filter customers by name or email or externalId.",
- ),
- includeExpandedFields: booleanQuerySchema
- .optional()
- .describe(
- "Whether to include expanded fields on the customer (`link`, `partner`, `discount`).",
- ),
-});
+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, externalId, or name. If `email` or `externalId` is provided, this will be ignored.",
+ ),
+ includeExpandedFields: booleanQuerySchema
+ .optional()
+ .describe(
+ "Whether to include expanded fields on the customer (`link`, `partner`, `discount`).",
+ ),
+ })
+ .merge(getPaginationQuerySchema({ pageSize: CUSTOMERS_MAX_PAGE_SIZE }));
+
+export const getCustomersQuerySchemaExtended = getCustomersQuerySchema.merge(
+ z.object({
+ 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 createCustomerBodySchema = z.object({
email: z
@@ -88,16 +102,3 @@ export const CustomerEnrichedSchema = CustomerSchema.extend({
}).nullish(),
discount: DiscountSchema.nullish(),
});
-
-export const CUSTOMERS_MAX_PAGE_SIZE = 100;
-
-export const customersQuerySchema = z
- .object({
- search: z.string().optional(),
- ids: z
- .union([z.string(), z.array(z.string())])
- .transform((v) => (Array.isArray(v) ? v : v.split(",")))
- .optional()
- .describe("IDs of customers to filter by."),
- })
- .merge(getPaginationQuerySchema({ pageSize: CUSTOMERS_MAX_PAGE_SIZE }));
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index 21a872851b..a0ba0de657 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -147,7 +147,7 @@ export default function Toggle({
foldersAsync && selectedFilter === "folderId" ? debouncedSearch : "",
},
});
- const { customers, loading: loadingCustomers } = useCustomers({
+ const { customers } = useCustomers({
query: {
search:
customersAsync && selectedFilter === "customerId"
diff --git a/packages/prisma/schema/customer.prisma b/packages/prisma/schema/customer.prisma
index 968ac5cc6d..557abdd72f 100644
--- a/packages/prisma/schema/customer.prisma
+++ b/packages/prisma/schema/customer.prisma
@@ -22,7 +22,7 @@ model Customer {
@@unique([projectId, externalId])
@@unique([projectConnectId, externalId])
+ @@index([projectId, email, externalId, name])
@@index(externalId)
@@index(linkId)
- @@index([projectId, email])
}
diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prisma
index 553119bb49..e4bb92bcc0 100644
--- a/packages/prisma/schema/partner.prisma
+++ b/packages/prisma/schema/partner.prisma
@@ -24,6 +24,7 @@ model Partner {
description String? @db.Text
country String?
status PartnerStatus @default(default)
+ paypalEmail String? @unique
stripeConnectId String? @unique
payoutsEnabledAt DateTime?
connectPayoutsLastRemindedAt DateTime?
diff --git a/packages/prisma/schema/payout.prisma b/packages/prisma/schema/payout.prisma
index c85b7cdb59..ba229249c6 100644
--- a/packages/prisma/schema/payout.prisma
+++ b/packages/prisma/schema/payout.prisma
@@ -19,6 +19,7 @@ model Payout {
periodStart DateTime?
periodEnd DateTime?
quantity Int? // Number of clicks/leads/sales in this payout
+ paypalTransferId String? @unique
stripeTransferId String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt