The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add HubSpot Deal Stage Reached lead trigger and event routing tests
Kiran Kea9e70a60d77
diff --git a/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/process/route.tsindex 9d85b9241a..73998c56d9 100644--- a/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts+++ b/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts@@ -2,6 +2,7 @@ import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";import { handleAndReturnErrorResponse } from "@/lib/api/errors";import { withAxiom } from "@/lib/axiom/server";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { getHubSpotEventAction } from "@/lib/integrations/hubspot/get-hubspot-event-action";import { hubSpotOAuthProvider } from "@/lib/integrations/hubspot/oauth";import {hubSpotSettingsSchema,@@ -79,60 +80,31 @@ export const POST = withAxiom(async (req) => {console.log("[HubSpot] Integration settings", settings);- let response = "";-- // Contact events- if (objectTypeId === "0-1") {- const isContactCreated = subscriptionType === "object.creation";-- const isLifecycleStageChanged =- subscriptionType === "object.propertyChange" &&- settings.leadTriggerEvent === "lifecycleStageReached";-- if (isContactCreated || isLifecycleStageChanged) {- response = await trackHubSpotLeadEvent({- payload: body,- workspace,- authToken,- settings,- });- } else {- response = `Skipping contact event: subscriptionType "${subscriptionType}" does not match the configured leadTriggerEvent "${settings.leadTriggerEvent}".`;- }- }+ const action = getHubSpotEventAction({+ event: body,+ settings,+ });- // Deal event- else if (objectTypeId === "0-3") {- const isDealCreated =- subscriptionType === "object.creation" &&- settings.leadTriggerEvent === "dealCreated";-- const isDealUpdated = subscriptionType === "object.propertyChange";-- // Track the final lead event- if (isDealCreated) {- response = await trackHubSpotLeadEvent({- payload: body,- workspace,- authToken,- settings,- });- }-- // Track the sale event when deal is closed won- else if (isDealUpdated) {- response = await trackHubSpotSaleEvent({- payload: body,- workspace,- authToken,- settings,- });- }- }+ console.log("[HubSpot] Event action", action);- // Unknown object type- else {- response = `Unknown objectTypeId ${objectTypeId}.`;+ let response: string;++ if (action === "trackLead") {+ response = await trackHubSpotLeadEvent({+ payload: body,+ workspace,+ authToken,+ settings,+ });+ } else if (action === "trackSale") {+ response = await trackHubSpotSaleEvent({+ payload: body,+ workspace,+ authToken,+ settings,+ });+ } else {+ response = `Skipping event: objectTypeId "${objectTypeId}", subscriptionType "${subscriptionType}", propertyName "${body.propertyName ?? ""}" does not match the configured leadTriggerEvent "${settings.leadTriggerEvent}".`;}await captureWebhookLog({diff --git a/apps/web/lib/integrations/hubspot/constants.ts b/apps/web/lib/integrations/hubspot/constants.tsindex 3f1bda4a3a..769ec4670b 100644--- a/apps/web/lib/integrations/hubspot/constants.ts+++ b/apps/web/lib/integrations/hubspot/constants.ts@@ -9,8 +9,9 @@ export const HUBSPOT_DEFAULT_SETTINGS = {};export const LEAD_TRIGGER_EVENT_OPTIONS = [- "lifecycleStageReached",- "dealCreated",+ "lifecycleStageReached", // contact's lifecyclestage reaches leadLifecycleStageId+ "dealCreated", // a deal is created for the contact+ "dealStageReached", // a deal's dealstage reaches leadDealStageId] as const;export const HUBSPOT_DUB_CONTACT_PROPERTIES = [diff --git a/apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts b/apps/web/lib/integrations/hubspot/get-hubspot-event-action.tsnew file mode 100644index 0000000000..c9ac690c5c--- /dev/null+++ b/apps/web/lib/integrations/hubspot/get-hubspot-event-action.ts@@ -0,0 +1,70 @@+import * as z from "zod/v4";+import { hubSpotLeadEventSchema, hubSpotSettingsSchema } from "./schema";++// Decide whether a HubSpot webhook event should record a lead, a sale, or be skipped+export function getHubSpotEventAction({+ event,+ settings,+}: {+ event: Pick<+ z.infer<typeof hubSpotLeadEventSchema>,+ "objectTypeId" | "subscriptionType" | "propertyName" | "propertyValue"+ >;+ settings: z.infer<typeof hubSpotSettingsSchema>;+}): "trackLead" | "trackSale" | "skip" {+ const { objectTypeId, subscriptionType, propertyName, propertyValue } = event;+ const { leadTriggerEvent } = settings;++ const isCreated = subscriptionType === "object.creation";+ const isPropertyChanged = subscriptionType === "object.propertyChange";++ // Contact events+ if (objectTypeId === "0-1") {+ // Deferred lead, recorded for every new contact+ if (isCreated) {+ return "trackLead";+ }++ // Final lead when the contact's lifecycle stage changes (lifecycleStageReached)+ if (isPropertyChanged && leadTriggerEvent === "lifecycleStageReached") {+ return "trackLead";+ }++ return "skip";+ }++ // Deal event+ if (objectTypeId === "0-3") {+ // Final lead when a deal is created (dealCreated)+ if (isCreated) {+ return leadTriggerEvent === "dealCreated" ? "trackLead" : "skip";+ }++ if (!isPropertyChanged || propertyName !== "dealstage") {+ return "skip";+ }++ const newDealStage = String(propertyValue ?? "").toLowerCase();+ const leadDealStageId = settings.leadDealStageId?.toLowerCase();+ const closedWonDealStageId = settings.closedWonDealStageId?.toLowerCase();++ // Final lead when a deal moves into the lead deal stage (dealStageReached)+ if (+ leadTriggerEvent === "dealStageReached" &&+ leadDealStageId &&+ newDealStage === leadDealStageId+ ) {+ return "trackLead";+ }++ // Track the sale event when deal is closed won+ if (closedWonDealStageId && newDealStage === closedWonDealStageId) {+ return "trackSale";+ }++ return "skip";+ }++ // Unknown object type+ return "skip";+}diff --git a/apps/web/lib/integrations/hubspot/schema.ts b/apps/web/lib/integrations/hubspot/schema.tsindex dd5a275a45..187a66ab3d 100644--- a/apps/web/lib/integrations/hubspot/schema.ts+++ b/apps/web/lib/integrations/hubspot/schema.ts@@ -29,6 +29,12 @@ export const hubSpotSettingsSchema = z.object({.describe("The ID of the contact lifecycle stage that represents a lead. Applicable only if leadTrackingTrigger is 'lifecycleStageReached'.",),+ leadDealStageId: z+ .string()+ .nullish()+ .describe(+ "The ID of the deal stage that represents a lead. Applicable only if leadTriggerEvent is 'dealStageReached'.",+ ),closedWonDealStageId: z.string().nullish()@@ -80,6 +86,8 @@ export const hubSpotLeadEventSchema = z.object({objectId: z.number(),subscriptionType: z.enum(["object.propertyChange", "object.creation"]),objectTypeId: z.enum(HUBSPOT_OBJECT_TYPE_IDS),+ propertyName: z.string().optional(),+ propertyValue: z.string().optional(),});export const hubSpotSaleEventSchema = z.object({diff --git a/apps/web/lib/integrations/hubspot/ui/settings.tsx b/apps/web/lib/integrations/hubspot/ui/settings.tsxindex 34d42348dd..0144ac616e 100644--- a/apps/web/lib/integrations/hubspot/ui/settings.tsx+++ b/apps/web/lib/integrations/hubspot/ui/settings.tsx@@ -33,6 +33,10 @@ export const HubSpotSettings = ({hubSpotSettings.leadLifecycleStageId,);+ const [leadDealStageId, setLeadDealStageId] = useState(+ hubSpotSettings.leadDealStageId,+ );+const [closedWonDealStageId, setClosedWonDealStageId] = useState(hubSpotSettings.closedWonDealStageId,);@@ -57,6 +61,7 @@ export const HubSpotSettings = ({workspaceId,leadTriggerEvent,leadLifecycleStageId,+ leadDealStageId,closedWonDealStageId,});};@@ -93,6 +98,11 @@ export const HubSpotSettings = ({label: "Lifecycle Stage Reached",description: "Track leads at specific lifecycle stages",},+ {+ key: "dealStageReached",+ label: "Deal Stage Reached",+ description: "Track leads when deals reach a specific stage",+ },]}value={leadTriggerEvent ?? undefined}onChange={(value) => {@@ -101,11 +111,15 @@ export const HubSpotSettings = ({setLeadTriggerEvent(newValue);- if (newValue === "dealCreated") {+ if (newValue !== "lifecycleStageReached") {setLeadLifecycleStageId(null);}++ if (newValue !== "dealStageReached") {+ setLeadDealStageId(null);+ }}}- gridCols="2"+ gridCols="3"/></div>@@ -133,6 +147,30 @@ export const HubSpotSettings = ({</div>)}+ {leadTriggerEvent === "dealStageReached" && (+ <div>+ <label className="mb-2 block text-sm font-semibold text-neutral-700">+ Lead Deal Stage ID+ </label>+ <p className="mb-3 text-sm leading-normal text-neutral-600">+ Enter the HubSpot deal stage ID that represents a qualified+ lead. This will be used to track lead when deals reach this+ stage.+ </p>+ <div className="relative rounded-md shadow-sm">+ <input+ className="w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ placeholder="appointmentscheduled"+ type="text"+ autoComplete="off"+ name="leadDealStageId"+ value={leadDealStageId ?? ""}+ onChange={(e) => setLeadDealStageId(e.target.value)}+ />+ </div>+ </div>+ )}+<div className="border-t border-neutral-200 pt-6"><label className="mb-2 block text-sm font-semibold text-neutral-700">Closed Won Deal Stage IDdiff --git a/apps/web/lib/integrations/hubspot/update-hubspot-settings.ts b/apps/web/lib/integrations/hubspot/update-hubspot-settings.tsindex 83c8e67443..c70443f755 100644--- a/apps/web/lib/integrations/hubspot/update-hubspot-settings.ts+++ b/apps/web/lib/integrations/hubspot/update-hubspot-settings.ts@@ -15,8 +15,26 @@ export const updateHubSpotSettingsAction = authActionClient.inputSchema(schema).action(async ({ parsedInput, ctx }) => {const { workspace } = ctx;- const { leadTriggerEvent, leadLifecycleStageId, closedWonDealStageId } =- parsedInput;+ const {+ leadTriggerEvent,+ leadLifecycleStageId,+ leadDealStageId,+ closedWonDealStageId,+ } = parsedInput;++ if (leadTriggerEvent === "dealStageReached") {+ if (!leadDealStageId) {+ throw new Error("Lead deal stage ID is required.");+ }++ if (+ leadDealStageId.toLowerCase() === closedWonDealStageId?.toLowerCase()+ ) {+ throw new Error(+ "Lead deal stage ID must be different from the closed won deal stage ID.",+ );+ }+ }const installedIntegration = await prisma.installedIntegration.findFirst({where: {@@ -41,7 +59,12 @@ export const updateHubSpotSettingsAction = authActionClientsettings: {...current,leadTriggerEvent,- leadLifecycleStageId,+ leadLifecycleStageId:+ leadTriggerEvent === "lifecycleStageReached"+ ? leadLifecycleStageId+ : null,+ leadDealStageId:+ leadTriggerEvent === "dealStageReached" ? leadDealStageId : null,closedWonDealStageId,},},diff --git a/apps/web/tests/misc/hubspot-event-action.test.ts b/apps/web/tests/misc/hubspot-event-action.test.tsnew file mode 100644index 0000000000..8d18c87764--- /dev/null+++ b/apps/web/tests/misc/hubspot-event-action.test.ts@@ -0,0 +1,371 @@+import { LEAD_TRIGGER_EVENT_OPTIONS } from "@/lib/integrations/hubspot/constants";+import { getHubSpotEventAction } from "@/lib/integrations/hubspot/get-hubspot-event-action";+import { hubSpotSettingsSchema } from "@/lib/integrations/hubspot/schema";+import { describe, expect, it } from "vitest";+import * as z from "zod/v4";++type Settings = z.infer<typeof hubSpotSettingsSchema>;+type Event = Parameters<typeof getHubSpotEventAction>[0]["event"];++const CONTACT = "0-1";+const DEAL = "0-3";++const settings = (overrides: Partial<Settings> = {}) =>+ hubSpotSettingsSchema.parse(overrides);++const contactCreated: Event = {+ objectTypeId: CONTACT,+ subscriptionType: "object.creation",+};++const contactPropertyChanged = (+ propertyName?: string,+ propertyValue?: string,+): Event => ({+ objectTypeId: CONTACT,+ subscriptionType: "object.propertyChange",+ propertyName,+ propertyValue,+});++const dealCreated: Event = {+ objectTypeId: DEAL,+ subscriptionType: "object.creation",+};++const dealPropertyChanged = (+ propertyName?: string,+ propertyValue?: string,+): Event => ({+ objectTypeId: DEAL,+ subscriptionType: "object.propertyChange",+ propertyName,+ propertyValue,+});++const dealStageChanged = (stage?: string) =>+ dealPropertyChanged("dealstage", stage);++describe("getHubSpotEventAction", () => {+ describe("default settings", () => {+ it("defaults to the dealCreated trigger and the closedwon stage", () => {+ const defaults = settings();++ expect(defaults.leadTriggerEvent).toBe("dealCreated");+ expect(defaults.closedWonDealStageId).toBe("closedwon");++ expect(+ getHubSpotEventAction({ event: dealCreated, settings: defaults }),+ ).toBe("trackLead");+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("closedwon"),+ settings: defaults,+ }),+ ).toBe("trackSale");+ });+ });++ describe("contact events", () => {+ it.each(LEAD_TRIGGER_EVENT_OPTIONS)(+ "tracks the deferred lead for a new contact when the trigger is %s",+ (leadTriggerEvent) => {+ expect(+ getHubSpotEventAction({+ event: contactCreated,+ settings: settings({ leadTriggerEvent }),+ }),+ ).toBe("trackLead");+ },+ );++ it.each([+ ["lifecyclestage", "customer"],+ ["lifecyclestage", undefined],+ ["phone", "123"],+ [undefined, undefined],+ ])(+ "tracks the lead for any contact property change (%s = %s) when the trigger is lifecycleStageReached",+ (propertyName, propertyValue) => {+ expect(+ getHubSpotEventAction({+ event: contactPropertyChanged(propertyName, propertyValue),+ settings: settings({+ leadTriggerEvent: "lifecycleStageReached",+ leadLifecycleStageId: "customer",+ }),+ }),+ ).toBe("trackLead");+ },+ );++ it.each(["dealCreated", "dealStageReached"] as const)(+ "skips contact property changes when the trigger is %s",+ (leadTriggerEvent) => {+ expect(+ getHubSpotEventAction({+ event: contactPropertyChanged("lifecyclestage", "customer"),+ settings: settings({ leadTriggerEvent }),+ }),+ ).toBe("skip");+ },+ );++ it("never tracks a sale for a contact, even when the value matches the closed won stage", () => {+ expect(+ getHubSpotEventAction({+ event: contactPropertyChanged("dealstage", "closedwon"),+ settings: settings({ leadTriggerEvent: "dealCreated" }),+ }),+ ).toBe("skip");+ });+ });++ describe("deal created", () => {+ it("tracks the lead when the trigger is dealCreated", () => {+ expect(+ getHubSpotEventAction({+ event: dealCreated,+ settings: settings({ leadTriggerEvent: "dealCreated" }),+ }),+ ).toBe("trackLead");+ });++ it.each(["lifecycleStageReached", "dealStageReached"] as const)(+ "skips when the trigger is %s",+ (leadTriggerEvent) => {+ expect(+ getHubSpotEventAction({+ event: dealCreated,+ settings: settings({+ leadTriggerEvent,+ leadDealStageId: "appointmentscheduled",+ }),+ }),+ ).toBe("skip");+ },+ );+ });++ describe("deal property changed", () => {+ it.each([+ ["amount", "closedwon"],+ ["dealname", "appointmentscheduled"],+ [undefined, "closedwon"],+ ])(+ "skips when the changed property is %s, even if the value matches a configured stage",+ (propertyName, propertyValue) => {+ expect(+ getHubSpotEventAction({+ event: dealPropertyChanged(propertyName, propertyValue),+ settings: settings({+ leadTriggerEvent: "dealStageReached",+ leadDealStageId: "appointmentscheduled",+ }),+ }),+ ).toBe("skip");+ },+ );++ describe("closed won sale", () => {+ it.each(LEAD_TRIGGER_EVENT_OPTIONS)(+ "tracks the sale when the deal moves to the closed won stage and the trigger is %s",+ (leadTriggerEvent) => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("closedwon"),+ settings: settings({+ leadTriggerEvent,+ leadDealStageId:+ leadTriggerEvent === "dealStageReached"+ ? "appointmentscheduled"+ : undefined,+ }),+ }),+ ).toBe("trackSale");+ },+ );++ it("matches the closed won stage case-insensitively", () => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("ClosedWon"),+ settings: settings({ closedWonDealStageId: "CLOSEDWON" }),+ }),+ ).toBe("trackSale");+ });++ it("uses a custom closed won stage ID instead of the default", () => {+ const custom = settings({ closedWonDealStageId: "12345" });++ expect(+ getHubSpotEventAction({+ event: dealStageChanged("12345"),+ settings: custom,+ }),+ ).toBe("trackSale");+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("closedwon"),+ settings: custom,+ }),+ ).toBe("skip");+ });++ it.each(["closedwon", "", undefined])(+ "skips when closedWonDealStageId is null and the new stage is %s",+ (stage) => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged(stage),+ settings: settings({ closedWonDealStageId: null }),+ }),+ ).toBe("skip");+ },+ );++ it.each(["", undefined])(+ "skips an empty stage change when closedWonDealStageId is an empty string (stage = %s)",+ (stage) => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged(stage),+ settings: settings({ closedWonDealStageId: "" }),+ }),+ ).toBe("skip");+ },+ );++ it("skips when the new stage is neither the lead stage nor the closed won stage", () => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("contractsent"),+ settings: settings(),+ }),+ ).toBe("skip");+ });+ });++ describe("dealStageReached lead", () => {+ const dealStageSettings = settings({+ leadTriggerEvent: "dealStageReached",+ leadDealStageId: "appointmentscheduled",+ });++ it("tracks the lead when the deal moves to the lead deal stage", () => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("appointmentscheduled"),+ settings: dealStageSettings,+ }),+ ).toBe("trackLead");+ });++ it("matches the lead deal stage case-insensitively", () => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("AppointmentScheduled"),+ settings: settings({+ leadTriggerEvent: "dealStageReached",+ leadDealStageId: "APPOINTMENTSCHEDULED",+ }),+ }),+ ).toBe("trackLead");+ });++ it("skips when the deal moves to a different stage", () => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("qualifiedtobuy"),+ settings: dealStageSettings,+ }),+ ).toBe("skip");+ });++ it("skips when the stage change has no value", () => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged(undefined),+ settings: dealStageSettings,+ }),+ ).toBe("skip");+ });++ it.each(["dealCreated", "lifecycleStageReached"] as const)(+ "ignores a stored leadDealStageId when the trigger is %s",+ (leadTriggerEvent) => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("appointmentscheduled"),+ settings: settings({+ leadTriggerEvent,+ leadDealStageId: "appointmentscheduled",+ }),+ }),+ ).toBe("skip");+ },+ );++ it.each([null, undefined, ""])(+ "never tracks a lead when leadDealStageId is %s",+ (leadDealStageId) => {+ const noLeadStage = settings({+ leadTriggerEvent: "dealStageReached",+ leadDealStageId,+ });++ expect(+ getHubSpotEventAction({+ event: dealStageChanged(""),+ settings: noLeadStage,+ }),+ ).toBe("skip");+ expect(+ getHubSpotEventAction({+ event: dealStageChanged(undefined),+ settings: noLeadStage,+ }),+ ).toBe("skip");+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("closedwon"),+ settings: noLeadStage,+ }),+ ).toBe("trackSale");+ },+ );++ it("prefers the lead over the sale when both stages are the same", () => {+ expect(+ getHubSpotEventAction({+ event: dealStageChanged("closedwon"),+ settings: settings({+ leadTriggerEvent: "dealStageReached",+ leadDealStageId: "closedwon",+ closedWonDealStageId: "closedwon",+ }),+ }),+ ).toBe("trackLead");+ });+ });+ });++ describe("unknown object type", () => {+ it.each(["object.creation", "object.propertyChange"] as const)(+ "skips %s events for an unsupported object type",+ (subscriptionType) => {+ expect(+ getHubSpotEventAction({+ event: {+ objectTypeId: "0-2" as Event["objectTypeId"],+ subscriptionType,+ propertyName: "dealstage",+ propertyValue: "closedwon",+ },+ settings: settings(),+ }),+ ).toBe("skip");+ },+ );+ });+});