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.

save the customer record

Kiran K8596d832e089
diff --git a/apps/web/app/api/campaigns/callback/stripe/route.ts b/apps/web/app/api/campaigns/callback/stripe/route.ts
index 4af535f2fa..bdcd908859 100644
--- a/apps/web/app/api/campaigns/callback/stripe/route.ts
+++ b/apps/web/app/api/campaigns/callback/stripe/route.ts
@@ -1,24 +1,32 @@
+import prisma from "@/lib/prisma";
import z from "@/lib/zod";
import { getSearchParams } from "@dub/utils";
+import { redirect } from "next/navigation";
+import { NextRequest } from "next/server";
const schema = z.object({
- code: z.string(),
- user_id: z.string(),
- account_id: z.string(),
+ state: z.string(),
stripe_user_id: z.string(),
});
-export const GET = async (req: Request) => {
- const {
- user_id: userId,
- account_id: accountId,
- stripe_user_id: stripeUserId,
- } = schema.parse(getSearchParams(req.url));
+export const GET = async (req: NextRequest) => {
+ const { state, stripe_user_id: stripeConnectId } = schema.parse(
+ getSearchParams(req.url),
+ );
- // Store this against the user in the database
- console.log({ userId, accountId, stripeUserId });
+ // TODO:
+ // Create a unique state before redirecting to Stripe (and store it in the Redis)
+ // And validate it here
+ const workspaceId = state.replace("ws_", "");
- return new Response("OK", {
- status: 200,
+ const workspace = await prisma.project.update({
+ where: {
+ id: workspaceId,
+ },
+ data: {
+ stripeConnectId,
+ },
});
+
+ redirect(`/${workspace.slug}`);
};
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index 2010f3a0ee..c4d5a2104d 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -1,5 +1,7 @@
+import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withSessionEdge } from "@/lib/auth/session-edge";
+import { createCustomer, getCustomer } from "@/lib/planetscale";
import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";
import { clickEventSchemaTB, trackLeadRequestSchema } from "@/lib/zod/schemas";
import { nanoid } from "@dub/utils";
@@ -14,12 +16,26 @@ export const POST = withSessionEdge(async ({ req, workspace }) => {
clickId,
eventName,
metadata,
- customerId,
customerName,
customerEmail,
customerAvatar,
+ customerId: externalId,
} = trackLeadRequestSchema.parse(await parseRequestBody(req));
+ if (externalId) {
+ const customer = await getCustomer({
+ externalId,
+ workspaceId: workspace.id,
+ });
+
+ if (customer) {
+ throw new DubApiError({
+ code: "conflict",
+ message: `A customer with the customerId ${externalId} already exists in this workspace.`,
+ });
+ }
+ }
+
waitUntil(
(async () => {
const clickEvent = await getClickEvent({ clickId });
@@ -28,15 +44,11 @@ export const POST = withSessionEdge(async ({ req, workspace }) => {
return;
}
+ const customerId = nanoid(16);
const clickData = clickEventSchemaTB
- .omit({ timestamp: true }) // timestamp is auto generated on insert
+ .omit({ timestamp: true })
.parse(clickEvent.data[0]);
- const customerInfoPresent =
- Boolean(customerName) ||
- Boolean(customerEmail) ||
- Boolean(customerAvatar);
-
await Promise.all([
recordLead({
...clickData,
@@ -46,14 +58,24 @@ export const POST = withSessionEdge(async ({ req, workspace }) => {
metadata,
}),
- customerInfoPresent &&
+ workspace.stripeConnectId &&
+ externalId &&
+ (createCustomer({
+ id: customerId,
+ name: customerName || "",
+ email: customerEmail || "",
+ avatar: customerAvatar || "",
+ externalId,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ }),
recordCustomer({
customer_id: customerId,
name: customerName,
email: customerEmail,
avatar: customerAvatar,
workspace_id: workspace.id,
- }),
+ })),
]);
})(),
);
diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.ts
index 31129352eb..446d550a81 100644
--- a/apps/web/lib/planetscale.ts
+++ b/apps/web/lib/planetscale.ts
@@ -1,6 +1,6 @@
import { nanoid, punyEncode } from "@dub/utils";
import { connect } from "@planetscale/database";
-import { Project, User } from "@prisma/client";
+import { Customer, Project, User } from "@prisma/client";
import { DomainProps } from "./types";
export const DATABASE_URL =
@@ -172,3 +172,42 @@ export const getWorkspaceBySlug = async (workspaceSlug: string) => {
return rows && Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
};
+
+export const createCustomer = async ({
+ id,
+ name,
+ email,
+ avatar,
+ externalId,
+ projectId,
+ projectConnectId,
+}: Omit<Customer, "createdAt" | "updatedAt">) => {
+ return await conn.execute(
+ "INSERT INTO Customer (id, name, email, avatar, externalId, projectId, projectConnectId, updatedAt) VALUES (?, ?, ?, ?, ?, ? ,?, ?)",
+ [
+ id,
+ name,
+ email,
+ avatar,
+ externalId,
+ projectId,
+ projectConnectId,
+ new Date(),
+ ],
+ );
+};
+
+export const getCustomer = async ({
+ externalId,
+ workspaceId,
+}: {
+ externalId: string;
+ workspaceId: string;
+}) => {
+ const { rows } = await conn.execute<Customer>(
+ "SELECT * FROM Customer WHERE externalId = ? AND projectId = ? LIMIT 1",
+ [externalId, workspaceId],
+ );
+
+ return rows && Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
+};
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index d631885c57..3bbd86c8f4 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -13,5 +13,5 @@ export const customersMetadataSchema = z.object({
email: z.string().nullish().default(""),
avatar: z.string().nullish().default(""),
workspace_id: z.string(),
- deleted: z.boolean().default(false),
+ deleted: z.number().default(0),
});
diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.ts
index 2a6c1f7482..1aab81d990 100644
--- a/apps/web/lib/zod/schemas/leads.ts
+++ b/apps/web/lib/zod/schemas/leads.ts
@@ -14,6 +14,7 @@ export const trackLeadRequestSchema = z.object({
customerId: z
.string()
.max(100)
+ .nullish()
.describe(
"This is the unique identifier for the customer in the client's app. This is used to track the customer's journey.",
),
diff --git a/packages/stripe-app/stripe-app.json b/packages/stripe-app/stripe-app.json
index 6420ff3527..a32a154b8f 100644
--- a/packages/stripe-app/stripe-app.json
+++ b/packages/stripe-app/stripe-app.json
@@ -1,6 +1,6 @@
{
"id": "com.example.dub",
- "version": "0.0.11",
+ "version": "0.0.12",
"name": "Dub",
"icon": "",
"permissions": [
@@ -33,7 +33,7 @@
}
},
"allowed_redirect_uris": [
- "https://bd67-103-177-27-104.ngrok-free.app/api/campaigns/callback/stripe"
+ "https://b0b3-103-70-36-129.ngrok-free.app/api/campaigns/callback/stripe"
],
"stripe_api_access_type": "oauth",
"distribution_type": "public"