The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improve the order processing
Kiran K2513e46a9fdf
diff --git a/apps/web/app/api/cron/shopify/order-paid/route.ts b/apps/web/app/api/cron/shopify/order-paid/route.tsindex 0be70737f8..8e96582a3b 100644--- a/apps/web/app/api/cron/shopify/order-paid/route.ts+++ b/apps/web/app/api/cron/shopify/order-paid/route.ts@@ -1,21 +1,8 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";-import { createSaleData } from "@/lib/api/sales/create-sale-data";-import { createId } from "@/lib/api/utils";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";-import { generateRandomName } from "@/lib/names";-import {- getClickEvent,- getLeadEvent,- recordLead,- recordSale,-} from "@/lib/tinybird";+import { processOrder } from "@/lib/integrations/shopify/process-order";import { redis } from "@/lib/upstash";-import z from "@/lib/zod";-import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";-import { prisma } from "@dub/prisma";-import { nanoid } from "@dub/utils";-import { Customer } from "@prisma/client";+import { z } from "zod";export const dynamic = "force-dynamic";@@ -24,15 +11,6 @@ const schema = z.object({checkoutToken: z.string(),});-const orderSchema = z.object({- total_price: z.string(),- currency: z.string(),- confirmation_number: z.string(),- customer: z.object({- id: z.number(),- }),-});-// POST /api/cron/shopify/order-paidexport async function POST(req: Request) {try {@@ -42,64 +20,37 @@ export async function POST(req: Request) {const { workspaceId, checkoutToken } = schema.parse(body);// Find Shopify order- const order = await redis.hget(+ const event = await redis.hget(`shopify:checkout:${checkoutToken}`,"order",);- if (!order) {- return new Response(`[Shopify] Shopify order not found. Skipping...`);- }-- const orderData = orderSchema.parse(order);- const externalId = orderData.customer.id.toString();-- // Fetch customer- const customer: Customer | null = await prisma.customer.findUnique({- where: {- projectId_externalId: {- projectId: workspaceId,- externalId,- },- },- });-- if (customer) {- // Existing customer- await createSale({- order,- workspaceId,- customerId: customer.id,- });- } else {- const clickId = await redis.hget<string>(- `shopify:checkout:${checkoutToken}`,- "clickId",+ if (!event) {+ return new Response(+ `[Shopify] Order with checkout token ${checkoutToken} not found. Skipping...`,);+ }- if (!clickId) {- // Wait for the click event to come from Shopify pixel- throw new DubApiError({- code: "bad_request",- message:- "[Shopify] Click event not found. Waiting for Shopify pixel event...",- });- }-- const leadData = await createLead({- clickId,- externalId,- workspaceId,- });+ const clickId = await redis.hget<string>(+ `shopify:checkout:${checkoutToken}`,+ "clickId",+ );- await createSale({- order,- workspaceId,- leadData,- customerId: leadData.customer_id,+ // Wait for the click event to come from Shopify pixel+ if (!clickId) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "[Shopify] Click event not found. Waiting for Shopify pixel event...",});}+ await processOrder({+ event,+ workspaceId,+ clickId,+ });+await redis.del(`shopify:checkout:${checkoutToken}`);return new Response("[Shopify] Order event processed successfully.");@@ -107,220 +58,3 @@ export async function POST(req: Request) {return handleAndReturnErrorResponse(error);}}--const createLead = async ({- clickId,- externalId,- workspaceId,-}: {- clickId: string;- externalId: string;- workspaceId: string;-}) => {- // find click- const clickEvent = await getClickEvent({ clickId });-- const clickData = clickEvent.data[0];- const { link_id: linkId, country, timestamp } = clickData;-- // create customer- const customer = await prisma.customer.create({- data: {- id: createId({ prefix: "cus_" }),- name: generateRandomName(),- externalId,- projectId: workspaceId,- clickedAt: new Date(timestamp + "Z"),- clickId,- linkId,- country,- },- });-- const leadData = leadEventSchemaTB.parse({- ...clickData,- event_id: nanoid(16),- event_name: "Account created",- customer_id: customer.id,- });-- await Promise.all([- // record lead- recordLead(leadData),-- // update link leads count- prisma.link.update({- where: {- id: linkId,- },- data: {- leads: {- increment: 1,- },- },- }),-- // update workspace usage- prisma.project.update({- where: {- id: workspaceId,- },- data: {- usage: {- increment: 1,- },- },- }),- ]);-- return leadData;-};--const createSale = async ({- order,- customerId,- workspaceId,- leadData,-}: {- order: any;- customerId: string;- workspaceId: string;- leadData?: z.infer<typeof leadEventSchemaTB>;-}) => {- if (!leadData) {- const leadEvent = await getLeadEvent({ customerId });-- if (!leadEvent || leadEvent.data.length === 0) {- return new Response(- `[Shopify] Lead event with customer ID ${customerId} not found, skipping...`,- );- }-- leadData = leadEvent.data[0];- }-- const { link_id: linkId, click_id: clickId } = leadData;-- const orderData = orderSchema.parse(order);- const eventId = nanoid(16);- const paymentProcessor = "shopify";-- const amount = Number(orderData.total_price) * 100;- const currency = orderData.currency;- const invoiceId = orderData.confirmation_number;-- const sale = await prisma.sale.findFirst({- where: {- invoiceId,- clickId,- },- });-- if (sale) {- return new Response(- `[Shopify] Order has been processed already. Skipping...`,- );- }-- const saleData = {- ...leadData,- event_id: eventId,- event_name: "Purchase",- payment_processor: paymentProcessor,- amount,- currency,- invoice_id: invoiceId,- metadata: JSON.stringify(order),- };-- const [_sale, link, _project] = await Promise.all([- // record sale- recordSale(saleData),-- // update link sales count- prisma.link.update({- where: {- id: linkId,- },- data: {- sales: {- increment: 1,- },- saleAmount: {- increment: amount,- },- },- }),-- // update workspace sales usage- prisma.project.update({- where: {- id: workspaceId,- },- data: {- usage: {- increment: 1,- },- salesUsage: {- increment: amount,- },- },- }),- ]);-- // for program links- if (link.programId) {- const { program, partnerId, commissionAmount } =- await prisma.programEnrollment.findUniqueOrThrow({- where: {- linkId,- },- select: {- program: true,- partnerId: true,- commissionAmount: true,- },- });-- const saleRecord = createSaleData({- program,- partner: {- id: partnerId,- commissionAmount,- },- customer: {- id: customerId,- linkId,- clickId,- },- sale: {- amount,- currency,- invoiceId,- eventId,- paymentProcessor,- },- metadata: {- ...order,- },- });-- await Promise.allSettled([- prisma.sale.create({- data: saleRecord,- }),-- notifyPartnerSale({- partner: {- id: partnerId,- referralLink: link.shortLink,- },- program,- sale: {- amount: saleRecord.amount,- earnings: saleRecord.earnings,- },- }),- ]);- }-};diff --git a/apps/web/app/api/shopify/integration/webhook/customers-data-request.ts b/apps/web/app/api/shopify/integration/webhook/customers-data-request.tsindex 0fb2e84e4f..1cc1c20f9d 100644--- a/apps/web/app/api/shopify/integration/webhook/customers-data-request.ts+++ b/apps/web/app/api/shopify/integration/webhook/customers-data-request.ts@@ -12,12 +12,12 @@ const schema = z.object({}),});-export async function customersDataRequest({ body }: { body: any }) {+export async function customersDataRequest({ event }: { event: any }) {const {customer,shop_domain: shopDomain,orders_requested: ordersRequested,- } = schema.parse(body);+ } = schema.parse(event);waitUntil(sendEmail({diff --git a/apps/web/app/api/shopify/integration/webhook/customers-redact.ts b/apps/web/app/api/shopify/integration/webhook/customers-redact.tsindex 511766e725..c12ff0c7f9 100644--- a/apps/web/app/api/shopify/integration/webhook/customers-redact.ts+++ b/apps/web/app/api/shopify/integration/webhook/customers-redact.ts@@ -12,12 +12,12 @@ const schema = z.object({}),});-export async function customersRedact({ body }: { body: any }) {+export async function customersRedact({ event }: { event: any }) {const {customer,shop_domain: shopDomain,orders_to_redact: ordersToRedact,- } = schema.parse(body);+ } = schema.parse(event);waitUntil(sendEmail({diff --git a/apps/web/app/api/shopify/integration/webhook/order-paid.ts b/apps/web/app/api/shopify/integration/webhook/order-paid.tsindex 9c94a00394..83b5906668 100644--- a/apps/web/app/api/shopify/integration/webhook/order-paid.ts+++ b/apps/web/app/api/shopify/integration/webhook/order-paid.ts@@ -1,23 +1,45 @@import { qstash } from "@/lib/cron";+import { processOrder } from "@/lib/integrations/shopify/process-order";+import { orderSchema } from "@/lib/integrations/shopify/schema";import { redis } from "@/lib/upstash";+import { prisma } from "@dub/prisma";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";-import { z } from "zod";--const schema = z.object({- checkout_token: z.string(),-});export async function orderPaid({- body,+ event,workspaceId,}: {- body: any;+ event: any;workspaceId: string;}) {- const { checkout_token: checkoutToken } = schema.parse(body);+ const {+ customer: { id: externalId },+ checkout_token: checkoutToken,+ } = orderSchema.parse(event);++ const customer = await prisma.customer.findUnique({+ where: {+ projectId_externalId: {+ projectId: workspaceId,+ externalId: externalId.toString(),+ },+ },+ });++ // customer is found, process the order right away+ if (customer) {+ await processOrder({+ event,+ workspaceId,+ customerId: customer.id,+ });++ return;+ }+ // if no customer is found, wait for the Pixel event to come in so that we can decide if the order is from a Dub link or notawait redis.hset(`shopify:checkout:${checkoutToken}`, {- order: body,+ order: event,});await qstash.publishJSON({@@ -26,7 +48,7 @@ export async function orderPaid({checkoutToken,workspaceId,},- retries: 3,+ retries: 5,delay: 3,});}diff --git a/apps/web/app/api/shopify/integration/webhook/route.ts b/apps/web/app/api/shopify/integration/webhook/route.tsindex a230d9c2d4..d9918331af 100644--- a/apps/web/app/api/shopify/integration/webhook/route.ts+++ b/apps/web/app/api/shopify/integration/webhook/route.ts@@ -42,7 +42,7 @@ export const POST = async (req: Request) => {return new Response(`[Shopify] Unsupported topic: ${topic}. Skipping...`);}- const body = JSON.parse(data);+ const event = JSON.parse(data);const shopDomain = headers.get("x-shopify-shop-domain") || "";// Find workspace@@ -65,23 +65,23 @@ export const POST = async (req: Request) => {switch (topic) {case "orders/paid":await orderPaid({- body,+ event,workspaceId: workspace.id,});break;case "customers/data_request":await customersDataRequest({- body,+ event,});break;case "customers/redact":await customersRedact({- body,+ event,});break;case "shop/redact":await shopRedact({- body,+ event,});break;case "app/uninstalled":diff --git a/apps/web/app/api/shopify/integration/webhook/shop-redact.ts b/apps/web/app/api/shopify/integration/webhook/shop-redact.tsindex d4fb50b131..26fb13141a 100644--- a/apps/web/app/api/shopify/integration/webhook/shop-redact.ts+++ b/apps/web/app/api/shopify/integration/webhook/shop-redact.ts@@ -6,8 +6,8 @@ const schema = z.object({shop_domain: z.string(),});-export async function shopRedact({ body }: { body: any }) {- const { shop_domain: shopDomain } = schema.parse(body);+export async function shopRedact({ event }: { event: any }) {+ const { shop_domain: shopDomain } = schema.parse(event);waitUntil(sendEmail({diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.tsnew file mode 100644index 0000000000..9ff0cd0a03--- /dev/null+++ b/apps/web/lib/integrations/shopify/process-order.ts@@ -0,0 +1,286 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";+import { createSaleData } from "@/lib/api/sales/create-sale-data";+import { createId } from "@/lib/api/utils";+import { generateRandomName } from "@/lib/names";+import {+ getClickEvent,+ getLeadEvent,+ recordLead,+ recordSale,+} from "@/lib/tinybird";+import z from "@/lib/zod";+import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";+import { prisma } from "@dub/prisma";+import { nanoid } from "@dub/utils";+import { orderSchema } from "./schema";++async function createLead({+ clickId,+ externalId,+ workspaceId,+}: {+ clickId: string;+ externalId: string;+ workspaceId: string;+}) {+ // find click+ const clickEvent = await getClickEvent({ clickId });++ const clickData = clickEvent.data[0];+ const { link_id: linkId, country, timestamp } = clickData;++ // create customer+ const customer = await prisma.customer.create({+ data: {+ id: createId({ prefix: "cus_" }),+ name: generateRandomName(),+ externalId,+ projectId: workspaceId,+ clickedAt: new Date(timestamp + "Z"),+ clickId,+ linkId,+ country,+ },+ });++ const leadData = leadEventSchemaTB.parse({+ ...clickData,+ event_id: nanoid(16),+ event_name: "Account created",+ customer_id: customer.id,+ });++ await Promise.all([+ // record lead+ recordLead(leadData),++ // update link leads count+ prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ leads: {+ increment: 1,+ },+ },+ }),++ // update workspace usage+ prisma.project.update({+ where: {+ id: workspaceId,+ },+ data: {+ usage: {+ increment: 1,+ },+ },+ }),+ ]);++ return leadData;+}++async function createSale({+ order,+ customerId,+ workspaceId,+ leadData,+}: {+ order: any;+ customerId: string;+ workspaceId: string;+ leadData: z.infer<typeof leadEventSchemaTB>;+}) {+ const orderData = orderSchema.parse(order);+ const eventId = nanoid(16);+ const paymentProcessor = "shopify";++ const amount = Number(orderData.total_price) * 100;+ const currency = orderData.currency;+ const invoiceId = orderData.confirmation_number;++ const { link_id: linkId, click_id: clickId } = leadData;++ const sale = await prisma.sale.findFirst({+ where: {+ invoiceId,+ clickId,+ },+ });++ if (sale) {+ return new Response(+ `[Shopify] Order has been processed already. Skipping...`,+ );+ }++ const saleData = {+ ...leadData,+ event_id: eventId,+ event_name: "Purchase",+ payment_processor: paymentProcessor,+ amount,+ currency,+ invoice_id: invoiceId,+ metadata: JSON.stringify(order),+ };++ const [_sale, link, _project] = await Promise.all([+ // record sale+ recordSale(saleData),++ // update link sales count+ prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ sales: {+ increment: 1,+ },+ saleAmount: {+ increment: amount,+ },+ },+ }),++ // update workspace sales usage+ prisma.project.update({+ where: {+ id: workspaceId,+ },+ data: {+ usage: {+ increment: 1,+ },+ salesUsage: {+ increment: amount,+ },+ },+ }),+ ]);++ // for program links+ if (link.programId) {+ const { program, partnerId, commissionAmount } =+ await prisma.programEnrollment.findUniqueOrThrow({+ where: {+ linkId,+ },+ select: {+ program: true,+ partnerId: true,+ commissionAmount: true,+ },+ });++ const saleRecord = createSaleData({+ program,+ partner: {+ id: partnerId,+ commissionAmount,+ },+ customer: {+ id: customerId,+ linkId,+ clickId,+ },+ sale: {+ amount,+ currency,+ invoiceId,+ eventId,+ paymentProcessor,+ },+ metadata: {+ ...order,+ },+ });++ await Promise.allSettled([+ prisma.sale.create({+ data: saleRecord,+ }),++ notifyPartnerSale({+ partner: {+ id: partnerId,+ referralLink: link.shortLink,+ },+ program,+ sale: {+ amount: saleRecord.amount,+ earnings: saleRecord.earnings,+ },+ }),+ ]);+ }+}++// Process the order from Shopify webhook+export async function processOrder({+ event,+ workspaceId,+ customerId,+ clickId,+}: {+ event: unknown;+ workspaceId: string;+ customerId?: string; // ID of the customer in Dub+ clickId?: string; // ID of the click event from Shopify pixel+}) {+ try {+ const order = orderSchema.parse(event);++ // for existing customer+ if (customerId) {+ const leadEvent = await getLeadEvent({ customerId });++ if (!leadEvent || leadEvent.data.length === 0) {+ return new Response(+ `[Shopify] Lead event with customer ID ${customerId} not found, skipping...`,+ );+ }++ const leadData = leadEvent.data[0];++ await createSale({+ leadData,+ order,+ workspaceId,+ customerId,+ });++ return;+ }++ // for new customer+ if (clickId) {+ const {+ customer: { id: externalId },+ } = orderSchema.parse(event);++ const leadData = await createLead({+ clickId,+ workspaceId,+ externalId: externalId.toString(),+ });++ const { customer_id: customerId } = leadData;++ await createSale({+ leadData,+ order,+ workspaceId,+ customerId,+ });+ }++ return new Response("[Shopify] Order event processed successfully.");+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/lib/integrations/shopify/schema.ts b/apps/web/lib/integrations/shopify/schema.tsnew file mode 100644index 0000000000..ced02b6b87--- /dev/null+++ b/apps/web/lib/integrations/shopify/schema.ts@@ -0,0 +1,11 @@+import { z } from "zod";++export const orderSchema = z.object({+ total_price: z.string(),+ currency: z.string(),+ confirmation_number: z.string(),+ checkout_token: z.string(),+ customer: z.object({+ id: z.number(),+ }),+});