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.

Add getLeadEvent helper + cache lead event in createNewCustomer (Stripe)

Steven Teyfc9d6ff7d99a
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
index 2a9b17e824..ad27d8625a 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
@@ -269,14 +269,15 @@ export async function checkoutSessionCompleted(
// if leadEvent is not defined yet, we need to pull it from Tinybird
if (!leadEvent) {
- leadEvent = await getLeadEvent({ customerId: customer.id }).then(
- (res) => res.data[0],
- );
- if (!leadEvent) {
+ const leadEventData = await getLeadEvent({ customerId: customer.id });
+ if (!leadEventData) {
return `No lead event found for customer ${customer.id}, skipping...`;
}
-
- linkId = leadEvent.link_id as string;
+ leadEvent = {
+ ...leadEventData,
+ workspace_id: leadEventData.workspace_id || customer.projectId, // in case for some reason the lead event doesn't have workspace_id
+ };
+ linkId = leadEvent.link_id;
}
} else {
return "No stripeCustomerId or dubCustomerExternalId found in Stripe checkout session metadata, skipping...";
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
index 2de879db5f..600a2e1076 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
@@ -118,7 +118,7 @@ export async function invoicePaid(event: Stripe.Event, mode: StripeMode) {
// Find lead
const leadEvent = await getLeadEvent({ customerId: customer.id });
- if (!leadEvent || leadEvent.data.length === 0) {
+ if (!leadEvent) {
return `Lead event with customer ID ${customer.id} not found, skipping...`;
}
@@ -130,8 +130,8 @@ export async function invoicePaid(event: Stripe.Event, mode: StripeMode) {
);
const saleData = {
- ...leadEvent.data[0],
- workspace_id: leadEvent.data[0].workspace_id || customer.projectId, // in case for some reason the lead event doesn't have workspace_id
+ ...leadEvent,
+ workspace_id: leadEvent.workspace_id || customer.projectId, // in case for some reason the lead event doesn't have workspace_id
event_id: eventId,
event_name: isOneTimePayment ? "Purchase" : "Invoice paid",
payment_processor: "stripe",
@@ -143,7 +143,7 @@ export async function invoicePaid(event: Stripe.Event, mode: StripeMode) {
}),
};
- const linkId = leadEvent.data[0].link_id;
+ const linkId = leadEvent.link_id;
const link = await prisma.link.findUnique({
where: {
id: linkId,
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
index 0a6e35d9d4..ff244a534b 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
@@ -4,6 +4,7 @@ import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-sta
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { generateRandomName } from "@/lib/names";
import { getClickEvent, recordLead } from "@/lib/tinybird";
+import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
import { prisma } from "@dub/prisma";
@@ -71,10 +72,15 @@ export async function createNewCustomer(event: Stripe.Event) {
customer_id: customer.id,
};
- const [_lead, linkUpdated, workspace] = await Promise.all([
- // Record lead
+ const [_lead, _leadCached, linkUpdated, workspace] = await Promise.all([
+ // record lead event in Tinybird
recordLead(leadData),
+ // cache lead event in Redis because the ingested event is not available immediately on Tinybird
+ redis.set(`leadCache:${customer.id}`, leadData, {
+ ex: 60 * 5,
+ }),
+
// update link leads count + lastLeadAt date
prisma.link.update({
where: {
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
index caa5c4bc81..c7264a344c 100644
--- a/apps/web/lib/api/conversions/track-sale.ts
+++ b/apps/web/lib/api/conversions/track-sale.ts
@@ -92,43 +92,28 @@ export const trackSale = async ({
eventName: leadEventName,
});
- if (!leadEvent || leadEvent.data.length === 0) {
- // Check cache to see if the lead event exists
- // if leadEventName is provided, we only check for that specific event
- // otherwise, we check for all cached lead events for that customer
+ if (!leadEvent) {
+ const errorMessage = `Lead event not found for externalId: ${customerExternalId} and leadEventName: ${leadEventName}`;
- const cachedLeadEvent = await redis.get<LeadEventTB>(
- `leadCache:${existingCustomer.id}${leadEventName ? `:${leadEventName.toLowerCase().replaceAll(" ", "-")}` : ""}`,
+ waitUntil(
+ logConversionEvent({
+ workspace_id: workspace.id,
+ path: "/track/sale",
+ body: JSON.stringify(rawBody),
+ error: errorMessage,
+ }),
);
- if (!cachedLeadEvent) {
- const errorMessage = `Lead event not found for externalId: ${customerExternalId} and leadEventName: ${leadEventName}`;
-
- waitUntil(
- logConversionEvent({
- workspace_id: workspace.id,
- path: "/track/sale",
- body: JSON.stringify(rawBody),
- error: errorMessage,
- }),
- );
-
- throw new DubApiError({
- code: "not_found",
- message: errorMessage,
- });
- }
-
- leadEventData = {
- ...cachedLeadEvent,
- workspace_id: cachedLeadEvent.workspace_id || workspace.id, // in case for some reason the lead event doesn't have workspace_id
- };
- } else {
- leadEventData = {
- ...leadEvent.data[0],
- workspace_id: leadEvent.data[0].workspace_id || workspace.id, // in case for some reason the lead event doesn't have workspace_id
- };
+ throw new DubApiError({
+ code: "not_found",
+ message: errorMessage,
+ });
}
+
+ leadEventData = {
+ ...leadEvent,
+ workspace_id: leadEvent.workspace_id || workspace.id, // in case for some reason the lead event doesn't have workspace_id
+ };
}
// If no existing customer is found and no clickId is provided, return an error
diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.ts
index a840173902..c75fdf3d24 100644
--- a/apps/web/lib/integrations/shopify/process-order.ts
+++ b/apps/web/lib/integrations/shopify/process-order.ts
@@ -20,16 +20,14 @@ export async function processOrder({
if (customerId) {
const leadEvent = await getLeadEvent({ customerId });
- if (!leadEvent || leadEvent.data.length === 0) {
+ if (!leadEvent) {
return new Response(
`[Shopify] Lead event with customer ID ${customerId} not found, skipping...`,
);
}
- const leadData = leadEvent.data[0];
-
await createShopifySale({
- leadData,
+ leadData: leadEvent,
event,
workspaceId,
customerId,
diff --git a/apps/web/lib/tinybird/get-lead-event.ts b/apps/web/lib/tinybird/get-lead-event.ts
index 4dc0ae7f17..e9d57b5978 100644
--- a/apps/web/lib/tinybird/get-lead-event.ts
+++ b/apps/web/lib/tinybird/get-lead-event.ts
@@ -1,8 +1,10 @@
import * as z from "zod/v4";
+import { LeadEventTB } from "../types";
+import { redis } from "../upstash";
import { leadEventSchemaTB } from "../zod/schemas/leads";
import { tb } from "./client";
-export const getLeadEvent = tb.buildPipe({
+export const getLeadEventTB = tb.buildPipe({
pipe: "get_lead_event",
parameters: z.object({
customerId: z.string(),
@@ -10,3 +12,30 @@ export const getLeadEvent = tb.buildPipe({
}),
data: leadEventSchemaTB,
});
+
+export const getLeadEvent = async ({
+ customerId,
+ eventName,
+}: {
+ customerId: string;
+ eventName?: string | null;
+}) => {
+ const cachedLeadEvent = await redis.get<LeadEventTB>(
+ `leadCache:${customerId}${eventName ? `:${eventName.toLowerCase().replaceAll(" ", "-")}` : ""}`,
+ );
+
+ if (cachedLeadEvent) {
+ return cachedLeadEvent;
+ }
+
+ try {
+ const { data } = await getLeadEventTB({ customerId, eventName });
+ return data[0];
+ } catch (error) {
+ console.error(
+ `[getLeadEvent] Error getting lead event for customerId: ${customerId}${eventName ? ` and eventName: ${eventName}` : ""}`,
+ error,
+ );
+ return null;
+ }
+};
diff --git a/apps/web/scripts/migrations/backfill-missing-sales.ts b/apps/web/scripts/migrations/backfill-missing-sales.ts
index 0e0b6a6450..eb55512821 100644
--- a/apps/web/scripts/migrations/backfill-missing-sales.ts
+++ b/apps/web/scripts/migrations/backfill-missing-sales.ts
@@ -82,7 +82,7 @@ async function main() {
const clickData = clickEventSchemaTB
.omit({ timestamp: true })
- .parse(leadEvent.data[0]);
+ .parse(leadEvent);
const saleAmount = parseInt((cs.amount * 100).toFixed(0));