The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
return discount for each customer
Kiran K31151b38a0e3
diff --git a/apps/web/app/api/customers/[id]/route.ts b/apps/web/app/api/customers/[id]/route.tsindex dc8a194f17..28694767f6 100644--- a/apps/web/app/api/customers/[id]/route.ts+++ b/apps/web/app/api/customers/[id]/route.ts@@ -1,3 +1,4 @@+import { determineCustomerDiscount } from "@/lib/api/customers/determine-customer-discount";import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";import { transformCustomer } from "@/lib/api/customers/transform-customer";import { DubApiError } from "@/lib/api/errors";@@ -9,6 +10,7 @@ import {updateCustomerBodySchema,} from "@/lib/zod/schemas/customers";import { prisma } from "@dub/prisma";+import { Discount } from "@prisma/client";import { NextResponse } from "next/server";// GET /api/customers/:id – Get a customer by ID@@ -23,10 +25,41 @@ export const GET = withWorkspace(id,workspaceId: workspace.id,},- { includeExpandedFields },+ {+ includeExpandedFields,+ },);- return NextResponse.json(CustomerSchema.parse(transformCustomer(customer)));+ let discount: Discount | null = null;++ if (includeExpandedFields) {+ const firstPurchase = await prisma.commission.findFirst({+ where: {+ customerId: customer.id,+ type: "sale",+ },+ orderBy: {+ createdAt: "asc",+ },+ select: {+ createdAt: true,+ },+ });++ discount = determineCustomerDiscount({+ customerLink: customer.link,+ firstPurchase,+ });+ }++ return NextResponse.json(+ CustomerSchema.parse(+ transformCustomer({+ ...customer,+ ...(includeExpandedFields ? { discount } : {}),+ }),+ ),+ );},{requiredPlan: [@@ -50,37 +83,59 @@ export const PATCH = withWorkspace(await parseRequestBody(req),);- const customer = await getCustomerOrThrow({- id,- workspaceId: workspace.id,- });+ const customer = await getCustomerOrThrow(+ {+ id,+ workspaceId: workspace.id,+ },+ {+ includeExpandedFields,+ },+ );try {const updatedCustomer = await prisma.customer.update({where: {id: customer.id,},- data: { name, email, avatar, externalId },- ...(includeExpandedFields- ? {- include: {- link: {- include: {- programEnrollment: {- include: {- partner: true,- discount: true,- },- },- },- },- },- }- : {}),+ data: {+ name,+ email,+ avatar,+ externalId,+ },});+ let discount: Discount | null = null;++ if (includeExpandedFields) {+ const firstPurchase = await prisma.commission.findFirst({+ where: {+ customerId: customer.id,+ type: "sale",+ },+ orderBy: {+ createdAt: "asc",+ },+ select: {+ createdAt: true,+ },+ });++ discount = determineCustomerDiscount({+ customerLink: customer.link,+ firstPurchase,+ });+ }+return NextResponse.json(- CustomerSchema.parse(transformCustomer(updatedCustomer)),+ CustomerSchema.parse(+ transformCustomer({+ ...customer,+ ...updatedCustomer,+ ...(includeExpandedFields ? { discount } : {}),+ }),+ ),);} catch (error) {if (error.code === "P2002") {diff --git a/apps/web/app/api/customers/route.ts b/apps/web/app/api/customers/route.tsindex 4ad784f899..940845b76a 100644--- a/apps/web/app/api/customers/route.ts+++ b/apps/web/app/api/customers/route.ts@@ -71,26 +71,44 @@ export const GET = withWorkspace(: {}),})) as CustomerResponse[];- const firstPurchaseMap = new Map();+ const discounts: Map<string, Discount | null> = new Map();- const firstPurchases = await prisma.commission.findMany({- where: {- customerId: {- in: customers.map((customer) => customer.id),+ if (includeExpandedFields) {+ const firstPurchases = await prisma.commission.findMany({+ where: {+ customerId: {+ in: customers.map((customer) => customer.id),+ },+ type: "sale",},- type: "sale",- },- orderBy: {- createdAt: "asc",- },- distinct: ["customerId"],- });+ select: {+ customerId: true,+ createdAt: true,+ },+ orderBy: {+ createdAt: "asc",+ },+ distinct: ["customerId"],+ });- firstPurchases.forEach((purchase) => {- if (!firstPurchaseMap.has(purchase.customerId)) {- firstPurchaseMap.set(purchase.customerId, purchase);- }- });+ const firstPurchaseMap = new Map();++ firstPurchases.forEach((purchase) => {+ if (!firstPurchaseMap.has(purchase.customerId)) {+ firstPurchaseMap.set(purchase.customerId, purchase);+ }+ });++ customers.forEach((customer) => {+ discounts.set(+ customer.id,+ determineCustomerDiscount({+ customerLink: customer.link,+ firstPurchase: firstPurchaseMap.get(customer.id),+ }),+ );+ });+ }// TODO:// Test customers with no first purchase@@ -98,10 +116,7 @@ export const GET = withWorkspace(const processedCustomers = customers.map((customer) => {return {...customer,- discount: determineCustomerDiscount(- customer,- firstPurchaseMap.get(customer.id),- ),+ discount: discounts.get(customer.id),};});diff --git a/apps/web/lib/api/customers/determine-customer-discount.ts b/apps/web/lib/api/customers/determine-customer-discount.tsindex 4dcfc26930..47191fe0b3 100644--- a/apps/web/lib/api/customers/determine-customer-discount.ts+++ b/apps/web/lib/api/customers/determine-customer-discount.ts@@ -2,24 +2,27 @@ import { Commission, Discount } from "@prisma/client";import { differenceInMonths } from "date-fns";type CustomerWithLink = {- link: {- programEnrollment: {- program: {- defaultDiscount: Discount;+ link?: {+ programEnrollment?: {+ discount?: Discount | null;+ program?: {+ defaultDiscount?: Discount;};- discount: Discount | null;- };- };+ } | null;+ } | null;};-export const determineCustomerDiscount = (- customer: CustomerWithLink,- firstPurchase: Pick<Commission, "createdAt"> | null,-) => {+export const determineCustomerDiscount = ({+ customerLink,+ firstPurchase,+}: {+ customerLink: CustomerWithLink["link"];+ firstPurchase: Pick<Commission, "createdAt"> | null;+}) => {// Use the partner discount or fallback to the program discountconst discount =- customer.link?.programEnrollment?.discount ||- customer.link?.programEnrollment?.program.defaultDiscount ||+ customerLink?.programEnrollment?.discount ||+ customerLink?.programEnrollment?.program?.defaultDiscount ||null;if (!discount) {diff --git a/apps/web/lib/api/customers/get-customer-or-throw.ts b/apps/web/lib/api/customers/get-customer-or-throw.tsindex 3fa9f2ac18..1e34cac2d7 100644--- a/apps/web/lib/api/customers/get-customer-or-throw.ts+++ b/apps/web/lib/api/customers/get-customer-or-throw.ts@@ -34,6 +34,11 @@ export const getCustomerOrThrow = async (include: {programEnrollment: {include: {+ program: {+ include: {+ defaultDiscount: true,+ },+ },partner: true,discount: true,},diff --git a/apps/web/lib/api/customers/transform-customer.ts b/apps/web/lib/api/customers/transform-customer.tsindex 7f8fbac035..15f4705f47 100644--- a/apps/web/lib/api/customers/transform-customer.ts+++ b/apps/web/lib/api/customers/transform-customer.ts@@ -14,10 +14,14 @@ export interface CustomerWithLink extends Customer {| (ProgramEnrollment & {partner: Partner;discount: Discount | null;+ program: {+ defaultDiscount: Discount;+ };})| null;})| null;+ discount?: Discount | null;}export const transformCustomer = (customer: CustomerWithLink) => {