163 lines
7.1 KiB
TypeScript
163 lines
7.1 KiB
TypeScript
// VA-P23 · auto-match wiring (M09 Block E + H). Bridges the sync engine's
|
|
// upsert hook to the pure decision (email-match.ts): gathers candidates from
|
|
// the CRM (KontaktEmail / Lead.email / open Projekte / subject Projekt), writes
|
|
// the match onto the message row, and logs the Activity-Stream entry
|
|
// (`email_received` / `email_sent`, actorKind `system`, DoD 14).
|
|
//
|
|
// A manual override wins: overridden messages are never re-matched, and the
|
|
// hook only matches NEWLY created rows (re-syncs of an existing mirror keep
|
|
// their match untouched).
|
|
|
|
import { logActivity } from "@hivegrid/activity";
|
|
import { decideEmailMatch, extractSubjectProjektNummer, type EmailMatchResult } from "./email-match.js";
|
|
import type { EmailMessageUpsertedHook, EmailWorkerClient } from "./email-worker-tasks.server.js";
|
|
import type { MappedEmailMessage } from "./email-message-mapping.js";
|
|
|
|
type KontaktEmailRow = { kontaktId: string; primaer: boolean };
|
|
type IdRow = { id: string };
|
|
type ProjektKontaktRow = { projektId: string };
|
|
type MessageMatchRow = { id: string; manualOverrideAt: Date | null };
|
|
|
|
/** The extra CRM read surface the matcher needs on top of the sync client. */
|
|
export type EmailMatchClient = EmailWorkerClient & {
|
|
kontaktEmail: { findMany(args: Record<string, unknown>): Promise<KontaktEmailRow[]> };
|
|
lead: { findMany(args: Record<string, unknown>): Promise<IdRow[]> };
|
|
projekt: { findFirst(args: Record<string, unknown>): Promise<IdRow | null> };
|
|
projektKontakt: { findMany(args: Record<string, unknown>): Promise<ProjektKontaktRow[]> };
|
|
emailIntegrationMessage: EmailWorkerClient["emailIntegrationMessage"] & {
|
|
findUnique?(args: Record<string, unknown>): Promise<MessageMatchRow | null>;
|
|
};
|
|
activity: { create(args: { data: Record<string, unknown> }): Promise<{ id: string }> };
|
|
};
|
|
|
|
function activitySummaryKey(message: MappedEmailMessage): string {
|
|
return message.direction === "inbound" ? "activity.runtime.email.received" : "activity.runtime.email.sent";
|
|
}
|
|
|
|
async function gatherAndDecide(
|
|
client: EmailMatchClient,
|
|
tenantId: string,
|
|
message: MappedEmailMessage,
|
|
): Promise<EmailMatchResult> {
|
|
// Every connected mailbox address of the tenant = "own" (self-mail exclusion).
|
|
const mailboxes = await client.emailIntegrationMailbox.findMany({
|
|
where: { tenantId, archivedAt: null },
|
|
select: { id: true, emailAddress: true },
|
|
});
|
|
const ownAddresses = mailboxes.map((m) => (m as unknown as { emailAddress: string }).emailAddress.toLowerCase());
|
|
|
|
// Subject token `[Projekt #<nummer>]` — must exist in the tenant (else ignored).
|
|
const nummer = extractSubjectProjektNummer(message.subject);
|
|
const subjectProjekt = nummer
|
|
? await client.projekt.findFirst({ where: { tenantId, projektNummer: nummer, archivedAt: null }, select: { id: true } })
|
|
: null;
|
|
|
|
const probe = decideEmailMatch({
|
|
direction: message.direction,
|
|
fromAddress: message.from.address,
|
|
toAddresses: message.to,
|
|
isNewsletter: message.isNewsletter,
|
|
ownAddresses,
|
|
subjectProjektId: subjectProjekt?.id ?? null,
|
|
kontaktCandidates: [],
|
|
leadCandidateIds: [],
|
|
openProjekteByKontaktId: {},
|
|
});
|
|
const address = probe.counterpartAddress;
|
|
if (!address && !subjectProjekt) {
|
|
return probe;
|
|
}
|
|
|
|
const kontaktCandidates = address
|
|
? await client.kontaktEmail.findMany({ where: { tenantId, email: address }, select: { kontaktId: true, primaer: true } })
|
|
: [];
|
|
const leadCandidates =
|
|
address && kontaktCandidates.length === 0
|
|
? await client.lead.findMany({ where: { tenantId, email: address, archivedAt: null, convertedAt: null }, select: { id: true }, take: 1 })
|
|
: [];
|
|
|
|
// Open Projekte only for the Kontakt the pure decision would pick (primary first).
|
|
const pickedKontaktId = kontaktCandidates.length > 0 ? (kontaktCandidates.find((c) => c.primaer) ?? kontaktCandidates[0]).kontaktId : null;
|
|
const openProjekteByKontaktId: Record<string, string[]> = {};
|
|
if (pickedKontaktId && !subjectProjekt) {
|
|
const links = await client.projektKontakt.findMany({
|
|
where: { tenantId, kontaktId: pickedKontaktId, projekt: { wonAt: null, lostAt: null, archivedAt: null } },
|
|
select: { projektId: true },
|
|
});
|
|
openProjekteByKontaktId[pickedKontaktId] = [...new Set(links.map((l) => l.projektId))];
|
|
}
|
|
|
|
return decideEmailMatch({
|
|
direction: message.direction,
|
|
fromAddress: message.from.address,
|
|
toAddresses: message.to,
|
|
isNewsletter: message.isNewsletter,
|
|
ownAddresses,
|
|
subjectProjektId: subjectProjekt?.id ?? null,
|
|
kontaktCandidates,
|
|
leadCandidateIds: leadCandidates.map((l) => l.id),
|
|
openProjekteByKontaktId,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Build the sync-engine hook. Failures inside the matcher degrade to "no match"
|
|
* — the message itself is already persisted, matching must never break the sync.
|
|
*/
|
|
export function createEmailAutoMatchHook(): EmailMessageUpsertedHook {
|
|
return async ({ client, tenantId, mailboxId, messageId, created, message }) => {
|
|
if (!created) {
|
|
return; // existing mirrors keep their match (and any manual override)
|
|
}
|
|
const matchClient = client as EmailMatchClient;
|
|
try {
|
|
const match = await gatherAndDecide(matchClient, tenantId, message);
|
|
if (match.confidence === "none") {
|
|
return;
|
|
}
|
|
await matchClient.emailIntegrationMessage.updateMany({
|
|
where: { id: messageId, tenantId, mailboxId, manualOverrideAt: null },
|
|
data: {
|
|
matchedKontaktId: match.matchedKontaktId,
|
|
matchedLeadId: match.matchedLeadId,
|
|
matchedProjektId: match.matchedProjektId,
|
|
matchConfidence: match.confidence,
|
|
},
|
|
});
|
|
|
|
// Activity at the primary matched entity; the rest ride as related refs.
|
|
const subject = match.matchedKontaktId
|
|
? { subjectType: "contact" as const, subjectId: match.matchedKontaktId }
|
|
: match.matchedLeadId
|
|
? { subjectType: "lead" as const, subjectId: match.matchedLeadId }
|
|
: { subjectType: "project" as const, subjectId: match.matchedProjektId as string };
|
|
const relatedEntityRefs = [
|
|
...(match.matchedProjektId && subject.subjectType !== "project" ? [{ type: "project" as const, id: match.matchedProjektId }] : []),
|
|
...(match.matchedLeadId && subject.subjectType !== "lead" ? [{ type: "lead" as const, id: match.matchedLeadId }] : []),
|
|
];
|
|
await logActivity(
|
|
{
|
|
tenantId,
|
|
actorKind: "system",
|
|
activityType: message.direction === "inbound" ? "email_received" : "email_sent",
|
|
subjectType: subject.subjectType,
|
|
subjectId: subject.subjectId,
|
|
summaryText: activitySummaryKey(message),
|
|
relatedEntityRefs: relatedEntityRefs.length > 0 ? relatedEntityRefs : undefined,
|
|
metadata: {
|
|
emailMessageId: messageId,
|
|
mailboxId,
|
|
providerMessageId: message.providerMessageId,
|
|
subject: message.subject,
|
|
snippet: message.snippet,
|
|
matchConfidence: match.confidence,
|
|
},
|
|
},
|
|
{ client: matchClient },
|
|
);
|
|
} catch {
|
|
// Matching is best-effort — the mirror row stays with confidence "none".
|
|
}
|
|
};
|
|
}
|