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

@@ -14,6 +14,7 @@ export type LeadAuditAction =
| "lead.convert_requested"
| "lead.source_created"
| "lead.source_updated"
| "lead.source_archived"
| "lead.anti_spam_updated";
export async function auditLeadEvent(input: {
@@ -0,0 +1,75 @@
// Pure query helpers for the lead inbox: the status dropdown maps a single UI
// value onto the query's status list (and back), and the statistics tiles turn a
// KPI into the search params that reproduce exactly what that tile counted.
import { describe, expect, it } from "vitest";
import {
canTransitionLeadStatus,
leadStatisticsKpiParams,
leadStatusFilterFromQuery,
leadStatusFilterToQuery,
parseLeadListQuery,
} from "./leadListQuery";
describe("lead status filter mapping", () => {
it("round-trips every value the dropdown can hold", () => {
for (const value of ["any", "new", "qualified", "converted", "lost", "spam"] as const) {
expect(leadStatusFilterFromQuery(leadStatusFilterToQuery(value))).toBe(value);
}
});
it("falls back to 'any' for a combination it cannot name", () => {
// The dropdown is single-select, so any multi-status query would be
// misreported by naming just one of them.
expect(leadStatusFilterFromQuery(["new", "qualified"])).toBe("any");
expect(leadStatusFilterFromQuery(["new", "spam", "lost"])).toBe("any");
expect(leadStatusFilterFromQuery([])).toBe("any");
expect(leadStatusFilterFromQuery(null)).toBe("any");
});
});
describe("leadStatisticsKpiParams", () => {
const parse = (kpi: Parameters<typeof leadStatisticsKpiParams>[0]) => parseLeadListQuery(leadStatisticsKpiParams(kpi));
it("links 'total' to an unfiltered list that also shows spam and converted", () => {
const query = parse("total");
expect(query.filter.status).toBeNull();
expect(query.filter.includeSpam).toBe(true);
expect(query.filter.includeConverted).toBe(true);
});
it("links the 'new' tile to exactly the new status it counts", () => {
expect(parse("new").filter.status).toEqual(["new"]);
});
it("makes the spam and converted tiles reveal what they count", () => {
// Both are hidden by default — without flipping visibility the tile would
// link to an empty table.
const spam = parse("spam");
expect(spam.filter.status).toEqual(["spam"]);
expect(spam.filter.includeSpam).toBe(true);
const converted = parse("converted");
expect(converted.filter.status).toEqual(["converted"]);
expect(converted.filter.includeConverted).toBe(true);
});
it("survives the round trip through the dropdown value", () => {
expect(leadStatusFilterFromQuery(parse("new").filter.status)).toBe("new");
expect(leadStatusFilterFromQuery(parse("spam").filter.status)).toBe("spam");
expect(leadStatusFilterFromQuery(parse("total").filter.status)).toBe("any");
});
});
describe("canTransitionLeadStatus", () => {
it("allows the forward moves and blocks every exit from a terminal status", () => {
expect(canTransitionLeadStatus("new", "qualified")).toBe(true);
expect(canTransitionLeadStatus("qualified", "converted")).toBe(true);
expect(canTransitionLeadStatus("qualified", "new")).toBe(false);
for (const terminal of ["converted", "lost", "spam"] as const) {
expect(canTransitionLeadStatus(terminal, "qualified")).toBe(false);
// Staying put is not a transition.
expect(canTransitionLeadStatus(terminal, terminal)).toBe(true);
}
});
});
@@ -1,4 +1,11 @@
export type LeadStatus = "new" | "qualified" | "converted" | "lost" | "spam";
import {
ALLOWED_LEAD_STATUS_TRANSITIONS,
canTransitionLeadStatus,
type LeadStatus,
} from "@hivegrid/db/lead-status-contract";
export { ALLOWED_LEAD_STATUS_TRANSITIONS, canTransitionLeadStatus };
export type { LeadStatus };
export type LeadQuelle = "form" | "email" | "aircall" | "manual" | "custom";
export type LeadSortField = "createdAt" | "status" | "quelle" | "spamScore";
export type SortDir = "asc" | "desc";
@@ -18,6 +25,37 @@ export interface LeadListQuery {
cursor: string | null;
}
/** What the single status dropdown in the inbox can stand for. */
export type LeadStatusFilterValue = "any" | LeadStatus;
export function leadStatusFilterToQuery(value: LeadStatusFilterValue): LeadStatus[] | null {
return value === "any" ? null : [value];
}
/** Inverse of the above; anything it cannot name exactly falls back to "any". */
export function leadStatusFilterFromQuery(status: readonly LeadStatus[] | null | undefined): LeadStatusFilterValue {
return status && status.length === 1 ? status[0] : "any";
}
/**
* Search params that make the inbox show exactly what a statistics KPI tile
* counts. Spam and converted leads are hidden by default, so the two tiles that
* count them have to turn their visibility on as well — otherwise the tile links
* to an empty table.
*/
export function leadStatisticsKpiParams(kpi: "total" | "new" | "converted" | "spam"): URLSearchParams {
const base = { quelle: null, zustaendigerUserId: null, search: null };
const filter: LeadListFilter =
kpi === "total"
? { ...base, status: null, includeSpam: true, includeConverted: true }
: kpi === "new"
? { ...base, status: ["new"], includeSpam: false, includeConverted: false }
: kpi === "converted"
? { ...base, status: ["converted"], includeSpam: false, includeConverted: true }
: { ...base, status: ["spam"], includeSpam: true, includeConverted: false };
return leadListQueryToParams({ filter, sort: { field: "createdAt", dir: "desc" }, cursor: null });
}
const STATUSES = new Set<LeadStatus>(["new", "qualified", "converted", "lost", "spam"]);
const QUELLEN = new Set<LeadQuelle>(["form", "email", "aircall", "manual", "custom"]);
const SORT_FIELDS = new Set<LeadSortField>(["createdAt", "status", "quelle", "spamScore"]);
@@ -12,8 +12,14 @@ export function leadDetailPath(tenantSlug: string, leadId: string): string {
return `/${tenantSlug}/leads/${leadId}`;
}
// Own top-level path (not /leads/statistics): the statistics screen is reached
// through the leads sub-sidenav, not from inside the inbox route family.
export function leadStatisticsPath(tenantSlug: string): string {
return `/${tenantSlug}/leads/statistics`;
return `/${tenantSlug}/leads-statistics`;
}
export function leadBoardPath(tenantSlug: string): string {
return `/${tenantSlug}/leads/board`;
}
export function leadEventsPath(tenantSlug: string): string {
@@ -0,0 +1,195 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tx: {
inboxLead: { findFirst: vi.fn(), update: vi.fn() },
kontakt: { findFirst: vi.fn() },
projekt: { findFirst: vi.fn() },
userRole: { findMany: vi.fn() },
groupUser: { findMany: vi.fn() },
},
publishOutboxEvent: vi.fn(),
publishLeadSearchUpsert: vi.fn(),
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
vi.mock("~/utils/db.server", () => ({ db: {} }));
vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: mocks.publishOutboxEvent }));
vi.mock("@hivegrid/queue", () => ({ buildWorkflowTriggerOutboxEvent: vi.fn(() => ({})) }));
vi.mock("~/services/search/searchIndexProjection.server", () => ({
publishLeadSearchUpsert: mocks.publishLeadSearchUpsert,
publishProjectSearchUpsert: vi.fn(),
}));
import { completeLeadProjectConversion, requestLeadProjectConversion } from "./leadService.server";
const qualifiedLead = {
id: "lead-a",
tenantId: "tenant-a",
createdByUserId: "actor-a",
zustaendigerUserId: "actor-a",
quelle: "manual",
quelleDetail: null,
sourceId: null,
sourceOrigin: null,
submitterIpHash: null,
status: "qualified",
weiterverarbeitungFreigabe: "ja",
vorname: "Marie",
nachname: "Muster",
email: "marie@example.test",
telefon: null,
message: null,
rohdaten: null,
spamScore: 0,
spamReason: null,
isQuarantined: false,
konvertiertProjektId: null,
verknuepfterKontaktId: null,
convertedAt: null,
lostAt: null,
spamMarkedAt: null,
autoDeleteAt: null,
isDemoData: false,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
archivedAt: null,
} as const;
describe("lead conversion target visibility", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tx.inboxLead.findFirst.mockResolvedValue(qualifiedLead);
mocks.tx.inboxLead.update.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({
...qualifiedLead,
...data,
}));
mocks.tx.kontakt.findFirst.mockResolvedValue({ id: "contact-a" });
mocks.tx.projekt.findFirst.mockResolvedValue({ id: "project-a" });
mocks.tx.userRole.findMany.mockResolvedValue([{ roleId: "role-a" }]);
mocks.tx.groupUser.findMany.mockResolvedValue([{ groupId: "group-a" }]);
});
it("returns 404 before mutation when a requested contact is outside crm.read_own", async () => {
mocks.tx.kontakt.findFirst.mockResolvedValueOnce(null);
await expect(
requestLeadProjectConversion({
tenantId: "tenant-a",
leadId: "lead-a",
kontaktId: " contact-from-tenant-b ",
ctx: { userId: "actor-a", permissions: ["leads.read_own", "leads.write", "crm.read_own"] },
})
).rejects.toMatchObject({ status: 404 });
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
where: {
id: "contact-from-tenant-b",
tenantId: "tenant-a",
archivedAt: null,
zustaendigerUserId: "actor-a",
},
select: { id: true },
});
expect(mocks.tx.inboxLead.update).not.toHaveBeenCalled();
});
it("returns 404 before mutation when the project is outside the project read scope", async () => {
mocks.tx.projekt.findFirst.mockResolvedValueOnce(null);
await expect(
completeLeadProjectConversion({
tenantId: "tenant-a",
leadId: "lead-a",
projektId: "project-from-tenant-b",
ctx: {
userId: "actor-a",
permissions: ["leads.read_own", "leads.write", "projects.read_all"],
roleIds: ["role-a"],
groupIds: ["group-a"],
},
})
).rejects.toMatchObject({ status: 404 });
expect(mocks.tx.projekt.findFirst).toHaveBeenCalledWith({
where: {
id: "project-from-tenant-b",
tenantId: "tenant-a",
archivedAt: null,
pipeline: {
accessRules: {
none: {
tenantId: "tenant-a",
kannSehen: false,
OR: [
{ principalType: "user", principalId: "actor-a" },
{ principalType: "role", principalId: "role-a" },
{ principalType: "group", principalId: "group-a" },
],
},
},
},
},
select: { id: true },
});
expect(mocks.tx.inboxLead.update).not.toHaveBeenCalled();
});
it("returns 404 when the actor has no project read permission", async () => {
await expect(
completeLeadProjectConversion({
tenantId: "tenant-a",
leadId: "lead-a",
projektId: "project-a",
ctx: { userId: "actor-a", permissions: ["leads.read_own", "leads.write"] },
})
).rejects.toMatchObject({ status: 404 });
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
expect(mocks.tx.inboxLead.update).not.toHaveBeenCalled();
});
it("validates and stores only visible normalized conversion targets", async () => {
await expect(
completeLeadProjectConversion({
tenantId: "tenant-a",
leadId: "lead-a",
projektId: " project-a ",
kontaktId: " contact-a ",
ctx: {
userId: "actor-a",
permissions: ["leads.read_own", "leads.write", "projects.read_all", "crm.read_own"],
roleIds: [],
groupIds: [],
},
})
).resolves.toMatchObject({
status: "converted",
konvertiertProjektId: "project-a",
verknuepfterKontaktId: "contact-a",
});
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
where: {
id: "contact-a",
tenantId: "tenant-a",
archivedAt: null,
zustaendigerUserId: "actor-a",
},
select: { id: true },
});
expect(mocks.tx.inboxLead.update).toHaveBeenCalledWith({
where: { id: "lead-a", tenantId: "tenant-a" },
data: {
status: "converted",
weiterverarbeitungFreigabe: "ja",
konvertiertProjektId: "project-a",
verknuepfterKontaktId: "contact-a",
convertedAt: expect.any(Date),
autoDeleteAt: null,
},
});
});
});
@@ -1,9 +1,13 @@
import { CatalogError, foundationErrors, notify } from "@hivegrid/foundation";
import { CatalogError, foundationErrors, massActionErrors, notify } from "@hivegrid/foundation";
import { leadStatusTimestampData } from "@hivegrid/db/lead-status-contract";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { buildWorkflowTriggerOutboxEvent, type QueueJsonValue } from "@hivegrid/queue";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { publishLeadSearchUpsert } from "~/services/search/searchIndexProjection.server";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { projectReadScopeWhere, type ProjectVisibilityContext } from "~/utils/integrations/projects/projectService.server";
import { canTransitionLeadStatus } from "./leadListQuery";
import type { LeadListFilter, LeadSortField, SortDir } from "./leadListQuery";
export class LeadServiceError extends Error {
@@ -21,10 +25,7 @@ export type LeadWeiterverarbeitungFreigabe = "ja" | "nein" | "unklar";
export type LeadSourceType = "system" | "custom";
export type LeadAntiSpamMode = "quarantine" | "spam";
export type LeadVisibilityContext = {
userId: string;
permissions: readonly string[];
};
export type LeadVisibilityContext = ProjectVisibilityContext;
export function canReadAllLeads(ctx: LeadVisibilityContext): boolean {
return ctx.permissions.includes("leads.read_all");
@@ -34,6 +35,70 @@ export function ownerScopeWhere(ctx: LeadVisibilityContext): { zustaendigerUserI
return canReadAllLeads(ctx) ? {} : { zustaendigerUserId: ctx.userId };
}
async function requireActiveTenantUserWithTx(tx: TenantRlsClient, tenantId: string, userId: string): Promise<void> {
const membership = await tx.tenantUser.findFirst({
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
select: { id: true },
});
if (!membership) throw new CatalogError(foundationErrors.notFound, { userId });
}
async function hydrateProjectVisibilityContextWithTx(tx: TenantRlsClient, tenantId: string, ctx: LeadVisibilityContext): Promise<ProjectVisibilityContext> {
const [roleIds, groupIds] = await Promise.all([
ctx.roleIds === undefined
? tx.userRole.findMany({ where: { tenantId, userId: ctx.userId }, select: { roleId: true } }).then((rows) => rows.map(({ roleId }) => roleId))
: Promise.resolve([...ctx.roleIds]),
ctx.groupIds === undefined
? tx.groupUser
.findMany({ where: { userId: ctx.userId, group: { tenantId } }, select: { groupId: true } })
.then((rows) => rows.map(({ groupId }) => groupId))
: Promise.resolve([...ctx.groupIds]),
]);
return { ...ctx, roleIds, groupIds };
}
async function requireVisibleConversionProjectWithTx(tx: TenantRlsClient, tenantId: string, projectId: string, ctx: LeadVisibilityContext): Promise<void> {
if (
!ctx.permissions.some((permission) => ["projects.read_all", "projects.read_own", "projects.read_own_pl", "projects.read_own_member"].includes(permission))
) {
throw new CatalogError(foundationErrors.notFound, { projectId });
}
const projectCtx = await hydrateProjectVisibilityContextWithTx(tx, tenantId, ctx);
const project = await tx.projekt.findFirst({
where: {
id: projectId,
tenantId,
archivedAt: null,
...projectReadScopeWhere(tenantId, projectCtx),
},
select: { id: true },
});
if (!project) throw new CatalogError(foundationErrors.notFound, { projectId });
}
async function requireVisibleConversionContactWithTx(
tx: TenantRlsClient,
tenantId: string,
kontaktId: string | null,
ctx: LeadVisibilityContext
): Promise<void> {
if (!kontaktId) return;
const canReadAll = ctx.permissions.includes("crm.read_all");
if (!canReadAll && !ctx.permissions.includes("crm.read_own")) {
throw new CatalogError(foundationErrors.notFound, { kontaktId });
}
const kontakt = await tx.kontakt.findFirst({
where: {
id: kontaktId,
tenantId,
archivedAt: null,
...(canReadAll ? {} : { zustaendigerUserId: ctx.userId }),
},
select: { id: true },
});
if (!kontakt) throw new CatalogError(foundationErrors.notFound, { kontaktId });
}
export type LeadRow = {
id: string;
tenantId: string;
@@ -101,15 +166,6 @@ export type LeadAntiSpamConfigRow = {
};
const DEFAULT_LIMIT = 50;
const SPAM_AUTO_DELETE_DAYS = 30;
const TERMINAL: ReadonlySet<LeadStatus> = new Set(["converted", "lost", "spam"]);
const ALLOWED_STATUS_TRANSITIONS: Readonly<Record<LeadStatus, readonly LeadStatus[]>> = {
new: ["qualified", "lost", "spam"],
qualified: ["converted", "lost", "spam"],
converted: [],
lost: [],
spam: [],
};
function normalizeEmail(email?: string | null): string | null {
const value = email?.trim().toLowerCase();
@@ -121,7 +177,13 @@ function normalizeTelefon(telefon?: string | null): string | null {
return value || null;
}
function leadNamePresent(input: { vorname?: string | null; nachname?: string | null; email?: string | null; telefon?: string | null; message?: string | null }): boolean {
function leadNamePresent(input: {
vorname?: string | null;
nachname?: string | null;
email?: string | null;
telefon?: string | null;
message?: string | null;
}): boolean {
return Boolean(input.vorname?.trim() || input.nachname?.trim() || input.email?.trim() || input.telefon?.trim() || input.message?.trim());
}
@@ -137,9 +199,7 @@ async function ensureAntiSpamConfigWithTx(tx: TenantRlsClient, tenantId: string)
return created as LeadAntiSpamConfigRow;
}
export function canTransitionLeadStatus(from: LeadStatus, to: LeadStatus): boolean {
return from === to || ALLOWED_STATUS_TRANSITIONS[from].includes(to);
}
export { canTransitionLeadStatus };
function assertStatusTransition(from: LeadStatus, to: LeadStatus): void {
if (!canTransitionLeadStatus(from, to)) {
@@ -148,27 +208,29 @@ function assertStatusTransition(from: LeadStatus, to: LeadStatus): void {
}
function autoDeleteAtForStatus(status: LeadStatus, now: Date, config: Pick<LeadAntiSpamConfigRow, "lostAutoDeleteDays">): Date | null {
if (status === "spam") {
return new Date(now.getTime() + SPAM_AUTO_DELETE_DAYS * 24 * 60 * 60 * 1000);
}
if (status === "lost" && config.lostAutoDeleteDays > 0) {
return new Date(now.getTime() + config.lostAutoDeleteDays * 24 * 60 * 60 * 1000);
}
return null;
const data = leadStatusTimestampData(status, now, config.lostAutoDeleteDays);
return "autoDeleteAt" in data ? (data.autoDeleteAt ?? null) : null;
}
function statusTimestamps(status: LeadStatus, now: Date, config: Pick<LeadAntiSpamConfigRow, "lostAutoDeleteDays">) {
return {
...(status === "qualified" ? { weiterverarbeitungFreigabe: "ja" as const } : {}),
...(status === "converted" ? { convertedAt: now } : {}),
...(status === "lost" ? { lostAt: now } : {}),
...(status === "spam" ? { spamMarkedAt: now } : {}),
...(TERMINAL.has(status) ? { autoDeleteAt: autoDeleteAtForStatus(status, now, config) } : {}),
};
return leadStatusTimestampData(status, now, config.lostAutoDeleteDays);
}
function toWorkflowPayload(input: {
lead: Pick<LeadRow, "id" | "tenantId" | "quelle" | "sourceId" | "status" | "weiterverarbeitungFreigabe" | "zustaendigerUserId" | "konvertiertProjektId" | "verknuepfterKontaktId" | "spamScore" | "isQuarantined">;
lead: Pick<
LeadRow,
| "id"
| "tenantId"
| "quelle"
| "sourceId"
| "status"
| "weiterverarbeitungFreigabe"
| "zustaendigerUserId"
| "konvertiertProjektId"
| "verknuepfterKontaktId"
| "spamScore"
| "isQuarantined"
>;
action: "created" | "qualified" | "status_changed" | "convert_requested" | "converted";
}): QueueJsonValue {
return {
@@ -195,7 +257,7 @@ async function publishLeadWorkflowEvent(
lead: LeadRow;
event: "lead.created" | "lead.qualified" | "lead.status_changed" | "lead.convert_requested" | "lead.converted";
action: "created" | "qualified" | "status_changed" | "convert_requested" | "converted";
},
}
): Promise<void> {
await publishOutboxEvent(
tx as unknown as OutboxPublisherTransaction,
@@ -205,13 +267,13 @@ async function publishLeadWorkflowEvent(
data: toWorkflowPayload({ lead: input.lead, action: input.action }),
userId: input.userId,
sourceId: `lead:${input.lead.id}:${input.action}`,
}),
})
);
}
async function notifyLeadSourcePausedAdmins(
tx: TenantRlsClient,
input: { tenantId: string; source: Pick<LeadSourceRow, "id" | "key" | "name">; reason: string },
input: { tenantId: string; source: Pick<LeadSourceRow, "id" | "key" | "name">; reason: string }
): Promise<void> {
try {
const admins = await tx.userRole.findMany({
@@ -234,9 +296,9 @@ async function notifyLeadSourcePausedAdmins(
sourceKey: `lead-source-paused:${input.source.id}`,
payloadMetadata: { sourceId: input.source.id, sourceKey: input.source.key, sourceName: input.source.name, reason: input.reason },
},
tx as unknown as Parameters<typeof notify>[1],
),
),
tx as unknown as Parameters<typeof notify>[1]
)
)
);
} catch {
// Notification failures must not lose the lead submission.
@@ -282,9 +344,7 @@ async function computeRateAndAnomalySignals(input: {
}): Promise<{ score: number; reasons: string[]; pauseSource: boolean }> {
const oneHourAgo = new Date(input.now.getTime() - 60 * 60 * 1000);
const dayAgo = new Date(input.now.getTime() - 24 * 60 * 60 * 1000);
const sourceWhere = input.source
? { sourceId: input.source.id }
: { sourceId: null, quelle: input.quelle };
const sourceWhere = input.source ? { sourceId: input.source.id } : { sourceId: null, quelle: input.quelle };
const [sourceHourCount, sourceDayCount, ipHourCount] = await Promise.all([
input.tx.inboxLead.count({ where: { tenantId: input.tenantId, createdAt: { gte: oneHourAgo }, ...sourceWhere } }),
input.tx.inboxLead.count({ where: { tenantId: input.tenantId, createdAt: { gte: dayAgo }, ...sourceWhere } }),
@@ -338,9 +398,7 @@ export async function createLead(input: CreateLeadInput): Promise<LeadRow> {
const lead = await withTenantRLS(input.tenantId, async (tx) => {
const now = new Date();
const config = await ensureAntiSpamConfigWithTx(tx, input.tenantId);
const source = input.sourceId
? await tx.leadSource.findFirst({ where: { id: input.sourceId, tenantId: input.tenantId, archivedAt: null } })
: null;
const source = input.sourceId ? await tx.leadSource.findFirst({ where: { id: input.sourceId, tenantId: input.tenantId, archivedAt: null } }) : null;
if (source?.pausedAt) {
throw new LeadServiceError("leads.error.sourcePaused");
}
@@ -361,6 +419,8 @@ export async function createLead(input: CreateLeadInput): Promise<LeadRow> {
const spamReasons = [...(spam.reason ? spam.reason.split(",") : []), ...rateSignals.reasons];
const status: LeadStatus = spamScore >= 80 && config.mode === "spam" ? "spam" : "new";
const isQuarantined = status !== "spam" && (spam.quarantine || spamScore >= 50);
const responsibleUserId = input.zustaendigerUserId ?? source?.defaultZustaendigerUserId ?? input.userId ?? null;
if (responsibleUserId) await requireActiveTenantUserWithTx(tx, input.tenantId, responsibleUserId);
if (source && rateSignals.pauseSource) {
await tx.leadSource.update({ where: { id: source.id }, data: { pausedAt: now } });
await notifyLeadSourcePausedAdmins(tx, { tenantId: input.tenantId, source: source as LeadSourceRow, reason: "source_anomaly_spike" });
@@ -369,7 +429,7 @@ export async function createLead(input: CreateLeadInput): Promise<LeadRow> {
data: {
tenantId: input.tenantId,
createdByUserId: input.userId ?? null,
zustaendigerUserId: input.zustaendigerUserId ?? source?.defaultZustaendigerUserId ?? input.userId ?? null,
zustaendigerUserId: responsibleUserId,
quelle: input.quelle,
quelleDetail: input.quelleDetail ?? undefined,
sourceId: source?.id ?? null,
@@ -468,10 +528,40 @@ export async function listLeadsForBrowser(input: {
});
}
export async function listLeadsForBoard(input: {
tenantId: string;
ctx: LeadVisibilityContext;
statuses: readonly LeadStatus[];
search?: string | null;
limitPerStatus?: number;
}): Promise<{ rows: LeadRow[]; countsByStatus: Partial<Record<LeadStatus, number>> }> {
const limitPerStatus = Math.min(Math.max(input.limitPerStatus ?? DEFAULT_LIMIT, 1), DEFAULT_LIMIT);
return withTenantRLS(input.tenantId, async (tx) => {
const queries = input.statuses.map(async (status) => {
const where = whereForLeadList(input.tenantId, input.ctx, {
status: [status],
quelle: null,
zustaendigerUserId: null,
search: input.search?.trim() || null,
includeSpam: false,
includeConverted: true,
});
const [rows, count] = await Promise.all([
tx.inboxLead.findMany({ where, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: limitPerStatus }),
tx.inboxLead.count({ where }),
]);
return { status, rows: rows as LeadRow[], count };
});
const results = await Promise.all(queries);
return {
rows: results.flatMap((result) => result.rows),
countsByStatus: Object.fromEntries(results.map((result) => [result.status, result.count])) as Partial<Record<LeadStatus, number>>,
};
});
}
export async function getVisibleLeadOrThrow(tenantId: string, leadId: string, ctx: LeadVisibilityContext): Promise<LeadRow> {
const lead = await withTenantRLS(tenantId, (tx) =>
tx.inboxLead.findFirst({ where: { id: leadId, tenantId, archivedAt: null, ...ownerScopeWhere(ctx) } }),
);
const lead = await withTenantRLS(tenantId, (tx) => tx.inboxLead.findFirst({ where: { id: leadId, tenantId, archivedAt: null, ...ownerScopeWhere(ctx) } }));
if (!lead) {
throw new CatalogError(foundationErrors.notFound, { leadId });
}
@@ -491,6 +581,9 @@ export async function updateLead(input: {
zustaendigerUserId?: string | null;
}): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
if (input.zustaendigerUserId) {
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
}
const existing = await tx.inboxLead.findFirst({
where: { id: input.leadId, tenantId: input.tenantId, archivedAt: null, ...(input.ctx ? ownerScopeWhere(input.ctx) : {}) },
select: { id: true },
@@ -512,7 +605,13 @@ export async function updateLead(input: {
});
}
export async function setLeadStatus(input: { tenantId: string; leadId: string; status: LeadStatus; ctx?: LeadVisibilityContext; userId?: string | null }): Promise<LeadRow> {
export async function setLeadStatus(input: {
tenantId: string;
leadId: string;
status: LeadStatus;
ctx?: LeadVisibilityContext;
userId?: string | null;
}): Promise<LeadRow> {
const now = new Date();
return withTenantRLS(input.tenantId, async (tx) => {
const config = await ensureAntiSpamConfigWithTx(tx, input.tenantId);
@@ -544,12 +643,13 @@ export async function setLeadStatus(input: { tenantId: string; leadId: string; s
}
export async function bulkSetLeadStatus(input: { tenantId: string; ctx: LeadVisibilityContext; leadIds: string[]; status: LeadStatus }): Promise<number> {
if (input.leadIds.length === 0) return 0;
const leadIds = normalizeBulkLeadIds(input.leadIds);
if (leadIds.length === 0) return 0;
const now = new Date();
const result = await withTenantRLS(input.tenantId, async (tx) => {
const config = await ensureAntiSpamConfigWithTx(tx, input.tenantId);
const leads = await tx.inboxLead.findMany({
where: { id: { in: input.leadIds }, tenantId: input.tenantId, archivedAt: null, ...ownerScopeWhere(input.ctx) },
where: { id: { in: leadIds }, tenantId: input.tenantId, archivedAt: null, ...ownerScopeWhere(input.ctx) },
});
if (leads.some((lead) => !canTransitionLeadStatus(lead.status as LeadStatus, input.status))) {
throw new LeadServiceError("leads.error.invalidStatusTransition");
@@ -574,7 +674,25 @@ export async function bulkSetLeadStatus(input: { tenantId: string; ctx: LeadVisi
return result.count;
}
export async function requestLeadProjectConversion(input: { tenantId: string; leadId: string; kontaktId?: string | null; ctx?: LeadVisibilityContext; userId?: string | null }): Promise<LeadRow> {
export const LEAD_BULK_MAX_ENTRIES = 100;
export function normalizeBulkLeadIds(leadIds: readonly string[]): string[] {
if (leadIds.length > LEAD_BULK_MAX_ENTRIES) {
throw new CatalogError(massActionErrors.exceedsLimit, {
affected: leadIds.length,
hardLimit: LEAD_BULK_MAX_ENTRIES,
});
}
return [...new Set(leadIds.map((id) => id.trim()).filter(Boolean))];
}
export async function requestLeadProjectConversion(input: {
tenantId: string;
leadId: string;
kontaktId?: string | null;
ctx: LeadVisibilityContext;
userId?: string | null;
}): Promise<LeadRow> {
// P8 owns the Projekt model. P7 prepares and validates the conversion point so
// later code can atomically create Projekt + set konvertiertProjektId.
return withTenantRLS(input.tenantId, async (tx) => {
@@ -585,12 +703,14 @@ export async function requestLeadProjectConversion(input: { tenantId: string; le
throw new CatalogError(foundationErrors.notFound, { leadId: input.leadId });
}
assertStatusTransition(current.status as LeadStatus, "qualified");
const kontaktId = normalizeOptionalText(input.kontaktId);
await requireVisibleConversionContactWithTx(tx, input.tenantId, kontaktId, input.ctx);
const updated = await tx.inboxLead.update({
where: { id: current.id },
where: { id: current.id, tenantId: input.tenantId },
data: {
status: "qualified",
weiterverarbeitungFreigabe: "ja",
verknuepfterKontaktId: input.kontaktId ?? undefined,
verknuepfterKontaktId: kontaktId ?? undefined,
},
});
const lead = updated as LeadRow;
@@ -601,13 +721,17 @@ export async function requestLeadProjectConversion(input: { tenantId: string; le
event: "lead.convert_requested",
action: "convert_requested",
});
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.userId ?? input.ctx?.userId ?? null,
lead,
event: "lead.qualified",
action: "qualified",
});
// Only when qualification actually happened here. Re-announcing it for an
// already-qualified lead is both untrue and a duplicate dispatch key.
if (current.status !== "qualified") {
await publishLeadWorkflowEvent(tx, {
tenantId: input.tenantId,
userId: input.userId ?? input.ctx?.userId ?? null,
lead,
event: "lead.qualified",
action: "qualified",
});
}
await publishLeadSearchUpsert(tx, lead);
return lead;
});
@@ -618,7 +742,7 @@ export async function completeLeadProjectConversion(input: {
leadId: string;
projektId: string;
kontaktId?: string | null;
ctx?: LeadVisibilityContext;
ctx: LeadVisibilityContext;
userId?: string | null;
}): Promise<LeadRow> {
const projektId = normalizeOptionalText(input.projektId);
@@ -633,13 +757,18 @@ export async function completeLeadProjectConversion(input: {
throw new CatalogError(foundationErrors.notFound, { leadId: input.leadId });
}
assertStatusTransition(current.status as LeadStatus, "converted");
const kontaktId = normalizeOptionalText(input.kontaktId) ?? current.verknuepfterKontaktId;
await Promise.all([
requireVisibleConversionProjectWithTx(tx, input.tenantId, projektId, input.ctx),
requireVisibleConversionContactWithTx(tx, input.tenantId, kontaktId, input.ctx),
]);
const updated = await tx.inboxLead.update({
where: { id: current.id },
where: { id: current.id, tenantId: input.tenantId },
data: {
status: "converted",
weiterverarbeitungFreigabe: "ja",
konvertiertProjektId: projektId,
verknuepfterKontaktId: input.kontaktId ?? current.verknuepfterKontaktId,
verknuepfterKontaktId: kontaktId,
convertedAt: new Date(),
autoDeleteAt: null,
},
@@ -659,7 +788,7 @@ export async function completeLeadProjectConversion(input: {
export async function listAssignableUsers(tenantId: string): Promise<{ id: string; label: string }[]> {
const rows = await db.tenantUser.findMany({
where: { tenantId },
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
orderBy: { createdAt: "asc" },
});
@@ -677,8 +806,9 @@ export async function resolveUserLabels(userIds: string[]): Promise<Map<string,
}
export async function listLeadSources(tenantId: string): Promise<LeadSourceRow[]> {
return withTenantRLS(tenantId, async (tx) =>
(await tx.leadSource.findMany({ where: { tenantId, archivedAt: null }, orderBy: [{ type: "asc" }, { name: "asc" }] })) as LeadSourceRow[],
return withTenantRLS(
tenantId,
async (tx) => (await tx.leadSource.findMany({ where: { tenantId, archivedAt: null }, orderBy: [{ type: "asc" }, { name: "asc" }] })) as LeadSourceRow[]
);
}
@@ -710,11 +840,27 @@ export async function upsertLeadSource(input: {
type: input.type ?? "custom",
defaultZustaendigerUserId: input.defaultZustaendigerUserId ?? null,
},
}),
})
);
return row as LeadSourceRow;
}
/**
* Soft-delete of a lead source: sets archivedAt so it drops out of the admin
* list and cannot be assigned to new leads, while leads already captured
* through it keep pointing at a row that still exists.
*/
export async function archiveLeadSource(input: { tenantId: string; sourceId: string }): Promise<void> {
await withTenantRLS(input.tenantId, async (tx) => {
const existing = await tx.leadSource.findFirst({
where: { id: input.sourceId, tenantId: input.tenantId, archivedAt: null },
select: { id: true },
});
if (!existing) throw new LeadServiceError("leads.error.sourceNotFound");
await tx.leadSource.updateMany({ where: { id: input.sourceId, tenantId: input.tenantId }, data: { archivedAt: new Date() } });
});
}
export async function getLeadAntiSpamConfig(tenantId: string): Promise<LeadAntiSpamConfigRow> {
return withTenantRLS(tenantId, (tx) => ensureAntiSpamConfigWithTx(tx, tenantId));
}
@@ -751,7 +897,7 @@ export async function updateLeadAntiSpamConfig(input: {
export async function getLeadStatistics(input: { tenantId: string; ctx: LeadVisibilityContext }): Promise<{
total: number;
open: number;
new: number;
converted: number;
spam: number;
byQuelle: { quelle: LeadQuelle; count: number }[];
@@ -759,9 +905,9 @@ export async function getLeadStatistics(input: { tenantId: string; ctx: LeadVisi
}> {
return withTenantRLS(input.tenantId, async (tx) => {
const where = { tenantId: input.tenantId, archivedAt: null, ...ownerScopeWhere(input.ctx) };
const [total, open, converted, spam, byQuelleRaw, byStatusRaw] = await Promise.all([
const [total, neu, converted, spam, byQuelleRaw, byStatusRaw] = await Promise.all([
tx.inboxLead.count({ where }),
tx.inboxLead.count({ where: { ...where, status: { in: ["new", "qualified"] } } }),
tx.inboxLead.count({ where: { ...where, status: "new" } }),
tx.inboxLead.count({ where: { ...where, status: "converted" } }),
tx.inboxLead.count({ where: { ...where, status: "spam" } }),
tx.inboxLead.groupBy({ by: ["quelle"], where, _count: { _all: true } }),
@@ -769,7 +915,7 @@ export async function getLeadStatistics(input: { tenantId: string; ctx: LeadVisi
]);
return {
total,
open,
new: neu,
converted,
spam,
byQuelle: byQuelleRaw.map((row) => ({ quelle: row.quelle as LeadQuelle, count: row._count._all })),
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { canTransitionLeadStatus, type LeadStatus } from "./leadService.server";
import { canTransitionLeadStatus, LEAD_BULK_MAX_ENTRIES, normalizeBulkLeadIds, type LeadStatus } from "./leadService.server";
describe("lead status workflow", () => {
test.each<[LeadStatus, LeadStatus]>([
@@ -25,4 +25,11 @@ describe("lead status workflow", () => {
test("allows idempotent status writes", () => {
expect(canTransitionLeadStatus("converted", "converted")).toBe(true);
});
test("bounds and deduplicates bulk lead IDs", () => {
expect(normalizeBulkLeadIds([" lead-a ", "lead-a", "", "lead-b"])).toEqual(["lead-a", "lead-b"]);
expect(() => normalizeBulkLeadIds(Array.from({ length: LEAD_BULK_MAX_ENTRIES + 1 }, (_, index) => `lead-${index}`))).toThrow(
"foundation.mass_action_exceeds_limit"
);
});
});