Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,39 @@
import { Colors } from "~/application/enums/shared/Colors";
import MonacoEditor from "~/components/editors/MonacoEditor";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import InputText from "~/components/ui/input/InputText";
import { useLocaleFormatters } from "~/locale/format";
import { EventWithDetails } from "../db/events.db.server";
import { redactDiagnosticJsonString } from "~/utils/redaction";
import EventUtils from "../utils/EventUtils";
import { useTranslation } from "react-i18next";
interface Props {
item: EventWithDetails;
}
export default function EventDetails({ item }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const formattedData = () => {
return redactDiagnosticJsonString(item.data);
};
return (
<div className="space-y-3 text-sm">
<div className="border-border flex justify-between border-b pb-3">
<h3>
<SimpleBadge className="text-lg" title={EventUtils.parseName(item.name, t)} color={Colors.VIOLET} />
</h3>
</div>
<div className="grid grid-cols-3 gap-4">
<InputText name="createdAt" title={t("shared.createdAt")} defaultValue={formatters.dateTime(item.createdAt)} readOnly={true} />
<InputText name="account" title={t("models.tenant.object")} defaultValue={item.tenant?.name ?? t("shared.notSet")} readOnly={true} />
<InputText name="user" title={t("models.user.object")} defaultValue={item.user?.email || t("shared.notSet")} readOnly={true} />
</div>
<div className="h-96 overflow-auto p-2">
<MonacoEditor value={formattedData()} onChange={() => {}} theme="vs-dark" language="json" />
</div>
</div>
);
}
@@ -0,0 +1,139 @@
import { Link, useParams } from "react-router";
import { Fragment, useState } from "react";
import { useTranslation } from "react-i18next";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { Colors } from "~/application/enums/shared/Colors";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import ExternalLinkEmptyIcon from "~/components/ui/icons/ExternalLinkEmptyIcon";
import OpenModal from "~/components/ui/modals/OpenModal";
import TableSimple from "~/components/ui/tables/TableSimple";
import { EventWithAttempts } from "../db/events.db.server";
import MonacoEditor from "~/components/editors/MonacoEditor";
import { Badge } from "~/components/ui/badge";
import { useLocaleFormatters } from "~/locale/format";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { redactDiagnosticJsonString } from "~/utils/redaction";
import EventUtils from "../utils/EventUtils";
interface Props {
items: EventWithAttempts[];
pagination: PaginationDto;
}
export default function EventsTable({ items, pagination }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const params = useParams();
const [selectedData, setSelectedData] = useState<EventWithAttempts | undefined>(undefined);
const formattedData = (item: EventWithAttempts) => {
return redactDiagnosticJsonString(item.data);
};
return (
<>
<TableSimple
items={items}
actions={[
{
title: t("shared.details"),
onClickRoute: (_, i) => i.id,
},
]}
pagination={pagination}
headers={[
{
name: "event",
title: t("models.event.object"),
value: (i) => EventUtils.parseName(i.name, t),
formattedValue: (i) => (
<div>
<Badge variant="secondary">{EventUtils.parseName(i.name, t)}</Badge>
</div>
),
},
{
name: "data",
title: t("models.event.data"),
value: (i) => (
<button type="button" onClick={() => setSelectedData(i)} className="hover:text-theme-500 truncate underline">
{EventUtils.parseDescription(i, t, formatters)}
</button>
),
className: "w-full",
},
// {
// name: "attempts",
// title: t("models.event.attempts"),
// value: (i) => i.attempts.length,
// formattedValue: (i) => (
// <div className="flex space-x-1">
// {i.attempts.map((f, idx) => (
// <Link to={i.id + "?attempt=" + f.id} key={idx}>
// <StatusBadge startedAt={f.startedAt} finishedAt={f.finishedAt} endpoint={f.endpoint} status={f.status} />
// </Link>
// ))}
// </div>
// ),
// },
{
name: "tenant",
title: t("models.tenant.object"),
value: (i) => (
<div className="text-xs">
{!i.tenant ? (
<span className="text-muted-foreground italic">{t("shared.notSet")}</span>
) : (
<Fragment>
<div className="font-medium">{i.tenant?.name}</div>
<Link
to={appPath({ tenantSlug: i.tenant.slug, mode: "host-aware" })}
target="_blank"
className="text-muted-foreground focus:bg-secondary/90 hover:border-border rounded-md border-b border-dashed text-xs hover:border-dashed"
>
<span>/{i.tenant.slug}</span>
</Link>
</Fragment>
)}
</div>
),
hidden: !!params.tenant,
},
{
name: "createdAt",
title: t("shared.createdAt"),
value: (i) => (
<div className="text-xs">
<div>{i.user?.email ?? <span className="text-muted-foreground italic">{t("shared.notSet")}</span>}</div>
<div className="text-muted-foreground text-xs">{formatters.relativeDate(i.createdAt)}</div>
</div>
),
},
]}
/>
{selectedData && (
<OpenModal className="max-w-md" onClose={() => setSelectedData(undefined)}>
<div className="space-y-3 text-sm">
<div className="border-border flex justify-between border-b pb-3">
<h3>
<SimpleBadge className="text-lg" title={EventUtils.parseName(selectedData.name, t)} color={Colors.VIOLET} />
</h3>
<div className="flex items-center space-x-2">
<div className="text-muted-foreground text-sm">{formatters.dateTime(selectedData.createdAt)}</div>
<Link to={selectedData.id} className="text-muted-foreground hover:text-foreground/80">
<ExternalLinkEmptyIcon className="h-5 w-5" />
</Link>
</div>
</div>
<div className="space-y-2">
<p className="text-xs font-bold">{t("models.event.data")}</p>
<div className="h-96 overflow-auto p-2">
<MonacoEditor value={formattedData(selectedData)} onChange={() => {}} theme="vs-dark" language="json" />
</div>
</div>
</div>
</OpenModal>
)}
</>
);
}
@@ -0,0 +1,53 @@
import { Colors } from "~/application/enums/shared/Colors";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import { useTranslation } from "react-i18next";
interface Props {
startedAt: Date | null;
finishedAt: Date | null;
endpoint: string;
status: number | null;
}
export default function StatusBadge({ startedAt, finishedAt, endpoint, status }: Props) {
const { t } = useTranslation();
function getState() {
if (status === null && startedAt === null) {
return t("events.webhookAttempts.status.notCaught");
} else if (status === null && startedAt !== null && finishedAt === null) {
return t("events.webhookAttempts.status.running");
} else if (status !== null && finishedAt !== null) {
if (status >= 200 && status < 300) {
return `[${status}] ${t("events.webhookAttempts.status.success")}`;
} else if (status >= 300 && status < 400) {
return `[${status}] ${t("events.webhookAttempts.status.redirect")}`;
} else if (status >= 400 && status < 500) {
return `[${status}] ${t("events.webhookAttempts.status.clientError")}`;
} else if (status >= 500) {
return `[${status}] ${t("events.webhookAttempts.status.serverError")}`;
} else {
return `[${status}] ${t("events.webhookAttempts.status.unknown")}`;
}
} else {
return t("events.webhookAttempts.status.unknown");
}
}
function getColor() {
if (status === null) {
return Colors.YELLOW;
} else if (status >= 200 && status < 300) {
return Colors.GREEN;
} else if (status >= 300 && status < 400) {
return Colors.ORANGE;
} else if (status >= 400 && status < 500) {
return Colors.RED;
} else {
return Colors.UNDEFINED;
}
}
return (
<div title={endpoint}>
<SimpleBadge title={getState()} color={getColor()} />
</div>
);
}
@@ -0,0 +1,218 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { ApplicationEvents, getApplicationEventNameKey } from "~/modules/events/types/ApplicationEvent";
const repoRoot = process.cwd();
const textCache = new Map<string, string>();
const jsonCache = new Map<string, unknown>();
type LocaleTranslations = {
admin: {
events: {
filters: {
eventOption: string;
};
};
};
events: {
descriptions: {
subscription: Record<string, string>;
};
names: Record<string, string>;
};
models: {
log: {
actions: Record<string, string>;
};
};
};
function resolveRepoPath(file: string) {
return path.resolve(repoRoot, file);
}
function readRepoFile(file: string) {
const resolved = resolveRepoPath(file);
const cached = textCache.get(resolved);
if (cached !== undefined) {
return cached;
}
const source = fs.readFileSync(resolved, "utf8");
textCache.set(resolved, source);
return source;
}
function readJsonFile<T>(file: string) {
const resolved = resolveRepoPath(file);
if (!jsonCache.has(resolved)) {
jsonCache.set(resolved, JSON.parse(readRepoFile(file)) as unknown);
}
return jsonCache.get(resolved) as T;
}
function readTranslations(locale: "en" | "de") {
return readJsonFile<LocaleTranslations>(`apps/web/public/locales/${locale}/translations.json`);
}
function getNestedValue(source: unknown, key: string) {
return key.split(".").reduce<unknown>((value, segment) => {
if (!value || typeof value !== "object") {
return undefined;
}
return (value as Record<string, unknown>)[segment];
}, source);
}
describe("events i18n", () => {
it("keeps event detail chrome behind semantic keys", () => {
const sources = [
"apps/web/app/modules/events/components/EventDetails.tsx",
"apps/web/app/modules/events/components/EventsTable.tsx",
"apps/web/app/modules/events/components/StatusBadge.tsx",
"apps/web/app/components/app/events/LogsTable.tsx",
"apps/web/app/routes/admin/events.tsx",
"apps/web/app/routes/app.$tenant/settings/logs/events.$id.tsx",
"apps/web/app/routes/app.$tenant/settings/logs/events.tsx",
]
.map((file) => readRepoFile(file))
.join("\n");
expect(sources).toContain("shared.createdAt");
expect(sources).toContain("models.tenant.object");
expect(sources).toContain("models.user.object");
expect(sources).toContain("models.log.action");
expect(sources).toContain("EventUtils.parseName");
expect(sources).toContain("admin.events.filters.eventOption");
expect(sources).toContain("settings.logs.events.filters.eventOption");
expect(sources).toContain("getLogActionI18nKey");
expect(sources).toContain("events.webhookAttempts.status.notCaught");
expect(sources).toContain("useLocaleFormatters");
expect(sources).toContain("createLocaleFormatters");
expect(sources).toContain("useTranslation");
expect(sources).toContain('t("shared.notSet")');
expect(sources).not.toContain("t as i18nT");
expect(sources).not.toContain("DateUtils.");
expect(sources).not.toContain('from "~/utils/shared/DateUtils"');
expect(sources).not.toContain("ui.autogenerated");
expect(sources).not.toContain("Webhook Attempt #");
expect(sources).not.toContain("Webhook not catched");
expect(sources).not.toContain("title={item.name}");
expect(sources).not.toContain("title: data.item.name");
expect(sources).not.toContain("${item.value} - ${t(");
expect(sources).not.toContain("{i.name}</Badge>");
expect(sources).not.toContain('italic">?</span>');
});
it("localizes event preference values before interpolation", () => {
const source = readRepoFile("apps/web/app/modules/events/utils/EventUtils.ts");
expect(source).toContain("translateEventValue");
expect(source).toContain("shared.locales.${oldLocale}");
expect(source).toContain("shared.locales.${newLocale}");
expect(source).toContain("shared.${oldTheme}");
expect(source).toContain("shared.${newTheme}");
expect(source).not.toContain("oldLocale,\n newLocale,");
expect(source).not.toContain("oldTheme,\n newTheme,");
});
it("keeps server-side event diagnostics behind semantic keys", () => {
const source = readRepoFile("apps/web/app/modules/events/services/.server/EventsService.ts");
expect(source).toContain("events.webhooks.errors.callEndpointFailed");
expect(source).toContain("events.actions.viewAccount");
expect(source).not.toContain("ui.autogenerated");
});
it("keeps localized audit log actions available in English and German", () => {
const en = readTranslations("en");
const de = readTranslations("de");
const actionKeys = [
"apiKeyCreated",
"apiKeyUpdated",
"apiKeyRotated",
"apiKeyDeleted",
"updateTenantDetails",
"updatedAiOverageConfiguration",
"workspaceRoleCreated",
"workspaceRoleUpdated",
"workspaceRoleDeleted",
];
for (const key of actionKeys) {
expect(en.models.log.actions[key]).toEqual(expect.any(String));
expect(de.models.log.actions[key]).toEqual(expect.any(String));
}
});
it("keeps admin event filter option locale keys in parity", () => {
const en = readTranslations("en");
const de = readTranslations("de");
expect(en.admin.events.filters.eventOption).toBe("{{eventValue}} - {{eventLabel}}");
expect(de.admin.events.filters.eventOption).toBe("{{eventValue}} - {{eventLabel}}");
});
it("keeps German subscription event names aligned with plan and subscription terminology", () => {
const de = readTranslations("de");
expect(de.events.descriptions.subscription.subscribed).toBe("{{tenant}} hat den Tarif {{product}} abonniert");
expect(de.events.descriptions.subscription.subscribedByUser).toBe("{{email}} hat für {{tenant}} den Tarif {{product}} abonniert");
expect(de.events.descriptions.subscription.upgraded).toBe("Tarif-Upgrade: {{tenant}} ({{product}})");
expect(de.events.descriptions.subscription.downgraded).toBe("Tarif-Downgrade: {{tenant}} ({{product}})");
expect(de.events.descriptions.subscription.cancelled).toBe("Abonnement gekündigt: {{tenant}} ({{product}})");
expect(de.events.names.subscription_subscribed).toBe("Tarif abonniert");
expect(de.events.names.subscription_upgraded).toBe("Tarif-Upgrade");
expect(de.events.names.subscription_downgraded).toBe("Tarif-Downgrade");
});
it("keeps German row event names aligned with Datensatz terminology", () => {
const de = readTranslations("de");
const rowEventNames = Object.entries(de.events.names).filter(([key]) => key.startsWith("row_"));
expect(rowEventNames.length).toBeGreaterThan(0);
for (const [, value] of rowEventNames) {
expect(value).toEqual(expect.any(String));
expect(value).not.toMatch(/Zeile|Zeilen/u);
}
expect(de.events.names.row_updated).toBe("Datensatz aktualisiert");
expect(de.events.names.row_comments_reacted).toBe("Reaktion auf Datensatzkommentar");
});
it("keeps every application event name backed by explicit en/de locale keys", () => {
const locales = ["en", "de"] as const;
for (const event of ApplicationEvents) {
expect(event, event.value).not.toHaveProperty("name");
for (const locale of locales) {
const translations = readTranslations(locale);
const key = getApplicationEventNameKey(event.value).replace("events.names.", "");
expect(translations.events.names, `${locale} ${getApplicationEventNameKey(event.value)}`).toHaveProperty(key);
expect(translations.events.names[key], `${locale} ${getApplicationEventNameKey(event.value)}`).toEqual(expect.any(String));
expect(translations.events.names[key].trim(), `${locale} ${getApplicationEventNameKey(event.value)}`).not.toBe("");
}
}
});
it("keeps every EventUtils description key backed by explicit en/de locale text", () => {
const source = readRepoFile("apps/web/app/modules/events/utils/EventUtils.ts");
const descriptionKeys = Array.from(source.matchAll(/translateEventDescription\(\s*t,\s*"([^"]+)"/g), ([, key]) => key)
.filter((key) => key.startsWith("events."))
.sort();
expect(descriptionKeys.length).toBeGreaterThan(0);
for (const locale of ["en", "de"] as const) {
const translations = readTranslations(locale);
for (const key of descriptionKeys) {
expect(getNestedValue(translations, key), `${locale} ${key}`).toEqual(expect.any(String));
expect((getNestedValue(translations, key) as string).trim(), `${locale} ${key}`).not.toBe("");
}
}
});
});
@@ -0,0 +1,23 @@
import { db } from "~/utils/db.server";
export async function createEventWebhookAttempt(data: { eventId: string; endpoint: string }) {
return await db.eventWebhookAttempt.create({
data,
});
}
export async function updateEventWebhookAttempt(
id: string,
data: { startedAt?: Date; finishedAt?: Date; success?: boolean; status?: number; message?: string; body?: string }
) {
return await db.eventWebhookAttempt.update({
where: { id },
data,
});
}
export async function deleteEventWebhookAttempt(id: string) {
return await db.eventWebhookAttempt.delete({
where: { id },
});
}
@@ -0,0 +1,109 @@
import { Event } from "@toolctrl/db/prisma-browser";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationResultDto } from "~/application/dtos/data/PaginationResultDto";
import { db } from "~/utils/db.server";
import { TenantSimple } from "~/utils/db/tenants.db.server";
import { UserSimple } from "~/utils/db/users.db.server";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import TenantModelHelper from "~/utils/helpers/models/TenantModelHelper";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
export type EventWithAttempts = Event & {
tenant: TenantSimple | null;
user: UserSimple | null;
// attempts: {
// id: string;
// startedAt: Date | null;
// finishedAt: Date | null;
// endpoint: string;
// success: boolean | null;
// status: number | null;
// message: string | null;
// }[];
};
export type EventWithDetails = Event & {
tenant: TenantSimple | null;
user: UserSimple | null;
// attempts: EventWebhookAttempt[];
};
export async function getEvents(
pagination: { current: { page: number; pageSize: number }; filters: FiltersDto },
tenantId?: string | null
): Promise<{
items: EventWithAttempts[];
pagination: PaginationResultDto;
}> {
const whereFilters = RowFiltersHelper.getFiltersCondition(pagination.filters);
const items = await db.event.findMany({
take: pagination.current.pageSize,
skip: pagination.current.pageSize * (pagination.current.page - 1),
where: {
AND: [whereFilters, { tenantId }],
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
user: { select: UserModelHelper.selectSimpleUserProperties },
// attempts: {
// select: {
// id: true,
// startedAt: true,
// finishedAt: true,
// endpoint: true,
// success: true,
// status: true,
// message: true,
// },
// },
},
orderBy: {
createdAt: "desc",
},
});
const totalItems = await db.event.count({
where: {
tenantId,
...whereFilters,
},
});
const totalPages = Math.ceil(totalItems / pagination.current.pageSize);
return {
items,
pagination: {
totalItems,
totalPages,
page: pagination.current.page,
pageSize: pagination.current.pageSize,
sortedBy: undefined,
query: undefined,
},
};
}
export async function getEvent(id: string, tenantId?: string | null): Promise<EventWithDetails | null> {
return await db.event.findFirst({
where: {
id,
...(tenantId !== undefined ? { tenantId } : {}),
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
user: { select: UserModelHelper.selectSimpleUserProperties },
// attempts: true,
},
});
}
export async function createEvent(data: { tenantId: string | null; userId: string | null; name: string; data: string; description: string | null }) {
return await db.event.create({
data: {
tenantId: data.tenantId,
userId: data.userId,
name: data.name,
data: data.data,
description: data.description,
},
});
}
@@ -0,0 +1,11 @@
export type AccountCreatedDto = {
tenant: {
id: string;
name: string;
slug: string;
};
user: {
id: string;
email: string;
};
};
@@ -0,0 +1,20 @@
export type AccountDeletedDto = {
tenant: {
id: string;
name: string;
};
user: {
id: string;
email: string;
};
subscription?: {
price: {
id: string;
amount: number;
};
product: {
id: string;
title: string;
};
};
};
@@ -0,0 +1,15 @@
export type AccountUpdatedDto = {
id: string;
new: {
name: string;
slug: string;
};
old: {
name: string;
slug: string;
};
user: {
id: string;
email: string;
};
};
@@ -0,0 +1,13 @@
import { ApiKeyEntityPermissionDto } from "~/application/dtos/apiKeys/ApiKeyEntityPermissionDto";
export type ApiKeyCreatedDto = {
id: string;
alias: string;
expires: Date | null;
active: boolean;
entities: ApiKeyEntityPermissionDto[];
user: {
id: string;
email: string;
};
};
@@ -0,0 +1,13 @@
import { ApiKeyEntityPermissionDto } from "~/application/dtos/apiKeys/ApiKeyEntityPermissionDto";
export type ApiKeyDeletedDto = {
id: string;
alias: string;
expires: Date | null;
active: boolean;
entities: ApiKeyEntityPermissionDto[];
user: {
id: string;
email: string;
};
};
@@ -0,0 +1,21 @@
import { ApiKeyEntityPermissionDto } from "~/application/dtos/apiKeys/ApiKeyEntityPermissionDto";
export type ApiKeyUpdatedDto = {
id: string;
new: {
alias: string;
expires: Date | null;
active: boolean;
entities: ApiKeyEntityPermissionDto[];
};
old: {
alias: string;
expires: Date | null;
active: boolean;
entities: ApiKeyEntityPermissionDto[];
};
user: {
id: string;
email: string;
};
};
@@ -0,0 +1,7 @@
export type EmailReceivedDto = {
fromEmail: string;
fromName?: string;
toEmail: string;
toName?: string;
subject: string;
};
@@ -0,0 +1,14 @@
export type MemberDeletedDto = {
tenant: {
id: string;
name: string;
};
fromUser: {
id: string;
email: string;
};
user: {
id: string;
email: string;
};
};
@@ -0,0 +1,22 @@
export type MemberInvitationAcceptedDto = {
newUser: boolean;
tenant: {
id: string;
name: string;
slug: string;
};
fromUser: {
id: string;
email: string;
} | null;
user: {
id: string;
email: string;
firstName: string;
lastName: string;
type: string;
};
invitation: {
id: string;
};
};
@@ -0,0 +1,16 @@
export type MemberInvitationCreatedDto = {
tenant: {
id: string;
name: string;
};
user: {
email: string;
firstName: string;
lastName: string;
type: string;
};
fromUser: {
id: string;
email: string;
};
};
@@ -0,0 +1,5 @@
export type OnboardingCompletedDto = {
session: { id: string };
onboarding: { title: string };
user: { id: string; email: string };
};
@@ -0,0 +1,5 @@
export type OnboardingDismissedDto = {
session: { id: string };
onboarding: { title: string };
user: { id: string; email: string };
};
@@ -0,0 +1,5 @@
export type OnboardingStartedDto = {
session: { id: string };
onboarding: { title: string };
user: { id: string; email: string };
};
@@ -0,0 +1,15 @@
export type RoleAssignedDto = {
fromUser: {
id: string;
email: string;
};
toUser: {
id: string;
email: string;
};
role: {
id: string;
name: string;
description: string;
};
};
@@ -0,0 +1,15 @@
export type RoleUnassignedDto = {
fromUser: {
id: string;
email: string;
};
toUser: {
id: string;
email: string;
};
role: {
id: string;
name: string;
description: string;
};
};
@@ -0,0 +1,11 @@
export type RowCommentsCreatedDto = {
rowId: string;
comment: {
id: string;
text: string;
};
user: {
id: string;
email: string;
} | null;
};
@@ -0,0 +1,11 @@
export type RowCommentsDeletedDto = {
rowId: string;
comment: {
id: string;
text: string;
};
user: {
id: string;
email: string;
} | null;
};
@@ -0,0 +1,12 @@
export type RowCommentsReactedDto = {
rowId: string;
reaction: string;
comment: {
id: string;
text: string;
};
user: {
id: string;
email: string;
} | null;
};
@@ -0,0 +1,15 @@
export type RowCreatedDto = {
id: string;
title: string;
row: { [key: string]: any };
entity: { id: string; name: string; slug: string; title: string };
visibility: string;
user?: {
id: string;
email: string;
};
apiKey?: {
id: string;
alias: string;
};
};
@@ -0,0 +1,14 @@
export type RowDeletedDto = {
id: string;
title: string;
row: { [key: string]: any };
entity: { id: string; name: string; slug: string; title: string };
user?: {
id: string;
email: string;
};
apiKey?: {
id: string;
alias: string;
};
};
@@ -0,0 +1,12 @@
export type RowSharedDto = {
id: string;
title: string;
entity: { id: string; name: string; slug: string; title: string };
type: "tenant" | "user" | "role" | "group" | "public";
to: string;
access: string;
user?: {
id: string;
email: string;
};
};
@@ -0,0 +1,15 @@
export type RowTasksCreatedDto = {
rowId: string;
task: {
id: string;
name: string;
};
user?: {
id: string;
email: string;
} | null;
apiKey?: {
id: string;
alias: string;
};
};
@@ -0,0 +1,15 @@
export type RowTasksDeletedDto = {
rowId: string;
task: {
id: string;
name: string;
};
user?: {
id: string;
email: string;
} | null;
apiKey?: {
id: string;
alias: string;
};
};
@@ -0,0 +1,21 @@
export type RowTasksUpdatedDto = {
rowId: string;
new: {
id: string;
name: string;
completedAt?: Date | null;
};
old: {
id: string;
name: string;
completedAt?: Date | null;
};
user?: {
id: string;
email: string;
} | null;
apiKey?: {
id: string;
alias: string;
};
};
@@ -0,0 +1,14 @@
export type RowUpdatedDto = {
id: string;
title: string;
row: { [key: string]: any };
entity: { id: string; name: string; slug: string; title: string };
user?: {
id: string;
email: string;
};
apiKey?: {
id: string;
alias: string;
};
};
@@ -0,0 +1,16 @@
export type SubscriptionCancelledDto = {
user: {
id: string;
email: string;
} | null;
tenant: {
id: string;
name: string;
};
subscription?: {
product: {
id: string;
title: string;
};
};
};
@@ -0,0 +1,39 @@
export type SubscriptionDowngradedDto = {
user: {
id: string;
email: string;
} | null;
tenant: {
id: string;
name: string;
};
// to: {
// price: {
// id: string;
// billingPeriod: SubscriptionBillingPeriod;
// amount: number;
// };
// product: {
// id: string;
// title: string;
// };
// };
// from: {
// price: {
// id: string;
// billingPeriod: SubscriptionBillingPeriod;
// amount: number;
// };
// product: {
// id: string;
// title: string;
// };
// };
subscription: {
product: {
id: string;
title: string;
};
session?: string;
};
};
@@ -0,0 +1,16 @@
export type SubscriptionEndedDto = {
user: {
id: string;
email: string;
} | null;
tenant: {
id: string;
name: string;
};
subscription?: {
product: {
id: string;
title: string;
};
};
};
@@ -0,0 +1,18 @@
export type SubscriptionSubscribedDto = {
user: {
id: string;
email: string;
} | null;
tenant: {
id: string;
name: string;
slug: string;
};
subscription: {
product: {
id: string;
title: string;
};
session?: string;
};
};
@@ -0,0 +1,39 @@
export type SubscriptionUpgradedDto = {
user: {
id: string;
email: string;
} | null;
tenant: {
id: string;
name: string;
};
// to: {
// price: {
// id: string;
// billingPeriod: SubscriptionBillingPeriod;
// amount: number;
// };
// product: {
// id: string;
// title: string;
// };
// };
// from: {
// price: {
// id: string;
// billingPeriod: SubscriptionBillingPeriod;
// amount: number;
// };
// product: {
// id: string;
// title: string;
// };
// };
subscription: {
product: {
id: string;
title: string;
};
session?: string;
};
};
@@ -0,0 +1,10 @@
export type UserPasswordUpdatedDto = {
user: {
id: string;
email: string;
};
fromUser?: {
id: string;
email: string;
};
};
@@ -0,0 +1,16 @@
import { LightOrDarkMode } from "~/utils/theme/userThemePreference.server";
export type UserPreferencesUpdatedDto = {
new: {
locale?: string;
lightOrDarkMode?: LightOrDarkMode;
};
old: {
locale?: string;
lightOrDarkMode?: LightOrDarkMode;
};
user: {
id: string;
email: string;
};
};
@@ -0,0 +1,9 @@
import { AccountDeletedDto } from "./AccountDeletedDto";
export type UserProfileDeletedDto = {
id: string;
email: string;
firstName: string;
lastName: string;
deletedAccounts?: AccountDeletedDto[];
};
@@ -0,0 +1,12 @@
export type UserProfileUpdatedDto = {
email: string;
new: {
firstName: string;
lastName: string;
};
old: {
firstName: string;
lastName: string;
};
userId: string;
};
@@ -0,0 +1,104 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const publishOutboxEventMock = vi.fn(async () => ({ id: "outbox_1" }));
vi.mock("@toolctrl/db/outbox", () => ({
publishOutboxEvent: (...args: unknown[]) => publishOutboxEventMock(...args),
}));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: {
sendToRoles: vi.fn(),
},
}));
vi.mock("~/utils/db.server", () => ({
db: {
$transaction: vi.fn(),
},
}));
vi.mock("~/utils/url.server", () => ({
getAbsoluteApiUrl: vi.fn(() => "https://app.example.test/api"),
getBaseURL: vi.fn(() => "https://app.example.test"),
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
adminPath: vi.fn((path: string) => `/admin/${path}`),
appPath: vi.fn((path: string) => `/app/${path}`),
}));
vi.mock("../../db/eventWebhookAttempts.db.server", () => ({
createEventWebhookAttempt: vi.fn(),
updateEventWebhookAttempt: vi.fn(),
}));
import EventsService from "./EventsService";
describe("EventsService workflow outbox producer", () => {
beforeEach(() => {
publishOutboxEventMock.mockClear();
});
it("records the application event before publishing the workflow outbox event in the same transaction", async () => {
const createdEvent = {
id: "evt_1",
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify({
id: "row_1",
title: "Acme deal",
row: { id: "row_1" },
entity: { id: "entity_1", name: "Deal", slug: "deals", title: "Deals" },
visibility: "tenant",
user: { id: "user_1", email: "owner@example.test" },
}),
description: "New Deal: Acme deal, by owner@example.test",
createdAt: new Date("2026-05-27T10:00:00.000Z"),
};
const tx = {
event: {
create: vi.fn(async () => createdEvent),
},
};
const payload = {
id: "row_1",
title: "Acme deal",
row: { id: "row_1" },
entity: { id: "entity_1", name: "Deal", slug: "deals", title: "Deals" },
visibility: "tenant",
user: { id: "user_1", email: "owner@example.test" },
};
const result = await EventsService.createInTransaction(tx as never, {
event: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: payload,
});
expect(result.item).toBe(createdEvent);
expect(tx.event.create).toHaveBeenCalledWith({
data: {
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify(payload),
description: "New Deal: Acme deal, by owner@example.test",
},
});
expect(publishOutboxEventMock).toHaveBeenCalledWith(tx, {
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: {
event: "row.created",
data: payload,
userId: "user_1",
},
dispatchKey: "workflow-trigger:evt_1",
});
expect(tx.event.create.mock.invocationCallOrder[0]).toBeLessThan(publishOutboxEventMock.mock.invocationCallOrder[0]);
});
});
@@ -0,0 +1,79 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const publishOutboxEventMock = vi.fn();
vi.mock("@toolctrl/db/outbox", () => ({
publishOutboxEvent: publishOutboxEventMock,
}));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: {
sendToRoles: vi.fn(),
},
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({
error: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
}),
}));
vi.mock("~/utils/db.server", () => ({
db: {
$transaction: vi.fn(),
},
}));
describe("EventsService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("publishes workflow trigger outbox events after the application event row is created", async () => {
const eventCreateMock = vi.fn().mockResolvedValue({ id: "event_1" });
const tx = {
event: {
create: eventCreateMock,
},
outboxEvent: {
create: vi.fn(),
findUnique: vi.fn(),
},
};
const EventsService = (await import("./EventsService")).default;
await EventsService.createInTransaction(tx as never, {
event: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: { id: "row_1", entity: { slug: "contacts", title: "Contacts" } },
});
expect(eventCreateMock).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify({ id: "row_1", entity: { slug: "contacts", title: "Contacts" } }),
}),
})
);
expect(publishOutboxEventMock).toHaveBeenCalledWith(
tx,
expect.objectContaining({
tenantId: "tenant_1",
type: "workflow.trigger.event",
dispatchKey: "workflow-trigger:event_1",
payload: {
event: "row.created",
data: { id: "row_1", entity: { slug: "contacts", title: "Contacts" } },
userId: "user_1",
},
})
);
expect(eventCreateMock.mock.invocationCallOrder[0]).toBeLessThan(publishOutboxEventMock.mock.invocationCallOrder[0]);
});
});
@@ -0,0 +1,354 @@
import { Event } from "@toolctrl/db/prisma-browser";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@toolctrl/db/outbox";
import { buildWorkflowTriggerOutboxEvent } from "@toolctrl/queue";
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
import { getBaseURL } from "~/utils/url.server";
import { createEventWebhookAttempt, updateEventWebhookAttempt } from "../../db/eventWebhookAttempts.db.server";
import { ApplicationEvent, ApplicationEvents } from "../../types/ApplicationEvent";
import EventUtils from "../../utils/EventUtils";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { getAbsoluteApiUrl } from "~/utils/url.server";
import { t as i18nT } from "i18next";
import { createScopedLogger } from "~/utils/logger.server";
import { db } from "~/utils/db.server";
const eventsLogger = createScopedLogger("events");
type ICreateApplicationEvent = {
request?: Request;
event: ApplicationEvent;
tenantId: string | null;
userId: string | null;
data: any;
};
type EventPublisherTransaction = OutboxPublisherTransaction & {
event: {
create(args: {
data: {
name: ApplicationEvent;
tenantId: string | null;
userId: string | null;
data: string;
description: string;
};
}): Promise<Event>;
};
};
type RecordedApplicationEvent = ICreateApplicationEvent & {
item: Event;
description: string;
endpoints?: string[];
};
async function createInTransaction(tx: EventPublisherTransaction, { event, tenantId, userId, data }: ICreateApplicationEvent) {
const description = EventUtils.getDescription(event, data) ?? "";
const item = await tx.event.create({
data: {
name: event,
tenantId,
userId,
data: JSON.stringify(data),
description,
},
});
await publishOutboxEvent(tx, buildWorkflowTriggerOutboxEvent({
tenantId,
event,
data,
userId,
sourceId: item.id,
}));
return { item, description };
}
async function dispatchPostCommitSideEffects({ request, event, tenantId, userId, data, description, endpoints, item }: RecordedApplicationEvent) {
await onEvent({ request, event, tenantId, userId, data, description }).catch((e) => {
eventsLogger.error({ err: e, op: "onEvent", event, tenantId }, "onEvent handler failed");
});
if (request && endpoints && endpoints.length > 0) {
await Promise.all(
endpoints.map(async (endpoint) => {
return await callEventEndpoint({ request, event: item, endpoint, body: JSON.stringify(data) }).catch((e) => {
eventsLogger.error({ err: e, op: "callEventEndpoint", endpoint, eventId: item.id }, "Event webhook callout failed");
});
})
);
}
}
async function create({
request,
event,
tenantId,
userId,
data,
endpoints,
}: ICreateApplicationEvent & {
endpoints?: string[];
}) {
const { item, description } = await db.$transaction((tx) =>
createInTransaction(tx as unknown as EventPublisherTransaction, { request, event, tenantId, userId, data })
);
await dispatchPostCommitSideEffects({ request, event, tenantId, userId, data, description, endpoints, item });
return event;
}
async function callEventEndpoint({ request, event, endpoint, body }: { request: Request; event: Event; endpoint: string; body: string }) {
const webhookAttempt = await createEventWebhookAttempt({ eventId: event.id, endpoint });
try {
await fetch(getAbsoluteApiUrl(request, `/v1/events/webhooks/attempts/${webhookAttempt.id}`), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body,
});
} catch (e: any) {
// While seeding the database it should not call endpoints
await updateEventWebhookAttempt(webhookAttempt.id, {
startedAt: new Date(),
finishedAt: new Date(),
success: false,
status: 500,
message: i18nT("events.webhooks.errors.callEndpointFailed", { message: e.message }),
});
}
}
function assertNever(x: never): never {
throw new Error("Unexpected event: " + x);
}
async function onEvent(params: ICreateApplicationEvent & { description: string }) {
eventsLogger.info({ op: "onEvent", event: params.event, tenantId: params.tenantId }, "Application event dispatched");
const event = ApplicationEvents.find((f) => f.value === params.event);
if (!event) {
eventsLogger.warn({ op: "onEvent", event: params.event }, "Event not found");
return;
}
const tenantId = params.tenantId;
try {
switch (event.value) {
case "user.profile.updated": {
break;
}
case "user.profile.deleted": {
break;
}
case "user.password.updated": {
break;
}
case "user.mfa.totp.enrollment.started": {
break;
}
case "user.mfa.totp.enabled": {
break;
}
case "user.mfa.totp.disabled": {
break;
}
case "user.preferences.updated": {
break;
}
case "account.created": {
await NotificationService.sendToRoles({
channel: "admin-accounts",
tenantId,
notification: {
message: params.description,
action: {
title: i18nT("events.actions.viewAccount"),
url: adminPath(`accounts/${tenantId ?? ""}`, { mode: "host-aware" }),
},
},
});
break;
}
case "account.updated": {
break;
}
case "account.deleted": {
break;
}
case "member.invitation.created": {
await NotificationService.sendToRoles({
channel: "admin-account-members",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: "settings/members", mode: "host-aware" }) },
},
});
break;
}
case "member.invitation.accepted": {
break;
}
case "member.deleted": {
break;
}
case "role.assigned": {
await NotificationService.sendToRoles({
channel: "roles",
tenantId,
notification: {
message: params.description,
},
});
break;
}
case "role.unassigned": {
break;
}
case "subscription.subscribed": {
await NotificationService.sendToRoles({
channel: "admin-subscriptions",
tenantId,
notification: {
message: params.description,
},
});
break;
}
case "subscription.upgraded": {
break;
}
case "subscription.downgraded": {
break;
}
case "subscription.cancelled": {
await NotificationService.sendToRoles({
channel: "admin-subscriptions",
tenantId,
notification: {
message: params.description,
action: { url: adminPath(`accounts/${tenantId ?? ""}`, { mode: "host-aware" }) },
},
});
break;
}
case "subscription.ended": {
await NotificationService.sendToRoles({
channel: "admin-subscriptions",
tenantId,
notification: {
message: params.description,
action: { url: adminPath(`accounts/${tenantId ?? ""}`, { mode: "host-aware" }) },
},
});
break;
}
case "api_key.created": {
break;
}
case "api_key.updated": {
break;
}
case "api_key.deleted": {
break;
}
case "email.received": {
break;
}
case "row.created": {
await NotificationService.sendToRoles({
channel: "admin-rows",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: `${params.data.entity.slug}/${params.data.id}`, mode: "host-aware" }) },
},
});
break;
}
case "row.updated": {
await NotificationService.sendToRoles({
channel: "admin-rows",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: `${params.data.entity.slug}/${params.data.id}`, mode: "host-aware" }) },
},
});
break;
}
case "row.deleted": {
await NotificationService.sendToRoles({
channel: "admin-rows",
tenantId: null,
notification: {
message: params.description,
action: { url: appPath({ tenantSlug: tenantId ?? "", path: params.data.entity.slug, mode: "host-aware" }) },
},
});
break;
}
case "row.shared": {
break;
}
case "row.tasks.created": {
break;
}
case "row.tasks.updated": {
break;
}
case "row.tasks.deleted": {
break;
}
case "row.comments.created": {
break;
}
case "row.comments.deleted": {
break;
}
case "row.comments.reacted": {
break;
}
case "onboarding.started": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: adminPath("onboarding/sessions", { mode: "host-aware" }) },
},
});
break;
}
case "onboarding.dismissed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: adminPath("onboarding/sessions", { mode: "host-aware" }) },
},
});
break;
}
case "onboarding.completed": {
await NotificationService.sendToRoles({
channel: "admin-onboarding",
tenantId,
notification: {
message: params.description,
action: { url: adminPath("onboarding/sessions", { mode: "host-aware" }) },
},
});
break;
}
default:
return assertNever(event);
}
} catch (e: any) {
// ignore
}
}
export default {
create,
createInTransaction,
dispatchPostCommitSideEffects,
};
@@ -0,0 +1,130 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const store = globalThis as typeof globalThis & {
__eventsServiceWorkflowOutboxMocks__?: {
transaction: ReturnType<typeof vi.fn>;
eventCreate: ReturnType<typeof vi.fn>;
publishOutboxEvent: ReturnType<typeof vi.fn>;
loggerError: ReturnType<typeof vi.fn>;
loggerInfo: ReturnType<typeof vi.fn>;
loggerWarn: ReturnType<typeof vi.fn>;
};
};
store.__eventsServiceWorkflowOutboxMocks__ ??= {
transaction: vi.fn(),
eventCreate: vi.fn(),
publishOutboxEvent: vi.fn(),
loggerError: vi.fn(),
loggerInfo: vi.fn(),
loggerWarn: vi.fn(),
};
const mocks = store.__eventsServiceWorkflowOutboxMocks__;
vi.mock("~/utils/db.server", () => ({
db: {
$transaction: mocks.transaction,
},
}));
vi.mock("@toolctrl/db/outbox", () => ({
publishOutboxEvent: mocks.publishOutboxEvent,
}));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: {
sendToRoles: vi.fn(async () => undefined),
},
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({
error: mocks.loggerError,
info: mocks.loggerInfo,
warn: mocks.loggerWarn,
debug: vi.fn(),
}),
}));
describe("EventsService workflow outbox publishing", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.eventCreate.mockResolvedValue({ id: "event_1" });
mocks.publishOutboxEvent.mockResolvedValue({ id: "outbox_1" });
mocks.transaction.mockImplementation(async (callback: (tx: unknown) => Promise<unknown>) =>
callback({
event: { create: mocks.eventCreate },
outboxEvent: {
create: vi.fn(),
findUnique: vi.fn(),
},
})
);
});
it("commits application events and workflow trigger outbox messages atomically", async () => {
const { default: EventsService } = await import("./EventsService");
await EventsService.create({
event: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: {
id: "row_1",
title: "Ada",
row: { id: "row_1" },
entity: { name: "employee", slug: "employees" },
},
});
expect(mocks.transaction).toHaveBeenCalledTimes(1);
expect(mocks.eventCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
name: "row.created",
tenantId: "tenant_1",
userId: "user_1",
data: JSON.stringify({
id: "row_1",
title: "Ada",
row: { id: "row_1" },
entity: { name: "employee", slug: "employees" },
}),
}),
});
expect(mocks.publishOutboxEvent).toHaveBeenCalledWith(expect.objectContaining({ event: { create: mocks.eventCreate } }), {
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: {
event: "row.created",
userId: "user_1",
data: {
id: "row_1",
title: "Ada",
row: { id: "row_1" },
entity: { name: "employee", slug: "employees" },
},
},
dispatchKey: "workflow-trigger:event_1",
});
});
it("uses a generic workflow outbox type so underscore event names remain valid", async () => {
const { default: EventsService } = await import("./EventsService");
await EventsService.create({
event: "api_key.created",
tenantId: "tenant_1",
userId: "user_1",
data: { id: "api_key_1" },
});
expect(mocks.publishOutboxEvent).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
type: "workflow.trigger.event",
payload: expect.objectContaining({ event: "api_key.created" }),
})
);
});
});
@@ -0,0 +1,49 @@
export const ApplicationEvents = [
{ adminOnly: false, value: "row.created" },
{ adminOnly: false, value: "row.updated" },
{ adminOnly: false, value: "row.deleted" },
{ adminOnly: true, value: "user.profile.updated" },
{ adminOnly: true, value: "user.profile.deleted" },
{ adminOnly: true, value: "user.password.updated" },
{ adminOnly: true, value: "user.mfa.totp.enrollment.started" },
{ adminOnly: true, value: "user.mfa.totp.enabled" },
{ adminOnly: true, value: "user.mfa.totp.disabled" },
{ adminOnly: true, value: "user.preferences.updated" },
{ adminOnly: false, value: "account.created" },
{ adminOnly: false, value: "account.updated" },
{ adminOnly: true, value: "account.deleted" },
{ adminOnly: false, value: "member.invitation.created" },
{ adminOnly: false, value: "member.invitation.accepted" },
{ adminOnly: false, value: "member.deleted" },
{ adminOnly: false, value: "role.assigned" },
{ adminOnly: false, value: "role.unassigned" },
{ adminOnly: false, value: "subscription.subscribed" },
{ adminOnly: false, value: "subscription.upgraded" },
{ adminOnly: false, value: "subscription.downgraded" },
{ adminOnly: false, value: "subscription.cancelled" },
{ adminOnly: false, value: "subscription.ended" },
{ adminOnly: false, value: "api_key.created" },
{ adminOnly: false, value: "api_key.updated" },
{ adminOnly: false, value: "api_key.deleted" },
{ adminOnly: false, value: "email.received" },
{ adminOnly: false, value: "row.shared" },
{ adminOnly: false, value: "row.tasks.created" },
{ adminOnly: false, value: "row.tasks.updated" },
{ adminOnly: false, value: "row.tasks.deleted" },
{ adminOnly: false, value: "row.comments.created" },
{ adminOnly: false, value: "row.comments.deleted" },
{ adminOnly: false, value: "row.comments.reacted" },
{ adminOnly: true, value: "onboarding.started" },
{ adminOnly: true, value: "onboarding.dismissed" },
{ adminOnly: true, value: "onboarding.completed" },
] as const;
export type ApplicationEvent = (typeof ApplicationEvents)[number]["value"];
export function getApplicationEventNameKey(eventName: string) {
return `events.names.${eventName.replace(/\./gu, "_")}`;
}
export function isApplicationEvent(eventName: string): eventName is ApplicationEvent {
return ApplicationEvents.some((event) => event.value === eventName);
}
@@ -0,0 +1,398 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import EventUtils from "./EventUtils";
import type { TFunction } from "i18next";
function createTranslationSpy() {
const calls: Array<{ key: string; values: Record<string, unknown> }> = [];
const t = ((key: string, values: Record<string, unknown>) => {
calls.push({ key, values });
return `translated:${key}`;
}) as TFunction;
return { calls, t };
}
function stripDefaultValues(calls: Array<{ key: string; values: Record<string, unknown> }>) {
return calls.map(({ key, values }) => {
const { defaultValue: _defaultValue, ...rest } = values;
return { key, values: rest };
});
}
describe("EventUtils user preference descriptions", () => {
it("describes locale preference updates", () => {
expect(
EventUtils.getDescription("user.preferences.updated", {
old: { locale: "en" },
new: { locale: "de" },
user: { id: "user-1", email: "user@example.com" },
})
).toBe("user@example.com updated their language: en -> de");
});
it("translates locale preference updates when a translator is provided", () => {
const { calls, t } = createTranslationSpy();
expect(
EventUtils.getDescription(
"user.preferences.updated",
{
old: { locale: "en" },
new: { locale: "de" },
user: { id: "user-1", email: "user@example.com" },
},
t
)
).toBe("translated:events.descriptions.userPreferences.localeUpdated");
expect(stripDefaultValues(calls)).toEqual([
{
key: "shared.locales.en",
values: {},
},
{
key: "shared.locales.de",
values: {},
},
{
key: "events.descriptions.userPreferences.localeUpdated",
values: {
email: "user@example.com",
newLocale: "translated:shared.locales.de",
oldLocale: "translated:shared.locales.en",
},
},
]);
});
it("describes light/dark mode preference updates", () => {
expect(
EventUtils.getDescription("user.preferences.updated", {
old: { lightOrDarkMode: "light" },
new: { lightOrDarkMode: "dark" },
user: { id: "user-1", email: "user@example.com" },
})
).toBe("user@example.com updated their theme mode: light -> dark");
});
it("translates theme preference updates with light as the default mode", () => {
const { calls, t } = createTranslationSpy();
expect(
EventUtils.getDescription(
"user.preferences.updated",
{
old: {},
new: { lightOrDarkMode: "dark" },
user: { id: "user-1", email: "user@example.com" },
},
t
)
).toBe("translated:events.descriptions.userPreferences.themeUpdated");
expect(stripDefaultValues(calls)).toEqual([
{
key: "shared.light",
values: {},
},
{
key: "shared.dark",
values: {},
},
{
key: "events.descriptions.userPreferences.themeUpdated",
values: {
email: "user@example.com",
newTheme: "translated:shared.dark",
oldTheme: "translated:shared.light",
},
},
]);
});
it("translates generic preference updates", () => {
const { calls, t } = createTranslationSpy();
expect(
EventUtils.getDescription(
"user.preferences.updated",
{
old: {},
new: {},
user: { id: "user-1", email: "user@example.com" },
},
t
)
).toBe("translated:events.descriptions.userPreferences.updated");
expect(stripDefaultValues(calls)).toEqual([
{
key: "events.descriptions.userPreferences.updated",
values: {
email: "user@example.com",
},
},
]);
});
});
describe("EventUtils translated event descriptions", () => {
it("passes readable default values to translated event descriptions", () => {
const { calls, t } = createTranslationSpy();
EventUtils.getDescription(
"account.created",
{
tenant: { id: "tenant-1", name: "Acme" },
},
t
);
expect(calls).toEqual([
{
key: "events.descriptions.account.created",
values: {
defaultValue: "Account created: Acme",
tenant: "Acme",
},
},
]);
});
it("translates unmapped event names with the raw name as fallback", () => {
const { calls, t } = createTranslationSpy();
expect(EventUtils.parseName("provider.webhook.delivered", t)).toBe("translated:events.names.unmapped");
expect(EventUtils.parseName("provider.webhook.delivered")).toBe("provider.webhook.delivered");
expect(calls).toEqual([
{
key: "events.names.unmapped",
values: {
defaultValue: "provider.webhook.delivered",
name: "provider.webhook.delivered",
},
},
]);
});
it("recomputes persisted descriptions with the active translator", () => {
const { calls, t } = createTranslationSpy();
expect(
EventUtils.parseDescription(
{
id: "event-1",
tenantId: "tenant-1",
userId: "user-1",
name: "account.created",
data: JSON.stringify({ tenant: { id: "tenant-1", name: "Acme" } }),
description: "Account created: Acme",
createdAt: new Date("2026-05-08T10:00:00.000Z"),
},
t
)
).toBe("translated:events.descriptions.account.created");
expect(stripDefaultValues(calls)).toEqual([
{
key: "events.descriptions.account.created",
values: {
tenant: "Acme",
},
},
]);
});
it("falls back to persisted descriptions when event payloads cannot be parsed", () => {
const { t } = createTranslationSpy();
expect(
EventUtils.parseDescription(
{
id: "event-1",
tenantId: "tenant-1",
userId: "user-1",
name: "account.created",
data: "{",
description: "Persisted fallback",
createdAt: new Date("2026-05-08T10:00:00.000Z"),
},
t
)
).toBe("Persisted fallback");
});
it("uses the unknown event translation key when an unmapped payload has no persisted description", () => {
const { calls, t } = createTranslationSpy();
expect(
EventUtils.parseDescription(
{
id: "event-1",
tenantId: "tenant-1",
userId: "user-1",
name: "provider.webhook.delivered",
data: "{",
description: null,
createdAt: new Date("2026-05-08T10:00:00.000Z"),
},
t
)
).toBe("translated:events.descriptions.unknownWithName");
expect(calls).toEqual([
{
key: "events.descriptions.unknownWithName",
values: {
defaultValue: "Unknown event: provider.webhook.delivered",
name: "provider.webhook.delivered",
},
},
]);
expect(
EventUtils.parseDescription({
id: "event-1",
tenantId: "tenant-1",
userId: "user-1",
name: "provider.webhook.delivered",
data: "{",
description: null,
createdAt: new Date("2026-05-08T10:00:00.000Z"),
})
).toBe("Unknown event: provider.webhook.delivered");
});
it("translates account descriptions", () => {
const { calls, t } = createTranslationSpy();
expect(
EventUtils.getDescription(
"account.created",
{
tenant: { id: "tenant-1", name: "Acme" },
},
t
)
).toBe("translated:events.descriptions.account.created");
expect(stripDefaultValues(calls)).toEqual([
{
key: "events.descriptions.account.created",
values: {
tenant: "Acme",
},
},
]);
});
it("translates new-user invitation prefixes before composing accepted invitation descriptions", () => {
const calls: Array<{ key: string; values: Record<string, unknown> }> = [];
const t = ((key: string, values: Record<string, unknown>) => {
calls.push({ key, values });
if (key === "events.descriptions.memberInvitation.newUserPrefix") return "translated-prefix ";
return `translated:${key}`;
}) as TFunction;
expect(
EventUtils.getDescription(
"member.invitation.accepted",
{
newUser: true,
user: { id: "user-1", email: "ada@example.com" },
tenant: { id: "tenant-1", name: "Acme" },
},
t
)
).toBe("translated:events.descriptions.memberInvitation.accepted");
expect(stripDefaultValues(calls)).toEqual([
{
key: "events.descriptions.memberInvitation.newUserPrefix",
values: {},
},
{
key: "events.descriptions.memberInvitation.accepted",
values: {
email: "ada@example.com",
prefix: "translated-prefix ",
tenant: "Acme",
},
},
]);
});
it("translates row descriptions with actor values", () => {
const { calls, t } = createTranslationSpy();
expect(
EventUtils.getDescription(
"row.created",
{
entity: { id: "entity-1", name: "Contact" },
title: "Ada Lovelace",
user: { id: "user-1", email: "ada@example.com" },
},
t
)
).toBe("translated:events.descriptions.row.created");
expect(stripDefaultValues(calls)).toEqual([
{
key: "events.descriptions.row.created",
values: {
actor: "ada@example.com",
entity: "Contact",
title: "Ada Lovelace",
},
},
]);
});
it("translates row task actors and status fragments", () => {
const calls: Array<{ key: string; values: Record<string, unknown> }> = [];
const t = ((key: string, values: Record<string, unknown>) => {
calls.push({ key, values });
if (key === "events.actors.apiKey") return `api-key:${values.alias}`;
if (key === "events.descriptions.rowTasks.changes.completedAt") return `completed:${values.date}`;
return `translated:${key}`;
}) as TFunction;
expect(
EventUtils.getDescription(
"row.tasks.updated",
{
rowId: "row-1",
new: { name: "Follow up", completedAt: "2026-05-27T01:00:00.000Z" },
apiKey: { id: "key-1", alias: "Zapier" },
},
t,
{ dateTime: () => "May 27, 2026, 3:00 AM" }
)
).toBe("translated:events.descriptions.rowTasks.updated");
expect(stripDefaultValues(calls)).toEqual([
{
key: "events.descriptions.rowTasks.changes.completedAt",
values: {
date: "May 27, 2026, 3:00 AM",
},
},
{
key: "events.actors.apiKey",
values: {
alias: "Zapier",
},
},
{
key: "events.descriptions.rowTasks.updated",
values: {
actor: "api-key:Zapier",
change: "completed:May 27, 2026, 3:00 AM",
rowId: "row-1",
task: "Follow up",
},
},
]);
});
});
@@ -0,0 +1,455 @@
import { AccountCreatedDto } from "../dtos/AccountCreatedDto";
import { AccountDeletedDto } from "../dtos/AccountDeletedDto";
import { AccountUpdatedDto } from "../dtos/AccountUpdatedDto";
import { ApiKeyCreatedDto } from "../dtos/ApiKeyCreatedDto";
import { ApiKeyDeletedDto } from "../dtos/ApiKeyDeletedDto";
import { ApiKeyUpdatedDto } from "../dtos/ApiKeyUpdatedDto";
import { EmailReceivedDto } from "../dtos/EmailReceivedDto";
import { MemberDeletedDto } from "../dtos/MemberDeletedDto";
import { MemberInvitationAcceptedDto } from "../dtos/MemberInvitationAcceptedDto";
import { MemberInvitationCreatedDto } from "../dtos/MemberInvitationCreatedDto";
import { RoleAssignedDto } from "../dtos/RoleAssignedDto";
import { RoleUnassignedDto } from "../dtos/RoleUnassignedDto";
import { RowCreatedDto } from "../dtos/RowCreatedDto";
import { RowDeletedDto } from "../dtos/RowDeletedDto";
import { RowSharedDto } from "../dtos/RowSharedDto";
import { RowUpdatedDto } from "../dtos/RowUpdatedDto";
import { SubscriptionCancelledDto } from "../dtos/SubscriptionCancelledDto";
import { SubscriptionEndedDto } from "../dtos/SubscriptionEndedDto";
import { SubscriptionSubscribedDto } from "../dtos/SubscriptionSubscribedDto";
import { SubscriptionUpgradedDto } from "../dtos/SubscriptionUpgradedDto";
import { UserPasswordUpdatedDto } from "../dtos/UserPasswordUpdatedDto";
import { UserPreferencesUpdatedDto } from "../dtos/UserPreferencesUpdatedDto";
import { UserProfileDeletedDto } from "../dtos/UserProfileDeletedDto";
import { UserProfileUpdatedDto } from "../dtos/UserProfileUpdatedDto";
import { ApplicationEvent, getApplicationEventNameKey, isApplicationEvent } from "../types/ApplicationEvent";
import { Event } from "@toolctrl/db/prisma-browser";
import { RowTasksCreatedDto } from "../dtos/RowTasksCreatedDto";
import { RowTasksUpdatedDto } from "../dtos/RowTasksUpdatedDto";
import { RowTasksDeletedDto } from "../dtos/RowTasksDeletedDto";
import { RowCommentsCreatedDto } from "../dtos/RowCommentsCreatedDto";
import { RowCommentsDeletedDto } from "../dtos/RowCommentsDeletedDto";
import { RowCommentsReactedDto } from "../dtos/RowCommentsReactedDto";
import { OnboardingStartedDto } from "../dtos/OnboardingStartedDto";
import { OnboardingDismissedDto } from "../dtos/OnboardingDismissedDto";
import { OnboardingCompletedDto } from "../dtos/OnboardingCompletedDto";
import { SubscriptionDowngradedDto } from "../dtos/SubscriptionDowngradedDto";
import type { TFunction } from "i18next";
type EventDescriptionFormatters = {
dateTime?: (value: Date | number | string, options?: Intl.DateTimeFormatOptions) => string;
};
function parseDescription(event: Event, t?: TFunction, formatters?: EventDescriptionFormatters) {
if (event.description && !t) {
return event.description;
}
try {
const data = JSON.parse(event.data);
return getDescription(event.name as ApplicationEvent, data, t, formatters);
} catch {
if (event.description) {
return event.description;
}
return translateEventDescription(t, "events.descriptions.unknownWithName", `Unknown event: ${event.name}`, { name: event.name });
}
}
function parseName(eventName: string, t?: TFunction) {
if (!isApplicationEvent(eventName)) {
return translateEventDescription(t, "events.names.unmapped", eventName, { name: eventName });
}
return t ? t(getApplicationEventNameKey(eventName)) : eventName;
}
function translateEventDescription(
t: TFunction | undefined,
key: string,
defaultValue: string,
values: Record<string, string | number | boolean | null | undefined> = {}
) {
return t ? t(key, { defaultValue, ...values }) : defaultValue;
}
function translateEventValue(t: TFunction | undefined, key: string, defaultValue: string) {
return t ? t(key, { defaultValue }) : defaultValue;
}
function getDescription(event: ApplicationEvent, data: any, t?: TFunction, formatters?: EventDescriptionFormatters) {
if (!isApplicationEvent(event)) {
return translateEventDescription(t, "events.descriptions.unknown", "Unknown event");
}
try {
switch (event) {
case "user.profile.updated": {
const payload = data as UserProfileUpdatedDto;
return translateEventDescription(t, "events.descriptions.userProfile.updated", `${payload.email} updated their profile`, { email: payload.email });
}
case "user.profile.deleted": {
const payload = data as UserProfileDeletedDto;
return translateEventDescription(t, "events.descriptions.userProfile.deleted", `${payload.email} deleted their profile`, { email: payload.email });
}
case "user.password.updated": {
const payload = data as UserPasswordUpdatedDto;
if (payload.fromUser) {
return translateEventDescription(
t,
"events.descriptions.userPassword.updatedByUser",
`${payload.fromUser.email} updated ${payload.user.email}'s password`,
{ fromEmail: payload.fromUser.email, email: payload.user.email }
);
}
return translateEventDescription(t, "events.descriptions.userPassword.updated", `${payload.user.email} updated their password`, { email: payload.user.email });
}
case "user.mfa.totp.enrollment.started": {
return translateEventDescription(t, "events.descriptions.userMfa.enrollmentStarted", `${data.user.email} started authenticator enrollment`, { email: data.user.email });
}
case "user.mfa.totp.enabled": {
return translateEventDescription(t, "events.descriptions.userMfa.enabled", `${data.user.email} enabled authenticator MFA`, { email: data.user.email });
}
case "user.mfa.totp.disabled": {
return translateEventDescription(t, "events.descriptions.userMfa.disabled", `${data.user.email} disabled authenticator MFA`, { email: data.user.email });
}
case "user.preferences.updated": {
const payload = data as UserPreferencesUpdatedDto;
if (payload.old.locale !== undefined || payload.new.locale !== undefined) {
const oldLocale = payload.old.locale ?? "";
const newLocale = payload.new.locale ?? "";
const oldLocaleLabel = oldLocale ? translateEventValue(t, `shared.locales.${oldLocale}`, oldLocale) : "";
const newLocaleLabel = newLocale ? translateEventValue(t, `shared.locales.${newLocale}`, newLocale) : "";
return translateEventDescription(
t,
"events.descriptions.userPreferences.localeUpdated",
`${payload.user.email} updated their language: ${oldLocale} -> ${newLocale}`,
{
email: payload.user.email,
oldLocale: oldLocaleLabel,
newLocale: newLocaleLabel,
}
);
}
if (payload.old.lightOrDarkMode !== undefined || payload.new.lightOrDarkMode !== undefined) {
const oldTheme = payload.old.lightOrDarkMode ?? "light";
const newTheme = payload.new.lightOrDarkMode ?? "light";
const oldThemeLabel = translateEventValue(t, `shared.${oldTheme}`, oldTheme);
const newThemeLabel = translateEventValue(t, `shared.${newTheme}`, newTheme);
return translateEventDescription(
t,
"events.descriptions.userPreferences.themeUpdated",
`${payload.user.email} updated their theme mode: ${oldTheme} -> ${newTheme}`,
{
email: payload.user.email,
oldTheme: oldThemeLabel,
newTheme: newThemeLabel,
}
);
}
return translateEventDescription(t, "events.descriptions.userPreferences.updated", `${payload.user.email} updated their preferences`, {
email: payload.user.email,
});
}
case "account.created": {
const payload = data as AccountCreatedDto;
return translateEventDescription(t, "events.descriptions.account.created", `Account created: ${payload.tenant.name}`, { tenant: payload.tenant.name });
}
case "account.updated": {
const payload = data as AccountUpdatedDto;
return translateEventDescription(
t,
"events.descriptions.account.updated",
`${payload.user.email} updated account: ${payload.old.name} (/${payload.old.slug}) -> ${payload.new.name} (/${payload.new.slug})`,
{ email: payload.user.email, oldName: payload.old.name, oldSlug: payload.old.slug, newName: payload.new.name, newSlug: payload.new.slug }
);
}
case "account.deleted": {
const payload = data as AccountDeletedDto;
let subscription = "";
if (payload.subscription) {
subscription = `, ${payload.subscription.product.title} - $${payload.subscription.price.amount}`;
}
return translateEventDescription(t, "events.descriptions.account.deleted", `${payload.user.email} deleted the account '${payload.tenant.name}'${subscription}.`, {
email: payload.user.email,
tenant: payload.tenant.name,
subscription,
});
}
case "member.invitation.created": {
const payload = data as MemberInvitationCreatedDto;
return translateEventDescription(t, "events.descriptions.memberInvitation.created", `${payload.fromUser.email} invited ${payload.user.email} to ${payload.tenant.name}`, {
fromEmail: payload.fromUser.email,
email: payload.user.email,
tenant: payload.tenant.name,
});
}
case "member.invitation.accepted": {
const payload = data as MemberInvitationAcceptedDto;
const defaultPrefix = payload.newUser ? "(New user) " : "";
const prefix = payload.newUser ? translateEventDescription(t, "events.descriptions.memberInvitation.newUserPrefix", defaultPrefix) : "";
if (payload.fromUser) {
return translateEventDescription(
t,
"events.descriptions.memberInvitation.acceptedFromUser",
`${defaultPrefix}${payload.user.email} accepted the invitation to ${payload.tenant.name} from user ${payload.fromUser.email}`,
{ prefix, email: payload.user.email, tenant: payload.tenant.name, fromEmail: payload.fromUser.email }
);
}
return translateEventDescription(t, "events.descriptions.memberInvitation.accepted", `${defaultPrefix}${payload.user.email} accepted the invitation to ${payload.tenant.name}`, {
prefix,
email: payload.user.email,
tenant: payload.tenant.name,
});
}
case "member.deleted": {
const payload = data as MemberDeletedDto;
return translateEventDescription(t, "events.descriptions.member.deleted", `${payload.fromUser.email} deleted ${payload.user.email} from ${payload.tenant.name}`, {
fromEmail: payload.fromUser.email,
email: payload.user.email,
tenant: payload.tenant.name,
});
}
case "role.assigned": {
const payload = data as RoleAssignedDto;
return translateEventDescription(t, "events.descriptions.role.assigned", `${payload.fromUser.email} assigned the role "${payload.role.name}" to ${payload.toUser.email}`, {
fromEmail: payload.fromUser.email,
role: payload.role.name,
email: payload.toUser.email,
});
}
case "role.unassigned": {
const payload = data as RoleUnassignedDto;
return translateEventDescription(t, "events.descriptions.role.unassigned", `${payload.fromUser.email} unassigned the role "${payload.role.name}" from ${payload.toUser.email}`, {
fromEmail: payload.fromUser.email,
role: payload.role.name,
email: payload.toUser.email,
});
}
case "subscription.subscribed": {
const payload = data as SubscriptionSubscribedDto;
if (payload.user) {
return translateEventDescription(t, "events.descriptions.subscription.subscribedByUser", `${payload.user.email} subscribed ${payload.tenant.name} to ${payload.subscription.product.title}`, {
email: payload.user.email,
tenant: payload.tenant.name,
product: payload.subscription.product.title,
});
}
return translateEventDescription(t, "events.descriptions.subscription.subscribed", `${payload.tenant.name} subscribed to ${payload.subscription.product.title}`, {
tenant: payload.tenant.name,
product: payload.subscription.product.title,
});
}
case "subscription.upgraded": {
const payload = data as SubscriptionUpgradedDto;
const product = payload.subscription?.product.title ?? "";
if (payload.user) {
return translateEventDescription(t, "events.descriptions.subscription.upgradedByUser", `Subscription upgraded: ${payload.tenant.name} (${product}), by ${payload.user.email}`, {
tenant: payload.tenant.name,
product,
email: payload.user.email,
});
}
return translateEventDescription(t, "events.descriptions.subscription.upgraded", `Subscription upgraded: ${payload.tenant.name} (${product})`, { tenant: payload.tenant.name, product });
}
case "subscription.downgraded": {
const payload = data as SubscriptionDowngradedDto;
const product = payload.subscription?.product.title ?? "";
if (payload.user) {
return translateEventDescription(t, "events.descriptions.subscription.downgradedByUser", `Subscription downgraded: ${payload.tenant.name} (${product}), by ${payload.user.email}`, {
tenant: payload.tenant.name,
product,
email: payload.user.email,
});
}
return translateEventDescription(t, "events.descriptions.subscription.downgraded", `Subscription downgraded: ${payload.tenant.name} (${product})`, { tenant: payload.tenant.name, product });
}
case "subscription.cancelled": {
const payload = data as SubscriptionCancelledDto;
const product = payload.subscription?.product.title ?? "";
if (payload.user) {
return translateEventDescription(t, "events.descriptions.subscription.cancelledByUser", `Subscription cancelled: ${payload.tenant.name} (${product}), by ${payload.user.email}`, {
tenant: payload.tenant.name,
product,
email: payload.user.email,
});
}
return translateEventDescription(t, "events.descriptions.subscription.cancelled", `Subscription cancelled: ${payload.tenant.name} (${product})`, { tenant: payload.tenant.name, product });
}
case "subscription.ended": {
const payload = data as SubscriptionEndedDto;
const product = payload.subscription?.product.title ?? "";
return translateEventDescription(t, "events.descriptions.subscription.ended", `Subscription ended: ${payload.tenant.name} (${product})`, { tenant: payload.tenant.name, product });
}
case "api_key.created": {
const payload = data as ApiKeyCreatedDto;
return translateEventDescription(t, "events.descriptions.apiKey.created", `${payload.user.email} created API key: ${payload.alias}`, { email: payload.user.email, alias: payload.alias });
}
case "api_key.updated": {
const payload = data as ApiKeyUpdatedDto;
return translateEventDescription(t, "events.descriptions.apiKey.updated", `${payload.user.email} updated API key: ${payload.old.alias} -> ${payload.new.alias}`, {
email: payload.user.email,
oldAlias: payload.old.alias,
newAlias: payload.new.alias,
});
}
case "api_key.deleted": {
const payload = data as ApiKeyDeletedDto;
return translateEventDescription(t, "events.descriptions.apiKey.deleted", `${payload.user.email} deleted API key: ${payload.alias}`, { email: payload.user.email, alias: payload.alias });
}
case "email.received": {
const payload = data as EmailReceivedDto;
return translateEventDescription(t, "events.descriptions.email.received", `New email from ${payload.fromEmail}: ${payload.subject}`, {
fromEmail: payload.fromEmail,
subject: payload.subject,
});
}
case "row.created": {
const payload = data as RowCreatedDto;
const actor = getUserOrApiKey(payload, t);
return translateEventDescription(t, "events.descriptions.row.created", `New ${payload.entity.name}: ${payload.title}, by ${actor}`, {
entity: payload.entity.name,
title: payload.title,
actor,
});
}
case "row.updated": {
const payload = data as RowUpdatedDto;
const actor = getUserOrApiKey(payload, t);
return translateEventDescription(t, "events.descriptions.row.updated", `Updated ${payload.entity.name}: ${payload.title}, by ${actor}`, {
entity: payload.entity.name,
title: payload.title,
actor,
});
}
case "row.deleted": {
const payload = data as RowDeletedDto;
const actor = getUserOrApiKey(payload, t);
return translateEventDescription(t, "events.descriptions.row.deleted", `Deleted ${payload.entity.name}: ${payload.title}, by ${actor}`, {
entity: payload.entity.name,
title: payload.title,
actor,
});
}
case "row.shared": {
const payload = data as RowSharedDto;
const actor = getUserOrApiKey(payload, t);
return translateEventDescription(
t,
"events.descriptions.row.shared",
`${payload.entity.name}: ${payload.title} shared with ${payload.type} "${payload.to}" (${payload.access}) by ${actor}`,
{ entity: payload.entity.name, title: payload.title, type: payload.type, to: payload.to, access: payload.access, actor }
);
}
case "row.tasks.created": {
const payload = data as RowTasksCreatedDto;
const actor = getUserOrApiKey(payload, t);
return translateEventDescription(t, "events.descriptions.rowTasks.created", `Row ${payload.rowId} task created '${payload.task.name}' by ${actor}`, {
rowId: payload.rowId,
task: payload.task.name,
actor,
});
}
case "row.tasks.updated": {
const payload = data as RowTasksUpdatedDto;
let change = "";
if (payload.new.completedAt) {
const completedAt = formatters?.dateTime ? formatters.dateTime(payload.new.completedAt) : String(payload.new.completedAt);
change = translateEventDescription(
t,
"events.descriptions.rowTasks.changes.completedAt",
`completed at ${completedAt}`,
{ date: completedAt }
);
} else {
change = translateEventDescription(t, "events.descriptions.rowTasks.changes.incomplete", "set as incomplete");
}
const actor = getUserOrApiKey(payload, t);
return translateEventDescription(t, "events.descriptions.rowTasks.updated", `Row ${payload.rowId} task updated '${payload.new.name}', ${change}, by ${actor}`, {
rowId: payload.rowId,
task: payload.new.name,
change,
actor,
});
}
case "row.tasks.deleted": {
const payload = data as RowTasksDeletedDto;
const actor = getUserOrApiKey(payload, t);
return translateEventDescription(t, "events.descriptions.rowTasks.deleted", `Row ${payload.rowId} task deleted '${payload.task.name}' by ${actor}`, {
rowId: payload.rowId,
task: payload.task.name,
actor,
});
}
case "row.comments.created": {
const payload = data as RowCommentsCreatedDto;
const actor = payload.user ? payload.user.email : "";
return translateEventDescription(t, "events.descriptions.rowComments.created", `Row ${payload.rowId} commented '${payload.comment.text}' by ${actor}`, {
rowId: payload.rowId,
comment: payload.comment.text,
actor,
});
}
case "row.comments.deleted": {
const payload = data as RowCommentsDeletedDto;
const actor = payload.user ? payload.user.email : "";
return translateEventDescription(t, "events.descriptions.rowComments.deleted", `Row ${payload.rowId} comment deleted '${payload.comment.text}' by ${actor}`, {
rowId: payload.rowId,
comment: payload.comment.text,
actor,
});
}
case "row.comments.reacted": {
const payload = data as RowCommentsReactedDto;
const actor = payload.user ? payload.user.email : "";
return translateEventDescription(t, "events.descriptions.rowComments.reacted", `Row ${payload.rowId} comment reaction (${payload.reaction}) '${payload.comment.text}' by ${actor}`, {
rowId: payload.rowId,
reaction: payload.reaction,
comment: payload.comment.text,
actor,
});
}
case "onboarding.started": {
const payload = data as OnboardingStartedDto;
return translateEventDescription(t, "events.descriptions.onboarding.started", `Onboarding started by ${payload.user.email}: ${payload.onboarding.title}`, {
email: payload.user.email,
title: payload.onboarding.title,
});
}
case "onboarding.dismissed": {
const payload = data as OnboardingDismissedDto;
return translateEventDescription(t, "events.descriptions.onboarding.dismissed", `Onboarding dismissed by ${payload.user.email}: ${payload.onboarding.title}`, {
email: payload.user.email,
title: payload.onboarding.title,
});
}
case "onboarding.completed": {
const payload = data as OnboardingCompletedDto;
return translateEventDescription(t, "events.descriptions.onboarding.completed", `Onboarding completed by ${payload.user.email}: ${payload.onboarding.title}`, {
email: payload.user.email,
title: payload.onboarding.title,
});
}
default:
return assertNever(event);
}
} catch {
return parseName(event, t);
}
}
function assertNever(x: never): never {
throw new Error("Unexpected event: " + x);
}
function getUserOrApiKey(item: { user?: { id: string; email: string } | null; apiKey?: { id: string; alias: string } | null }, t?: TFunction) {
if (item.user) {
return item.user.email;
} else if (item.apiKey) {
return translateEventDescription(t, "events.actors.apiKey", "API Key {{alias}}", { alias: item.apiKey.alias });
}
return "";
}
export default {
parseName,
parseDescription,
getDescription,
};