Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+257
-76
@@ -14,8 +14,11 @@
|
||||
// cutover). The only access NOT wrapped is the global User lookup
|
||||
// (resolveUserLabels): User is not tenant-scoped, so it stays on the db singleton.
|
||||
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import { CatalogError, foundationErrors, massActionErrors } from "@hivegrid/foundation";
|
||||
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
|
||||
import { crmContactsIndex } from "@hivegrid/search";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { publishKontaktSearchUpsert, publishSearchProjectionDelete } from "~/services/search/searchIndexProjection.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
|
||||
@@ -64,6 +67,16 @@ export function ownerScopeWhere(ctx: CrmVisibilityContext): { zustaendigerUserId
|
||||
return canReadAllKontakte(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 });
|
||||
}
|
||||
}
|
||||
|
||||
// --- Row types (returned to routes; relation fields excluded) --------------
|
||||
|
||||
export type KontaktRow = {
|
||||
@@ -142,7 +155,9 @@ export type AdresseInput = {
|
||||
* primary; an empty list has no primary. Returns the denormalised primary value
|
||||
* plus the per-item primary flags to persist. Pure (no DB) — used at create time.
|
||||
*/
|
||||
function pickPrimary<T extends { value: string; primaer?: boolean }>(items: readonly T[]): {
|
||||
function pickPrimary<T extends { value: string; primaer?: boolean }>(
|
||||
items: readonly T[]
|
||||
): {
|
||||
primaryValue: string | null;
|
||||
flags: boolean[];
|
||||
} {
|
||||
@@ -243,6 +258,39 @@ function hasAddressData(adresse?: AdresseInput | null): boolean {
|
||||
return Boolean(adresse.strasse?.trim() || adresse.hausnummer?.trim() || adresse.plz?.trim() || adresse.ort?.trim() || adresse.land?.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* R-P12c: kontakt domain events feed the generic automation trigger bus via
|
||||
* the durable workflow-trigger outbox (same delivery as lead/project events).
|
||||
* Published inside the mutation transaction so event and write commit together.
|
||||
*/
|
||||
async function publishKontaktWorkflowEvent(
|
||||
tx: TenantRlsClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
userId: string | null;
|
||||
event: "kontakt.created" | "kontakt.updated";
|
||||
kontakt: { id: string; kontaktTyp: string; kontaktStatus: string; updatedAt?: Date };
|
||||
changedFields?: readonly string[];
|
||||
}
|
||||
): Promise<void> {
|
||||
const suffix = input.event === "kontakt.updated" ? `:${input.kontakt.updatedAt?.getTime() ?? Date.now()}` : "";
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: input.event,
|
||||
data: {
|
||||
kontaktId: input.kontakt.id,
|
||||
kontaktTyp: input.kontakt.kontaktTyp,
|
||||
kontaktStatus: input.kontakt.kontaktStatus,
|
||||
...(input.changedFields ? { changedFields: [...input.changedFields] } : {}),
|
||||
},
|
||||
userId: input.userId,
|
||||
sourceId: `kontakt:${input.kontakt.id}:${input.event}${suffix}`,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function createKontakt(input: CreateKontaktInput): Promise<KontaktRow> {
|
||||
validateKontaktName(input);
|
||||
const emailItems = (input.emails ?? []).map((entry) => ({ value: entry.email.trim(), primaer: entry.primaer })).filter((entry) => entry.value);
|
||||
@@ -251,6 +299,8 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
const primaryTelefon = pickPrimary(telefonItems);
|
||||
|
||||
const kontakt = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const responsibleUserId = input.zustaendigerUserId ?? input.userId;
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, responsibleUserId);
|
||||
let adresseId: string | null = null;
|
||||
if (hasAddressData(input.adresse)) {
|
||||
const adresse = await tx.adresse.create({
|
||||
@@ -280,7 +330,7 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
primaerEmail: primaryEmail.primaryValue,
|
||||
primaerTelefon: primaryTelefon.primaryValue,
|
||||
adresseId,
|
||||
zustaendigerUserId: input.zustaendigerUserId ?? input.userId,
|
||||
zustaendigerUserId: responsibleUserId,
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
});
|
||||
@@ -289,9 +339,17 @@ export async function createKontakt(input: CreateKontaktInput): Promise<KontaktR
|
||||
await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: created.id, email: emailItems[i].value, primaer: primaryEmail.flags[i] } });
|
||||
}
|
||||
for (let i = 0; i < telefonItems.length; i += 1) {
|
||||
await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: created.id, telefon: telefonItems[i].value, primaer: primaryTelefon.flags[i] } });
|
||||
await tx.kontaktTelefon.create({
|
||||
data: { tenantId: input.tenantId, kontaktId: created.id, telefon: telefonItems[i].value, primaer: primaryTelefon.flags[i] },
|
||||
});
|
||||
}
|
||||
await publishKontaktSearchUpsert(tx, created);
|
||||
await publishKontaktWorkflowEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
event: "kontakt.created",
|
||||
kontakt: created,
|
||||
});
|
||||
return created;
|
||||
});
|
||||
return kontakt as KontaktRow;
|
||||
@@ -324,6 +382,16 @@ export async function updateKontakt(input: UpdateKontaktInput): Promise<void> {
|
||||
},
|
||||
});
|
||||
await publishKontaktSearchUpsert(tx, updated);
|
||||
const changedFields = (["kontaktStatus", "vorname", "nachname", "orgName", "orgMerkmal"] as const).filter(
|
||||
(field) => input[field] !== undefined
|
||||
);
|
||||
await publishKontaktWorkflowEvent(tx, {
|
||||
tenantId: input.tenantId,
|
||||
userId: null,
|
||||
event: "kontakt.updated",
|
||||
kontakt: updated,
|
||||
changedFields,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -374,6 +442,7 @@ export async function hardDeleteKontakt(input: { tenantId: string; kontaktId: st
|
||||
|
||||
export async function reassignKontakt(input: { tenantId: string; kontaktId: string; zustaendigerUserId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
|
||||
const existing = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!existing) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
@@ -385,108 +454,124 @@ export async function reassignKontakt(input: { tenantId: string; kontaktId: stri
|
||||
|
||||
// --- Email channels --------------------------------------------------------
|
||||
|
||||
export async function addKontaktEmail(input: { tenantId: string; kontaktId: string; email: string; primaer?: boolean }): Promise<KontaktEmailRow> {
|
||||
type KontaktScopedMutationInput = {
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
};
|
||||
|
||||
export async function addKontaktEmail(input: KontaktScopedMutationInput & { email: string; primaer?: boolean }): Promise<KontaktEmailRow> {
|
||||
const email = input.email.trim();
|
||||
if (!email) {
|
||||
throw new CrmServiceError("crm.error.emailRequired");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const created = await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, email, primaer: false } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const created = await tx.kontaktEmail.create({ data: { tenantId: input.tenantId, kontaktId: kontakt.id, email, primaer: false } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktEmailRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
export async function setPrimaryEmail(input: KontaktScopedMutationInput & { emailId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const email = await tx.kontaktEmail.findFirst({
|
||||
where: { id: input.emailId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!email) {
|
||||
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
|
||||
}
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId, email.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id, email.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktEmail(input: { tenantId: string; emailId: string }): Promise<void> {
|
||||
export async function removeKontaktEmail(input: KontaktScopedMutationInput & { emailId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const email = await tx.kontaktEmail.findFirst({ where: { id: input.emailId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const email = await tx.kontaktEmail.findFirst({
|
||||
where: { id: input.emailId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!email) {
|
||||
throw new CatalogError(foundationErrors.notFound, { emailId: input.emailId });
|
||||
}
|
||||
await tx.kontaktEmail.deleteMany({ where: { id: input.emailId, tenantId: input.tenantId } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, email.kontaktId);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: email.kontaktId, tenantId: input.tenantId } });
|
||||
await tx.kontaktEmail.deleteMany({ where: { id: email.id, tenantId: input.tenantId, kontaktId: kontakt.id } });
|
||||
await syncPrimaryEmailWithTx(tx, input.tenantId, kontakt.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Telephone channels ----------------------------------------------------
|
||||
|
||||
export async function addKontaktTelefon(input: { tenantId: string; kontaktId: string; telefon: string; primaer?: boolean }): Promise<KontaktTelefonRow> {
|
||||
export async function addKontaktTelefon(input: KontaktScopedMutationInput & { telefon: string; primaer?: boolean }): Promise<KontaktTelefonRow> {
|
||||
const telefon = input.telefon.trim();
|
||||
if (!telefon) {
|
||||
throw new CrmServiceError("crm.error.telefonRequired");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId: input.kontaktId });
|
||||
}
|
||||
const created = await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: input.kontaktId, telefon, primaer: false } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, input.kontaktId, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: input.kontaktId, tenantId: input.tenantId } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const created = await tx.kontaktTelefon.create({ data: { tenantId: input.tenantId, kontaktId: kontakt.id, telefon, primaer: false } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id, input.primaer ? created.id : undefined);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
return created as KontaktTelefonRow;
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPrimaryTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
export async function setPrimaryTelefon(input: KontaktScopedMutationInput & { telefonId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const telefon = await tx.kontaktTelefon.findFirst({
|
||||
where: { id: input.telefonId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!telefon) {
|
||||
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
|
||||
}
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId, telefon.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id, telefon.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktTelefon(input: { tenantId: string; telefonId: string }): Promise<void> {
|
||||
export async function removeKontaktTelefon(input: KontaktScopedMutationInput & { telefonId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const telefon = await tx.kontaktTelefon.findFirst({ where: { id: input.telefonId, tenantId: input.tenantId }, select: { id: true, kontaktId: true } });
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const telefon = await tx.kontaktTelefon.findFirst({
|
||||
where: { id: input.telefonId, tenantId: input.tenantId, kontaktId: kontakt.id },
|
||||
select: { id: true, kontaktId: true },
|
||||
});
|
||||
if (!telefon) {
|
||||
throw new CatalogError(foundationErrors.notFound, { telefonId: input.telefonId });
|
||||
}
|
||||
await tx.kontaktTelefon.deleteMany({ where: { id: input.telefonId, tenantId: input.tenantId } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, telefon.kontaktId);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: telefon.kontaktId, tenantId: input.tenantId } });
|
||||
await tx.kontaktTelefon.deleteMany({ where: { id: telefon.id, tenantId: input.tenantId, kontaktId: kontakt.id } });
|
||||
await syncPrimaryTelefonWithTx(tx, input.tenantId, kontakt.id);
|
||||
const updated = await tx.kontakt.findFirst({ where: { id: kontakt.id, tenantId: input.tenantId } });
|
||||
if (updated) await publishKontaktSearchUpsert(tx, updated);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Relations -------------------------------------------------------------
|
||||
|
||||
export async function addKontaktRelation(input: { tenantId: string; vonKontaktId: string; zuKontaktId: string; rolle: KontaktArt; kontext?: string | null }): Promise<KontaktRelationRow> {
|
||||
if (input.vonKontaktId === input.zuKontaktId) {
|
||||
export async function addKontaktRelation(
|
||||
input: KontaktScopedMutationInput & { zuKontaktId: string; rolle: KontaktArt; kontext?: string | null }
|
||||
): Promise<KontaktRelationRow> {
|
||||
if (input.kontaktId === input.zuKontaktId) {
|
||||
throw new CrmServiceError("crm.error.selfRelation");
|
||||
}
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const endpoints = await tx.kontakt.findMany({ where: { id: { in: [input.vonKontaktId, input.zuKontaktId] }, tenantId: input.tenantId }, select: { id: true } });
|
||||
if (endpoints.length !== 2) {
|
||||
throw new CatalogError(foundationErrors.notFound, { vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId });
|
||||
}
|
||||
const source = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const target = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.zuKontaktId, input.ctx);
|
||||
try {
|
||||
const created = await tx.kontaktRelation.create({
|
||||
data: { tenantId: input.tenantId, vonKontaktId: input.vonKontaktId, zuKontaktId: input.zuKontaktId, rolle: input.rolle, kontext: input.kontext ?? null },
|
||||
data: { tenantId: input.tenantId, vonKontaktId: source.id, zuKontaktId: target.id, rolle: input.rolle, kontext: input.kontext ?? null },
|
||||
});
|
||||
return created as KontaktRelationRow;
|
||||
} catch (error) {
|
||||
@@ -498,30 +583,37 @@ export async function addKontaktRelation(input: { tenantId: string; vonKontaktId
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeKontaktRelation(input: { tenantId: string; relationId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, (tx) => tx.kontaktRelation.deleteMany({ where: { id: input.relationId, tenantId: input.tenantId } }));
|
||||
}
|
||||
|
||||
/** All relations touching a contact, in both directions (von/zu). */
|
||||
export async function listRelationsForKontakt(tenantId: string, kontaktId: string): Promise<KontaktRelationRow[]> {
|
||||
const rows = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.kontaktRelation.findMany({
|
||||
where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
);
|
||||
return rows as KontaktRelationRow[];
|
||||
export async function removeKontaktRelation(input: KontaktScopedMutationInput & { relationId: string }): Promise<void> {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const kontakt = await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, input.kontaktId, input.ctx);
|
||||
const relation = await tx.kontaktRelation.findFirst({
|
||||
where: {
|
||||
id: input.relationId,
|
||||
tenantId: input.tenantId,
|
||||
OR: [{ vonKontaktId: kontakt.id }, { zuKontaktId: kontakt.id }],
|
||||
},
|
||||
select: { id: true, vonKontaktId: true, zuKontaktId: true },
|
||||
});
|
||||
if (!relation) {
|
||||
throw new CatalogError(foundationErrors.notFound, { relationId: input.relationId });
|
||||
}
|
||||
const otherKontaktId = relation.vonKontaktId === kontakt.id ? relation.zuKontaktId : relation.vonKontaktId;
|
||||
await getVisibleKontaktOrThrowWithTx(tx, input.tenantId, otherKontaktId, input.ctx);
|
||||
await tx.kontaktRelation.deleteMany({
|
||||
where: {
|
||||
id: relation.id,
|
||||
tenantId: input.tenantId,
|
||||
OR: [{ vonKontaktId: kontakt.id }, { zuKontaktId: kontakt.id }],
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// --- Visibility / read -----------------------------------------------------
|
||||
|
||||
function isKontaktVisible(kontakt: Pick<KontaktRow, "createdByUserId" | "zustaendigerUserId">, ctx: CrmVisibilityContext): boolean {
|
||||
return canReadAllKontakte(ctx) || kontakt.zustaendigerUserId === ctx.userId || kontakt.createdByUserId === ctx.userId;
|
||||
}
|
||||
|
||||
async function getVisibleKontaktOrThrowWithTx(tx: TenantRlsClient, tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRow> {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: kontaktId, tenantId } });
|
||||
if (!kontakt || !isKontaktVisible(kontakt as KontaktRow, ctx)) {
|
||||
const kontakt = await tx.kontakt.findFirst({ where: { id: kontaktId, tenantId, ...ownerScopeWhere(ctx) } });
|
||||
if (!kontakt) {
|
||||
throw new CatalogError(foundationErrors.notFound, { kontaktId });
|
||||
}
|
||||
return kontakt as KontaktRow;
|
||||
@@ -532,6 +624,35 @@ export async function getVisibleKontaktOrThrow(tenantId: string, kontaktId: stri
|
||||
return withTenantRLS(tenantId, (tx) => getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx));
|
||||
}
|
||||
|
||||
async function listVisibleRelationsForKontaktWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
kontaktId: string,
|
||||
ctx: CrmVisibilityContext
|
||||
): Promise<KontaktRelationRow[]> {
|
||||
const rows = await tx.kontaktRelation.findMany({
|
||||
where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] },
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
const otherKontaktIds = [...new Set(rows.map((row) => (row.vonKontaktId === kontaktId ? row.zuKontaktId : row.vonKontaktId)))];
|
||||
const visibleContacts = await tx.kontakt.findMany({
|
||||
where: { id: { in: otherKontaktIds }, tenantId, ...ownerScopeWhere(ctx) },
|
||||
select: { id: true },
|
||||
});
|
||||
const visibleIds = new Set(visibleContacts.map(({ id }) => id));
|
||||
return rows.filter((row) => visibleIds.has(row.vonKontaktId === kontaktId ? row.zuKontaktId : row.vonKontaktId)) as KontaktRelationRow[];
|
||||
}
|
||||
|
||||
/** All relations whose source and target contacts are visible to the caller. */
|
||||
export async function listRelationsForKontakt(tenantId: string, kontaktId: string, ctx: CrmVisibilityContext): Promise<KontaktRelationRow[]> {
|
||||
return withTenantRLS(tenantId, async (tx) => {
|
||||
await getVisibleKontaktOrThrowWithTx(tx, tenantId, kontaktId, ctx);
|
||||
return listVisibleRelationsForKontaktWithTx(tx, tenantId, kontaktId, ctx);
|
||||
});
|
||||
}
|
||||
|
||||
export type KontaktDetail = {
|
||||
kontakt: KontaktRow;
|
||||
emails: KontaktEmailRow[];
|
||||
@@ -547,7 +668,7 @@ export async function getKontaktDetail(tenantId: string, kontaktId: string, ctx:
|
||||
const [emails, telefone, relationen, adresse] = await Promise.all([
|
||||
tx.kontaktEmail.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
|
||||
tx.kontaktTelefon.findMany({ where: { tenantId, kontaktId }, orderBy: { createdAt: "asc" } }),
|
||||
tx.kontaktRelation.findMany({ where: { tenantId, OR: [{ vonKontaktId: kontaktId }, { zuKontaktId: kontaktId }] }, orderBy: { createdAt: "asc" } }),
|
||||
listVisibleRelationsForKontaktWithTx(tx, tenantId, kontaktId, ctx),
|
||||
kontakt.adresseId ? tx.adresse.findFirst({ where: { id: kontakt.adresseId, tenantId } }) : Promise.resolve(null),
|
||||
]);
|
||||
return {
|
||||
@@ -604,7 +725,7 @@ async function resolveKontaktBrowserWhereWithTx(
|
||||
tx: TenantRlsClient,
|
||||
tenantId: string,
|
||||
ctx: CrmVisibilityContext,
|
||||
filter: ListKontakteFilter,
|
||||
filter: ListKontakteFilter
|
||||
): Promise<{ where: Record<string, unknown>; empty: boolean }> {
|
||||
const search = filter.search?.trim();
|
||||
let tagScopedIds: string[] | undefined;
|
||||
@@ -681,7 +802,12 @@ export async function listKontakteForBrowser(input: {
|
||||
|
||||
/** All contacts matching the same browser filter, unpaginated, for CSV export
|
||||
* (DoD 2). The CSV string itself is built in the route / a pure util. */
|
||||
export async function listKontakteForCsv(input: { tenantId: string; ctx: CrmVisibilityContext; filter?: ListKontakteFilter; sort?: ListKontakteSort }): Promise<KontaktRow[]> {
|
||||
export async function listKontakteForCsv(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
filter?: ListKontakteFilter;
|
||||
sort?: ListKontakteSort;
|
||||
}): Promise<KontaktRow[]> {
|
||||
const filter = input.filter ?? {};
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const { where, empty } = await resolveKontaktBrowserWhereWithTx(tx, input.tenantId, input.ctx, filter);
|
||||
@@ -719,7 +845,10 @@ export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise
|
||||
|
||||
const hardConds: Record<string, unknown>[] = [];
|
||||
if (email) {
|
||||
hardConds.push({ primaerEmail: { equals: email, mode: "insensitive" as const } }, { emails: { some: { email: { equals: email, mode: "insensitive" as const } } } });
|
||||
hardConds.push(
|
||||
{ primaerEmail: { equals: email, mode: "insensitive" as const } },
|
||||
{ emails: { some: { email: { equals: email, mode: "insensitive" as const } } } }
|
||||
);
|
||||
}
|
||||
if (telefon) {
|
||||
hardConds.push({ primaerTelefon: telefon }, { telefone: { some: { telefon } } });
|
||||
@@ -750,26 +879,75 @@ export async function findDuplicateKontakte(input: DuplicateCheckInput): Promise
|
||||
|
||||
// --- Bulk actions (DoD 2) --------------------------------------------------
|
||||
|
||||
export const CRM_BULK_MAX_CONTACTS = 100;
|
||||
|
||||
export function normalizeBulkKontaktIds(kontaktIds: readonly string[]): string[] {
|
||||
if (kontaktIds.length > CRM_BULK_MAX_CONTACTS) {
|
||||
throw new CatalogError(massActionErrors.exceedsLimit, {
|
||||
affected: kontaktIds.length,
|
||||
hardLimit: CRM_BULK_MAX_CONTACTS,
|
||||
});
|
||||
}
|
||||
return [...new Set(kontaktIds.map((id) => id.trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
export async function listVisibleKontakteByIds(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
kontaktIds: readonly string[];
|
||||
/** Archived contacts are excluded by default; set for the un-archive path. */
|
||||
includeArchived?: boolean;
|
||||
}): Promise<KontaktRow[]> {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (kontaktIds.length === 0) return [];
|
||||
const rows = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.findMany({
|
||||
where: {
|
||||
id: { in: kontaktIds },
|
||||
tenantId: input.tenantId,
|
||||
...(input.includeArchived ? {} : { archivedAt: null }),
|
||||
...ownerScopeWhere(input.ctx),
|
||||
},
|
||||
})
|
||||
);
|
||||
const rowById = new Map(rows.map((row) => [row.id, row as KontaktRow]));
|
||||
return kontaktIds.flatMap((id) => {
|
||||
const row = rowById.get(id);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** Archive many contacts; only contacts inside the caller's owner-scope are
|
||||
* affected (read_own may not touch others'). Returns the number affected. */
|
||||
export async function bulkArchiveKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[] }): Promise<{ affected: number }> {
|
||||
if (input.kontaktIds.length === 0) {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (kontaktIds.length === 0) {
|
||||
return { affected: 0 };
|
||||
}
|
||||
const result = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { archivedAt: new Date() } }),
|
||||
tx.kontakt.updateMany({ where: { id: { in: kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { archivedAt: new Date() } })
|
||||
);
|
||||
return { affected: result.count };
|
||||
}
|
||||
|
||||
/** Reassign many contacts; owner-scoped like {@link bulkArchiveKontakte}. */
|
||||
export async function bulkReassignKontakte(input: { tenantId: string; ctx: CrmVisibilityContext; kontaktIds: string[]; zustaendigerUserId: string }): Promise<{ affected: number }> {
|
||||
if (input.kontaktIds.length === 0) {
|
||||
export async function bulkReassignKontakte(input: {
|
||||
tenantId: string;
|
||||
ctx: CrmVisibilityContext;
|
||||
kontaktIds: string[];
|
||||
zustaendigerUserId: string;
|
||||
}): Promise<{ affected: number }> {
|
||||
const kontaktIds = normalizeBulkKontaktIds(input.kontaktIds);
|
||||
if (kontaktIds.length === 0) {
|
||||
return { affected: 0 };
|
||||
}
|
||||
const result = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.kontakt.updateMany({ where: { id: { in: input.kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) }, data: { zustaendigerUserId: input.zustaendigerUserId } }),
|
||||
);
|
||||
const result = await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await requireActiveTenantUserWithTx(tx, input.tenantId, input.zustaendigerUserId);
|
||||
return tx.kontakt.updateMany({
|
||||
where: { id: { in: kontaktIds }, tenantId: input.tenantId, ...ownerScopeWhere(input.ctx) },
|
||||
data: { zustaendigerUserId: input.zustaendigerUserId },
|
||||
});
|
||||
});
|
||||
return { affected: result.count };
|
||||
}
|
||||
|
||||
@@ -795,7 +973,10 @@ export async function resolveUserLabels(userIds: readonly string[]): Promise<Map
|
||||
/** Tenant members as zustaendigerUser picker options (id + display label). */
|
||||
export async function listAssignableUsers(tenantId: string): Promise<LabeledOption[]> {
|
||||
const members = await withTenantRLS(tenantId, (tx) =>
|
||||
tx.tenantUser.findMany({ where: { tenantId }, select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } } }),
|
||||
tx.tenantUser.findMany({
|
||||
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
|
||||
select: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
|
||||
})
|
||||
);
|
||||
return members.filter((member) => member.user).map((member) => ({ id: member.user.id, label: userLabel(member.user) }));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user