Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions apps/web/app/(ee)/api/cron/import/lemonsqueezy/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { withCron } from "@/lib/cron/with-cron";
import { importCommissions } from "@/lib/lemonsqueezy/import-commissions";
import { importCustomers } from "@/lib/lemonsqueezy/import-customers";
import { importPartners } from "@/lib/lemonsqueezy/import-partners";
import { lemonSqueezyImportPayloadSchema } from "@/lib/lemonsqueezy/schemas";
import { logAndRespond } from "../../utils";

export const dynamic = "force-dynamic";

export const POST = withCron(async ({ rawBody }) => {
const payload = lemonSqueezyImportPayloadSchema.parse(JSON.parse(rawBody));

switch (payload.action) {
case "import-partners":
await importPartners(payload);
break;
case "import-customers":
await importCustomers(payload);
break;
case "import-commissions":
await importCommissions(payload);
break;
}

return logAndRespond("OK");
});
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";
import { getCheckoutSessionProducts } from "./utils/get-checkout-session-products";
import { getConnectedCustomer } from "./utils/get-connected-customer";
import { getDubCustomerExternalIdFromMetadata } from "./utils/get-dub-customer-external-id-from-metadata";
import { incrementLinkLeads } from "./utils/increment-link-leads";
import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";

Expand All @@ -36,9 +37,9 @@ export async function checkoutSessionCompleted({
workspace,
}: WebhookHandlerInput<Stripe.CheckoutSessionCompletedEvent>): Promise<WebhookHandlerResponse> {
let checkoutSession = event.data.object;
let dubCustomerExternalId =
checkoutSession.metadata?.dubCustomerExternalId ||
checkoutSession.metadata?.dubCustomerId;
let dubCustomerExternalId = getDubCustomerExternalIdFromMetadata(
checkoutSession.metadata,
);
const clientReferenceId = checkoutSession.client_reference_id;
const stripeAccountId = event.account as string;
const stripeCustomerId = checkoutSession.customer as string;
Expand Down Expand Up @@ -250,8 +251,7 @@ export async function checkoutSessionCompleted({
});

const connectedCustomerDubCustomerExternalId =
connectedCustomer?.metadata.dubCustomerExternalId ||
connectedCustomer?.metadata.dubCustomerId;
getDubCustomerExternalIdFromMetadata(connectedCustomer?.metadata);

if (connectedCustomerDubCustomerExternalId) {
dubCustomerExternalId = connectedCustomerDubCustomerExternalId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type Stripe from "stripe";
import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";
import { getConnectedCustomer } from "./utils/get-connected-customer";
import { getDubCustomerExternalIdFromMetadata } from "./utils/get-dub-customer-external-id-from-metadata";

// Handle event "invoice.paid"
export async function invoicePaid({
Expand Down Expand Up @@ -57,9 +58,9 @@ export async function invoicePaid({
mode,
});

const dubCustomerExternalId =
connectedCustomer?.metadata.dubCustomerExternalId ||
connectedCustomer?.metadata.dubCustomerId;
const dubCustomerExternalId = getDubCustomerExternalIdFromMetadata(
connectedCustomer?.metadata,
);

if (dubCustomerExternalId) {
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Resolve Dub customer.externalId from Stripe object metadata.
* Precedence:
* 1. dubCustomerExternalId
* 2. dubCustomerId
* 3. user_id (Lemon Squeezy customer id after LS → Stripe migration)
*/
export function getDubCustomerExternalIdFromMetadata(
metadata?: Record<string, string> | null,
): string | undefined {
if (!metadata) return undefined;

const value =
metadata.dubCustomerExternalId ||
metadata.dubCustomerId ||
metadata.user_id;

if (value == null || value === "") return undefined;

return String(value);
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { WebhookHandlerInput, WebhookHandlerResponse } from "../types";
import { getDubCustomerExternalIdFromMetadata } from "./get-dub-customer-external-id-from-metadata";

export async function syncCustomer({
event,
Expand All @@ -28,9 +29,9 @@ export async function syncCustomer({
>): Promise<WebhookHandlerResponse> {
const stripeCustomer = event.data.object;
const stripeAccountId = event.account as string;
const dubCustomerExternalId =
stripeCustomer.metadata?.dubCustomerExternalId ||
stripeCustomer.metadata?.dubCustomerId;
const dubCustomerExternalId = getDubCustomerExternalIdFromMetadata(
stripeCustomer.metadata,
);
const clickId = stripeCustomer.metadata?.dubClickId;

console.log(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { PROGRAM_IMPORT_SOURCES } from "@/lib/constants/program";
import useWorkspace from "@/lib/swr/use-workspace";
import { useExportPartnersModal } from "@/ui/modals/export-partners-modal";
import { useImportFirstPromoterModal } from "@/ui/modals/import-firstpromoter-modal";
import { useImportLemonSqueezyModal } from "@/ui/modals/import-lemonsqueezy-modal";
import { useImportPartnerStackModal } from "@/ui/modals/import-partnerstack-modal";
import { useImportRewardfulModal } from "@/ui/modals/import-rewardful-modal";
import { useImportTapfiliateModal } from "@/ui/modals/import-tapfiliate-modal";
Expand All @@ -23,6 +24,7 @@ export function PartnersMenuPopover() {
const { ImportPartnerStackModal } = useImportPartnerStackModal();
const { ImportFirstPromoterModal } = useImportFirstPromoterModal();
const { ImportTapfiliateModal } = useImportTapfiliateModal();
const { ImportLemonSqueezyModal } = useImportLemonSqueezyModal();

const { ExportPartnersModal, setShowExportPartnersModal } =
useExportPartnersModal();
Expand All @@ -34,6 +36,7 @@ export function PartnersMenuPopover() {
<ImportFirstPromoterModal />
<ImportPartnerStackModal />
<ImportTapfiliateModal />
<ImportLemonSqueezyModal />
<ExportPartnersModal />
<Popover
content={
Expand Down
50 changes: 50 additions & 0 deletions apps/web/lib/actions/partners/set-lemonsqueezy-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"use server";

import { LemonSqueezyApi } from "@/lib/lemonsqueezy/api";
import { lemonSqueezyImporter } from "@/lib/lemonsqueezy/importer";
import { LemonSqueezyStore } from "@/lib/lemonsqueezy/types";
import * as z from "zod/v4";
import { authActionClient } from "../safe-action";
import { throwIfNoPermission } from "../throw-if-no-permission";

const schema = z.object({
workspaceId: z.string(),
apiKey: z.string().trim().min(1),
});

export const setLemonSqueezyTokenAction = authActionClient
.inputSchema(schema)
.action(async ({ parsedInput, ctx }) => {
const { workspace } = ctx;
const { apiKey } = parsedInput;

throwIfNoPermission({
role: workspace.role,
requiredRoles: ["owner", "member"],
});

const lemonSqueezyApi = new LemonSqueezyApi({
apiKey,
});

let stores: LemonSqueezyStore[];

try {
stores = await lemonSqueezyApi.listStores();
} catch (error) {
console.error(error);
throw new Error("Invalid Lemon Squeezy API key.");
}

if (stores.length === 0) {
throw new Error("No stores found in your Lemon Squeezy account.");
}

await lemonSqueezyImporter.setCredentials(workspace.id, {
apiKey,
});

return {
stores,
};
});
62 changes: 62 additions & 0 deletions apps/web/lib/actions/partners/start-lemonsqueezy-import.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"use server";

import { createId } from "@/lib/api/create-id";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { LemonSqueezyApi } from "@/lib/lemonsqueezy/api";
import { lemonSqueezyImporter } from "@/lib/lemonsqueezy/importer";
import * as z from "zod/v4";
import { getProgramOrThrow } from "../../api/programs/get-program-or-throw";
import { authActionClient } from "../safe-action";
import { throwIfNoPermission } from "../throw-if-no-permission";

const schema = z.object({
workspaceId: z.string(),
storeId: z.string().trim().min(1),
});

export const startLemonSqueezyImportAction = authActionClient
.inputSchema(schema)
.action(async ({ ctx, parsedInput }) => {
const { workspace, user } = ctx;
const { storeId } = parsedInput;

throwIfNoPermission({
role: workspace.role,
requiredRoles: ["owner", "member"],
});

const programId = getDefaultProgramIdOrThrow(workspace);

const program = await getProgramOrThrow({
workspaceId: workspace.id,
programId,
});

if (!program.domain) {
throw new Error("Program domain is not set.");
}

if (!program.url) {
throw new Error("Program URL is not set.");
}

const credentials = await lemonSqueezyImporter.getCredentials(workspace.id);

const lemonSqueezyApi = new LemonSqueezyApi({
apiKey: credentials.apiKey,
});

const stores = await lemonSqueezyApi.listStores();

if (!stores.some((store) => store.id === storeId)) {
throw new Error("Invalid Lemon Squeezy store ID.");
}

await lemonSqueezyImporter.queue({
importId: createId({ prefix: "import_" }),
userId: user.id,
programId: program.id,
storeId,
action: "import-partners",
});
});
6 changes: 6 additions & 0 deletions apps/web/lib/constants/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ export const PROGRAM_IMPORT_SOURCES = [
image: "https://assets.dub.co/misc/icons/tapfiliate.svg",
helpUrl: "https://dub.co/help/article/migrating-from-tapfiliate",
},
{
id: "lemonsqueezy",
value: "Lemon Squeezy",
image: "https://assets.dub.co/misc/icons/lemonsqueezy.svg",
helpUrl: "https://dub.co/help/article/migrating-from-lemonsqueezy",
},
Comment thread
coderabbitai[bot] marked this conversation as resolved.
] as const;

export const PROGRAM_APPLICATION_IMAGE_MAX_FILE_SIZE_MB = 5;
Expand Down
Loading
Loading