πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(sfdc): add plan and lead sources to SFDC sync and prep backfill script (#14505)
Steffen Schmitz85d233edc65e
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 38186c1096..1700440fa6 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -956,6 +956,9 @@ importers:tailwindcss:specifier: ^4.2.2version: 4.2.2+ tsx:+ specifier: ^4.20.5+ version: 4.20.5typescript:specifier: 'catalog:'version: 6.0.3diff --git a/web/package.json b/web/package.jsonindex 6dbe0acabb..714b783459 100644--- a/web/package.json+++ b/web/package.json@@ -26,7 +26,8 @@"test:e2e:server": "vitest run --project e2e-server","build-trace": "dotenv -e ../.env -- next internal trace .next/trace-turbopack","storybook": "dotenv -e ../.env -- storybook dev -p 6006",- "build-storybook": "dotenv -e ../.env -- storybook build"+ "build-storybook": "dotenv -e ../.env -- storybook build",+ "sfdc:backfill": "dotenv -e ../.env -- tsx src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.ts"},"dependencies": {"@ag-ui/client": "^0.0.52",@@ -212,6 +213,7 @@"raw-loader": "^4.0.2","storybook": "10.3.6","tailwindcss": "^4.2.2",+ "tsx": "^4.20.5","typescript": "catalog:","vite": "^7.3.5","vite-tsconfig-paths": "^6.1.1",diff --git a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts b/web/src/__tests__/server/unit/sfdc-sync.servertest.tsindex 1bf6f27fe2..700d1dd13c 100644--- a/web/src/__tests__/server/unit/sfdc-sync.servertest.ts+++ b/web/src/__tests__/server/unit/sfdc-sync.servertest.ts@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from "vitest";+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";// ---- Hoisted mocks ----@@ -26,7 +26,7 @@ const { envMock, prismaMock, loggerMock, fetchMock } = vi.hoisted(() => {},prismaMock: {user: {- findUnique: vi.fn(async (): Promise<unknown> => null),+ findUnique: vi.fn(async (_args?: unknown): Promise<unknown> => null),update: vi.fn(async () => ({})),},organization: {@@ -35,23 +35,42 @@ const { envMock, prismaMock, loggerMock, fetchMock } = vi.hoisted(() => {),update: vi.fn(async () => ({})),create: vi.fn(- async (): Promise<unknown> => ({ id: "org-new", name: "New Org" }),+ async (): Promise<unknown> => ({+ id: "org-new",+ name: "New Org",+ createdAt: new Date("2026-06-01T08:30:00.900Z"),+ }),),},organizationMembership: {findFirst: vi.fn(async (): Promise<unknown> => null),+ findMany: vi.fn(async (): Promise<unknown[]> => []),count: vi.fn(async () => 1),+ create: vi.fn(async (): Promise<unknown> => ({})),update: vi.fn(async (): Promise<unknown> => ({})),upsert: vi.fn(async (): Promise<unknown> => ({})),},+ membershipInvitation: {+ findFirst: vi.fn(async (): Promise<unknown> => null),+ findMany: vi.fn(async (): Promise<unknown[]> => []),+ deleteMany: vi.fn(async () => ({ count: 0 })),+ },+ project: {+ findUnique: vi.fn(async (): Promise<unknown> => null),+ create: vi.fn(async (): Promise<unknown> => ({ id: "proj-new" })),+ },auditLog: {create: vi.fn(async () => ({})),},- // tRPC organizations.create wraps its writes in a transaction; run the- // callback with prismaMock standing in for the tx client.+ // Starter-org provisioning serializes on SELECT ... FOR UPDATE.+ $queryRaw: vi.fn(async (): Promise<unknown> => []),+ // tRPC organizations.create wraps its writes in a callback transaction;+ // invitation processing uses the array form β support both.$transaction: vi.fn(- async (cb: (tx: unknown) => Promise<unknown>): Promise<unknown> =>- cb(prismaMock),+ async (+ arg: ((tx: unknown) => Promise<unknown>) | Promise<unknown>[],+ ): Promise<unknown> =>+ Array.isArray(arg) ? Promise.all(arg) : arg(prismaMock),),},loggerMock: {@@ -99,11 +118,14 @@ import {SfdcService,getSfdcService,resetSfdcServiceCacheForTests,+ toSfdcPlan,+ syncOrgPlanChangeToSfdc,} from "@/src/ee/features/sfdc-sync/server";+import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/createProjectMembershipsOnSignup";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { handleUpdateMembership } from "@/src/ee/features/admin-api/server/memberships";-import { Role } from "@langfuse/shared";+import { CloudConfigSchema, Role } from "@langfuse/shared";import { type PrismaClient } from "@langfuse/shared/src/db";import type { Session } from "next-auth";import { type NextApiRequest, type NextApiResponse } from "next";@@ -129,6 +151,40 @@ function expectedBasicAuthHeader(): string {return "Basic " + Buffer.from("mule-user:mule-pass").toString("base64");}+// Fixed dates with millisecond components β payload asserts verify the wire+// formats: user dates are seconds-precision ISO UTC (millis stripped), org+// dates are date-only (the SFDC org fields are Date-typed and reject+// datetimes).+const SIGNUP_AT = new Date("2026-07-08T09:41:23.123Z");+const SIGNUP_AT_ISO_SECONDS = "2026-07-08T09:41:23Z";+const ORG_CREATED_AT = new Date("2026-06-01T08:30:00.900Z");+const ORG_CREATED_AT_ISO_DATE = "2026-06-01";+const CONVERTED_AT = new Date("2026-06-15T12:00:00.450Z");+const CONVERTED_AT_ISO_DATE = "2026-06-15";++/** Minimal valid upsertUser input; tests override what they assert on. */+function upsertUserInput(overrides: Record<string, unknown> = {}) {+ return {+ userId: "user-123",+ email: "[email protected]",+ name: "Test User",+ createdAt: SIGNUP_AT,+ leadSource: "Langfuse Cloud Signup" as const,+ ...overrides,+ };+}++/** Minimal valid upsertOrg input; tests override what they assert on. */+function upsertOrgInput(overrides: Record<string, unknown> = {}) {+ return {+ orgId: "org-1",+ orgName: "Org One",+ createdAt: ORG_CREATED_AT,+ plan: "Hobby" as const,+ ...overrides,+ };+}+beforeEach(() => {vi.clearAllMocks();resetSfdcServiceCacheForTests();@@ -163,15 +219,11 @@ describe("SfdcService β factory gating", () => {});describe("SfdcService.upsertUser", () => {- it("sends isLangfuse + companyName sentinel + basic-auth", async () => {+ it("sends isLangfuse + companyName sentinel + signup date + lead source + basic-auth", async () => {fetchMock.mockResolvedValueOnce(emptyOkResponse());const sfdc = SfdcService.tryCreate();expect(sfdc).not.toBeNull();- await sfdc!.upsertUser({- userId: "user-123",- email: "[email protected]",- name: "Test User",- });+ await sfdc!.upsertUser(upsertUserInput());expect(fetchMock).toHaveBeenCalledOnce();const [url, init] = fetchMock.mock.calls[0];expect(url).toBe("https://mulesoft.test/manage-user");@@ -185,17 +237,26 @@ describe("SfdcService.upsertUser", () => {email: "[email protected]",fullName: "Test User",companyName: envMock.MULESOFT_SFDC_DEFAULT_COMPANY_NAME,+ // Mulesoft date contract: ISO UTC, seconds precision, no millis.+ createdAt: SIGNUP_AT_ISO_SECONDS,+ leadSource: "Langfuse Cloud Signup",});});+ it("passes the invite lead source through verbatim", async () => {+ fetchMock.mockResolvedValueOnce(emptyOkResponse());+ await SfdcService.tryCreate()!.upsertUser(+ upsertUserInput({ leadSource: "Langfuse Cloud Invite" }),+ );+ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);+ expect(body.leadSource).toBe("Langfuse Cloud Invite");+ });+it("uses caller-provided companyName when given", async () => {fetchMock.mockResolvedValueOnce(emptyOkResponse());- await SfdcService.tryCreate()!.upsertUser({- userId: "u1",- email: "[email protected]",- name: "U",- companyName: "Acme Inc",- });+ await SfdcService.tryCreate()!.upsertUser(+ upsertUserInput({ companyName: "Acme Inc" }),+ );const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);expect(body.companyName).toBe("Acme Inc");});@@ -204,22 +265,14 @@ describe("SfdcService.upsertUser", () => {"falls back to email as fullName when name is %s",async (name) => {fetchMock.mockResolvedValueOnce(emptyOkResponse());- await SfdcService.tryCreate()!.upsertUser({- userId: "u1",- email: "[email protected]",- name,- });+ await SfdcService.tryCreate()!.upsertUser(upsertUserInput({ name }));const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);expect(body.fullName).toBe("[email protected]");},);it("skips without calling fetch when email is missing", async () => {- await SfdcService.tryCreate()!.upsertUser({- userId: "u1",- email: null,- name: "U",- });+ await SfdcService.tryCreate()!.upsertUser(upsertUserInput({ email: null }));expect(fetchMock).not.toHaveBeenCalled();expect(loggerMock.warn).toHaveBeenCalled();});@@ -228,11 +281,7 @@ describe("SfdcService.upsertUser", () => {// /manage-user never returns JSON or an id; CH Cloud discards this// response too.fetchMock.mockResolvedValueOnce(new Response("Success", { status: 200 }));- await SfdcService.tryCreate()!.upsertUser({- userId: "user-42",- email: "[email protected]",- name: "U",- });+ await SfdcService.tryCreate()!.upsertUser(upsertUserInput());expect(loggerMock.warn).not.toHaveBeenCalled();expect(loggerMock.error).not.toHaveBeenCalled();expect(prismaMock.user.update).not.toHaveBeenCalled();@@ -240,11 +289,7 @@ describe("SfdcService.upsertUser", () => {it("does not throw on non-2xx; logs an error instead", async () => {fetchMock.mockResolvedValueOnce(nonOkResponse(500));- await SfdcService.tryCreate()!.upsertUser({- userId: "user-42",- email: "[email protected]",- name: "U",- });+ await SfdcService.tryCreate()!.upsertUser(upsertUserInput());expect(loggerMock.error).toHaveBeenCalled();expect(prismaMock.user.update).not.toHaveBeenCalled();});@@ -252,22 +297,16 @@ describe("SfdcService.upsertUser", () => {it("does not throw on fetch network error; logs an error instead", async () => {fetchMock.mockRejectedValueOnce(new Error("ECONNRESET"));await expect(- SfdcService.tryCreate()!.upsertUser({- userId: "user-42",- email: "[email protected]",- name: "U",- }),+ SfdcService.tryCreate()!.upsertUser(upsertUserInput()),).resolves.toBeUndefined();expect(loggerMock.error).toHaveBeenCalled();});it("never rejects on invalid email β logs warn and skips fetch", async () => {await expect(- SfdcService.tryCreate()!.upsertUser({- userId: "u",- email: "not-an-email",- name: "U",- }),+ SfdcService.tryCreate()!.upsertUser(+ upsertUserInput({ email: "not-an-email" }),+ ),).resolves.toBeUndefined();expect(fetchMock).not.toHaveBeenCalled();expect(loggerMock.warn).toHaveBeenCalled();@@ -275,15 +314,9 @@ describe("SfdcService.upsertUser", () => {});describe("SfdcService.upsertOrg", () => {- it("sends type:updateOrg + isLangfuse + mapped role", async () => {+ it("sends the org-only updateOrg payload β created date + tier, no user fields", async () => {fetchMock.mockResolvedValueOnce(emptyOkResponse());- await SfdcService.tryCreate()!.upsertOrg({- orgId: "org-1",- orgName: "Org One",- userId: "user-1",- email: "[email protected]",- role: "OWNER",- });+ await SfdcService.tryCreate()!.upsertOrg(upsertOrgInput({ plan: "Pro" }));const [url, init] = fetchMock.mock.calls[0];expect(url).toBe("https://mulesoft.test/manage-org");const body = JSON.parse(init.body as string);@@ -292,9 +325,8 @@ describe("SfdcService.upsertOrg", () => {type: "updateOrg",orgId: "org-1",orgName: "Org One",- userId: "user-1",- email: "[email protected]",- role: "ADMIN",+ createdAt: ORG_CREATED_AT_ISO_DATE,+ plan: "Pro",// Cloud region the org lives in, sourced from NEXT_PUBLIC_LANGFUSE_CLOUD_REGION.langfuseDataRegion: "STAGING",// Mulesoft's updateOrg flow 500s when the CH service counts are@@ -303,31 +335,37 @@ describe("SfdcService.upsertOrg", () => {numServicesGcp: 0,numServicesAzure: 0,});+ // Mulesoft ignores user fields on updateOrg β they must not be sent.+ expect(body).not.toHaveProperty("userId");+ expect(body).not.toHaveProperty("email");+ expect(body).not.toHaveProperty("role");+ // Never converted β the field is omitted, not sent as null.+ expect(body).not.toHaveProperty("convertedToPaidAt");+ });++ it("sends convertedToPaidAt (date-only) when the org has converted", async () => {+ fetchMock.mockResolvedValueOnce(emptyOkResponse());+ await SfdcService.tryCreate()!.upsertOrg(+ upsertOrgInput({ plan: "Team", convertedToPaidAt: CONVERTED_AT }),+ );+ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);+ expect(body.plan).toBe("Team");+ expect(body.convertedToPaidAt).toBe(CONVERTED_AT_ISO_DATE);});it("sends langfuseDataRegion from NEXT_PUBLIC_LANGFUSE_CLOUD_REGION", async () => {envMock.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "EU";fetchMock.mockResolvedValueOnce(emptyOkResponse());- await SfdcService.tryCreate()!.upsertOrg({- orgId: "org-1",- orgName: "Org One",- userId: "user-1",- email: "[email protected]",- role: "OWNER",- });+ await SfdcService.tryCreate()!.upsertOrg(upsertOrgInput());const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);expect(body.langfuseDataRegion).toBe("EU");});it("persists sfdcOrgId on 2xx with id in response", async () => {fetchMock.mockResolvedValueOnce(okJsonResponse({ sfdcOrgId: "sfdc-o-9" }));- await SfdcService.tryCreate()!.upsertOrg({- orgId: "org-9",- orgName: "Org Nine",- userId: "user-1",- email: "[email protected]",- role: "OWNER",- });+ await SfdcService.tryCreate()!.upsertOrg(+ upsertOrgInput({ orgId: "org-9" }),+ );expect(prismaMock.organization.update).toHaveBeenCalledWith({where: { id: "org-9" },data: { sfdcOrgId: "sfdc-o-9" },@@ -336,13 +374,9 @@ describe("SfdcService.upsertOrg", () => {it("does not persist when the response omits sfdcOrgId", async () => {fetchMock.mockResolvedValueOnce(okJsonResponse({}));- await SfdcService.tryCreate()!.upsertOrg({- orgId: "org-9",- orgName: "Org Nine",- userId: "user-1",- email: "[email protected]",- role: "OWNER",- });+ await SfdcService.tryCreate()!.upsertOrg(+ upsertOrgInput({ orgId: "org-9" }),+ );expect(prismaMock.organization.update).not.toHaveBeenCalled();});@@ -351,13 +385,9 @@ describe("SfdcService.upsertOrg", () => {sfdcOrgId: "sfdc-old",});fetchMock.mockResolvedValueOnce(okJsonResponse({ sfdcOrgId: "sfdc-new" }));- await SfdcService.tryCreate()!.upsertOrg({- orgId: "org-9",- orgName: "Org Nine",- userId: "user-1",- email: "[email protected]",- role: "OWNER",- });+ await SfdcService.tryCreate()!.upsertOrg(+ upsertOrgInput({ orgId: "org-9" }),+ );expect(loggerMock.error).toHaveBeenCalledWith(expect.stringContaining("sfdcOrgId changed"),expect.objectContaining({@@ -376,18 +406,31 @@ describe("SfdcService.upsertOrg", () => {new Error("db down"),);await expect(- SfdcService.tryCreate()!.upsertOrg({- orgId: "org-9",- orgName: "Org Nine",- userId: "user-1",- email: "[email protected]",- role: "OWNER",- }),+ SfdcService.tryCreate()!.upsertOrg(upsertOrgInput({ orgId: "org-9" })),).resolves.toBeUndefined();expect(loggerMock.error).toHaveBeenCalled();});});+describe("toSfdcPlan β resolved entitlement plan to SFDC tier picklist", () => {+ it.each([+ ["cloud:hobby", "Hobby"],+ ["cloud:core", "Core"],+ ["cloud:pro", "Pro"],+ ["cloud:team", "Team"],+ ["cloud:enterprise", "Enterprise"],+ ] as const)("maps %s to %s", (plan, sfdcPlan) => {+ expect(toSfdcPlan(plan)).toBe(sfdcPlan);+ });++ it.each(["oss", "self-hosted:pro", "self-hosted:enterprise"] as const)(+ "returns null for non-cloud plan %s",+ (plan) => {+ expect(toSfdcPlan(plan)).toBeNull();+ },+ );+});+describe("SfdcService.setUserRole β Langfuse roles map onto the SFDC picklist", () => {// SFDC only accepts ADMIN and DEVELOPER as org-member roles.it.each([@@ -476,6 +519,125 @@ describe("SfdcService.removeUser", () => {});});+describe("syncOrgPlanChangeToSfdc β plan-change gate for billing updates", () => {+ // Stripe product ids from the catalogue (identical in sandbox and live).+ const PRO_PRODUCT = "prod_QhK7UMhrkVeF6R";+ const TEAM_PRODUCT = "prod_QhK9qKGH25BTcS";++ // getOrganizationPlanServerSide reads process.env directly (not env.mjs),+ // so the region must be stubbed on the real process env.+ const originalRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ beforeEach(() => {+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "STAGING";+ });+ afterEach(() => {+ if (originalRegion === undefined) {+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ } else {+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ }+ });++ const orgBefore = (cloudConfig: unknown) => ({+ id: "org-1",+ name: "Org One",+ createdAt: ORG_CREATED_AT,+ cloudConfig:+ cloudConfig === null ? null : CloudConfigSchema.parse(cloudConfig),+ });++ const stripeConfig = (productId: string) => ({+ stripe: {+ customerId: "cus_1",+ activeSubscriptionId: "sub_1",+ activeProductId: productId,+ activeUsageProductId: "prod_usage",+ subscriptionStatus: "active",+ },+ });++ it("pushes tier + conversion date on the first upgrade from Hobby", async () => {+ fetchMock.mockResolvedValueOnce(emptyOkResponse());+ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: orgBefore(null),+ updatedCloudConfig: stripeConfig(PRO_PRODUCT),+ billingCycleAnchor: CONVERTED_AT,+ });+ expect(fetchMock).toHaveBeenCalledOnce();+ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);+ expect(body).toMatchObject({+ type: "updateOrg",+ orgId: "org-1",+ orgName: "Org One",+ createdAt: ORG_CREATED_AT_ISO_DATE,+ plan: "Pro",+ convertedToPaidAt: CONVERTED_AT_ISO_DATE,+ });+ expect(body).not.toHaveProperty("userId");+ });++ it("pushes tier switches between paid plans, keeping the conversion date", async () => {+ fetchMock.mockResolvedValueOnce(emptyOkResponse());+ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: orgBefore(stripeConfig(PRO_PRODUCT)),+ updatedCloudConfig: stripeConfig(TEAM_PRODUCT),+ billingCycleAnchor: CONVERTED_AT,+ });+ expect(fetchMock).toHaveBeenCalledOnce();+ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);+ expect(body.plan).toBe("Team");+ expect(body.convertedToPaidAt).toBe(CONVERTED_AT_ISO_DATE);+ });++ it("pushes a Hobby downgrade WITHOUT convertedToPaidAt so SFDC keeps the old value", async () => {+ fetchMock.mockResolvedValueOnce(emptyOkResponse());+ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: orgBefore(stripeConfig(PRO_PRODUCT)),+ // subscription.deleted keeps only the customer id+ updatedCloudConfig: { stripe: { customerId: "cus_1" } },+ billingCycleAnchor: null,+ });+ expect(fetchMock).toHaveBeenCalledOnce();+ const body = JSON.parse(fetchMock.mock.calls[0][1].body as string);+ expect(body.plan).toBe("Hobby");+ expect(body).not.toHaveProperty("convertedToPaidAt");+ });++ it("does NOT push when the resolved plan is unchanged (monthly invoice cycling)", async () => {+ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: orgBefore(stripeConfig(PRO_PRODUCT)),+ updatedCloudConfig: stripeConfig(PRO_PRODUCT),+ billingCycleAnchor: CONVERTED_AT,+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("does NOT push for orgs on a manual plan override β the override wins on both sides", async () => {+ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: orgBefore({+ plan: "Enterprise",+ ...stripeConfig(PRO_PRODUCT),+ }),+ updatedCloudConfig: {+ plan: "Enterprise",+ stripe: { customerId: "cus_1" },+ },+ billingCycleAnchor: null,+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("skips and logs when the updated cloudConfig does not parse", async () => {+ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: orgBefore(null),+ updatedCloudConfig: { plan: 123 },+ billingCycleAnchor: null,+ });+ expect(fetchMock).not.toHaveBeenCalled();+ expect(loggerMock.error).toHaveBeenCalled();+ });+});+// ---- Call sites ----//// A downgrade of an existing membership to NONE means the user effectively@@ -677,6 +839,7 @@ describe("call site: tRPC organizations.create", () => {prismaMock.organization.create.mockResolvedValueOnce({id: "org-new",name: "New Org",+ createdAt: ORG_CREATED_AT,});// [0] upsertOrg (Account), [1] setUserRole (OWNER member bridge)fetchMock@@ -692,10 +855,14 @@ describe("call site: tRPC organizations.create", () => {type: "updateOrg",orgId: "org-new",orgName: "New Org",- userId: "owner-user",- email: "[email protected]",- role: "ADMIN", // OWNER -> ADMIN+ createdAt: ORG_CREATED_AT_ISO_DATE,+ plan: "Hobby", // a freshly created org is always on Hobby});+ // Mulesoft ignores user fields on updateOrg β they must not be sent.+ expect(upsertOrgBody).not.toHaveProperty("userId");+ expect(upsertOrgBody).not.toHaveProperty("email");+ expect(upsertOrgBody).not.toHaveProperty("role");+ expect(upsertOrgBody).not.toHaveProperty("convertedToPaidAt");const setRoleBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);expect(setRoleBody).toMatchObject({@@ -707,3 +874,121 @@ describe("call site: tRPC organizations.create", () => {});});});++describe("call site: createProjectMembershipsOnSignup", () => {+ // Pins the signup cascade payloads and that the lead-source lookup runs+ // against pending invitations BEFORE invitation processing consumes them.+ const overriddenEnvKeys = [+ "NEXT_PUBLIC_DEMO_ORG_ID",+ "NEXT_PUBLIC_DEMO_PROJECT_ID",+ "LANGFUSE_DEFAULT_ORG_ID",+ "LANGFUSE_DEFAULT_PROJECT_ID",+ "LANGFUSE_ALLOWED_ORGANIZATION_CREATORS",+ ] as const;+ const savedEnv: Record<string, unknown> = {};++ beforeEach(() => {+ for (const key of overriddenEnvKeys) {+ savedEnv[key] = envMock[key];+ envMock[key] = undefined;+ }+ // First user lookup fetches the signup date for the lead; the later+ // v4-rollout lookup (selects v4BetaEnabled) must miss so that block is+ // skipped.+ prismaMock.user.findUnique.mockImplementation(async (args: unknown) => {+ const select = (args as { select?: Record<string, unknown> })?.select;+ return select?.createdAt && !select?.v4BetaEnabled+ ? { createdAt: SIGNUP_AT }+ : null;+ });+ fetchMock.mockImplementation(async () => emptyOkResponse());+ });++ afterEach(() => {+ Object.assign(envMock, savedEnv);+ prismaMock.user.findUnique.mockReset();+ prismaMock.user.findUnique.mockImplementation(async () => null);+ fetchMock.mockReset();+ });++ it("organic signup: Signup lead with the user's createdAt, then starter org + OWNER bridge", async () => {+ prismaMock.organization.create.mockResolvedValueOnce({+ id: "org-starter",+ name: "New User's Organization",+ createdAt: ORG_CREATED_AT,+ });++ await createProjectMembershipsOnSignup(+ { id: "user-new", email: "[email protected]", name: "New User" },+ { userWasJustCreated: true },+ );++ // [0] upsertUser (lead), [1] upsertOrg (starter org), [2] setUserRole+ expect(fetchMock).toHaveBeenCalledTimes(3);++ const leadBody = JSON.parse(fetchMock.mock.calls[0][1].body as string);+ expect(leadBody).toMatchObject({+ userId: "user-new",+ email: "[email protected]",+ createdAt: SIGNUP_AT_ISO_SECONDS,+ leadSource: "Langfuse Cloud Signup",+ });++ const orgBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);+ expect(orgBody).toMatchObject({+ type: "updateOrg",+ orgId: "org-starter",+ createdAt: ORG_CREATED_AT_ISO_DATE,+ plan: "Hobby",+ });+ expect(orgBody).not.toHaveProperty("userId");++ const bridgeBody = JSON.parse(fetchMock.mock.calls[2][1].body as string);+ expect(bridgeBody).toMatchObject({+ type: "setUserRole",+ orgId: "org-starter",+ userId: "user-new",+ role: "ADMIN", // OWNER -> ADMIN+ });+ });++ it("invited signup: Invite lead; the invited org is linked and no starter org is provisioned", async () => {+ prismaMock.membershipInvitation.findFirst.mockResolvedValueOnce({+ id: "inv-1",+ });+ prismaMock.membershipInvitation.findMany.mockResolvedValueOnce([+ {+ id: "inv-1",+ orgId: "org-9",+ orgRole: "MEMBER",+ projectId: "proj-9",+ projectRole: "MEMBER",+ email: "[email protected]",+ },+ ]);++ await createProjectMembershipsOnSignup(+ { id: "user-invited", email: "[email protected]", name: "Invitee" },+ { userWasJustCreated: true },+ );++ // [0] upsertUser (lead), [1] setUserRole for the accepted invitation+ expect(fetchMock).toHaveBeenCalledTimes(2);++ const leadBody = JSON.parse(fetchMock.mock.calls[0][1].body as string);+ expect(leadBody).toMatchObject({+ userId: "user-invited",+ createdAt: SIGNUP_AT_ISO_SECONDS,+ leadSource: "Langfuse Cloud Invite",+ });++ const bridgeBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);+ expect(bridgeBody).toMatchObject({+ type: "setUserRole",+ orgId: "org-9",+ userId: "user-invited",+ email: "[email protected]",+ role: "DEVELOPER", // MEMBER -> DEVELOPER+ });+ });+});diff --git a/web/src/ee/features/billing/server/stripeWebhookHandler.ts b/web/src/ee/features/billing/server/stripeWebhookHandler.tsindex 64f8358e8f..788dd6d26e 100644--- a/web/src/ee/features/billing/server/stripeWebhookHandler.ts+++ b/web/src/ee/features/billing/server/stripeWebhookHandler.ts@@ -23,6 +23,7 @@ import {import { auditLog } from "@/src/features/audit-logs/auditLog";import { type StripeSubscriptionMetadata } from "@/src/ee/features/billing/utils/stripeSubscriptionMetadata";import { mapStripeProductIdToPlan } from "@/src/ee/features/billing/utils/stripeCatalogue";+import { syncOrgPlanChangeToSfdc } from "@/src/ee/features/sfdc-sync/server";/*** Stripe webhook handler for managing subscription events, billing alerts, and invoice notifications.@@ -688,6 +689,17 @@ export async function handleSubscriptionChanged(before: parsedOrg.cloudConfig,after: updatedCloudConfig,});++ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: parsedOrg,+ updatedCloudConfig,+ // On "created" the anchor was just re-persisted from this subscription;+ // mirror that value here since parsedOrg still holds the stale one.+ billingCycleAnchor:+ action === "created" && subscription.billing_cycle_anchor+ ? new Date(subscription.billing_cycle_anchor * 1000)+ : parsedOrg.cloudBillingCycleAnchor,+ });} else if (action === "deleted") {// When subscription is deleted, only keep customerId and remove all other subscription fields// Note: We omit fields entirely rather than setting to undefined, as undefined gets converted@@ -726,6 +738,14 @@ export async function handleSubscriptionChanged(before: parsedOrg.cloudConfig,after: updatedCloudConfig,});++ // Downgrade to Hobby: convertedToPaidAt is omitted for Hobby pushes, so+ // the (just reset) anchor value is irrelevant here.+ await syncOrgPlanChangeToSfdc({+ orgBeforeUpdate: parsedOrg,+ updatedCloudConfig,+ billingCycleAnchor: null,+ });}return;diff --git a/web/src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.ts b/web/src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.tsnew file mode 100644index 0000000000..e78b12e268--- /dev/null+++ b/web/src/ee/features/sfdc-sync/scripts/backfillSfdcLeads.ts@@ -0,0 +1,432 @@+/**+ * One-off backfill of pre-existing orgs, users, and memberships into SFDC via+ * the live Mulesoft sync service.+ *+ * WHY THIS EXISTS+ * ---------------+ * The live sync (web/src/ee/features/sfdc-sync) only fires going forward, from+ * user/org/membership lifecycle events. Everything created before the+ * integration shipped β plus self-serve starter orgs, which the live sync does+ * not cover β is absent from SFDC. This script reconstructs that state by+ * replaying the live sync's additive events (upsertUser, upsertOrg,+ * setUserRole); it never issues removeUser, since a backfill only adds.+ *+ * WHAT IT DOES β three dependency-ordered passes (leads must exist before they+ * can be linked to accounts, exactly as the live sync enforces):+ *+ * Pass 1 upsertUser β one Lead per user that has an email, with the+ * signup date (users.created_at) and a lead source+ * derived from history: earliest surviving non-NONE,+ * non-excluded org membership created with role+ * OWNER β "Langfuse Cloud Signup", any other role β+ * "Langfuse Cloud Invite". Users without memberships+ * are Signup unless a pending invitation exists for+ * their email (β Invite). Accepted invitations are+ * deleted on accept, so this is a heuristic, not a+ * record.+ * Pass 2 upsertOrg β one Account per org, org-only payload (Mulesoft+ * ignores user fields on updateOrg; members are+ * linked in pass 3): created date, current tier+ * (resolved like entitlements), and β for orgs paid+ * via Stripe β the converted-to-paid date, which is+ * the billing cycle anchor (set from the first paid+ * subscription). Orgs on a manual cloudConfig.plan+ * send their tier but no conversion date; sales owns+ * those records in SFDC. Also persists+ * organizations.sfdc_org_id.+ * Pass 3 setUserRole β one org-member bridge per non-NONE membership,+ * INCLUDING the owner (upsertOrg links nobody, so+ * every member β owner included β needs setUserRole).+ *+ * IDEMPOTENCY / SAFETY+ * --------------------+ * Re-running is safe ONLY if Mulesoft matches records by Langfuse id/email+ * (Langfuse stores no Lead id, so dedup is delegated entirely to Mulesoft).+ * CONFIRM THAT before running with --execute, or you risk one duplicate Lead+ * per existing user. See the team's Mulesoft/SFDC contract.+ *+ * Defaults to DRY-RUN: it logs intended calls and never hits Mulesoft unless+ * --execute is passed. SfdcService never throws and returns void, so per-call+ * success/failure is only visible in the `[SFDC]` log lines, not in this+ * script's tallies (which count attempts, not outcomes).+ *+ * HOW TO RUN+ * ----------+ * The web prod image is a Next.js standalone build and does NOT ship src/tsx,+ * so run this from a full repo checkout / CI job that has prod env set+ * (DATABASE_URL, MULESOFT_SFDC_*, NEXT_PUBLIC_LANGFUSE_CLOUD_REGION), e.g.:+ *+ * pnpm --filter web sfdc:backfill # dry-run, all orgs+ * pnpm --filter web sfdc:backfill -- --org-id <id> # dry-run, one org+ * pnpm --filter web sfdc:backfill -- --org-id <id> --execute # canary+ * pnpm --filter web sfdc:backfill -- --execute # full run+ *+ * Flags:+ * --execute send to Mulesoft (default: dry-run)+ * --org-id <id> restrict all passes to a single org (canary)+ * --concurrency <n> in-flight requests per pass (default 3)+ * --batch-size <n> DB page size (default 500)+ * --limit <n> cap rows processed per pass (smoke test)+ * --exclude-org <id> extra org id to skip (repeatable)+ * --skip-recent-minutes <n> skip memberships updated within the last n+ * minutes (reduces the resurrection race vs the+ * live sync; pass 3 only)+ */+import { parseArgs } from "node:util";++import { env } from "@/src/env.mjs";+import {+ getSfdcService,+ toSfdcPlan,+ type SfdcLeadSource,+} from "@/src/ee/features/sfdc-sync/server";+import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";+import { parseDbOrg } from "@langfuse/shared";+import { prisma, Role } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";++type Cli = {+ execute: boolean;+ orgId?: string;+ concurrency: number;+ batchSize: number;+ limit?: number;+ excludeOrgIds: Set<string>;+ skipRecentMinutes: number;+};++function parseCli(): Cli {+ const { values } = parseArgs({+ options: {+ execute: { type: "boolean", default: false },+ "org-id": { type: "string" },+ concurrency: { type: "string", default: "3" },+ "batch-size": { type: "string", default: "500" },+ limit: { type: "string" },+ "exclude-org": { type: "string", multiple: true, default: [] },+ "skip-recent-minutes": { type: "string", default: "0" },+ },+ allowPositionals: false,+ });++ const toInt = (v: string | undefined, fallback: number) => {+ if (v === undefined) return fallback;+ const n = Number.parseInt(v, 10);+ if (!Number.isFinite(n) || n < 0)+ throw new Error(`Invalid numeric flag value: ${v}`);+ return n;+ };++ const excludeOrgIds = new Set<string>(values["exclude-org"] as string[]);+ if (env.NEXT_PUBLIC_DEMO_ORG_ID)+ excludeOrgIds.add(env.NEXT_PUBLIC_DEMO_ORG_ID);++ return {+ execute: values.execute as boolean,+ orgId: values["org-id"] as string | undefined,+ concurrency: toInt(values.concurrency as string, 3),+ batchSize: toInt(values["batch-size"] as string, 500),+ limit: values.limit ? toInt(values.limit as string, 0) : undefined,+ excludeOrgIds,+ skipRecentMinutes: toInt(values["skip-recent-minutes"] as string, 0),+ };+}++/** Bounded-concurrency map; preserves input order, never rejects on item error. */+async function mapWithConcurrency<T>(+ items: T[],+ limit: number,+ fn: (item: T, index: number) => Promise<void>,+): Promise<void> {+ let cursor = 0;+ const worker = async () => {+ while (true) {+ const i = cursor++;+ if (i >= items.length) return;+ await fn(items[i], i);+ }+ };+ await Promise.all(+ Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker),+ );+}++async function main() {+ const cli = parseCli();+ const sfdc = getSfdcService();+ if (!sfdc) {+ throw new Error(+ "[SFDC backfill] getSfdcService() returned null β not on Langfuse Cloud " ++ "or a MULESOFT_SFDC_* env var is missing. Refusing to run.",+ );+ }++ const mode = cli.execute ? "EXECUTE (live POSTs)" : "DRY-RUN (no POSTs)";+ logger.info(`[SFDC backfill] starting β mode=${mode}`, {+ orgId: cli.orgId ?? "(all)",+ concurrency: cli.concurrency,+ batchSize: cli.batchSize,+ limit: cli.limit ?? "(none)",+ excludeOrgIds: [...cli.excludeOrgIds],+ skipRecentMinutes: cli.skipRecentMinutes,+ });++ const counts = {+ leads: 0,+ leadsSkippedNoEmail: 0,+ orgs: 0,+ orgsSkippedNonCloudPlan: 0,+ orgsSkippedExcluded: 0,+ bridges: 0,+ };+ let sampled = 0;+ const sample = (label: string, payload: Record<string, unknown>) => {+ if (!cli.execute && sampled < 10) {+ logger.info(`[SFDC backfill] would ${label}`, payload);+ sampled++;+ }+ };++ // Pending invitations mark not-yet-accepted invite leads. Accepted+ // invitations are deleted, so for everyone else the lead source is derived+ // from membership role history below. Pending invites are a small table β+ // load the emails once instead of querying per user.+ const pendingInviteEmails = new Set(+ (+ await prisma.membershipInvitation.findMany({ select: { email: true } })+ ).map((invite) => invite.email.toLowerCase()),+ );++ // ---- Pass 1: Leads (upsertUser) ----+ {+ let cursorId: string | undefined;+ let processed = 0;+ for (;;) {+ if (cli.limit !== undefined && processed >= cli.limit) break;+ const take = cli.limit+ ? Math.min(cli.batchSize, cli.limit - processed)+ : cli.batchSize;+ const users = await prisma.user.findMany({+ where: {+ email: { not: null },+ ...(cli.orgId+ ? { organizationMemberships: { some: { orgId: cli.orgId } } }+ : {}),+ },+ select: {+ id: true,+ email: true,+ name: true,+ createdAt: true,+ organizationMemberships: {+ where: { role: { not: Role.NONE } },+ select: { orgId: true, role: true },+ orderBy: { createdAt: "asc" },+ },+ },+ orderBy: { id: "asc" },+ take,+ ...(cursorId ? { skip: 1, cursor: { id: cursorId } } : {}),+ });+ if (users.length === 0) break;+ cursorId = users[users.length - 1].id;+ processed += users.length;++ await mapWithConcurrency(users, cli.concurrency, async (u) => {+ if (!u.email) {+ counts.leadsSkippedNoEmail++;+ return;+ }+ // Heuristic: users whose earliest real membership was created as+ // OWNER signed up on their own (starter org / self-created org);+ // everyone else got pulled in by an existing org. Excluded orgs+ // (demo org, --exclude-org) don't count as "real".+ const firstMembership = u.organizationMemberships.find(+ (m) => !cli.excludeOrgIds.has(m.orgId),+ );+ const leadSource: SfdcLeadSource = firstMembership+ ? firstMembership.role === Role.OWNER+ ? "Langfuse Cloud Signup"+ : "Langfuse Cloud Invite"+ : pendingInviteEmails.has(u.email.toLowerCase())+ ? "Langfuse Cloud Invite"+ : "Langfuse Cloud Signup";+ sample("upsertUser", {+ userId: u.id,+ email: u.email,+ createdAt: u.createdAt.toISOString(),+ leadSource,+ });+ if (cli.execute)+ await sfdc.upsertUser({+ userId: u.id,+ email: u.email,+ name: u.name,+ createdAt: u.createdAt,+ leadSource,+ });+ counts.leads++;+ });+ logger.info(`[SFDC backfill] pass 1 (leads): ${counts.leads} processed`);+ }+ }++ // ---- Pass 2: Accounts (upsertOrg) ----+ // Org-only payload β Mulesoft ignores user fields on updateOrg, so no+ // representative member is needed (orgs without any emailed member get an+ // Account too). Member bridges (every member, owner included) are+ // established in pass 3.+ {+ let cursorId: string | undefined;+ let processed = 0;+ for (;;) {+ if (cli.limit !== undefined && processed >= cli.limit) break;+ const take = cli.limit+ ? Math.min(cli.batchSize, cli.limit - processed)+ : cli.batchSize;+ // Full rows: parseDbOrg + plan resolution need cloudConfig et al.+ const orgs = await prisma.organization.findMany({+ where: cli.orgId ? { id: cli.orgId } : {},+ orderBy: { id: "asc" },+ take,+ ...(cursorId ? { skip: 1, cursor: { id: cursorId } } : {}),+ });+ if (orgs.length === 0) break;+ cursorId = orgs[orgs.length - 1].id;+ processed += orgs.length;++ await mapWithConcurrency(orgs, cli.concurrency, async (org) => {+ if (cli.excludeOrgIds.has(org.id)) {+ counts.orgsSkippedExcluded++;+ return;+ }+ const parsedOrg = parseDbOrg(org);+ const resolvedPlan = getOrganizationPlanServerSide(+ parsedOrg.cloudConfig ?? undefined,+ );+ const plan = toSfdcPlan(resolvedPlan);+ if (!plan) {+ // Non-cloud plan cannot happen here (the service factory asserted+ // we are on Cloud) β skip defensively rather than guessing a tier.+ counts.orgsSkippedNonCloudPlan++;+ logger.warn("[SFDC backfill] skipping org β non-cloud plan", {+ orgId: org.id,+ resolvedPlan,+ });+ return;+ }+ // The billing cycle anchor is set from the org's first paid Stripe+ // subscription and untouched by plan switches, so it doubles as the+ // Hobbyβpaid conversion date. Only trust it for orgs currently paid+ // via Stripe; manual cloudConfig.plan orgs carry the row default+ // (org creation) β sales owns their conversion dates in SFDC.+ const convertedToPaidAt =+ resolvedPlan !== "cloud:hobby" &&+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId+ ? parsedOrg.cloudBillingCycleAnchor+ : undefined;+ sample("upsertOrg", {+ orgId: org.id,+ createdAt: org.createdAt.toISOString(),+ plan,+ convertedToPaidAt: convertedToPaidAt?.toISOString() ?? "(omitted)",+ });+ if (cli.execute)+ await sfdc.upsertOrg({+ orgId: org.id,+ orgName: org.name,+ createdAt: org.createdAt,+ plan,+ convertedToPaidAt,+ });+ counts.orgs++;+ });+ logger.info(`[SFDC backfill] pass 2 (orgs): ${counts.orgs} processed`);+ }+ }++ // ---- Pass 3: Member bridges (setUserRole) for every non-NONE member ----+ {+ const recentCutoff =+ cli.skipRecentMinutes > 0+ ? new Date(Date.now() - cli.skipRecentMinutes * 60_000)+ : undefined;+ let cursorId: string | undefined;+ let processed = 0;+ for (;;) {+ if (cli.limit !== undefined && processed >= cli.limit) break;+ const take = cli.limit+ ? Math.min(cli.batchSize, cli.limit - processed)+ : cli.batchSize;+ const memberships = await prisma.organizationMembership.findMany({+ where: {+ role: { not: Role.NONE },+ user: { email: { not: null } },+ // Single orgId condition: two spreads both writing the `orgId` key+ // would silently drop the canary --org-id filter whenever the+ // exclusion list is non-empty (the demo org always is in it).+ ...(cli.orgId+ ? { orgId: cli.orgId }+ : cli.excludeOrgIds.size+ ? { orgId: { notIn: [...cli.excludeOrgIds] } }+ : {}),+ ...(recentCutoff ? { updatedAt: { lt: recentCutoff } } : {}),+ },+ select: {+ id: true,+ orgId: true,+ userId: true,+ role: true,+ user: { select: { email: true } },+ },+ orderBy: { id: "asc" },+ take,+ ...(cursorId ? { skip: 1, cursor: { id: cursorId } } : {}),+ });+ if (memberships.length === 0) break;+ cursorId = memberships[memberships.length - 1].id;+ processed += memberships.length;++ await mapWithConcurrency(memberships, cli.concurrency, async (m) => {+ if (!m.user.email) return;+ sample("setUserRole", {+ orgId: m.orgId,+ userId: m.userId,+ role: m.role,+ });+ if (cli.execute)+ await sfdc.setUserRole({+ orgId: m.orgId,+ userId: m.userId,+ email: m.user.email,+ role: m.role,+ });+ counts.bridges++;+ });+ logger.info(+ `[SFDC backfill] pass 3 (bridges): ${counts.bridges} processed`,+ );+ }+ }++ logger.info(`[SFDC backfill] done β mode=${mode}`, counts);+ if (!cli.execute)+ logger.info(+ "[SFDC backfill] DRY-RUN complete β re-run with --execute to send. " ++ "Confirm Mulesoft Lead idempotency first.",+ );+}++if (require.main === module) {+ main()+ .catch((err) => {+ logger.error("[SFDC backfill] failed", {+ error: err instanceof Error ? err.message : String(err),+ });+ process.exitCode = 1;+ })+ .finally(async () => {+ await prisma.$disconnect();+ process.exit(process.exitCode ?? 0);+ });+}diff --git a/web/src/ee/features/sfdc-sync/server/index.ts b/web/src/ee/features/sfdc-sync/server/index.tsindex 96f632cd13..9e541f2e8d 100644--- a/web/src/ee/features/sfdc-sync/server/index.ts+++ b/web/src/ee/features/sfdc-sync/server/index.ts@@ -2,11 +2,15 @@ export {SfdcService,getSfdcService,resetSfdcServiceCacheForTests,+ toSfdcPlan,} from "./sfdcService";+export { syncOrgPlanChangeToSfdc } from "./planChangeSync";export type {UpsertUserInput,UpsertOrgInput,SetUserRoleInput,RemoveUserInput,LangfuseRole,+ SfdcLeadSource,+ SfdcPlan,} from "./sfdcService";diff --git a/web/src/ee/features/sfdc-sync/server/planChangeSync.ts b/web/src/ee/features/sfdc-sync/server/planChangeSync.tsnew file mode 100644index 0000000000..b748dc8ab6--- /dev/null+++ b/web/src/ee/features/sfdc-sync/server/planChangeSync.ts@@ -0,0 +1,63 @@+import { CloudConfigSchema, type ParsedOrganization } from "@langfuse/shared";+import { logger } from "@langfuse/shared/src/server";++import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";+import { getSfdcService, toSfdcPlan } from "./sfdcService";++/**+ * Push a plan change to SFDC (fire-and-forget, never throws β the underlying+ * SfdcService swallows all errors). Compares the entitlement plan resolved+ * from the org's cloudConfig before vs. after a billing update and only syncs+ * when it actually changed β Stripe subscription events also fire for monthly+ * invoice cycling and payment-status flaps, which must not spam Mulesoft.+ *+ * `billingCycleAnchor` doubles as the Hobbyβpaid conversion date: it is set+ * from the org's paid subscription and stable across plan switches, but NOT+ * across churn-and-resubscribe β subscription deletion resets the anchor and+ * a later resubscription re-anchors it, so the pushed value tracks the MOST+ * RECENT Hobbyβpaid conversion and overwrites the SFDC field on each paid+ * push. It is omitted on downgrades to Hobby (SFDC keeps the previously+ * written value). Orgs on a manual cloudConfig.plan override never reach the+ * push: the override wins plan resolution on both sides of the comparison,+ * so their resolved plan cannot change here β sales owns those SFDC records.+ */+export async function syncOrgPlanChangeToSfdc(args: {+ orgBeforeUpdate: Pick<+ ParsedOrganization,+ "id" | "name" | "createdAt" | "cloudConfig"+ >;+ /** The org's cloudConfig as persisted by the billing update. */+ updatedCloudConfig: unknown;+ /** Anchor consistent with the update that was just persisted. */+ billingCycleAnchor: Date | null;+}): Promise<void> {+ const { orgBeforeUpdate, updatedCloudConfig, billingCycleAnchor } = args;++ const planBefore = getOrganizationPlanServerSide(+ orgBeforeUpdate.cloudConfig ?? undefined,+ );+ const parsedUpdated = CloudConfigSchema.safeParse(updatedCloudConfig);+ if (!parsedUpdated.success) {+ // Never guess a plan from an unparsable config β skipping only delays+ // the SFDC tier update until the next real plan change.+ logger.error(+ "[SFDC] could not parse updated cloudConfig for plan sync β skipping",+ { orgId: orgBeforeUpdate.id, error: parsedUpdated.error.message },+ );+ return;+ }+ const planAfter = getOrganizationPlanServerSide(parsedUpdated.data);+ if (planBefore === planAfter) return;++ const sfdcPlan = toSfdcPlan(planAfter);+ if (!sfdcPlan) return; // non-cloud plan β cannot happen on Cloud++ await getSfdcService()?.upsertOrg({+ orgId: orgBeforeUpdate.id,+ orgName: orgBeforeUpdate.name,+ createdAt: orgBeforeUpdate.createdAt,+ plan: sfdcPlan,+ convertedToPaidAt:+ planAfter !== "cloud:hobby" ? billingCycleAnchor : undefined,+ });+}diff --git a/web/src/ee/features/sfdc-sync/server/sfdcService.ts b/web/src/ee/features/sfdc-sync/server/sfdcService.tsindex f2e636d59e..035540bdb9 100644--- a/web/src/ee/features/sfdc-sync/server/sfdcService.ts+++ b/web/src/ee/features/sfdc-sync/server/sfdcService.ts@@ -3,6 +3,7 @@ import { SpanKind } from "@opentelemetry/api";import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";+import { cloudConfigPlans, planLabels, type Plan } from "@langfuse/shared";import {instrumentAsync,logger,@@ -13,13 +14,24 @@ import {* SFDC sync via Mulesoft (Langfuse Cloud only).** Two endpoints, four logical events:- * - `/manage-user` β upsertUser (lead/contact)- * - org endpoint β upsertOrg (type:"updateOrg") on org create+ * - `/manage-user` β upsertUser (lead/contact) on user signup+ * - org endpoint β upsertOrg (type:"updateOrg") on org create and on plan+ * changes (Stripe webhook). Mulesoft ignores user fields+ * on updateOrg, so the payload is org-only; members are+ * linked exclusively via setUserRole.* β setUserRole (type:"setUserRole") on member add or role change* (a NONE role is synced as removeUser instead)* β removeUser (type:"removeUser") on member removal** Every payload carries `isLangfuse: true` to distinguish Langfuse traffic.+ * Date formats follow the SFDC field types behind the Mulesoft mapping+ * (which passes values through verbatim and falls back to `now` when a date+ * field is absent):+ * - user `createdAt` β ISO-8601 UTC seconds precision+ * (`YYYY-MM-DDThh:mm:ssZ`); the Lead field accepts datetimes.+ * - org `createdAt` / `convertedToPaidAt` β date-only (`YYYY-MM-DD`); the+ * org fields are SFDC Date-typed and reject datetimes with+ * INVALID_TYPE_ON_FIELD_IN_RECORD.** Contract for callers: every public method is fire-and-forget safe.* Methods NEVER throw/reject β missing emails, NONE roles, validation@@ -49,11 +61,52 @@ const LANGFUSE_TO_SFDC_ROLE = {VIEWER: "DEVELOPER",} as const;+/**+ * SFDC Lead Source picklist values for Langfuse leads. Mulesoft passes them+ * to the SFDC Lead Source field verbatim: signup = organic account creation,+ * invite = user pulled in by an existing org (pending invitation at signup,+ * SCIM provisioning).+ */+const SFDC_LEAD_SOURCES = [+ "Langfuse Cloud Signup",+ "Langfuse Cloud Invite",+] as const;+export type SfdcLeadSource = (typeof SFDC_LEAD_SOURCES)[number];++/**+ * SFDC tier picklist (`Langfuse_Active_Plan__c`) β identical to the+ * `cloudConfig.plan` values, so the shared constant is the schema source.+ */+export type SfdcPlan = (typeof cloudConfigPlans)[number];++/**+ * Map a resolved entitlement plan to the SFDC tier picklist value. Returns+ * null for non-cloud plans (oss / self-hosted), which have no SFDC tier β+ * callers should skip the sync in that case (cannot happen on Cloud, where+ * this service is the only way to reach Mulesoft).+ */+export function toSfdcPlan(plan: Plan): SfdcPlan | null {+ const label = planLabels[plan];+ return (cloudConfigPlans as readonly string[]).includes(label)+ ? (label as SfdcPlan)+ : null;+}++/** Datetime-accepting SFDC fields: ISO-8601 UTC, seconds precision, no millis. */+const toIsoUtcSeconds = (date: Date): string =>+ date.toISOString().replace(/\.\d{3}Z$/, "Z");++/** SFDC Date-typed fields (the org dates) accept only `YYYY-MM-DD` (UTC). */+const toIsoUtcDate = (date: Date): string => date.toISOString().slice(0, 10);+const UpsertUserPayload = z.object({userId: z.string().min(1),email: z.email(),fullName: z.string().min(1),companyName: z.string().min(1),+ // -> SFDC "Langfuse Cloud Signup Date" (Langfuse_Signup_Date__c)+ createdAt: z.iso.datetime(),+ leadSource: z.enum(SFDC_LEAD_SOURCES),});const SyncableRole = LangfuseRole.exclude(["NONE"]).transform(@@ -63,9 +116,16 @@ const SyncableRole = LangfuseRole.exclude(["NONE"]).transform(const UpsertOrgPayload = z.object({orgId: z.string().min(1),orgName: z.string().min(1),- userId: z.string().min(1),- email: z.email(),- role: SyncableRole,+ // -> SFDC "Langfuse Created Date" (Langfuse_Created_Date__c), Date-typed:+ // date-only strings, datetimes are rejected.+ createdAt: z.iso.date(),+ // -> SFDC "Langfuse Tier" (Langfuse_Active_Plan__c)+ plan: z.enum(cloudConfigPlans),+ // -> SFDC "Converted to Paid" (Converted_to_Paid_Date__c), Date-typed.+ // Only sent when the org left Hobby at least once; omitted otherwise so+ // SFDC keeps any previously written value (e.g. across a later downgrade+ // push).+ convertedToPaidAt: z.iso.date().optional(),});const SetUserRolePayload = z.object({@@ -89,13 +149,18 @@ export type UpsertUserInput = {email: string | null | undefined;name?: string | null;companyName?: string;+ /** User signup timestamp β sent as the SFDC Langfuse Cloud Signup Date. */+ createdAt: Date;+ leadSource: SfdcLeadSource;};export type UpsertOrgInput = {orgId: string;orgName: string;- userId: string;- email: string | null | undefined;- role: LangfuseRole;+ /** Org creation timestamp β sent as the SFDC Langfuse Created Date. */+ createdAt: Date;+ plan: SfdcPlan;+ /** First Hobbyβpaid conversion; omit while the org never converted. */+ convertedToPaidAt?: Date | null;};export type SetUserRoleInput = {orgId: string;@@ -166,6 +231,8 @@ export class SfdcService {fullName: input.name || input.email,companyName:input.companyName || env.MULESOFT_SFDC_DEFAULT_COMPANY_NAME,+ createdAt: toIsoUtcSeconds(input.createdAt),+ leadSource: input.leadSource,});if (!parsed.success) {logger.warn("[SFDC] invalid upsertUser input β skipping", {@@ -184,19 +251,21 @@ export class SfdcService {}/**- * Org upsert on organization create. POSTs to org endpoint; Mulesoft links- * the creator's lead to the org as an org-member server-side.+ * Org upsert on organization create and on plan changes. POSTs to the org+ * endpoint. Carries no user fields (Mulesoft ignores them on updateOrg) β+ * member links are established exclusively via setUserRole.*/async upsertOrg(input: UpsertOrgInput): Promise<void> {return this.run("upsertOrg", { orgId: input.orgId }, async () => {- if (!input.email) {- logger.warn("[SFDC] skipping upsertOrg β creator has no email", {- orgId: input.orgId,- userId: input.userId,- });- return;- }- const parsed = UpsertOrgPayload.safeParse(input);+ const parsed = UpsertOrgPayload.safeParse({+ orgId: input.orgId,+ orgName: input.orgName,+ createdAt: toIsoUtcDate(input.createdAt),+ plan: input.plan,+ ...(input.convertedToPaidAt+ ? { convertedToPaidAt: toIsoUtcDate(input.convertedToPaidAt) }+ : {}),+ });if (!parsed.success) {logger.warn("[SFDC] invalid upsertOrg input β skipping", {orgId: input.orgId,@@ -355,7 +424,9 @@ export class SfdcService {* Single POST helper. Returns the parsed response on 2xx, null otherwise.* Never throws β HTTP errors, timeouts, and malformed bodies are logged.* Every request leaves exactly one outcome log line (info on 2xx, warn- * otherwise) so each Mulesoft call is auditable in the log stream.+ * otherwise) so each Mulesoft call is auditable in the log stream. At+ * debug level, every call additionally logs its full request payload+ * before send and the full raw response body once received.*/private async post(args: {url: string;@@ -372,6 +443,12 @@ export class SfdcService {);const startTime = Date.now();+ logger.debug("[SFDC] Mulesoft request payload", {+ ...context,+ url,+ payload,+ });+try {const response = await fetch(url, {method: "POST",@@ -383,8 +460,15 @@ export class SfdcService {signal: controller.signal,});+ const responseText = await response.text().catch(() => "");+ logger.debug("[SFDC] Mulesoft response body", {+ ...context,+ url,+ status: response.status,+ responseBody: responseText,+ });+if (!response.ok) {- const responseBody = await response.text().catch(() => "");traceException(new Error(`Mulesoft returned ${response.status}`));logger.error("[SFDC] Mulesoft returned non-2xx", {...context,@@ -392,7 +476,7 @@ export class SfdcService {status: response.status,statusText: response.statusText,durationMs: Date.now() - startTime,- responseBody: responseBody.slice(0, 500),+ responseBody: responseText.slice(0, 500),});return null;}@@ -405,7 +489,6 @@ export class SfdcService {});// Tolerate empty / non-JSON bodies; we only care if an ID comes back.- const responseText = await response.text();if (!expectJsonResponse || !responseText) return null;let parsed: unknown;diff --git a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts b/web/src/features/auth/lib/createProjectMembershipsOnSignup.tsindex 4b84e9e7ac..71b4250851 100644--- a/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts+++ b/web/src/features/auth/lib/createProjectMembershipsOnSignup.ts@@ -161,13 +161,32 @@ export async function createProjectMembershipsOnSignup(// SFDC lead upsert (never throws; no-op when SfdcService is not// configured).// Must run BEFORE processMembershipInvitations below so the lead exists- // when setUserRole events fire for accepted invitations.+ // when setUserRole events fire for accepted invitations β which is also+ // why the invitation lookup for the lead source runs here, while the+ // invitations still exist.if (options?.userWasJustCreated || isNewUser) {- await getSfdcService()?.upsertUser({- userId: user.id,- email: user.email,- name: user.name,- });+ const sfdcService = getSfdcService();+ if (sfdcService) {+ const dbUser = await prisma.user.findUnique({+ where: { id: user.id },+ select: { createdAt: true },+ });+ const hasPendingInvitation = user.email+ ? (await prisma.membershipInvitation.findFirst({+ where: { email: user.email.toLowerCase() },+ select: { id: true },+ })) !== null+ : false;+ await sfdcService.upsertUser({+ userId: user.id,+ email: user.email,+ name: user.name,+ createdAt: dbUser?.createdAt ?? new Date(),+ leadSource: hasPendingInvitation+ ? "Langfuse Cloud Invite"+ : "Langfuse Cloud Signup",+ });+ }}// Invites do not work for users without emails (some future SSO users)@@ -191,9 +210,8 @@ export async function createProjectMembershipsOnSignup(await getSfdcService()?.upsertOrg({orgId: starterOrg.organization.id,orgName: starterOrg.organization.name,- userId: user.id,- email: user.email,- role: "OWNER",+ createdAt: starterOrg.organization.createdAt,+ plan: "Hobby",});await getSfdcService()?.setUserRole({orgId: starterOrg.organization.id,diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsindex a9f41a6385..a028e1bd38 100644--- a/web/src/features/organizations/server/organizationRouter.ts+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -134,9 +134,8 @@ export const organizationsRouter = createTRPCRouter({await getSfdcService()?.upsertOrg({orgId: organization.id,orgName: organization.name,- userId: ctx.session.user.id,- email: ctx.session.user.email,- role: "OWNER",+ createdAt: organization.createdAt,+ plan: "Hobby",});await getSfdcService()?.setUserRole({orgId: organization.id,diff --git a/web/src/pages/api/public/scim/Users/index.ts b/web/src/pages/api/public/scim/Users/index.tsindex e917cd1a37..694f620468 100644--- a/web/src/pages/api/public/scim/Users/index.ts+++ b/web/src/pages/api/public/scim/Users/index.ts@@ -262,6 +262,9 @@ export default async function handler(userId: user.id,email: user.email,name: user.name,+ createdAt: user.createdAt,+ // SCIM provisioning is org-admin-driven, never an organic signup.+ leadSource: "Langfuse Cloud Invite",});await getSfdcService()?.setUserRole({orgId: authCheck.scope.orgId,