The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
FEAT: Customers API
Steven Teyb06b9f5a7609
diff --git a/apps/web/app/api/customers/[id]/route.ts b/apps/web/app/api/customers/[id]/route.tsnew file mode 100644index 0000000000..5a3fc12bef--- /dev/null+++ b/apps/web/app/api/customers/[id]/route.ts@@ -0,0 +1,113 @@+import { DubApiError } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { withWorkspace } from "@/lib/auth";+import { prisma } from "@/lib/prisma";+import {+ CustomerSchema,+ updateCustomerBodySchema,+} from "@/lib/zod/schemas/customers";+import { NextResponse } from "next/server";++// GET /api/customers/:id – Get a customer by external ID+export const GET = withWorkspace(async ({ workspace, params }) => {+ const { id: externalId } = params;+ const customer = await prisma.customer.findUnique({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId,+ },+ },+ });+ if (!customer) {+ throw new DubApiError({+ code: "not_found",+ message: "Customer not found",+ });+ }++ return NextResponse.json(+ CustomerSchema.parse({+ ...customer,+ id: customer.externalId,+ }),+ );+});++// PATCH /api/customers/:id – Update a customer by external ID+export const PATCH = withWorkspace(async ({ workspace, params, req }) => {+ const { id: externalId } = params;+ const {+ id: newExternalId,+ name,+ email,+ avatar,+ } = updateCustomerBodySchema.parse(await parseRequestBody(req));++ try {+ const customer = await prisma.customer.update({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId,+ },+ },+ data: { name, email, avatar, externalId: newExternalId },+ });++ return NextResponse.json(+ CustomerSchema.parse({+ ...customer,+ id: customer.externalId,+ }),+ );+ } catch (error) {+ if (error.code === "P2002") {+ throw new DubApiError({+ code: "conflict",+ message: "A customer with this external ID already exists.",+ });+ } else if (error.code === "P2025") {+ throw new DubApiError({+ code: "not_found",+ message: "Customer not found",+ });+ }++ throw new DubApiError({+ code: "unprocessable_entity",+ message: error.message,+ });+ }+});++// DELETE /api/customers/:id – Delete a customer by external ID+export const DELETE = withWorkspace(async ({ workspace, params }) => {+ const { id: externalId } = params;+ try {+ const customer = await prisma.customer.delete({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId,+ },+ },+ });++ return NextResponse.json({+ id: customer.externalId,+ });+ } catch (error) {+ if (error.code === "P2025") {+ throw new DubApiError({+ code: "not_found",+ message: "Customer not found",+ });+ }++ throw new DubApiError({+ code: "unprocessable_entity",+ message: error.message,+ });+ }+});diff --git a/apps/web/app/api/customers/route.ts b/apps/web/app/api/customers/route.tsnew file mode 100644index 0000000000..258e949520--- /dev/null+++ b/apps/web/app/api/customers/route.ts@@ -0,0 +1,54 @@+import { DubApiError } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { withWorkspace } from "@/lib/auth";+import { generateRandomName } from "@/lib/names";+import { prisma } from "@/lib/prisma";+import {+ createCustomerBodySchema,+ CustomerSchema,+} from "@/lib/zod/schemas/customers";+import { NextResponse } from "next/server";++// POST /api/customers – Create a new customer+export const POST = withWorkspace(+ async ({ req, workspace }) => {+ const { id, email, name, avatar } = createCustomerBodySchema.parse(+ await parseRequestBody(req),+ );++ const finalCustomerName = name || email || generateRandomName();++ try {+ const customer = await prisma.customer.create({+ data: {+ name: finalCustomerName,+ email,+ avatar,+ externalId: id,+ projectId: workspace.id,+ projectConnectId: workspace.stripeConnectId,+ },+ });++ return NextResponse.json(+ CustomerSchema.parse({ ...customer, id: customer.externalId }),+ );+ } catch (error) {+ if (error.code === "P2002") {+ throw new DubApiError({+ code: "conflict",+ message: "A customer with this external ID already exists.",+ });+ }++ throw new DubApiError({+ code: "unprocessable_entity",+ message: error.message,+ });+ }+ },+ {+ requiredAddOn: "conversion",+ requiredPermissions: ["conversions.write"],+ },+);diff --git a/apps/web/lib/analytics/get-events.ts b/apps/web/lib/analytics/get-events.tsindex 81e29b633c..d1591cedaf 100644--- a/apps/web/lib/analytics/get-events.ts+++ b/apps/web/lib/analytics/get-events.ts@@ -10,7 +10,7 @@ import {clickEventSchema,clickEventSchemaTBEndpoint,} from "../zod/schemas/clicks";-import { customerSchema } from "../zod/schemas/customers";+import { CustomerSchema } from "../zod/schemas/customers";import {leadEventResponseSchema,leadEventSchemaTBEndpoint,@@ -167,7 +167,7 @@ const getCustomersMap = async (customerIds: string[]) => {return customers.reduce((acc, customer) => {- acc[customer.id] = customerSchema.parse({+ acc[customer.id] = CustomerSchema.parse({id: customer.externalId ?? customer.id,name: customer.name || "",email: customer.email || "",@@ -177,6 +177,6 @@ const getCustomersMap = async (customerIds: string[]) => {});return acc;},- {} as Record<string, z.infer<typeof customerSchema>>,+ {} as Record<string, z.infer<typeof CustomerSchema>>,);};diff --git a/apps/web/lib/openapi/customers/create-customer.ts b/apps/web/lib/openapi/customers/create-customer.tsnew file mode 100644index 0000000000..dd8256ef6a--- /dev/null+++ b/apps/web/lib/openapi/customers/create-customer.ts@@ -0,0 +1,33 @@+import { openApiErrorResponses } from "@/lib/openapi/responses";+import { ZodOpenApiOperationObject } from "zod-openapi";+import {+ createCustomerBodySchema,+ CustomerSchema,+} from "../../zod/schemas/customers";++export const createCustomer: ZodOpenApiOperationObject = {+ operationId: "createCustomer",+ "x-speakeasy-name-override": "create",+ summary: "Create a customer",+ description: "Create a customer for the authenticated workspace.",+ requestBody: {+ content: {+ "application/json": {+ schema: createCustomerBodySchema,+ },+ },+ },+ responses: {+ "201": {+ description: "The customer was created.",+ content: {+ "application/json": {+ schema: CustomerSchema,+ },+ },+ },+ ...openApiErrorResponses,+ },+ tags: ["Customers"],+ security: [{ token: [] }],+};diff --git a/apps/web/lib/openapi/customers/delete-customer.ts b/apps/web/lib/openapi/customers/delete-customer.tsnew file mode 100644index 0000000000..f9a5ebed58--- /dev/null+++ b/apps/web/lib/openapi/customers/delete-customer.ts@@ -0,0 +1,27 @@+import { openApiErrorResponses } from "@/lib/openapi/responses";+import { CustomerSchema } from "@/lib/zod/schemas/customers";+import { ZodOpenApiOperationObject } from "zod-openapi";++export const deleteCustomer: ZodOpenApiOperationObject = {+ operationId: "deleteCustomer",+ "x-speakeasy-name-override": "delete",+ "x-speakeasy-max-method-params": 1,+ summary: "Delete a customer",+ description: "Delete a customer from a workspace.",+ requestParams: {+ path: CustomerSchema.pick({ id: true }),+ },+ responses: {+ "200": {+ description: "The customer was deleted.",+ content: {+ "application/json": {+ schema: CustomerSchema.pick({ id: true }),+ },+ },+ },+ ...openApiErrorResponses,+ },+ tags: ["Customers"],+ security: [{ token: [] }],+};diff --git a/apps/web/lib/openapi/customers/index.ts b/apps/web/lib/openapi/customers/index.tsnew file mode 100644index 0000000000..ac995604e9--- /dev/null+++ b/apps/web/lib/openapi/customers/index.ts@@ -0,0 +1,14 @@+import { ZodOpenApiPathsObject } from "zod-openapi";+import { createCustomer } from "./create-customer";+import { deleteCustomer } from "./delete-customer";+import { updateCustomer } from "./update-customer";++export const customersPaths: ZodOpenApiPathsObject = {+ "/customers": {+ post: createCustomer,+ },+ "/customers/{id}": {+ patch: updateCustomer,+ delete: deleteCustomer,+ },+};diff --git a/apps/web/lib/openapi/customers/update-customer.ts b/apps/web/lib/openapi/customers/update-customer.tsnew file mode 100644index 0000000000..5e02dde2a9--- /dev/null+++ b/apps/web/lib/openapi/customers/update-customer.ts@@ -0,0 +1,37 @@+import { openApiErrorResponses } from "@/lib/openapi/responses";+import {+ CustomerSchema,+ updateCustomerBodySchema,+} from "@/lib/zod/schemas/customers";+import { ZodOpenApiOperationObject } from "zod-openapi";++export const updateCustomer: ZodOpenApiOperationObject = {+ operationId: "updateCustomer",+ "x-speakeasy-name-override": "update",+ "x-speakeasy-max-method-params": 2,+ summary: "Update a customer",+ description: "Update a customer for the authenticated workspace.",+ requestParams: {+ path: CustomerSchema.pick({ id: true }),+ },+ requestBody: {+ content: {+ "application/json": {+ schema: updateCustomerBodySchema,+ },+ },+ },+ responses: {+ "200": {+ description: "The customer was updated.",+ content: {+ "application/json": {+ schema: CustomerSchema,+ },+ },+ },+ ...openApiErrorResponses,+ },+ tags: ["Customers"],+ security: [{ token: [] }],+};diff --git a/apps/web/lib/openapi/track/customer.ts b/apps/web/lib/openapi/track/customer.tsindex 1cd03d3ff4..d0a07699fe 100644--- a/apps/web/lib/openapi/track/customer.ts+++ b/apps/web/lib/openapi/track/customer.ts@@ -30,4 +30,5 @@ export const trackCustomer: ZodOpenApiOperationObject = {},tags: ["Track"],security: [{ token: [] }],+ deprecated: true,};diff --git a/apps/web/lib/webhook/schemas.ts b/apps/web/lib/webhook/schemas.tsindex b28e12c2ab..3caaf72bc5 100644--- a/apps/web/lib/webhook/schemas.ts+++ b/apps/web/lib/webhook/schemas.ts@@ -3,7 +3,7 @@ import { clickEventSchema } from "../zod/schemas/clicks";import { linkEventSchema } from "../zod/schemas/links";import { WEBHOOK_TRIGGERS } from "./constants";-const customerSchema = z.object({+const CustomerSchema = z.object({id: z.string(),name: z.string().nullable(),email: z.string().nullable(),@@ -24,14 +24,14 @@ export const clickWebhookEventSchema = z.object({export const leadWebhookEventSchema = z.object({eventName: z.string(),- customer: customerSchema,+ customer: CustomerSchema,click: clickEventSchema,link: linkEventSchema,});export const saleWebhookEventSchema = z.object({eventName: z.string(),- customer: customerSchema,+ customer: CustomerSchema,click: clickEventSchema,link: linkEventSchema,sale: saleSchema,diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex 793e1a15bd..d1018415f6 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -1,5 +1,37 @@import z from "@/lib/zod";+export const createCustomerBodySchema = z.object({+ id: z+ .string()+ .describe("Unique identifier for the customer in the client's app."),+ email: z+ .string()+ .email()+ .nullish()+ .describe("Email of the customer in the client's app."),+ name: z+ .string()+ .nullish()+ .describe(+ "Name of the customer in the client's app. If not provided, a random name will be generated.",+ ),+ avatar: z+ .string()+ .url()+ .nullish()+ .describe("Avatar of the customer in the client's app."),+});++export const updateCustomerBodySchema = createCustomerBodySchema.partial();++// customer object schema+export const CustomerSchema = z.object({+ id: z.string(),+ name: z.string(),+ email: z.string().nullish(),+ avatar: z.string().nullish(),+});+export const trackCustomerRequestSchema = z.object({// RequiredcustomerId: z@@ -36,11 +68,3 @@ export const trackCustomerResponseSchema = z.object({customerEmail: z.string().nullable(),customerAvatar: z.string().nullable(),});--// simple schema returned by /events API-export const customerSchema = z.object({- id: z.string(),- name: z.string(),- email: z.string(),- avatar: z.string(),-});diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.tsindex 2efb042f92..be6f607324 100644--- a/apps/web/lib/zod/schemas/leads.ts+++ b/apps/web/lib/zod/schemas/leads.ts@@ -1,6 +1,6 @@import z from "@/lib/zod";import { clickEventSchema, clickEventSchemaTB } from "./clicks";-import { customerSchema } from "./customers";+import { CustomerSchema } from "./customers";import { commonDeprecatedEventFields } from "./deprecated";import { linkEventSchema } from "./links";@@ -112,7 +112,7 @@ export const leadEventResponseSchema = z// nested objectsclick: clickEventSchema,link: linkEventSchema,- customer: customerSchema,+ customer: CustomerSchema,}).merge(commonDeprecatedEventFields).openapi({ ref: "LeadEvent" });diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.tsindex 6da0fd32a0..11abaa55f2 100644--- a/apps/web/lib/zod/schemas/sales.ts+++ b/apps/web/lib/zod/schemas/sales.ts@@ -1,6 +1,6 @@import z from "@/lib/zod";import { clickEventSchema, clickEventSchemaTB } from "./clicks";-import { customerSchema } from "./customers";+import { CustomerSchema } from "./customers";import { commonDeprecatedEventFields } from "./deprecated";import { linkEventSchema } from "./links";@@ -118,7 +118,7 @@ export const saleEventResponseSchema = z// nested objectslink: linkEventSchema,click: clickEventSchema,- customer: customerSchema,+ customer: CustomerSchema,sale: trackSaleRequestSchema.pick({amount: true,invoiceId: true,