feat: google ads conversion tracking (#25198)
* feat: google ads conversion tracking * gaClientid * store gclid in stripe metadata * tracking only in the us * track google campaign id as well * rename gclid -> google ads * fix: build * fix * refactor * fix: type check * fix: type check * fix: type check * fix: type check * fix: store it in cookie * refactor * fix * cleanup * linked ads tracking * refactor checkout session tracking
This commit is contained in:
1 parent
700d8e7f30
commit
81224f324a
22 files changed
+181
-95
No files matched your search
@@ -1,5 +1,7 @@
|
||||
import type { Logger } from "tslog";
|
||||
|
||||
import type { TrackingData } from "@calcom/lib/tracking";
|
||||
|
||||
import type { RetellAIPhoneServiceProviderTypeMap } from "../providers/retellAI";
|
||||
|
||||
/**
|
||||
@@ -243,6 +245,7 @@ export interface AIPhoneServiceProvider<T extends AIPhoneServiceProviderType = A
|
||||
teamId?: number;
|
||||
agentId?: string | null;
|
||||
workflowId?: string;
|
||||
tracking?: TrackingData;
|
||||
}): Promise<{ url: string; message: string }>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { TrackingData } from "@calcom/lib/tracking";
|
||||
|
||||
import type {
|
||||
AIPhoneServiceProvider,
|
||||
AIPhoneServiceProviderType,
|
||||
@@ -169,6 +171,7 @@ export class RetellAIPhoneServiceProvider
|
||||
teamId?: number;
|
||||
agentId?: string | null;
|
||||
workflowId?: string;
|
||||
tracking?: TrackingData;
|
||||
}): Promise<{ url: string; message: string }> {
|
||||
return await this.service.generatePhoneNumberCheckoutSession(params);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { TrackingData } from "@calcom/lib/tracking";
|
||||
|
||||
import type {
|
||||
AIPhoneServiceUpdateModelParams,
|
||||
AIPhoneServiceCreatePhoneNumberParams,
|
||||
@@ -265,6 +267,7 @@ export class RetellAIService {
|
||||
teamId?: number;
|
||||
agentId?: string | null;
|
||||
workflowId?: string;
|
||||
tracking?: TrackingData;
|
||||
}) {
|
||||
return this.billingService.generatePhoneNumberCheckoutSession(params);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { WEBAPP_URL, IS_PRODUCTION } from "@calcom/lib/constants";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { TrackingData } from "@calcom/lib/tracking";
|
||||
import { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
|
||||
|
||||
import type { PhoneNumberRepositoryInterface } from "../../interfaces/PhoneNumberRepositoryInterface";
|
||||
@@ -25,18 +26,20 @@ export class BillingService {
|
||||
phoneNumberRepository: PhoneNumberRepositoryInterface;
|
||||
retellRepository: RetellAIRepository;
|
||||
}
|
||||
) {}
|
||||
) { }
|
||||
|
||||
async generatePhoneNumberCheckoutSession({
|
||||
userId,
|
||||
teamId,
|
||||
agentId,
|
||||
workflowId,
|
||||
tracking,
|
||||
}: {
|
||||
userId: number;
|
||||
teamId?: number;
|
||||
agentId?: string | null;
|
||||
workflowId?: string;
|
||||
tracking?: TrackingData;
|
||||
}) {
|
||||
const phoneNumberPriceId = getPhoneNumberMonthlyPriceId();
|
||||
|
||||
@@ -80,6 +83,8 @@ export class BillingService {
|
||||
agentId: agentId || "",
|
||||
workflowId: workflowId || "",
|
||||
type: CHECKOUT_SESSION_TYPES.PHONE_NUMBER_SUBSCRIPTION,
|
||||
...(tracking?.googleAds?.gclid && { gclid: tracking.googleAds.gclid, campaignId: tracking.googleAds.campaignId }),
|
||||
...(tracking?.linkedInAds?.liFatId && { liFatId: tracking.linkedInAds.liFatId, linkedInCampaignId: tracking.linkedInAds?.campaignId }),
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
@@ -114,14 +119,14 @@ export class BillingService {
|
||||
// Find phone number with proper team authorization
|
||||
const phoneNumber = teamId
|
||||
? await this.deps.phoneNumberRepository.findByIdWithTeamAccess({
|
||||
id: phoneNumberId,
|
||||
teamId,
|
||||
userId,
|
||||
})
|
||||
id: phoneNumberId,
|
||||
teamId,
|
||||
userId,
|
||||
})
|
||||
: await this.deps.phoneNumberRepository.findByIdAndUserId({
|
||||
id: phoneNumberId,
|
||||
userId,
|
||||
});
|
||||
id: phoneNumberId,
|
||||
userId,
|
||||
});
|
||||
|
||||
if (!phoneNumber) {
|
||||
throw new HttpError({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
|
||||
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
|
||||
import { CreditsRepository } from "@calcom/lib/server/repository/credits";
|
||||
@@ -10,9 +11,36 @@ import { CHECKOUT_SESSION_TYPES } from "../../constants";
|
||||
import type { SWHMap } from "./__handler";
|
||||
import { HttpCode } from "./__handler";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["checkout.session.completed"] });
|
||||
|
||||
const handler = async (data: SWHMap["checkout.session.completed"]["data"]) => {
|
||||
const session = data.object;
|
||||
|
||||
// Store ad tracking data in Stripe customer metadata for Zapier tracking
|
||||
if (session.customer && session.metadata) {
|
||||
try {
|
||||
const trackingMetadata = {
|
||||
gclid: session.metadata?.gclid,
|
||||
campaignId: session.metadata?.campaignId,
|
||||
liFatId: session.metadata?.liFatId,
|
||||
linkedInCampaignId: session.metadata?.linkedInCampaignId,
|
||||
};
|
||||
|
||||
const cleanedMetadata = Object.fromEntries(
|
||||
Object.entries(trackingMetadata).filter(([_, value]) => value)
|
||||
);
|
||||
|
||||
if (Object.keys(cleanedMetadata).length > 0) {
|
||||
const customerId = typeof session.customer === "string" ? session.customer : session.customer.id;
|
||||
await stripe.customers.update(customerId, {
|
||||
metadata: cleanedMetadata,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
log.error("Failed to update Stripe customer metadata with ad tracking data", { error });
|
||||
}
|
||||
}
|
||||
|
||||
if (session.metadata?.type === CHECKOUT_SESSION_TYPES.PHONE_NUMBER_SUBSCRIPTION) {
|
||||
return await handleCalAIPhoneNumberSubscription(session);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useSession } from "next-auth/react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useLayoutEffect, useState } from "react";
|
||||
@@ -32,7 +31,6 @@ import { ImageUploader } from "@calcom/ui/components/image-uploader";
|
||||
import { SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import { showToast } from "@calcom/ui/components/toast";
|
||||
import { revalidateTeamDataCache } from "@calcom/web/app/(booking-page-wrapper)/team/[slug]/[type]/actions";
|
||||
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
|
||||
|
||||
import { subdomainSuffix } from "../../../organizations/lib/orgDomains";
|
||||
|
||||
@@ -54,7 +52,6 @@ const OtherTeamProfileView = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const utils = trpc.useUtils();
|
||||
const session = useSession();
|
||||
const [firstRender, setFirstRender] = useState(true);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -133,19 +130,6 @@ const OtherTeamProfileView = () => {
|
||||
},
|
||||
});
|
||||
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
revalidateTeamsList();
|
||||
await utils.viewer.eventTypes.invalidate();
|
||||
showToast(t("success"), "success");
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
});
|
||||
|
||||
const publishMutation = trpc.viewer.teams.publish.useMutation({
|
||||
async onSuccess(data: { url?: string }) {
|
||||
if (data.url) {
|
||||
@@ -161,14 +145,6 @@ const OtherTeamProfileView = () => {
|
||||
if (team?.id) deleteTeamMutation.mutate({ teamId: team.id });
|
||||
}
|
||||
|
||||
function leaveTeam() {
|
||||
if (team?.id && session.data)
|
||||
removeMemberMutation.mutate({
|
||||
teamIds: [team.id],
|
||||
memberIds: [session.data.user.id],
|
||||
});
|
||||
}
|
||||
|
||||
if (!team) return null;
|
||||
|
||||
return (
|
||||
@@ -291,7 +267,6 @@ const OtherTeamProfileView = () => {
|
||||
<Label className="text-emphasis mt-5">{t("about")}</Label>
|
||||
<div
|
||||
className=" text-subtle break-words text-sm [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
|
||||
// eslint-disable-next-line react/no-danger
|
||||
dangerouslySetInnerHTML={{ __html: markdownToSafeHTML(team.bio) }}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -17,6 +17,7 @@ import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { BillingPeriod } from "@calcom/prisma/zod-utils";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
import { TrackingData } from "@calcom/lib/tracking";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["teams/lib/payments"] });
|
||||
const teamPaymentMetadataSchema = z.object({
|
||||
@@ -51,11 +52,13 @@ export const generateTeamCheckoutSession = async ({
|
||||
teamSlug,
|
||||
userId,
|
||||
isOnboarding,
|
||||
tracking,
|
||||
}: {
|
||||
teamName: string;
|
||||
teamSlug: string;
|
||||
userId: number;
|
||||
isOnboarding?: boolean;
|
||||
tracking?: TrackingData;
|
||||
}) => {
|
||||
const [customer, dubCustomer] = await Promise.all([
|
||||
getStripeCustomerIdFromUserId(userId),
|
||||
@@ -66,15 +69,15 @@ export const generateTeamCheckoutSession = async ({
|
||||
mode: "subscription",
|
||||
...(dubCustomer?.discount?.couponId
|
||||
? {
|
||||
discounts: [
|
||||
{
|
||||
coupon:
|
||||
process.env.NODE_ENV !== "production" && dubCustomer.discount.couponTestId
|
||||
? dubCustomer.discount.couponTestId
|
||||
: dubCustomer.discount.couponId,
|
||||
},
|
||||
],
|
||||
}
|
||||
discounts: [
|
||||
{
|
||||
coupon:
|
||||
process.env.NODE_ENV !== "production" && dubCustomer.discount.couponTestId
|
||||
? dubCustomer.discount.couponTestId
|
||||
: dubCustomer.discount.couponId,
|
||||
},
|
||||
],
|
||||
}
|
||||
: { allow_promotion_codes: true }),
|
||||
success_url: `${WEBAPP_URL}/api/teams/create?session_id={CHECKOUT_SESSION_ID}`,
|
||||
cancel_url: `${WEBAPP_URL}/settings/my-account/profile`,
|
||||
@@ -102,6 +105,8 @@ export const generateTeamCheckoutSession = async ({
|
||||
userId,
|
||||
dubCustomerId: userId, // pass the userId during checkout creation for sales conversion tracking: https://d.to/conversions/stripe
|
||||
...(isOnboarding !== undefined && { isOnboarding: isOnboarding.toString() }),
|
||||
...(tracking?.googleAds?.gclid && { gclid: tracking.googleAds.gclid, campaignId: tracking.googleAds?.campaignId }),
|
||||
...(tracking?.linkedInAds?.liFatId && { liFatId: tracking.linkedInAds.liFatId, linkedInCampaignId: tracking.linkedInAds?.campaignId }),
|
||||
},
|
||||
});
|
||||
return session;
|
||||
@@ -127,6 +132,7 @@ export const purchaseTeamOrOrgSubscription = async (input: {
|
||||
isOrg?: boolean;
|
||||
pricePerSeat: number | null;
|
||||
billingPeriod?: BillingPeriod;
|
||||
tracking?: TrackingData;
|
||||
}) => {
|
||||
const {
|
||||
teamId,
|
||||
@@ -136,6 +142,7 @@ export const purchaseTeamOrOrgSubscription = async (input: {
|
||||
isOrg,
|
||||
pricePerSeat,
|
||||
billingPeriod = BillingPeriod.MONTHLY,
|
||||
tracking,
|
||||
} = input;
|
||||
const { url } = await checkIfTeamPaymentRequired({ teamId });
|
||||
if (url) return { url };
|
||||
@@ -193,6 +200,8 @@ export const purchaseTeamOrOrgSubscription = async (input: {
|
||||
},
|
||||
metadata: {
|
||||
teamId,
|
||||
...(tracking?.googleAds?.gclid && { gclid: tracking.googleAds.gclid, campaignId: tracking.googleAds.campaignId }),
|
||||
...(tracking?.linkedInAds?.liFatId && { liFatId: tracking.linkedInAds.liFatId, linkedInCampaignId: tracking.linkedInAds?.campaignId }),
|
||||
},
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
|
||||
Reference in new issue
Block a user