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.

2.0 KB
Raw Blame
"use server";

import { authActionClient } from "@/lib/actions/safe-action";
import { prisma } from "@/lib/prisma";
import { HUBSPOT_INTEGRATION_ID } from "@dub/utils";
import { revalidatePath } from "next/cache";
import * as z from "zod/v4";
import { hubSpotSettingsSchema } from "./schema";

const schema = hubSpotSettingsSchema.extend({
  workspaceId: z.string(),
});

export const updateHubSpotSettingsAction = authActionClient
  .inputSchema(schema)
  .action(async ({ parsedInput, ctx }) => {
    const { workspace } = ctx;
    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: {
        integrationId: HUBSPOT_INTEGRATION_ID,
        projectId: workspace.id,
      },
    });

    if (!installedIntegration) {
      throw new Error(
        "HubSpot integration is not installed on your workspace.",
      );
    }

    const current = (installedIntegration.settings as any) ?? {};

    await prisma.installedIntegration.update({
      where: {
        id: installedIntegration.id,
      },
      data: {
        settings: {
          ...current,
          leadTriggerEvent,
          leadLifecycleStageId:
            leadTriggerEvent === "lifecycleStageReached"
              ? leadLifecycleStageId
              : null,
          leadDealStageId:
            leadTriggerEvent === "dealStageReached" ? leadDealStageId : null,
          closedWonDealStageId,
        },
      },
    });

    revalidatePath(`/${workspace.slug}/settings/integrations/hubspot`);
  });