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 shopify implementation

Steven Tey30dc0543110e
diff --git a/apps/web/lib/integrations/shopify/create-lead.ts b/apps/web/lib/integrations/shopify/create-lead.ts
new file mode 100644
index 0000000000..5a415c3a3b
--- /dev/null
+++ b/apps/web/lib/integrations/shopify/create-lead.ts
@@ -0,0 +1,81 @@
+import { createId } from "@/lib/api/utils";
+import { generateRandomName } from "@/lib/names";
+import { getClickEvent, recordLead } from "@/lib/tinybird";
+import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
+import { prisma } from "@dub/prisma";
+import { nanoid } from "@dub/utils";
+import { orderSchema } from "./schema";
+
+export async function createShopifyLead({
+ clickId,
+ workspaceId,
+ event,
+}: {
+ clickId: string;
+ workspaceId: string;
+ event: any;
+}) {
+ const {
+ customer: { id: externalId, email, first_name, last_name },
+ } = orderSchema.parse(event);
+
+ // 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_" }),
+ // need to convert to string because Shopify customer ID is a number
+ externalId: externalId.toString(),
+ name: `${first_name} ${last_name}`.trim() || generateRandomName(),
+ email: email || null,
+ 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;
+}
diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.ts
new file mode 100644
index 0000000000..958d534452
--- /dev/null
+++ b/apps/web/lib/integrations/shopify/create-sale.ts
@@ -0,0 +1,149 @@
+import { notifyPartnerSale } from "@/lib/api/partners/notify-partner-sale";
+import { createSaleData } from "@/lib/api/sales/create-sale-data";
+import { recordSale } from "@/lib/tinybird";
+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 { orderSchema } from "./schema";
+
+export async function createShopifySale({
+ 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.current_subtotal_price) * 100;
+ const currency = orderData.currency;
+ const invoiceId = orderData.confirmation_number;
+ const checkoutToken = orderData.checkout_token;
+
+ 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,
+ },
+ },
+ }),
+
+ redis.del(`shopify:checkout:${checkoutToken}`),
+ ]);
+
+ // 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/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.ts
index 244a18e6fe..92f04d980d 100644
--- a/apps/web/lib/integrations/shopify/process-order.ts
+++ b/apps/web/lib/integrations/shopify/process-order.ts
@@ -1,229 +1,9 @@
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 { 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 { getLeadEvent } from "@/lib/tinybird";
+import { createShopifyLead } from "./create-lead";
+import { createShopifySale } from "./create-sale";
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.current_subtotal_price) * 100;
- const currency = orderData.currency;
- const invoiceId = orderData.confirmation_number;
- const checkoutToken = orderData.checkout_token;
-
- 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,
- },
- },
- }),
-
- redis.del(`shopify:checkout:${checkoutToken}`),
- ]);
-
- // 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,
@@ -251,7 +31,7 @@ export async function processOrder({
const leadData = leadEvent.data[0];
- await createSale({
+ await createShopifySale({
leadData,
order,
workspaceId,
@@ -263,19 +43,15 @@ export async function processOrder({
// for new customer
if (clickId) {
- const {
- customer: { id: externalId },
- } = orderSchema.parse(event);
-
- const leadData = await createLead({
+ const leadData = await createShopifyLead({
clickId,
workspaceId,
- externalId: externalId.toString(),
+ event,
});
const { customer_id: customerId } = leadData;
- await createSale({
+ await createShopifySale({
leadData,
order,
workspaceId,
diff --git a/apps/web/lib/integrations/shopify/schema.ts b/apps/web/lib/integrations/shopify/schema.ts
index 2db2e3918b..6b4ae4220c 100644
--- a/apps/web/lib/integrations/shopify/schema.ts
+++ b/apps/web/lib/integrations/shopify/schema.ts
@@ -7,5 +7,8 @@ export const orderSchema = z.object({
checkout_token: z.string(),
customer: z.object({
id: z.number(),
+ email: z.string().nullish(),
+ first_name: z.string().nullish(),
+ last_name: z.string().nullish(),
}),
});