The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Merge branch 'main' into staging-sandbox
Kiran K8040afec3197
diff --cc apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex 117a801451,d746573c6c..087ee5b4fe--- 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@@@ -14,23 -12,19 +12,20 @@@ importrecordLead,recordSale,} from "@/lib/tinybird";- import { recordFakeClick } from "@/lib/tinybird/record-fake-click";--import { ClickEventTB, LeadEventTB, StripeMode } from "@/lib/types";++import { ClickEventTB, LeadEventTB } from "@/lib/types";import { redis } from "@/lib/upstash";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";- import {- transformLeadEventData,- transformSaleEventData,- } from "@/lib/webhook/transform";+ import { transformSaleEventData } from "@/lib/webhook/transform";import { prisma } from "@dub/prisma";- import { Customer, Project } from "@dub/prisma/client";- import { COUNTRIES_TO_CONTINENTS, nanoid, pick } from "@dub/utils";+ import { Customer } from "@dub/prisma/client";+ import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";+ import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";import { getCheckoutSessionProductId } from "./utils/get-checkout-session-product-id";import { getConnectedCustomer } from "./utils/get-connected-customer";- import { getPromotionCode } from "./utils/get-promotion-code";+ import { incrementLinkLeads } from "./utils/increment-link-leads";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";// Handle event "checkout.session.completed"@@@ -563,214 -582,6 +556,5 @@@ export async function checkoutSessionCoreturn {response: `Checkout session completed for customer with external ID ${dubCustomerExternalId} and invoice ID ${invoiceId}`,- workspaceId: workspace.id,};}-- async function attributeViaPromoCode({- promotionCodeId,- stripeAccountId,- workspace,- mode,- charge,- }: {- promotionCodeId: string;- stripeAccountId: string;- workspace: Pick<- Project,- "id" | "defaultProgramId" | "stripeConnectId" | "webhookEnabled"- >;- mode: StripeMode;- charge: Stripe.Checkout.Session;- }) {- // Find the promotion code for the promotion code id- const promotionCode = await getPromotionCode({- promotionCodeId,- stripeAccountId,- mode,- });-- if (!promotionCode) {- console.log(- `Promotion code ${promotionCodeId} not found in connected account ${stripeAccountId}, skipping...`,- );- return null;- }-- if (!workspace.defaultProgramId) {- console.log(- `Workspace with stripeConnectId ${stripeAccountId} has no default program, skipping...`,- );- return null;- }-- const discountCode = await prisma.discountCode.findUnique({- where: {- programId_code: {- programId: workspace.defaultProgramId,- code: promotionCode.code,- },- },- select: {- link: true,- },- });-- if (!discountCode) {- console.log(- `Couldn't find link associated with promotion code ${promotionCode.code}, skipping...`,- );- return null;- }-- const link = discountCode.link;- const linkId = link.id;-- // Record a fake click for this event- const customerDetails = charge.customer_details;- const customerAddress = customerDetails?.address;-- const clickEvent = await recordFakeClick({- link,- customer: {- continent: customerAddress?.country- ? COUNTRIES_TO_CONTINENTS[customerAddress.country]- : "Unknown",- country: customerAddress?.country ?? "Unknown",- region: customerAddress?.state ?? "Unknown",- },- });-- const customer = await prisma.customer.create({- data: {- id: createId({ prefix: "cus_" }),- name:- customerDetails?.name || customerDetails?.email || generateRandomName(),- email: customerDetails?.email,- externalId: clickEvent.click_id,- stripeCustomerId: charge.customer as string,- linkId: clickEvent.link_id,- clickId: clickEvent.click_id,- clickedAt: new Date(clickEvent.timestamp + "Z"),- country: customerAddress?.country,- projectId: workspace.id,- projectConnectId: workspace.stripeConnectId,- },- });-- // Prepare the payload for the lead event- const { timestamp, ...rest } = clickEvent;-- const leadEvent = {- ...rest,- workspace_id: clickEvent.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id- event_id: nanoid(16),- event_name: "Checkout with discount code",- customer_id: customer.id,- metadata: "",- };-- await recordLead(leadEvent);-- // record lead side effects (link stats, partner commissions, workflows, workspace webhook)- waitUntil(- (async () => {- const linkUpdated = await incrementLinkLeads(link.id);-- let createdCommission:- | Awaited<ReturnType<typeof createPartnerCommission>>- | undefined = undefined;-- if (link.programId && link.partnerId) {- createdCommission = await createPartnerCommission({- event: "lead",- programId: link.programId,- partnerId: link.partnerId,- linkId: link.id,- eventId: leadEvent.event_id,- customerId: customer.id,- quantity: 1,- context: {- customer: {- country: customer.country,- },- },- });-- await Promise.allSettled([- executeWorkflows({- trigger: "partnerMetricsUpdated",- reason: "lead",- identity: {- workspaceId: workspace.id,- programId: link.programId,- partnerId: link.partnerId,- },- metrics: {- current: {- leads: 1,- },- },- }),-- syncPartnerLinksStats({- partnerId: link.partnerId,- programId: link.programId,- eventType: "lead",- }),- ]);- }-- await Promise.allSettled([- sendWorkspaceWebhook({- trigger: "lead.created",- workspace,- data: transformLeadEventData({- ...leadEvent,- eventName: "Checkout session completed",- link: linkUpdated,- customer,- partner: createdCommission?.webhookPartner,- metadata: null,- }),- }),-- ...(link.partnerId- ? [- sendPartnerPostback({- partnerId: link.partnerId,- event: "lead.created",- data: {- ...leadEvent,- eventName: "Checkout session completed",- link: linkUpdated,- customer,- },- }),- ]- : []),- ]);- })(),- );-- return {- linkId,- customer,- clickEvent,- leadEvent,- };- }-- async function incrementLinkLeads(linkId: string) {- return prisma.link.update({- where: {- id: linkId,- },- data: {- leads: {- increment: 1,- },- lastLeadAt: new Date(),- },- include: includeTags,- });- }diff --cc apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsindex 5a27ac4757,041ded72d3..f03969d143--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts@@@ -11,24 -12,34 +12,38 @@@ import { redis } from "@/lib/upstash"import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import { transformSaleEventData } from "@/lib/webhook/transform";import { prisma } from "@dub/prisma";- import { nanoid, pick } from "@dub/utils";+ import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";+ import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";import { getConnectedCustomer } from "./utils/get-connected-customer";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "invoice.paid"-export async function invoicePaid(- event: Stripe.InvoicePaidEvent,- mode: StripeMode,-) {+export async function invoicePaid({+ event,+ mode,+ workspace,+}: StripeWebhookInput & {+ event: Stripe.InvoicePaidEvent;+}): Promise<StripeWebhookOutput> {const invoice = event.data.object;- const stripeCustomerId = invoice.customer as string;- const stripeAccountId = event.account as string;+ const stripeCustomerId = invoice.customer as string | null;++ const stripeAccountId = event.account as string;const invoiceId = invoice.id;+ if (!invoiceId) {+ return {+ response: "Invoice ID not found, skipping...",+ };+ }++ if (!stripeCustomerId) {+ return {+ response: "Stripe customer ID not found on invoice, skipping...",+ };+ }+// Find customer using stripeCustomerIdlet customer = await prisma.customer.findUnique({where: {@@@ -71,11 -82,69 +86,67 @@@}}- // if customer is still not found, we skip the event+ // if customer is still not found, try to attribute via partner discount on the invoiceif (!customer) {- return {- response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor does the connected customer ${stripeCustomerId} have a valid dubCustomerExternalId), skipping...`,- };+ const workspace = await prisma.project.findUnique({+ where: {+ stripeConnectId: stripeAccountId,+ },+ select: {+ id: true,+ defaultProgramId: true,+ stripeConnectId: true,+ webhookEnabled: true,+ },+ });++ if (!workspace) {+ return {+ response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,+ };+ }++ if (!workspace.defaultProgramId) {+ return {+ response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub and workspace has no default program, skipping...`,- workspaceId: workspace.id,+ };+ }++ const { promotionCodeId, resolvePromotionCodeError } =+ await resolvePromotionCodeIdFromInvoice({+ invoiceId,+ stripeAccountId,+ mode,+ });++ if (promotionCodeId) {+ const promoCodeResponse = await attributeViaPromotionCodeId({+ promotionCodeId,+ stripeAccountId,+ workspace,+ mode,+ stripeCustomerId,+ customerDetails: {+ name: invoice.customer_name,+ email: invoice.customer_email,+ address: invoice.customer_address,+ },+ });++ if (promoCodeResponse) {+ customer = promoCodeResponse.customer;+ }+ } else if (resolvePromotionCodeError) {+ console.log(+ `Failed to resolve promotion code from invoice ${invoiceId}: ${resolvePromotionCodeError}`,+ );+ }++ if (!customer) {+ return {+ response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor does the connected customer ${stripeCustomerId} have a valid dubCustomerExternalId or partner discount code on the invoice), skipping...`,- workspaceId: workspace.id,+ };+ }}// Sale amount excluding tax: use total_excluding_tax only when invoice was paid in full@@@ -342,5 -404,60 +402,59 @@@return {response: `Sale recorded for customer ID ${customer.id} and invoice ID ${invoiceId}`,- workspaceId: customer.projectId,};}++ async function resolvePromotionCodeIdFromInvoice({+ invoiceId,+ stripeAccountId,+ mode,+ }: {+ invoiceId: string;+ stripeAccountId: string;+ mode: StripeMode;+ }): Promise<+ | {+ promotionCodeId: string;+ resolvePromotionCodeError: null;+ }+ | {+ promotionCodeId: null;+ resolvePromotionCodeError: string;+ }+ > {+ const stripe = stripeAppClient({ mode });++ const expandedInvoice = (await stripe.invoices.retrieve(+ invoiceId,+ {+ expand: ["discounts", "discounts.promotion_code"],+ },+ {+ stripeAccount: stripeAccountId,+ },+ )) as Stripe.Invoice & {+ discounts: {+ promotion_code: Stripe.PromotionCode;+ }[];+ };++ if (!expandedInvoice) {+ return {+ promotionCodeId: null,+ resolvePromotionCodeError: "Invoice not found", // should never happen, but just in case+ };+ }++ if (!expandedInvoice.discounts || expandedInvoice.discounts.length === 0) {+ return {+ promotionCodeId: null,+ resolvePromotionCodeError: "No discounts found on invoice",+ };+ }++ return {+ promotionCodeId: expandedInvoice.discounts[0].promotion_code.id,+ resolvePromotionCodeError: null,+ };+ }diff --cc apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.tsindex b14371211e,9f503ad083..b6fccbcde4--- a/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts@@@ -19,7 -37,8 +19,7 @@@ export async function promotionCodeUpdaif (promotionCode.active) {return {- response: `Promotion code ${promotionCode.id} is active.`,+ response: `Promotion code ${promotionCode.id} is active, no action needed.`,- workspaceId,};}diff --cc apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsxindex 8047957e7e,60b64e5633..b9d65b353c--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx@@@ -71,93 -70,68 +71,93 @@@ const DiscountItem = (group: GroupProps;}) => {const { slug } = useParams();+ const { environment } = useWorkspace();const { queryParams } = useRouterStuff();+ const { openCopyDiscountToLiveModal, CopyDiscountToLiveModal } =+ useCopyDiscountToLiveModal();++const As = discount ? Link : "div";return (- <As- href={- discount- ? `/${slug}/program/groups/${group.slug}/discounts?discountId=${discount.id}`- : ""- }- scroll={false}- className={cn(- "flex cursor-pointer flex-col gap-4 rounded-lg p-6 transition-all md:flex-row md:items-center",- discount && "border border-neutral-200 hover:border-neutral-300",- !discount && "bg-neutral-50 hover:bg-neutral-100",+ <>+ {discount && environment === WorkspaceEnvironment.staging && (+ <CopyDiscountToLiveModal />)}- onClick={(e) => {- if (isClickOnInteractiveChild(e)) return;- queryParams({- set: {- discountId: discount?.id ?? "new",- },- });- }}- >- <div className="flex size-10 items-center justify-center rounded-full border border-neutral-200 bg-white">- <BadgePercent className="size-4 text-neutral-600" />- </div>- <div className="flex flex-1 flex-col justify-between gap-y-4 md:flex-row md:items-center">- <div className="flex items-center gap-2">- <span className="text-sm font-normal">- {discount ? (- <ProgramRewardDescription discount={discount} />- ) : (- <span className="text-sm font-normal text-neutral-600">- No referral discount created- </span>- )}- </span>+ <As+ href={+ discount+ ? `/${slug}/program/groups/${group.slug}/discounts?discountId=${discount.id}`+ : ""+ }+ scroll={false}+ className={cn(+ "flex cursor-pointer flex-col gap-4 rounded-lg p-6 transition-all md:flex-row md:items-center",+ discount && "border border-neutral-200 hover:border-neutral-300",+ !discount && "bg-neutral-50 hover:bg-neutral-100",+ )}+ onClick={(e) => {+ e.preventDefault();+ if (isClickOnInteractiveChild(e)) return;+ queryParams({+ set: {+ discountId: discount?.id ?? "new",+ },+ scroll: false,+ });+ }}+ >+ <div className="flex size-10 items-center justify-center rounded-full border border-neutral-200 bg-white">+ <BadgePercent className="size-4 text-neutral-600" /></div>+ <div className="flex flex-1 flex-col justify-between gap-y-4 md:flex-row md:items-center">+ <div className="flex items-center gap-2">+ <span className="text-sm font-normal">+ {discount ? (+ <ProgramRewardDescription discount={discount} />+ ) : (+ <span className="text-sm font-normal text-neutral-600">+ No referral discount created+ </span>+ )}+ </span>+ </div>++ <div className="flex flex-col-reverse items-center gap-2 md:flex-row">+ {!discount && group.slug !== DEFAULT_PARTNER_GROUP.slug && (+ <CopyDefaultDiscountButton />+ )}++ {discount && environment === WorkspaceEnvironment.staging && (+ <Button+ text="Copy to live"+ variant="secondary"+ className="h-9 w-full rounded-lg md:w-fit"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ openCopyDiscountToLiveModal(discount);+ }}+ />+ )}- <div className="flex flex-col-reverse items-center gap-2 md:flex-row">- {!discount && group.slug !== DEFAULT_PARTNER_GROUP.slug && (- <CopyDefaultDiscountButton />- )}- <Button- text={discount ? "Edit" : "Create"}- variant={discount ? "secondary" : "primary"}- className="h-9 w-full rounded-lg md:w-fit"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- queryParams({- set: {- discountId: discount?.id ?? "new",- },- });- }}- />+ <Button+ text={discount ? "Edit" : "Create"}+ variant={discount ? "secondary" : "primary"}+ className="h-9 w-full rounded-lg md:w-fit"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ queryParams({+ set: {+ discountId: discount?.id ?? "new",+ },- scroll: false,+ });+ }}+ />+ </div></div>- </div>- </As>+ </As>+ </>);};diff --cc apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsxindex a4a2eea3cc,d910226173..68f61e0500--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/group-rewards.tsx@@@ -272,36 -256,20 +272,35 @@@ const RewardItem = (</div>{reward ? (- <Button- text="Edit"- variant="secondary"- className="h-9 w-fit rounded-lg"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- queryParams({- set: {- rewardId: reward.id,- },- });- }}- />+ <div className="flex items-center gap-2">+ {environment === WorkspaceEnvironment.staging && (+ <Button+ text="Copy to live"+ variant="secondary"+ className="h-9 w-fit rounded-lg"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ openCopyRewardToLiveModal(reward);+ }}+ />+ )}++ <Button+ text="Edit"+ variant="secondary"+ className="h-9 w-fit rounded-lg"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ queryParams({+ set: {+ rewardId: reward.id,+ },- scroll: false,+ });+ }}+ />+ </div>) : (<div className="flex flex-col-reverse items-center gap-2 md:flex-row">{group.slug !== DEFAULT_PARTNER_GROUP.slug &&