503 lines
19 KiB
TypeScript
503 lines
19 KiB
TypeScript
import type {
|
|
AdminCompany,
|
|
AdminContact,
|
|
AdminDeal,
|
|
AdminPipelineStage,
|
|
Prisma,
|
|
PrismaClient,
|
|
} from "../generated/prisma/client/client.js";
|
|
import { createAuditEventInExistingTransaction, type AuditEventWriterClient } from "./audit-events.server.js";
|
|
import type { AdminPermissionName } from "./admin-permissions.js";
|
|
import {
|
|
UNRESTRICTED_ADMIN_SALES_ACCESS,
|
|
assertAdminSalesWriteOwner,
|
|
type AdminSalesAccessScope,
|
|
} from "./admin-sales-access-scope.js";
|
|
|
|
const MAX_TEXT_LENGTH = 2_000;
|
|
const MAX_NAME_LENGTH = 200;
|
|
const CURRENCY_PATTERN = /^[A-Z]{3}$/u;
|
|
|
|
export type AdminSalesActor = {
|
|
readonly adminUserId: string;
|
|
readonly email?: string | null;
|
|
readonly reason: string;
|
|
readonly requestId?: string | null;
|
|
readonly ip?: string | null;
|
|
readonly userAgent?: string | null;
|
|
};
|
|
|
|
export type CreateAdminCompanyInput = {
|
|
readonly name: string;
|
|
readonly legalName?: string | null;
|
|
readonly domain?: string | null;
|
|
readonly website?: string | null;
|
|
readonly phone?: string | null;
|
|
readonly region?: string | null;
|
|
readonly countryCode?: string | null;
|
|
readonly industry?: string | null;
|
|
readonly employeeRange?: string | null;
|
|
readonly ownerAdminUserId?: string | null;
|
|
readonly sourceLeadId?: string | null;
|
|
readonly actor: AdminSalesActor;
|
|
};
|
|
|
|
export type CreateAdminContactInput = {
|
|
readonly companyId?: string | null;
|
|
readonly firstName: string;
|
|
readonly lastName: string;
|
|
readonly jobTitle?: string | null;
|
|
readonly email?: string | null;
|
|
readonly phone?: string | null;
|
|
readonly locale?: string | null;
|
|
readonly timeZone?: string | null;
|
|
readonly ownerAdminUserId?: string | null;
|
|
readonly sourceLeadId?: string | null;
|
|
readonly actor: AdminSalesActor;
|
|
};
|
|
|
|
export type CreateAdminDealInput = {
|
|
readonly title: string;
|
|
readonly pipelineId: string;
|
|
readonly stageId: string;
|
|
readonly companyId?: string | null;
|
|
readonly sourceLeadId?: string | null;
|
|
readonly ownerAdminUserId: string;
|
|
readonly amountCents?: number | null;
|
|
readonly currencyCode?: string;
|
|
readonly probabilityBasisPoints?: number;
|
|
readonly expectedCloseDate?: Date | null;
|
|
readonly nextStep?: string | null;
|
|
readonly nextStepDueAt?: Date | null;
|
|
readonly contactIds?: readonly string[];
|
|
readonly actor: AdminSalesActor;
|
|
};
|
|
|
|
export type AdminSalesCoreRepository = {
|
|
createCompany(input: CreateAdminCompanyInput): Promise<AdminCompany>;
|
|
createContact(input: CreateAdminContactInput): Promise<AdminContact>;
|
|
createDeal(input: CreateAdminDealInput): Promise<AdminDeal>;
|
|
};
|
|
|
|
export type AdminSalesCoreService = ReturnType<typeof createAdminSalesCoreService>;
|
|
export type AdminSalesAuditWriter = (
|
|
tx: Prisma.TransactionClient,
|
|
input: {
|
|
readonly actor: AdminSalesActor;
|
|
readonly action: string;
|
|
readonly targetType: string;
|
|
readonly targetId: string;
|
|
readonly after: Prisma.InputJsonValue;
|
|
}
|
|
) => Promise<void>;
|
|
|
|
export function createAdminSalesCoreService(input: {
|
|
readonly repository: AdminSalesCoreRepository;
|
|
readonly authorize: (permission: AdminPermissionName) => Promise<void> | void;
|
|
}) {
|
|
return {
|
|
async createCompany(command: CreateAdminCompanyInput) {
|
|
await input.authorize("admin_sales.crm.write");
|
|
return input.repository.createCompany(normalizeCompanyCommand(command));
|
|
},
|
|
async createContact(command: CreateAdminContactInput) {
|
|
await input.authorize("admin_sales.crm.write");
|
|
return input.repository.createContact(normalizeContactCommand(command));
|
|
},
|
|
async createDeal(command: CreateAdminDealInput) {
|
|
await input.authorize("admin_sales.crm.write");
|
|
return input.repository.createDeal(normalizeDealCommand(command));
|
|
},
|
|
};
|
|
}
|
|
|
|
type AdminSalesCorePrismaClient = Pick<
|
|
PrismaClient,
|
|
"$transaction" | "adminCompany" | "adminContact" | "adminDeal" | "adminPipelineStage" | "adminLead"
|
|
>;
|
|
|
|
export function createPrismaAdminSalesCoreRepository(
|
|
client: AdminSalesCorePrismaClient,
|
|
dependencies: {
|
|
readonly writeAudit?: AdminSalesAuditWriter;
|
|
readonly accessScope?: AdminSalesAccessScope;
|
|
} = {}
|
|
): AdminSalesCoreRepository {
|
|
const auditWriter = dependencies.writeAudit ?? writeAdminSalesAudit;
|
|
const accessScope =
|
|
dependencies.accessScope ?? UNRESTRICTED_ADMIN_SALES_ACCESS;
|
|
return {
|
|
createCompany: (command) =>
|
|
client.$transaction(async (tx) => {
|
|
if (command.sourceLeadId) await assertLeadAvailable(tx, command.sourceLeadId);
|
|
const company = await tx.adminCompany.create({
|
|
data: {
|
|
name: command.name,
|
|
normalizedName: normalizeSearchText(command.name),
|
|
legalName: command.legalName,
|
|
domain: command.domain,
|
|
website: command.website,
|
|
phone: command.phone,
|
|
normalizedPhone: normalizePhone(command.phone),
|
|
region: command.region,
|
|
countryCode: command.countryCode,
|
|
industry: command.industry,
|
|
employeeRange: command.employeeRange,
|
|
ownerAdminUserId: command.ownerAdminUserId,
|
|
sourceLeadId: command.sourceLeadId,
|
|
},
|
|
});
|
|
await tx.adminActivity.create({
|
|
data: {
|
|
type: "company_created",
|
|
actorAdminUserId: command.actor.adminUserId,
|
|
leadId: command.sourceLeadId,
|
|
companyId: company.id,
|
|
summary: `Firma ${company.name} angelegt`,
|
|
payload: { source: command.sourceLeadId ? "lead_conversion" : "manual" },
|
|
},
|
|
});
|
|
await auditWriter(tx, {
|
|
actor: command.actor,
|
|
action: "admin.sales.company.created",
|
|
targetType: "AdminCompany",
|
|
targetId: company.id,
|
|
after: {
|
|
name: company.name,
|
|
sourceLeadId: company.sourceLeadId,
|
|
ownerAdminUserId: company.ownerAdminUserId,
|
|
},
|
|
});
|
|
return company;
|
|
}),
|
|
|
|
createContact: (command) =>
|
|
client.$transaction(async (tx) => {
|
|
if (command.sourceLeadId) await assertLeadAvailable(tx, command.sourceLeadId);
|
|
if (command.companyId) await assertCompanyExists(tx, command.companyId);
|
|
const contact = await tx.adminContact.create({
|
|
data: {
|
|
companyId: command.companyId,
|
|
firstName: command.firstName,
|
|
lastName: command.lastName,
|
|
jobTitle: command.jobTitle,
|
|
email: command.email,
|
|
normalizedEmail: normalizeEmail(command.email),
|
|
phone: command.phone,
|
|
normalizedPhone: normalizePhone(command.phone),
|
|
locale: command.locale,
|
|
timeZone: command.timeZone,
|
|
ownerAdminUserId: command.ownerAdminUserId,
|
|
sourceLeadId: command.sourceLeadId,
|
|
},
|
|
});
|
|
await tx.adminActivity.create({
|
|
data: {
|
|
type: "contact_created",
|
|
actorAdminUserId: command.actor.adminUserId,
|
|
leadId: command.sourceLeadId,
|
|
companyId: command.companyId,
|
|
contactId: contact.id,
|
|
summary: `Kontakt ${contact.firstName} ${contact.lastName} angelegt`,
|
|
payload: { source: command.sourceLeadId ? "lead_conversion" : "manual" },
|
|
},
|
|
});
|
|
await auditWriter(tx, {
|
|
actor: command.actor,
|
|
action: "admin.sales.contact.created",
|
|
targetType: "AdminContact",
|
|
targetId: contact.id,
|
|
after: {
|
|
companyId: contact.companyId,
|
|
sourceLeadId: contact.sourceLeadId,
|
|
ownerAdminUserId: contact.ownerAdminUserId,
|
|
},
|
|
});
|
|
return contact;
|
|
}),
|
|
|
|
createDeal: (command) =>
|
|
client.$transaction(async (tx) => {
|
|
assertAdminSalesWriteOwner(command.ownerAdminUserId, accessScope);
|
|
const stage = await assertDealStage(tx, command.pipelineId, command.stageId);
|
|
if (command.sourceLeadId) await assertLeadAvailable(tx, command.sourceLeadId);
|
|
if (command.companyId) await assertCompanyExists(tx, command.companyId);
|
|
const contactIds = uniqueIds(command.contactIds ?? []);
|
|
if (contactIds.length > 0) await assertContactsExist(tx, contactIds);
|
|
const probabilityBasisPoints = command.probabilityBasisPoints ?? stage.probabilityBasisPoints;
|
|
const deal = await tx.adminDeal.create({
|
|
data: {
|
|
title: command.title,
|
|
pipelineId: command.pipelineId,
|
|
stageId: command.stageId,
|
|
companyId: command.companyId,
|
|
sourceLeadId: command.sourceLeadId,
|
|
ownerAdminUserId: command.ownerAdminUserId,
|
|
amountCents: command.amountCents,
|
|
currencyCode: command.currencyCode ?? "EUR",
|
|
probabilityBasisPoints,
|
|
expectedCloseDate: command.expectedCloseDate,
|
|
nextStep: command.nextStep,
|
|
nextStepDueAt: command.nextStepDueAt,
|
|
contacts:
|
|
contactIds.length > 0
|
|
? {
|
|
create: contactIds.map((contactId, index) => ({
|
|
contactId,
|
|
isPrimary: index === 0,
|
|
})),
|
|
}
|
|
: undefined,
|
|
history: {
|
|
create: {
|
|
toStageId: command.stageId,
|
|
actorAdminUserId: command.actor.adminUserId,
|
|
enteredAt: new Date(),
|
|
reason: "deal_created",
|
|
},
|
|
},
|
|
},
|
|
});
|
|
await tx.adminActivity.create({
|
|
data: {
|
|
type: "deal_created",
|
|
actorAdminUserId: command.actor.adminUserId,
|
|
leadId: command.sourceLeadId,
|
|
companyId: command.companyId,
|
|
dealId: deal.id,
|
|
summary: `Deal ${deal.title} angelegt`,
|
|
payload: {
|
|
stageId: deal.stageId,
|
|
amountCents: deal.amountCents,
|
|
currencyCode: deal.currencyCode,
|
|
contactCount: contactIds.length,
|
|
},
|
|
},
|
|
});
|
|
await auditWriter(tx, {
|
|
actor: command.actor,
|
|
action: "admin.sales.deal.created",
|
|
targetType: "AdminDeal",
|
|
targetId: deal.id,
|
|
after: {
|
|
pipelineId: deal.pipelineId,
|
|
stageId: deal.stageId,
|
|
companyId: deal.companyId,
|
|
sourceLeadId: deal.sourceLeadId,
|
|
ownerAdminUserId: deal.ownerAdminUserId,
|
|
},
|
|
});
|
|
return deal;
|
|
}),
|
|
};
|
|
}
|
|
|
|
function normalizeCompanyCommand(command: CreateAdminCompanyInput): CreateAdminCompanyInput {
|
|
return {
|
|
...command,
|
|
name: requiredText(command.name, "company name", MAX_NAME_LENGTH),
|
|
legalName: optionalText(command.legalName, MAX_NAME_LENGTH),
|
|
domain: normalizeDomain(command.domain),
|
|
website: optionalUrl(command.website),
|
|
phone: optionalText(command.phone, 80),
|
|
region: optionalText(command.region, 120),
|
|
countryCode: optionalCountryCode(command.countryCode),
|
|
industry: optionalText(command.industry, 120),
|
|
employeeRange: optionalText(command.employeeRange, 80),
|
|
ownerAdminUserId: optionalId(command.ownerAdminUserId),
|
|
sourceLeadId: optionalId(command.sourceLeadId),
|
|
actor: normalizeActor(command.actor),
|
|
};
|
|
}
|
|
|
|
function normalizeContactCommand(command: CreateAdminContactInput): CreateAdminContactInput {
|
|
const email = optionalText(command.email, 320)?.toLowerCase() ?? null;
|
|
if (email && !email.includes("@")) throw new Error("Admin sales contact email is invalid.");
|
|
return {
|
|
...command,
|
|
companyId: optionalId(command.companyId),
|
|
firstName: requiredText(command.firstName, "contact first name", 120),
|
|
lastName: requiredText(command.lastName, "contact last name", 120),
|
|
jobTitle: optionalText(command.jobTitle, 160),
|
|
email,
|
|
phone: optionalText(command.phone, 80),
|
|
locale: optionalText(command.locale, 20),
|
|
timeZone: optionalText(command.timeZone, 80),
|
|
ownerAdminUserId: optionalId(command.ownerAdminUserId),
|
|
sourceLeadId: optionalId(command.sourceLeadId),
|
|
actor: normalizeActor(command.actor),
|
|
};
|
|
}
|
|
|
|
function normalizeDealCommand(command: CreateAdminDealInput): CreateAdminDealInput {
|
|
const probabilityBasisPoints = command.probabilityBasisPoints;
|
|
if (probabilityBasisPoints !== undefined && (!Number.isInteger(probabilityBasisPoints) || probabilityBasisPoints < 0 || probabilityBasisPoints > 10_000)) {
|
|
throw new Error("Admin sales deal probability must be between 0 and 100 percent.");
|
|
}
|
|
if (command.amountCents !== undefined && command.amountCents !== null && (!Number.isSafeInteger(command.amountCents) || command.amountCents < 0)) {
|
|
throw new Error("Admin sales deal amount must be a non-negative integer.");
|
|
}
|
|
const currencyCode = (command.currencyCode ?? "EUR").trim().toUpperCase();
|
|
if (!CURRENCY_PATTERN.test(currencyCode)) throw new Error("Admin sales deal currency must be an ISO 4217 code.");
|
|
return {
|
|
...command,
|
|
title: requiredText(command.title, "deal title", MAX_NAME_LENGTH),
|
|
pipelineId: requiredId(command.pipelineId, "pipelineId"),
|
|
stageId: requiredId(command.stageId, "stageId"),
|
|
companyId: optionalId(command.companyId),
|
|
sourceLeadId: optionalId(command.sourceLeadId),
|
|
ownerAdminUserId: requiredId(command.ownerAdminUserId, "ownerAdminUserId"),
|
|
currencyCode,
|
|
probabilityBasisPoints,
|
|
nextStep: optionalText(command.nextStep, MAX_TEXT_LENGTH),
|
|
contactIds: uniqueIds(command.contactIds ?? []),
|
|
actor: normalizeActor(command.actor),
|
|
};
|
|
}
|
|
|
|
function normalizeActor(actor: AdminSalesActor): AdminSalesActor {
|
|
return {
|
|
adminUserId: requiredId(actor.adminUserId, "actor.adminUserId"),
|
|
email: optionalText(actor.email, 320),
|
|
reason: requiredText(actor.reason, "audit reason", MAX_TEXT_LENGTH, 5),
|
|
requestId: optionalText(actor.requestId, 191),
|
|
ip: optionalText(actor.ip, 100),
|
|
userAgent: optionalText(actor.userAgent, 1_000),
|
|
};
|
|
}
|
|
|
|
async function assertLeadAvailable(tx: Prisma.TransactionClient, leadId: string): Promise<void> {
|
|
const lead = await tx.adminLead.findUnique({
|
|
where: { id: leadId },
|
|
select: { id: true, archivedAt: true },
|
|
});
|
|
if (!lead || lead.archivedAt) throw new Error("Admin sales source lead was not found.");
|
|
}
|
|
|
|
async function assertCompanyExists(tx: Prisma.TransactionClient, companyId: string): Promise<void> {
|
|
const company = await tx.adminCompany.findUnique({
|
|
where: { id: companyId },
|
|
select: { id: true, archivedAt: true },
|
|
});
|
|
if (!company || company.archivedAt) throw new Error("Admin sales company was not found.");
|
|
}
|
|
|
|
async function assertContactsExist(tx: Prisma.TransactionClient, contactIds: readonly string[]): Promise<void> {
|
|
const count = await tx.adminContact.count({
|
|
where: { id: { in: [...contactIds] }, archivedAt: null },
|
|
});
|
|
if (count !== contactIds.length) throw new Error("One or more admin sales contacts were not found.");
|
|
}
|
|
|
|
async function assertDealStage(
|
|
tx: Prisma.TransactionClient,
|
|
pipelineId: string,
|
|
stageId: string
|
|
): Promise<Pick<AdminPipelineStage, "id" | "probabilityBasisPoints">> {
|
|
const stage = await tx.adminPipelineStage.findFirst({
|
|
where: { id: stageId, pipelineId, archivedAt: null, pipeline: { archivedAt: null } },
|
|
select: { id: true, probabilityBasisPoints: true },
|
|
});
|
|
if (!stage) throw new Error("Admin sales pipeline stage was not found.");
|
|
return stage;
|
|
}
|
|
|
|
export async function writeAdminSalesAudit(
|
|
tx: Prisma.TransactionClient,
|
|
input: {
|
|
readonly actor: AdminSalesActor;
|
|
readonly action: string;
|
|
readonly targetType: string;
|
|
readonly targetId: string;
|
|
readonly after: Prisma.InputJsonValue;
|
|
}
|
|
): Promise<void> {
|
|
await createAuditEventInExistingTransaction(
|
|
{
|
|
tenantId: null,
|
|
actorId: input.actor.adminUserId,
|
|
actorType: "admin",
|
|
actorEmail: input.actor.email,
|
|
actorIp: input.actor.ip,
|
|
actorUserAgent: input.actor.userAgent,
|
|
action: input.action,
|
|
targetType: input.targetType,
|
|
targetId: input.targetId,
|
|
requestId: input.actor.requestId,
|
|
sourceModule: "admin-sales",
|
|
dataSensitivity: "pii",
|
|
regulatoryScope: ["gdpr"],
|
|
metadata: { reason: input.actor.reason },
|
|
afterDiff: input.after,
|
|
summaryText: input.actor.reason,
|
|
},
|
|
tx as unknown as AuditEventWriterClient
|
|
);
|
|
}
|
|
|
|
function requiredId(value: string, field: string): string {
|
|
const normalized = requiredText(value, field, 191);
|
|
if (!/^[A-Za-z0-9_:-]+$/u.test(normalized)) throw new Error(`Admin sales ${field} is invalid.`);
|
|
return normalized;
|
|
}
|
|
|
|
function optionalId(value: string | null | undefined): string | null {
|
|
return value == null || value.trim() === "" ? null : requiredId(value, "identifier");
|
|
}
|
|
|
|
function requiredText(value: string, field: string, limit: number, minimum = 1): string {
|
|
if (typeof value !== "string") throw new Error(`Admin sales ${field} is required.`);
|
|
const normalized = value.trim();
|
|
if (normalized.length < minimum || normalized.length > limit || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(normalized)) {
|
|
throw new Error(`Admin sales ${field} is invalid.`);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function optionalText(value: string | null | undefined, limit: number): string | null {
|
|
if (value == null || value.trim() === "") return null;
|
|
return requiredText(value, "text", limit);
|
|
}
|
|
|
|
function optionalCountryCode(value: string | null | undefined): string | null {
|
|
const normalized = optionalText(value, 2)?.toUpperCase() ?? null;
|
|
if (normalized && !/^[A-Z]{2}$/u.test(normalized)) throw new Error("Admin sales country code is invalid.");
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeDomain(value: string | null | undefined): string | null {
|
|
const normalized = optionalText(value, 253)?.toLowerCase().replace(/^www\./u, "") ?? null;
|
|
if (normalized && (!normalized.includes(".") || normalized.includes("/") || normalized.includes("@"))) {
|
|
throw new Error("Admin sales company domain is invalid.");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function optionalUrl(value: string | null | undefined): string | null {
|
|
const normalized = optionalText(value, 2_048);
|
|
if (!normalized) return null;
|
|
const url = new URL(normalized);
|
|
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("Admin sales website URL is invalid.");
|
|
return url.toString();
|
|
}
|
|
|
|
function normalizeSearchText(value: string): string {
|
|
return value.normalize("NFKC").trim().toLocaleLowerCase("de-DE");
|
|
}
|
|
|
|
function normalizeEmail(value: string | null | undefined): string | null {
|
|
return value ? value.trim().toLowerCase() : null;
|
|
}
|
|
|
|
function normalizePhone(value: string | null | undefined): string | null {
|
|
if (!value) return null;
|
|
const trimmed = value.trim();
|
|
const digits = trimmed.replace(/\D/gu, "");
|
|
if (digits.length < 6) throw new Error("Admin sales phone number is invalid.");
|
|
return `${trimmed.startsWith("+") ? "+" : ""}${digits}`;
|
|
}
|
|
|
|
function uniqueIds(values: readonly string[]): string[] {
|
|
return [...new Set(values.map((value) => requiredId(value, "identifier")))];
|
|
}
|