Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -16,8 +16,7 @@
*/
import { createHash } from "node:crypto";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { db } from "~/utils/db.server";
import { captureMarketingLeadCapability } from "@hivegrid/db/pretenant-security.server";
export interface CaptureLeadInput {
email: string;
@@ -60,74 +59,29 @@ export async function captureLead(input: CaptureLeadInput): Promise<CaptureLeadR
const ua = input.userAgent ? input.userAgent.slice(0, 500) : null;
const attr = input.attribution ?? {};
const existing = await db.lead.findUnique({ where: { email }, select: { id: true } });
if (!existing) {
const lead = await db.lead.create({
data: {
email,
firstName: trim(input.firstName),
lastName: trim(input.lastName),
phone: trim(input.phone),
company: trim(input.company),
source: trim(input.source),
utmSource: trim(attr.utmSource),
utmMedium: trim(attr.utmMedium),
utmCampaign: trim(attr.utmCampaign),
utmTerm: trim(attr.utmTerm),
utmContent: trim(attr.utmContent),
gclid: trim(attr.gclid),
fbclid: trim(attr.fbclid),
referrer: trim(attr.referrer),
landingPage: trim(attr.landingPage),
lastIpHash: ipHash,
userAgent: ua,
events: {
create: {
type: "captured",
payload: serialisePayload({
source: trim(input.source),
attribution: cleanAttribution(attr),
}),
},
},
},
select: { id: true },
});
return { leadId: lead.id, created: true };
}
// Existing — only fill blanks, never overwrite. First-touch attribution wins.
const updateData: Prisma.LeadUpdateInput = {
lastTouchAt: new Date(),
return captureMarketingLeadCapability({
email,
firstName: trim(input.firstName),
lastName: trim(input.lastName),
phone: trim(input.phone),
company: trim(input.company),
source: trim(input.source),
utmSource: trim(attr.utmSource),
utmMedium: trim(attr.utmMedium),
utmCampaign: trim(attr.utmCampaign),
utmTerm: trim(attr.utmTerm),
utmContent: trim(attr.utmContent),
gclid: trim(attr.gclid),
fbclid: trim(attr.fbclid),
referrer: trim(attr.referrer),
landingPage: trim(attr.landingPage),
lastIpHash: ipHash,
userAgent: ua,
firstName: nonNullSetIfMissing(input.firstName),
lastName: nonNullSetIfMissing(input.lastName),
phone: nonNullSetIfMissing(input.phone),
company: nonNullSetIfMissing(input.company),
events: {
create: {
type: "re-captured",
payload: serialisePayload({
source: trim(input.source),
attribution: cleanAttribution(attr),
}),
},
},
};
// Only conditionally fill blanks — Prisma update treats `undefined` as
// "leave alone", and `null` as "set to NULL" which we explicitly do NOT want.
// We re-fetch the row only for fields that need conditional patching to
// avoid extra reads; the merge logic happens in the next query batch.
await db.lead.update({ where: { id: existing.id }, data: updateData });
// Best-effort fill-blanks: only touches columns where the existing value is
// NULL and the incoming value is set. This is two queries in the dup-case
// which keeps the common path simple.
await fillBlankProfileFields(existing.id, input);
return { leadId: existing.id, created: false };
eventPayload: serialisePayload({
source: trim(input.source),
attribution: cleanAttribution(attr),
}),
});
}
function trim(v: string | null | undefined): string | null {
@@ -136,27 +90,6 @@ function trim(v: string | null | undefined): string | null {
return t === "" ? null : t;
}
function nonNullSetIfMissing(_v: string | null | undefined): undefined {
// Returning `undefined` so Prisma keeps the existing value untouched.
// The fill-blanks step (`fillBlankProfileFields`) handles actual patches.
return undefined;
}
async function fillBlankProfileFields(leadId: string, input: CaptureLeadInput): Promise<void> {
const row = await db.lead.findUnique({
where: { id: leadId },
select: { firstName: true, lastName: true, phone: true, company: true },
});
if (!row) return;
const patch: Prisma.LeadUpdateInput = {};
if (row.firstName == null && trim(input.firstName)) patch.firstName = trim(input.firstName);
if (row.lastName == null && trim(input.lastName)) patch.lastName = trim(input.lastName);
if (row.phone == null && trim(input.phone)) patch.phone = trim(input.phone);
if (row.company == null && trim(input.company)) patch.company = trim(input.company);
if (Object.keys(patch).length === 0) return;
await db.lead.update({ where: { id: leadId }, data: patch });
}
function cleanAttribution(attr: NonNullable<CaptureLeadInput["attribution"]>): Record<string, string> {
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(attr)) {
@@ -166,7 +99,7 @@ function cleanAttribution(attr: NonNullable<CaptureLeadInput["attribution"]>): R
return out;
}
function serialisePayload(obj: Record<string, unknown>): Prisma.InputJsonValue {
function serialisePayload(obj: Record<string, unknown>): Record<string, unknown> {
// Drop top-level keys with empty / undefined values for compact JSON storage.
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(obj)) {
@@ -174,5 +107,5 @@ function serialisePayload(obj: Record<string, unknown>): Prisma.InputJsonValue {
if (typeof v === "object" && Object.keys(v as Record<string, unknown>).length === 0) continue;
out[k] = v;
}
return out as Prisma.InputJsonValue;
return out;
}
@@ -3,20 +3,22 @@
* Phase 05 #79).
*
* `convertLeadToTenant` runs inside a single Prisma `$transaction` so the
* following five effects either all commit or all roll back together:
* following six effects either all commit or all roll back together:
*
* 1. New Tenant row (via direct prisma.create — we cannot reuse the
* higher-level `createTenant` helper because it runs outside a
* transaction. Slug + inboundAddress allocation is delegated to the
* pre-computed values passed in by the caller).
* 2. Lead row update: `status` advances to `trial` (default) or
* 2. A single pending OWNER invitation plus its transactional-mail
* outbox row.
* 3. Lead row update: `status` advances to `trial` (default) or
* `customer` (when caller requests it), `convertedToTenantId` +
* `convertedAt` populated.
* 3. `LeadEvent` of type `converted` appended for the activity
* 4. `LeadEvent` of type `converted` appended for the activity
* timeline.
* 4. `TenantAcquisition` row inserted with first-touch attribution
* 5. `TenantAcquisition` row inserted with first-touch attribution
* snapshot copied from the Lead.
* 5. `OutboxEvent` published — `marketing.lead.convertedtotrial` or
* 6. `OutboxEvent` published — `marketing.lead.convertedtotrial` or
* `marketing.lead.convertedtocustomer` — picked up downstream by
* the marketing-outbound worker handler to fan out webhooks (Slack,
* Discord, Mailchimp, HubSpot, Brevo, custom).
@@ -28,9 +30,18 @@
* into no-ops, returning the already-created Tenant + Lead.
*/
import { randomUUID } from "node:crypto";
import { Prisma } from "@hivegrid/db/prisma-browser";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { convertSelfServiceMarketingLeadCapability } from "@hivegrid/db/pretenant-security.server";
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
import {
issueReservedOwnerInvitationWithTx,
type ReservedOwnerInvitationDraft,
} from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
export type ConvertedStatus = "trial" | "customer";
export type ConversionPath = "self-service" | "admin-override" | "api";
@@ -51,6 +62,8 @@ export interface ConvertLeadInput {
};
/** Optional acting admin user id when conversionPath === "admin-override". */
actorId?: string | null;
/** Prepared capability + mail content; persisted atomically with conversion. */
ownerInvitation: ReservedOwnerInvitationDraft;
/**
* Optional plan-id (SubscriptionProduct.id) carried through to the
* webhook payload — does NOT enrol the tenant into a subscription. The
@@ -72,9 +85,10 @@ export interface ConvertLeadResult {
export interface RecordExistingTenantLeadConversionInput {
leadId: string;
tenantId: string;
targetStatus?: ConvertedStatus;
conversionPath?: ConversionPath;
actorId?: string | null;
userId: string;
expectedEmail: string;
targetStatus?: "trial";
conversionPath?: "self-service";
planId?: string | null;
}
@@ -105,159 +119,78 @@ export class LeadConversionDisabledError extends Error {
export const MARKETING_LEAD_EVENT_PREFIX = "marketing.lead";
export function buildLeadConversionEventType(status: ConvertedStatus): string {
return status === "customer"
? `${MARKETING_LEAD_EVENT_PREFIX}.convertedtocustomer`
: `${MARKETING_LEAD_EVENT_PREFIX}.convertedtotrial`;
return status === "customer" ? `${MARKETING_LEAD_EVENT_PREFIX}.convertedtocustomer` : `${MARKETING_LEAD_EVENT_PREFIX}.convertedtotrial`;
}
export async function recordExistingTenantLeadConversion(input: RecordExistingTenantLeadConversionInput): Promise<ConvertLeadResult> {
if (process.env.LEAD_CONVERSION_ENABLED === "false") {
throw new LeadConversionDisabledError();
}
const status: ConvertedStatus = input.targetStatus ?? "trial";
const conversionPath: ConversionPath = input.conversionPath ?? "self-service";
const status = "trial" as const;
const conversionPath = "self-service" as const;
return await db.$transaction(async (tx) => {
const lead = await tx.lead.findUnique({
where: { id: input.leadId },
select: {
id: true,
email: true,
firstName: true,
lastName: true,
company: true,
source: true,
utmSource: true,
utmMedium: true,
utmCampaign: true,
utmTerm: true,
utmContent: true,
gclid: true,
fbclid: true,
referrer: true,
landingPage: true,
firstSeenAt: true,
convertedToTenantId: true,
},
});
if (!lead) throw new LeadNotFoundError(input.leadId);
if (lead.convertedToTenantId) {
return runWithRlsContext({ tenantId: input.tenantId, userId: input.userId }, () =>
db.$transaction(async (tx) => {
const lead = await convertSelfServiceMarketingLeadCapability(
{
leadId: input.leadId,
tenantId: input.tenantId,
userId: input.userId,
expectedEmail: input.expectedEmail,
planId: input.planId,
},
tx as never
);
if (!lead) throw new LeadNotFoundError(input.leadId);
if (lead.convertedToTenantId !== input.tenantId) {
throw new LeadAlreadyConvertedError(lead.id, lead.convertedToTenantId);
throw new LeadAlreadyConvertedError(lead.leadId, lead.convertedToTenantId);
}
if (lead.alreadyConverted) {
return {
tenantId: input.tenantId,
leadId: lead.leadId,
status,
alreadyConverted: true,
outboxEventId: null,
};
}
const outboxEvent = await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
type: buildLeadConversionEventType(status),
payload: {
leadId: lead.leadId,
tenantId: input.tenantId,
targetStatus: status,
conversionPath,
planId: input.planId ?? null,
email: lead.email,
firstName: lead.firstName,
lastName: lead.lastName,
company: lead.company,
utm: {
source: lead.utmSource,
medium: lead.utmMedium,
campaign: lead.utmCampaign,
term: lead.utmTerm,
content: lead.utmContent,
},
referrer: lead.referrer,
landingPage: lead.landingPage,
convertedAt: lead.convertedAt,
} as Prisma.InputJsonValue,
dispatchKey: `lead-convert:${lead.leadId}`,
});
return {
tenantId: input.tenantId,
leadId: lead.id,
leadId: lead.leadId,
status,
alreadyConverted: true,
outboxEventId: null,
alreadyConverted: false,
outboxEventId: outboxEvent.id,
};
}
const now = new Date();
await tx.lead.update({
where: { id: lead.id },
data: {
status,
convertedToTenantId: input.tenantId,
convertedAt: now,
},
});
await tx.leadEvent.create({
data: {
leadId: lead.id,
type: "converted",
actorId: input.actorId ?? null,
payload: {
tenantId: input.tenantId,
conversionPath,
targetStatus: status,
planId: input.planId ?? null,
} as Prisma.InputJsonValue,
},
});
await tx.tenantAcquisition.upsert({
where: { tenantId: input.tenantId },
create: {
tenantId: input.tenantId,
leadId: lead.id,
source: lead.source ?? conversionPath,
utmSource: lead.utmSource,
utmMedium: lead.utmMedium,
utmCampaign: lead.utmCampaign,
utmTerm: lead.utmTerm,
utmContent: lead.utmContent,
gclid: lead.gclid,
fbclid: lead.fbclid,
referrer: lead.referrer,
landingPage: lead.landingPage,
capturedAt: lead.firstSeenAt,
convertedAt: now,
conversionPath,
customFields:
input.planId != null
? ({ planId: input.planId } as Prisma.InputJsonValue)
: Prisma.JsonNull,
},
update: {
leadId: lead.id,
source: lead.source ?? conversionPath,
utmSource: lead.utmSource,
utmMedium: lead.utmMedium,
utmCampaign: lead.utmCampaign,
utmTerm: lead.utmTerm,
utmContent: lead.utmContent,
gclid: lead.gclid,
fbclid: lead.fbclid,
referrer: lead.referrer,
landingPage: lead.landingPage,
capturedAt: lead.firstSeenAt,
convertedAt: now,
conversionPath,
customFields:
input.planId != null
? ({ planId: input.planId } as Prisma.InputJsonValue)
: Prisma.JsonNull,
},
});
const outboxEvent = await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId: input.tenantId,
type: buildLeadConversionEventType(status),
payload: {
leadId: lead.id,
tenantId: input.tenantId,
targetStatus: status,
conversionPath,
planId: input.planId ?? null,
email: lead.email,
firstName: lead.firstName,
lastName: lead.lastName,
company: lead.company,
utm: {
source: lead.utmSource,
medium: lead.utmMedium,
campaign: lead.utmCampaign,
term: lead.utmTerm,
content: lead.utmContent,
},
referrer: lead.referrer,
landingPage: lead.landingPage,
convertedAt: now.toISOString(),
} as Prisma.InputJsonValue,
dispatchKey: `lead-convert:${lead.id}`,
});
return {
tenantId: input.tenantId,
leadId: lead.id,
status,
alreadyConverted: false,
outboxEventId: outboxEvent.id,
};
});
})
);
}
export async function convertLeadToTenant(input: ConvertLeadInput): Promise<ConvertLeadResult> {
@@ -266,8 +199,16 @@ export async function convertLeadToTenant(input: ConvertLeadInput): Promise<Conv
}
const status: ConvertedStatus = input.targetStatus ?? "trial";
const conversionPath: ConversionPath = input.conversionPath ?? "self-service";
const tenantId = randomUUID();
const transaction = async (tx: Prisma.TransactionClient): Promise<ConvertLeadResult> => {
// Serialize every conversion attempt for this lead before reading its
// conversion state. The lock is transaction-scoped, so a concurrent
// request observes the committed winner instead of creating an orphaned
// ownerless tenant and overwriting convertedToTenantId.
const conversionLockKey = `lead-convert:${input.leadId}`;
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${conversionLockKey}, 0))`;
return await db.$transaction(async (tx) => {
const lead = await tx.lead.findUnique({
where: { id: input.leadId },
select: {
@@ -292,6 +233,7 @@ export async function convertLeadToTenant(input: ConvertLeadInput): Promise<Conv
},
});
if (!lead) throw new LeadNotFoundError(input.leadId);
assertLeadOwnerInvitation(input, lead);
// Idempotent re-run: already-converted leads return existing tenant.
if (lead.convertedToTenantId) {
@@ -306,9 +248,12 @@ export async function convertLeadToTenant(input: ConvertLeadInput): Promise<Conv
const tenant = await tx.tenant.create({
data: {
id: tenantId,
name: input.tenant.name,
slug: input.tenant.slug,
icon: input.tenant.icon ?? undefined,
active: false,
deactivatedReason: TENANT_PENDING_OWNER_REASON,
inboundAddresses: {
create: [{ address: input.tenant.inboundAddress }],
},
@@ -316,6 +261,11 @@ export async function convertLeadToTenant(input: ConvertLeadInput): Promise<Conv
select: { id: true },
});
await issueReservedOwnerInvitationWithTx(tx, {
tenantId: tenant.id,
...input.ownerInvitation,
});
const now = new Date();
await tx.lead.update({
where: { id: lead.id },
@@ -358,10 +308,7 @@ export async function convertLeadToTenant(input: ConvertLeadInput): Promise<Conv
capturedAt: lead.firstSeenAt,
convertedAt: now,
conversionPath,
customFields:
input.planId != null
? ({ planId: input.planId } as Prisma.InputJsonValue)
: Prisma.JsonNull,
customFields: input.planId != null ? ({ planId: input.planId } as Prisma.InputJsonValue) : Prisma.JsonNull,
},
});
@@ -400,5 +347,37 @@ export async function convertLeadToTenant(input: ConvertLeadInput): Promise<Conv
alreadyConverted: false,
outboxEventId: outboxEvent.id,
};
});
};
const execute = () => runWithRlsContext({ tenantId, userId: input.actorId ?? undefined }, () => db.$transaction(transaction));
const current = getRlsExecutionContext();
const actorUserId = input.actorId ?? current?.userId;
return current?.userId && current.userId === actorUserId && (current.tenantId || current.transaction)
? runWithIsolatedUserRlsContext(current.userId, execute)
: execute();
}
function assertLeadOwnerInvitation(
input: ConvertLeadInput,
lead: { email: string; firstName: string | null; lastName: string | null }
): void {
const firstName = lead.firstName?.trim() ?? "";
const lastName = lead.lastName?.trim() ?? "";
if (
!firstName ||
!lastName ||
input.ownerInvitation.issuanceKey !== `lead:${input.leadId}` ||
input.ownerInvitation.email.trim().toLowerCase() !== lead.email.trim().toLowerCase() ||
input.ownerInvitation.firstName.trim() !== firstName ||
input.ownerInvitation.lastName.trim() !== lastName ||
input.ownerInvitation.fromUserId !== (input.actorId ?? null)
) {
throw new LeadOwnerInvitationMismatchError(input.leadId);
}
}
export class LeadOwnerInvitationMismatchError extends Error {
override readonly name = "LeadOwnerInvitationMismatchError";
constructor(leadId: string) {
super(`Lead ${leadId} owner invitation does not match the conversion request.`);
}
}
@@ -1,5 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
import { buildLeadConversionEventType, LeadAlreadyConvertedError, LeadNotFoundError } from "./convertLead.server";
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
const capabilityMocks = vi.hoisted(() => ({ convertSelfServiceMarketingLeadCapability: vi.fn() }));
const ownerInvitationMocks = vi.hoisted(() => ({ issueReservedOwnerInvitationWithTx: vi.fn() }));
vi.mock("~/utils/db.server", () => {
return { db: { $transaction: vi.fn() } };
@@ -11,6 +16,28 @@ vi.mock("@hivegrid/db/outbox", () => {
};
});
vi.mock("@hivegrid/db/pretenant-security.server", () => ({
convertSelfServiceMarketingLeadCapability: (...args: unknown[]) => capabilityMocks.convertSelfServiceMarketingLeadCapability(...args),
}));
vi.mock("~/domain/tenant-bootstrap/tenantBootstrap.constants", () => ({
TENANT_PENDING_OWNER_REASON: "pending_owner",
}));
vi.mock("~/domain/tenant-bootstrap/ownerInvitationIssuance.server", () => ({
issueReservedOwnerInvitationWithTx: ownerInvitationMocks.issueReservedOwnerInvitationWithTx,
}));
const OWNER_INVITATION_TOKEN = "o".repeat(43);
const OWNER_INVITATION = {
issuanceKey: "lead:lead_1",
email: "test@example.com",
firstName: "Test",
lastName: "User",
fromUserId: null,
token: OWNER_INVITATION_TOKEN,
mail: { subject: "Invitation", html: `https://app.example.test/invitation/${OWNER_INVITATION_TOKEN}` },
};
describe("buildLeadConversionEventType", () => {
it("returns convertedtotrial for trial status", () => {
expect(buildLeadConversionEventType("trial")).toBe("marketing.lead.convertedtotrial");
@@ -30,6 +57,7 @@ describe("convertLeadToTenant", () => {
dbMock = (await import("~/utils/db.server")).db as any;
publishMock = (await import("@hivegrid/db/outbox")).publishOutboxEvent as any;
convertLeadToTenant = (await import("./convertLead.server")).convertLeadToTenant;
ownerInvitationMocks.issueReservedOwnerInvitationWithTx.mockResolvedValue({ invitationId: "invite_owner", replayed: false });
});
afterEach(() => {
@@ -38,6 +66,7 @@ describe("convertLeadToTenant", () => {
function buildTx(leadOverrides: Record<string, unknown> = {}) {
const tx: any = {
$executeRaw: vi.fn().mockResolvedValue(1),
lead: {
findUnique: vi.fn().mockResolvedValue({
id: "lead_1",
@@ -83,6 +112,7 @@ describe("convertLeadToTenant", () => {
const result = await convertLeadToTenant({
leadId: "lead_1",
ownerInvitation: OWNER_INVITATION,
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
@@ -90,16 +120,20 @@ describe("convertLeadToTenant", () => {
expect(result.status).toBe("trial");
expect(result.alreadyConverted).toBe(false);
expect(result.outboxEventId).toBe("outbox_1");
expect(tx.$executeRaw).toHaveBeenCalledOnce();
expect(String(tx.$executeRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
expect(tx.tenant.create).toHaveBeenCalledOnce();
expect(ownerInvitationMocks.issueReservedOwnerInvitationWithTx).toHaveBeenCalledWith(tx, {
tenantId: "tenant_1",
...OWNER_INVITATION,
});
expect(tx.lead.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "lead_1" },
data: expect.objectContaining({ status: "trial", convertedToTenantId: "tenant_1" }),
})
);
expect(tx.leadEvent.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ type: "converted" }) })
);
expect(tx.leadEvent.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ type: "converted" }) }));
expect(tx.tenantAcquisition.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
@@ -118,6 +152,7 @@ describe("convertLeadToTenant", () => {
dispatchKey: "lead-convert:lead_1",
})
);
expect(JSON.stringify(publishMock.mock.calls)).not.toContain(OWNER_INVITATION_TOKEN);
});
it("publishes customer event when targetStatus=customer", async () => {
@@ -127,12 +162,29 @@ describe("convertLeadToTenant", () => {
await convertLeadToTenant({
leadId: "lead_1",
targetStatus: "customer",
ownerInvitation: OWNER_INVITATION,
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
expect(publishMock).toHaveBeenCalledWith(
tx,
expect.objectContaining({ type: "marketing.lead.convertedtocustomer" })
);
expect(publishMock).toHaveBeenCalledWith(tx, expect.objectContaining({ type: "marketing.lead.convertedtocustomer" }));
});
it("propagates owner-mail issuance failure before mutating the lead or publishing the business event", async () => {
const tx = buildTx();
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
ownerInvitationMocks.issueReservedOwnerInvitationWithTx.mockRejectedValueOnce(new Error("mail outbox unavailable"));
await expect(
convertLeadToTenant({
leadId: "lead_1",
ownerInvitation: OWNER_INVITATION,
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
).rejects.toThrow("mail outbox unavailable");
expect(tx.lead.update).not.toHaveBeenCalled();
expect(tx.leadEvent.create).not.toHaveBeenCalled();
expect(tx.tenantAcquisition.create).not.toHaveBeenCalled();
expect(publishMock).not.toHaveBeenCalled();
});
it("returns alreadyConverted=true without re-creating tenant when lead already converted", async () => {
@@ -140,6 +192,7 @@ describe("convertLeadToTenant", () => {
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
const result = await convertLeadToTenant({
leadId: "lead_1",
ownerInvitation: OWNER_INVITATION,
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
expect(result.alreadyConverted).toBe(true);
@@ -148,6 +201,111 @@ describe("convertLeadToTenant", () => {
expect(publishMock).not.toHaveBeenCalled();
});
it("rejects changed owner identity before an already-converted replay can disclose the tenant id", async () => {
const tx = buildTx({ convertedToTenantId: "tenant_existing" });
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
await expect(
convertLeadToTenant({
leadId: "lead_1",
ownerInvitation: { ...OWNER_INVITATION, email: "attacker@example.com" },
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
).rejects.toMatchObject({ name: "LeadOwnerInvitationMismatchError" });
expect(tx.tenant.create).not.toHaveBeenCalled();
expect(ownerInvitationMocks.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled();
expect(publishMock).not.toHaveBeenCalled();
});
it.each([
{ firstName: null, lastName: "User" },
{ firstName: "Test", lastName: " " },
])("rejects an incomplete lead owner identity before creating the tenant", async (leadNames) => {
const tx = buildTx(leadNames);
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
await expect(
convertLeadToTenant({
leadId: "lead_1",
ownerInvitation: {
...OWNER_INVITATION,
firstName: leadNames.firstName ?? "",
lastName: leadNames.lastName,
},
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
).rejects.toMatchObject({ name: "LeadOwnerInvitationMismatchError" });
expect(tx.tenant.create).not.toHaveBeenCalled();
expect(ownerInvitationMocks.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled();
expect(tx.lead.update).not.toHaveBeenCalled();
expect(publishMock).not.toHaveBeenCalled();
});
it("serializes concurrent conversions so only one ownerless tenant is created", async () => {
let convertedToTenantId: string | null = null;
let lockTail = Promise.resolve();
const transactions: any[] = [];
dbMock.$transaction.mockImplementation(async (fn: (tx: any) => Promise<unknown>) => {
const tx = buildTx();
let releaseLock: (() => void) | undefined;
tx.$executeRaw.mockImplementationOnce(async () => {
const previous = lockTail;
lockTail = new Promise<void>((resolve) => {
releaseLock = resolve;
});
await previous;
return 1;
});
tx.lead.findUnique.mockImplementation(async () => ({
id: "lead_1",
email: "test@example.com",
firstName: "Test",
lastName: "User",
company: "Acme",
source: "landing-pro",
utmSource: null,
utmMedium: null,
utmCampaign: null,
utmTerm: null,
utmContent: null,
gclid: null,
fbclid: null,
referrer: null,
landingPage: null,
firstSeenAt: new Date("2026-05-10T00:00:00Z"),
status: "new",
convertedToTenantId,
}));
tx.tenant.create.mockImplementation(async ({ data }: { data: { id: string } }) => ({ id: data.id }));
tx.lead.update.mockImplementation(async ({ data }: { data: { convertedToTenantId: string } }) => {
convertedToTenantId = data.convertedToTenantId;
return {};
});
transactions.push(tx);
try {
return await fn(tx);
} finally {
releaseLock?.();
}
});
publishMock.mockResolvedValue({ id: "outbox_concurrent" });
const input = {
leadId: "lead_1",
ownerInvitation: OWNER_INVITATION,
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
} as const;
const [first, second] = await Promise.all([convertLeadToTenant(input), convertLeadToTenant(input)]);
expect([first.alreadyConverted, second.alreadyConverted].sort()).toEqual([false, true]);
expect(first.tenantId).toBe(second.tenantId);
expect(transactions.reduce((count, tx) => count + tx.tenant.create.mock.calls.length, 0)).toBe(1);
expect(transactions.every((tx) => tx.$executeRaw.mock.calls.length === 1)).toBe(true);
});
it("throws LeadNotFoundError when lead missing", async () => {
const tx = buildTx();
tx.lead.findUnique.mockResolvedValue(null);
@@ -155,6 +313,7 @@ describe("convertLeadToTenant", () => {
await expect(
convertLeadToTenant({
leadId: "lead_unknown",
ownerInvitation: { ...OWNER_INVITATION, issuanceKey: "lead:lead_unknown" },
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
).rejects.toMatchObject({ name: "LeadNotFoundError" });
@@ -163,12 +322,17 @@ describe("convertLeadToTenant", () => {
it("admin-override path stamps conversionPath=admin-override + actorId on LeadEvent", async () => {
const tx = buildTx();
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
let transactionContext: ReturnType<typeof getRlsExecutionContext>;
dbMock.$transaction.mockImplementation(async (fn: any) => {
transactionContext = getRlsExecutionContext();
return fn(tx);
});
publishMock.mockResolvedValue({ id: "outbox_3" });
await convertLeadToTenant({
leadId: "lead_1",
conversionPath: "admin-override",
actorId: "user_admin",
ownerInvitation: { ...OWNER_INVITATION, fromUserId: "user_admin" },
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
});
expect(tx.leadEvent.create).toHaveBeenCalledWith(
@@ -181,6 +345,45 @@ describe("convertLeadToTenant", () => {
data: expect.objectContaining({ conversionPath: "admin-override" }),
})
);
expect(transactionContext!).toMatchObject({ tenantId: expect.any(String), userId: "user_admin" });
expect(tx.tenant.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
id: transactionContext!.tenantId,
active: false,
deactivatedReason: TENANT_PENDING_OWNER_REASON,
}),
})
);
expect(getRlsExecutionContext()).toBeNull();
});
it("isolates conversion from an inherited tenant transaction for the same operator", async () => {
const tx = buildTx();
const inheritedTransaction = { id: "old-transaction" };
let transactionContext: ReturnType<typeof getRlsExecutionContext>;
dbMock.$transaction.mockImplementation(async (fn: any) => {
transactionContext = getRlsExecutionContext();
return fn(tx);
});
publishMock.mockResolvedValue({ id: "outbox_isolated" });
await runWithRlsContext({ tenantId: "tenant-old", userId: "user_admin" }, () =>
runWithRlsTransaction(inheritedTransaction, () =>
convertLeadToTenant({
leadId: "lead_1",
conversionPath: "admin-override",
actorId: "user_admin",
ownerInvitation: { ...OWNER_INVITATION, fromUserId: "user_admin" },
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
)
);
expect(transactionContext!).toMatchObject({ tenantId: expect.any(String), userId: "user_admin" });
expect(transactionContext!.tenantId).not.toBe("tenant-old");
expect(transactionContext!.transaction).toBeUndefined();
expect(getRlsExecutionContext()).toBeNull();
});
it("respects LEAD_CONVERSION_ENABLED=false rollback flag", async () => {
@@ -190,6 +393,7 @@ describe("convertLeadToTenant", () => {
await expect(
convertLeadToTenant({
leadId: "lead_1",
ownerInvitation: OWNER_INVITATION,
tenant: { name: "Acme", slug: "acme", inboundAddress: "acme@inbox.local" },
})
).rejects.toThrow(/disabled/i);
@@ -210,72 +414,63 @@ describe("recordExistingTenantLeadConversion", () => {
dbMock = (await import("~/utils/db.server")).db as any;
publishMock = (await import("@hivegrid/db/outbox")).publishOutboxEvent as any;
recordExistingTenantLeadConversion = (await import("./convertLead.server")).recordExistingTenantLeadConversion;
capabilityMocks.convertSelfServiceMarketingLeadCapability.mockReset();
});
afterEach(() => {
vi.clearAllMocks();
});
function buildExistingTenantTx(leadOverrides: Record<string, unknown> = {}) {
const tx: any = {
lead: {
findUnique: vi.fn().mockResolvedValue({
id: "lead_1",
email: "test@example.com",
firstName: "Test",
lastName: "User",
company: "Acme",
source: "landing-pro",
utmSource: "google",
utmMedium: "cpc",
utmCampaign: "q2-launch",
utmTerm: null,
utmContent: null,
gclid: null,
fbclid: null,
referrer: null,
landingPage: "/pricing",
firstSeenAt: new Date("2026-05-10T00:00:00Z"),
convertedToTenantId: null,
...leadOverrides,
}),
update: vi.fn().mockResolvedValue({}),
},
leadEvent: {
create: vi.fn().mockResolvedValue({}),
},
tenantAcquisition: {
upsert: vi.fn().mockResolvedValue({}),
},
function conversionSummary(overrides: Record<string, unknown> = {}) {
return {
leadId: "lead_1",
convertedToTenantId: "tenant_registered",
alreadyConverted: false,
email: "test@example.com",
firstName: "Test",
lastName: "User",
company: "Acme",
source: "landing-pro",
utmSource: "google",
utmMedium: "cpc",
utmCampaign: "q2-launch",
utmTerm: null,
utmContent: null,
gclid: null,
fbclid: null,
referrer: null,
landingPage: "/pricing",
firstSeenAt: "2026-05-10T00:00:00.000Z",
convertedAt: "2026-05-11T00:00:00.000Z",
...overrides,
};
return tx;
}
it("links an already-created registration tenant to the lead attribution and outbox event", async () => {
const tx = buildExistingTenantTx();
const tx = {};
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
capabilityMocks.convertSelfServiceMarketingLeadCapability.mockResolvedValue(conversionSummary());
publishMock.mockResolvedValue({ id: "outbox_4" });
const result = await recordExistingTenantLeadConversion({
leadId: "lead_1",
tenantId: "tenant_registered",
userId: "user_1",
expectedEmail: "test@example.com",
planId: "plan_pro",
conversionPath: "self-service",
});
expect(result).toMatchObject({ tenantId: "tenant_registered", leadId: "lead_1", alreadyConverted: false, outboxEventId: "outbox_4" });
expect(tx.lead.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "lead_1" },
data: expect.objectContaining({ status: "trial", convertedToTenantId: "tenant_registered" }),
})
);
expect(tx.tenantAcquisition.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: "tenant_registered" },
create: expect.objectContaining({ tenantId: "tenant_registered", leadId: "lead_1", conversionPath: "self-service" }),
update: expect.objectContaining({ leadId: "lead_1", conversionPath: "self-service" }),
})
expect(capabilityMocks.convertSelfServiceMarketingLeadCapability).toHaveBeenCalledWith(
{
leadId: "lead_1",
tenantId: "tenant_registered",
userId: "user_1",
expectedEmail: "test@example.com",
planId: "plan_pro",
},
tx
);
expect(publishMock).toHaveBeenCalledWith(
tx,
@@ -289,26 +484,36 @@ describe("recordExistingTenantLeadConversion", () => {
});
it("is idempotent when the same tenant already owns the lead conversion", async () => {
const tx = buildExistingTenantTx({ convertedToTenantId: "tenant_registered" });
const tx = {};
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
capabilityMocks.convertSelfServiceMarketingLeadCapability.mockResolvedValue(conversionSummary({ alreadyConverted: true }));
const result = await recordExistingTenantLeadConversion({ leadId: "lead_1", tenantId: "tenant_registered" });
const result = await recordExistingTenantLeadConversion({
leadId: "lead_1",
tenantId: "tenant_registered",
userId: "user_1",
expectedEmail: "test@example.com",
});
expect(result.alreadyConverted).toBe(true);
expect(tx.lead.update).not.toHaveBeenCalled();
expect(tx.tenantAcquisition.upsert).not.toHaveBeenCalled();
expect(publishMock).not.toHaveBeenCalled();
});
it("rejects a lead already converted to a different tenant", async () => {
const tx = buildExistingTenantTx({ convertedToTenantId: "tenant_other" });
const tx = {};
dbMock.$transaction.mockImplementation(async (fn: any) => fn(tx));
capabilityMocks.convertSelfServiceMarketingLeadCapability.mockResolvedValue(
conversionSummary({ convertedToTenantId: "tenant_other", alreadyConverted: true })
);
await expect(recordExistingTenantLeadConversion({ leadId: "lead_1", tenantId: "tenant_registered" })).rejects.toMatchObject({
name: "LeadAlreadyConvertedError",
convertedToTenantId: "tenant_other",
});
await expect(
recordExistingTenantLeadConversion({
leadId: "lead_1",
tenantId: "tenant_registered",
userId: "user_1",
expectedEmail: "test@example.com",
})
).rejects.toMatchObject({ name: "LeadAlreadyConvertedError", convertedToTenantId: "tenant_other" });
expect(LeadAlreadyConvertedError.name).toBe("LeadAlreadyConvertedError");
expect(tx.lead.update).not.toHaveBeenCalled();
});
});
@@ -190,17 +190,17 @@ export async function updateLeadStatus(
const current = await db.lead.findUnique({ where: { id: leadId }, select: { status: true } });
if (!current) return;
if (current.status === next) return;
await db.$transaction([
db.lead.update({ where: { id: leadId }, data: { status: next } }),
db.leadEvent.create({
await db.$transaction(async (tx) => {
await tx.lead.update({ where: { id: leadId }, data: { status: next } });
await tx.leadEvent.create({
data: {
leadId,
type: "status-changed",
actorId,
payload: { from: current.status, to: next } as object,
},
}),
]);
});
});
}
export async function appendNote(leadId: string, body: string, actorId: string | null): Promise<void> {
@@ -215,15 +215,15 @@ export async function appendNote(leadId: string, body: string, actorId: string |
{ body: (previous?.body as string | undefined) ?? "", at: (previous?.updatedAt as string | undefined) ?? null },
],
};
await db.$transaction([
db.lead.update({ where: { id: leadId }, data: { notes: updated as object } }),
db.leadEvent.create({
await db.$transaction(async (tx) => {
await tx.lead.update({ where: { id: leadId }, data: { notes: updated as object } });
await tx.leadEvent.create({
data: {
leadId,
type: "note-added",
actorId,
payload: { length: body.length } as object,
},
}),
]);
});
});
}
@@ -23,6 +23,13 @@ describe("escapeCsvValue", () => {
expect(escapeCsvValue("line1\nline2")).toBe('"line1\nline2"');
expect(escapeCsvValue("line1\r\nline2")).toBe('"line1\r\nline2"');
});
it.each(["=1+1", "+cmd", "-2+3", "@SUM(A1:A2)", " =1+1", "\tformula", "\rformula", "\nformula"])(
"neutralizes spreadsheet formula value %j",
(value) => {
expect(escapeCsvValue(value)).toBe(/[\r\n]/.test(value) ? `"'${value}"` : `'${value}`);
},
);
});
describe("serializeLeadsCsv", () => {
@@ -6,6 +6,7 @@
* leads/export.ts` so the admin-UI download and the `hivegrid-cli leads
* export` operator-side dump are byte-compatible.
*/
import { neutralizeSpreadsheetFormula } from "@hivegrid/foundation/spreadsheet-safety";
export const LEAD_CSV_COLUMNS = [
"id",
@@ -38,11 +39,11 @@ export type LeadCsvRow = {
export function escapeCsvValue(value: unknown): string {
if (value === null || value === undefined) return "";
const raw = value instanceof Date ? value.toISOString() : String(value);
if (/[",\n\r]/.test(raw)) {
return `"${raw.replace(/"/g, '""')}"`;
const safeValue = neutralizeSpreadsheetFormula(value instanceof Date ? value.toISOString() : String(value));
if (/[",\n\r]/.test(safeValue)) {
return `"${safeValue.replace(/"/g, '""')}"`;
}
return raw;
return safeValue;
}
export function serializeLeadsCsv(rows: ReadonlyArray<LeadCsvRow>): string {
@@ -1,13 +1,10 @@
/**
* CORS-allowlist matcher for the marketing-funnel capture endpoint (Phase 05 #78).
* CORS-allowlist matcher retained for the retired browser-capture drain response.
*
* The endpoint is intentionally public so external landing-pages can ingest
* leads, but the Origin header is matched against `MARKETING_ALLOWED_ORIGINS`
* (comma-separated env list). Wildcards are supported via a single leading `*`
* in the host (e.g. `https://*.hivegrid.de`).
*
* Server-to-server bots can spoof Origin — this layer is one of three (origin
* allowlist, rate-limit, optional Turnstile). It does NOT replace rate-limiting.
* `/api/leads/capture` no longer writes and always returns 410. The allowlist
* only permits known stale browser deployments to read that structured response
* cross-origin during the R-LEADS drain window. Native intake is authenticated
* server-to-server at `/v1/platform/leads` and does not use this helper.
*/
export function parseAllowedOrigins(raw: string | undefined | null): string[] {