Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
+45
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { sanitizeNotificationPayloadForDisplay } from "./NotificationMessagesTable";
|
||||
|
||||
describe("NotificationMessagesTable", () => {
|
||||
it("redacts sensitive notification payload fields before display", () => {
|
||||
const payload = JSON.stringify({
|
||||
token: "secret-token",
|
||||
authorization: "Bearer abc123",
|
||||
nested: { email: "user@example.com", message: "ok" },
|
||||
});
|
||||
|
||||
const redacted = sanitizeNotificationPayloadForDisplay(payload);
|
||||
|
||||
expect(redacted).not.toContain("secret-token");
|
||||
expect(redacted).not.toContain("Bearer abc123");
|
||||
expect(redacted).toContain("[REDACTED]");
|
||||
expect(redacted).toContain("user@example.com");
|
||||
});
|
||||
|
||||
it("stringifies object payloads before redaction", () => {
|
||||
const redacted = sanitizeNotificationPayloadForDisplay({
|
||||
token: "secret-token",
|
||||
nested: { authorization: "Bearer abc123", message: "ok" },
|
||||
});
|
||||
|
||||
expect(redacted).not.toContain("secret-token");
|
||||
expect(redacted).not.toContain("Bearer abc123");
|
||||
expect(redacted).toContain("[REDACTED]");
|
||||
expect(redacted).toContain("ok");
|
||||
});
|
||||
|
||||
it("keeps notification table dates on locale-aware formatters", () => {
|
||||
const componentsRoot = path.resolve(process.cwd(), "apps/web/app/modules/notifications/components");
|
||||
const source = ["NotificationMessagesTable.tsx", "NotificationSubscribersTable.tsx"]
|
||||
.map((file) => fs.readFileSync(path.join(componentsRoot, file), "utf8"))
|
||||
.join("\n");
|
||||
|
||||
expect(source).toContain("useLocaleFormatters");
|
||||
expect(source).toContain("formatters.relativeDate");
|
||||
expect(source).not.toContain("DateUtils");
|
||||
});
|
||||
});
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { redactDiagnosticJsonString } from "~/utils/redaction";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import type { IGetMessagesData } from "../services/.server/NotificationService";
|
||||
|
||||
export function sanitizeNotificationPayloadForDisplay(payload: unknown) {
|
||||
const value = typeof payload === "string" ? payload : JSON.stringify(payload ?? null);
|
||||
return redactDiagnosticJsonString(value);
|
||||
}
|
||||
|
||||
export default function NotificationMessagesTable({ items, withPagination = true }: { items: IGetMessagesData | null; withPagination?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const channelLabel = (channel: string) =>
|
||||
t(`notifications.center.channels.${channel.toLowerCase().replace(/[-\s]/g, "_")}`, { defaultValue: t("notifications.center.channels.unknown") });
|
||||
const templateLabel = (templateIdentifier: string) =>
|
||||
t(`notifications.admin.messageTemplates.${templateIdentifier}`, { defaultValue: t("notifications.admin.messages.unknownTemplate") });
|
||||
|
||||
return (
|
||||
<TableSimple
|
||||
items={items?.data ?? []}
|
||||
pagination={
|
||||
!withPagination
|
||||
? undefined
|
||||
: {
|
||||
page: (items?.page ?? 0) + 1,
|
||||
pageSize: items?.pageSize ?? 0,
|
||||
totalItems: items?.totalCount ?? 0,
|
||||
totalPages: Math.ceil((items?.totalCount ?? 0) / (items?.pageSize ?? 0)),
|
||||
}
|
||||
}
|
||||
headers={[
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("notifications.admin.messages.createdAt"),
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{formatters.date(i.createdAt, { dateStyle: "medium" })}</div>
|
||||
<div className="text-xs">{formatters.relativeDate(i.createdAt)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ name: "templateIdentifier", title: t("notifications.admin.messages.template"), value: (i) => templateLabel(i.templateIdentifier) },
|
||||
{ name: "channel", title: t("notifications.admin.messages.channel"), value: (i) => channelLabel(i.channel) },
|
||||
{
|
||||
name: "seen",
|
||||
title: t("notifications.admin.messages.seen"),
|
||||
value: (i) => <div>{i.seen ? <CheckIcon className="text-theme-500 h-4 w-4" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "read",
|
||||
title: t("notifications.admin.messages.read"),
|
||||
value: (i) => <div>{i.read ? <CheckIcon className="text-theme-500 h-4 w-4" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>,
|
||||
},
|
||||
{
|
||||
name: "payload",
|
||||
title: t("notifications.admin.messages.payload"),
|
||||
value: (i) => (
|
||||
<pre className="max-w-sm truncate">
|
||||
<ShowPayloadModalButton payload={sanitizeNotificationPayloadForDisplay(i.payload)} />
|
||||
</pre>
|
||||
),
|
||||
},
|
||||
{ name: "provider", title: t("notifications.admin.messages.provider"), value: () => t("notifications.admin.provider.novu") },
|
||||
]}
|
||||
></TableSimple>
|
||||
);
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import { Link } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import UserBadge from "~/components/core/users/UserBadge";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import type { IGetSubscribersData } from "../services/.server/NotificationService";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export default function NotificationSubscribersTable({ items }: { items: IGetSubscribersData | null }) {
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
return (
|
||||
<TableSimple
|
||||
items={items?.data ?? []}
|
||||
pagination={{
|
||||
page: (items?.page ?? 0) + 1,
|
||||
pageSize: items?.pageSize ?? 0,
|
||||
totalItems: items?.totalCount ?? 0,
|
||||
totalPages: Math.ceil((items?.totalCount ?? 0) / (items?.pageSize ?? 0)),
|
||||
}}
|
||||
headers={[
|
||||
{
|
||||
name: "subscriber",
|
||||
title: i18nT("notifications.admin.subscribers.columns.subscriber"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
{!i.email ? (
|
||||
<div>-</div>
|
||||
) : (
|
||||
<Link to={adminPath("notifications/messages?subscriberId=" + i.subscriberId, { mode: "host-aware" })}>
|
||||
<UserBadge
|
||||
item={{
|
||||
id: i.subscriberId,
|
||||
email: i.email,
|
||||
firstName: i.firstName,
|
||||
lastName: i.lastName,
|
||||
}}
|
||||
/>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ name: "createdAt", title: i18nT("notifications.admin.subscribers.columns.createdAt"), value: (i) => formatters.relativeDate(i.createdAt) },
|
||||
{ name: "updatedAt", title: i18nT("notifications.admin.subscribers.columns.updatedAt"), value: (i) => formatters.relativeDate(i.updatedAt) },
|
||||
{
|
||||
name: "deleted",
|
||||
title: i18nT("notifications.admin.subscribers.columns.deleted"),
|
||||
value: (i) => <div>{i.deleted ? <CheckIcon className="text-theme-500 h-4 w-4" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>,
|
||||
},
|
||||
]}
|
||||
></TableSimple>
|
||||
);
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CheckIcon from "~/components/ui/icons/CheckIcon";
|
||||
import ExclamationTriangleIcon from "~/components/ui/icons/ExclamationTriangleIcon";
|
||||
import XIcon from "~/components/ui/icons/XIcon";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import { NotificationChannelDto, NotificationChannels } from "../services/NotificationChannels";
|
||||
import type { IGetTemplatesData } from "../services/.server/NotificationService";
|
||||
|
||||
export default function NotificationTemplatesTable({
|
||||
items,
|
||||
onDelete,
|
||||
onSendPreview,
|
||||
}: {
|
||||
items: IGetTemplatesData | null;
|
||||
onDelete: (id: string) => void;
|
||||
onSendPreview: (item: NotificationChannelDto) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const channelLabel = (item: NotificationChannelDto) =>
|
||||
t(`notifications.admin.channelLabels.${item.name}`, {
|
||||
defaultValue: item.name.replace(/[-_.]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase()),
|
||||
});
|
||||
const channelDescription = (item: NotificationChannelDto) =>
|
||||
t(item.descriptionKey, {
|
||||
defaultValue: item.name.replace(/[-_.]+/g, " "),
|
||||
});
|
||||
const roleLabel = (role: string) => t(`notifications.admin.roleLabels.${role}`, { defaultValue: role.replace(/([a-z0-9])([A-Z])/g, "$1 $2") });
|
||||
|
||||
function getCreated(i: NotificationChannelDto) {
|
||||
return items?.data?.find((f) => f.name === i.name);
|
||||
}
|
||||
function isValid(item: NotificationChannelDto, templates: IGetTemplatesData | null) {
|
||||
const existing = templates?.data?.find((f) => f.name === item.name);
|
||||
if (!existing || !existing.steps || existing.steps.length === 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
<TableSimple
|
||||
items={NotificationChannels}
|
||||
pagination={{
|
||||
page: (items?.page ?? 0) + 1,
|
||||
pageSize: items?.pageSize ?? 0,
|
||||
totalItems: items?.totalCount ?? 0,
|
||||
totalPages: Math.ceil((items?.totalCount ?? 0) / (items?.pageSize ?? 0)),
|
||||
}}
|
||||
headers={[
|
||||
{
|
||||
name: "name",
|
||||
title: t("notifications.admin.templates.name"),
|
||||
value: (i) => (
|
||||
<>
|
||||
{!isValid(i, items) ? (
|
||||
<div className="flex items-center space-x-1 text-red-600">
|
||||
<ExclamationTriangleIcon className="h-5 w-5 text-red-600" />
|
||||
<div>{channelLabel(i)}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>{channelLabel(i)}</div>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "description",
|
||||
title: t("notifications.admin.templates.description"),
|
||||
className: "w-full",
|
||||
value: (i) => (
|
||||
<div className="text-muted-foreground max-w-xs overflow-x-auto">
|
||||
<div className={clsx(!isValid(i, items) && "text-red-600")}>{channelDescription(i)}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "roles",
|
||||
title: t("notifications.admin.templates.roles"),
|
||||
value: (i) => <div className="text-muted-foreground">{i.roles?.map((role) => roleLabel(role)).join(", ") || t("shared.notSet")}</div>,
|
||||
},
|
||||
{
|
||||
name: "send",
|
||||
title: t("shared.preview"),
|
||||
value: (i) => (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(
|
||||
"font-medium",
|
||||
getCreated(i)?.active ? "border-theme-300 border-b border-dashed hover:border-dotted" : "cursor-not-allowed opacity-90"
|
||||
)}
|
||||
onClick={() => onSendPreview(i)}
|
||||
>
|
||||
{t("shared.send")}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "active",
|
||||
title: t("notifications.admin.templates.active"),
|
||||
value: (i) => (
|
||||
<div>{getCreated(i)?.active ? <CheckIcon className="text-theme-500 h-4 w-4" /> : <XIcon className="text-muted-foreground h-4 w-4" />}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "hasSteps",
|
||||
title: t("notifications.admin.templates.hasSteps"),
|
||||
value: (i) => (
|
||||
<div>{(getCreated(i)?.steps ?? []).length > 0 ? <CheckIcon className="text-theme-500 h-4 w-4" /> : <XIcon className="h-4 w-4 text-red-600" />}</div>
|
||||
),
|
||||
},
|
||||
// {
|
||||
// name: "tags",
|
||||
// title: "Tags",
|
||||
// value: (i) =>
|
||||
// getCreated(i)
|
||||
// ?.tags.map((f) => f)
|
||||
// .join(", "),
|
||||
// },
|
||||
{
|
||||
name: "_id",
|
||||
title: t("notifications.admin.templates.provider"),
|
||||
value: (i) => (
|
||||
<>
|
||||
{getCreated(i)?._id ? (
|
||||
<a
|
||||
href={`https://web.novu.co/templates/edit/${getCreated(i)?._id}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="hover:border-dotter hover:border-theme-300 border-border border-b border-dashed"
|
||||
>
|
||||
{t("notifications.admin.templates.openProvider")}
|
||||
</a>
|
||||
) : (
|
||||
<a
|
||||
href={"https://web.novu.co/templates/create"}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="hover:border-dotter hover:border-theme-300 border-border border-b border-dashed"
|
||||
>
|
||||
{t("shared.create")}
|
||||
</a>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
},
|
||||
// {
|
||||
// name: "delete",
|
||||
// title: "Delete",
|
||||
// value: (i) => (
|
||||
// <div className="flex items-center justify-center">
|
||||
// {i._id !== undefined && (
|
||||
// <button
|
||||
// type="button"
|
||||
// onClick={() => onDelete(i._id ?? "")}
|
||||
// className="mr-2 flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-red-600"
|
||||
// >
|
||||
// <TrashIcon className="h-4 w-4" />
|
||||
// </button>
|
||||
// )}
|
||||
// </div>
|
||||
// ),
|
||||
// },
|
||||
]}
|
||||
></TableSimple>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// https://docs.novu.co/api/get-integrations/
|
||||
export interface NotificationIntegrationDto {
|
||||
_id: string;
|
||||
_environmentId: string;
|
||||
_organizationId: string;
|
||||
providerId: string;
|
||||
channel: string;
|
||||
credentials: any;
|
||||
active: boolean;
|
||||
deleted: boolean;
|
||||
deletedAt: string;
|
||||
deletedBy: string;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// https://docs.novu.co/api/get-messages/
|
||||
export interface NotificationMessageDto {
|
||||
_id: string;
|
||||
_templateId: string;
|
||||
_environmentId: string;
|
||||
_messageTemplateId: string;
|
||||
_notificationId: string;
|
||||
_organizationId: string;
|
||||
_subscriberId: string;
|
||||
_jobId: string;
|
||||
templateIdentifier: string;
|
||||
cta?: { data?: { url?: string } }[];
|
||||
channel: string;
|
||||
seen?: boolean;
|
||||
read?: boolean;
|
||||
status: string;
|
||||
transactionId: string;
|
||||
payload: any;
|
||||
deleted?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt?: string;
|
||||
lastReadDate?: string;
|
||||
lastSeenDate?: string;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// https://docs.novu.co/api/get-subscribers/
|
||||
export interface NotificationSubscriberDto {
|
||||
_id: string; // The internal id novu generated for your subscriber, this is not the subscriberId matching your query. See `subscriberId` for that
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
avatar: string;
|
||||
subscriberId: string; // The internal identifier you used to create this subscriber, usually correlates to the id the user in your systems
|
||||
channels?: { _integrationId?: string; providerId?: string; credentials: string }[];
|
||||
_organizationId: string;
|
||||
_environmentId: string;
|
||||
deleted: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
__v: number;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// https://docs.novu.co/api/get-notification-templates/
|
||||
export interface NotificationTemplateDto {
|
||||
_id?: string;
|
||||
name: string;
|
||||
description: string;
|
||||
active: boolean;
|
||||
draft: boolean;
|
||||
preferenceSettings: {
|
||||
email: boolean;
|
||||
sms: boolean;
|
||||
in_app: boolean;
|
||||
chat: boolean;
|
||||
push: boolean;
|
||||
};
|
||||
critical: boolean;
|
||||
tags: string[];
|
||||
steps: any[];
|
||||
_organizationId: string;
|
||||
_creatorId: string;
|
||||
_environmentId: string;
|
||||
triggers: any[];
|
||||
_notificationGroupId: string;
|
||||
_parentId?: string;
|
||||
deleted: boolean;
|
||||
deletedAt: string;
|
||||
deletedBy: string;
|
||||
notificationGroup?: {
|
||||
_id?: string;
|
||||
name?: string;
|
||||
_environmentId?: string;
|
||||
_organizationId?: string;
|
||||
_parentId?: string;
|
||||
};
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@toolctrl/queue", () => ({
|
||||
buildNotificationJob: vi.fn((payload) => ({ name: "notification", payload })),
|
||||
enqueueJob: vi.fn(),
|
||||
queueNames: { notifications: "notifications" },
|
||||
resolveRedisConnectionOptions: vi.fn(() => undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/queue/runtime", () => ({
|
||||
createQueue: vi.fn(() => ({ close: vi.fn(async () => undefined) })),
|
||||
}));
|
||||
|
||||
vi.mock("@toolctrl/db/notifications.server", () => ({
|
||||
createNotificationDelivery: vi.fn(async (input) => ({ id: "delivery_1", ...input })),
|
||||
redactNotificationDiagnosticText: vi.fn((value: string) => value),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({
|
||||
getRolesByName: vi.fn(async () => []),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getUsersRolesInTenant: vi.fn(async () => []),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/users.db.server", () => ({
|
||||
getAdminUsersInRoles: vi.fn(async () => []),
|
||||
}));
|
||||
|
||||
import { createNotificationDelivery } from "@toolctrl/db/notifications.server";
|
||||
import { enqueueJob, resolveRedisConnectionOptions } from "@toolctrl/queue";
|
||||
import NotificationService, { mapNotificationChannelToCategory } from "./NotificationService";
|
||||
|
||||
const user = {
|
||||
id: "user_1",
|
||||
email: "user@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
phone: null,
|
||||
defaultTenantId: "tenant_1",
|
||||
};
|
||||
|
||||
describe("NotificationService", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete process.env.NOTIFICATIONS_NOVU_API_KEY;
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("records skipped deliveries when the queue is not configured", async () => {
|
||||
await NotificationService.send({
|
||||
channel: "admin-users",
|
||||
tenantId: "tenant_1",
|
||||
to: user,
|
||||
notification: { message: "Profile changed" },
|
||||
});
|
||||
|
||||
expect(createNotificationDelivery).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "in-app",
|
||||
category: "team",
|
||||
messageKey: "admin-users",
|
||||
status: "SKIPPED",
|
||||
lastError: "Notification queue is not configured.",
|
||||
payloadMetadata: {
|
||||
source: "legacy-notification-service",
|
||||
reason: "queue-not-configured",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("records skipped deliveries when a configured queue fails", async () => {
|
||||
vi.mocked(resolveRedisConnectionOptions).mockReturnValue({ host: "127.0.0.1", port: 6379 } as any);
|
||||
vi.mocked(enqueueJob).mockRejectedValue(new Error("Redis connection failed"));
|
||||
|
||||
await NotificationService.send({
|
||||
channel: "admin-users",
|
||||
tenantId: "tenant_1",
|
||||
to: user,
|
||||
notification: { message: "Profile changed" },
|
||||
});
|
||||
|
||||
expect(createNotificationDelivery).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "in-app",
|
||||
category: "team",
|
||||
messageKey: "admin-users",
|
||||
status: "SKIPPED",
|
||||
lastError: "Redis connection failed",
|
||||
payloadMetadata: {
|
||||
source: "legacy-notification-service",
|
||||
reason: "queue-enqueue-failed",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("maps subscription notifications to billing preferences", () => {
|
||||
expect(mapNotificationChannelToCategory("admin-subscriptions")).toBe("billing");
|
||||
});
|
||||
|
||||
it("returns null for Novu provider error responses", async () => {
|
||||
process.env.NOTIFICATIONS_NOVU_API_KEY = "novu-secret";
|
||||
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ message: "unauthorized" }), { status: 401 }));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
await expect(NotificationService.getSubscribers({})).resolves.toBeNull();
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://api.novu.co/v1/subscribers?page=0",
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ Authorization: "ApiKey novu-secret" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("passes tenantId through to enqueueJob so the priority resolver can run", async () => {
|
||||
vi.mocked(resolveRedisConnectionOptions).mockReturnValue({ host: "127.0.0.1", port: 6379 } as any);
|
||||
vi.mocked(enqueueJob).mockResolvedValue({ id: "job_priority_1" } as any);
|
||||
|
||||
await NotificationService.send({
|
||||
channel: "admin-users",
|
||||
tenantId: "tenant_priority_1",
|
||||
to: user,
|
||||
notification: { message: "Profile changed" },
|
||||
});
|
||||
|
||||
const lastCall = vi.mocked(enqueueJob).mock.calls.at(-1);
|
||||
expect(lastCall?.[2]).toMatchObject({ tenantId: "tenant_priority_1" });
|
||||
});
|
||||
|
||||
it("returns null for Novu provider network failures", async () => {
|
||||
process.env.NOTIFICATIONS_NOVU_API_KEY = "novu-secret";
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => {
|
||||
throw new Error("network down");
|
||||
})
|
||||
);
|
||||
|
||||
await expect(NotificationService.getIntegrations()).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
import { buildNotificationJob, enqueueJob, queueNames, resolveRedisConnectionOptions, type RedisConnectionEnv, type TypedQueue } from "@toolctrl/queue";
|
||||
import { createNotificationDelivery, redactNotificationDiagnosticText } from "@toolctrl/db/notifications.server";
|
||||
import { getRolesByName } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getUsersRolesInTenant } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getAdminUsersInRoles } from "~/utils/db/users.db.server";
|
||||
import { NotificationIntegrationDto } from "../../dtos/NotificationIntegrationDto";
|
||||
import { NotificationMessageDto } from "../../dtos/NotificationMessageDto";
|
||||
import { NotificationSubscriberDto } from "../../dtos/NotificationSubscriberDto";
|
||||
import { NotificationTemplateDto } from "../../dtos/NotificationTemplateDto";
|
||||
import { NotificationChannel, NotificationChannels } from "../NotificationChannels";
|
||||
|
||||
type NotificationQueue = TypedQueue<typeof queueNames.notifications>;
|
||||
|
||||
async function withNotificationQueue<T>(env: RedisConnectionEnv | undefined, task: (queue: NotificationQueue) => Promise<T>): Promise<T | undefined> {
|
||||
const connection = resolveRedisConnectionOptions({ env });
|
||||
if (!connection) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const queueRuntimeModule = "@toolctrl/queue/runtime";
|
||||
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@toolctrl/queue/runtime");
|
||||
const queue = createQueue(queueNames.notifications, { connection });
|
||||
try {
|
||||
return await task(queue);
|
||||
} finally {
|
||||
await queue.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function novuApiFetch<T>(path: string, init?: RequestInit): Promise<T | null> {
|
||||
if (!process.env.NOTIFICATIONS_NOVU_API_KEY) {
|
||||
return null;
|
||||
}
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`https://api.novu.co/v1${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `ApiKey ${process.env.NOTIFICATIONS_NOVU_API_KEY}`,
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return (await response.json()) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface IGetSubscribersData {
|
||||
page: number;
|
||||
totalCount: number;
|
||||
pageSize: number;
|
||||
data: NotificationSubscriberDto[];
|
||||
}
|
||||
async function getSubscribers({ page }: { page?: number }): Promise<IGetSubscribersData | null> {
|
||||
const query = new URLSearchParams({ page: String((page ?? 1) - 1) });
|
||||
return novuApiFetch<IGetSubscribersData>(`/subscribers?${query}`);
|
||||
}
|
||||
|
||||
export interface IGetMessagesData {
|
||||
page: number;
|
||||
totalCount: number;
|
||||
pageSize: number;
|
||||
data: NotificationMessageDto[];
|
||||
}
|
||||
async function getMessages({ channel, subscriberId, limit, page }: { channel?: string; subscriberId?: string; limit?: number; page?: number }) {
|
||||
let query = new URLSearchParams();
|
||||
if (channel) {
|
||||
query.append("channel", channel);
|
||||
}
|
||||
if (subscriberId) {
|
||||
query.append("subscriberId", subscriberId);
|
||||
}
|
||||
if (limit) {
|
||||
query.append("limit", limit.toString());
|
||||
}
|
||||
if (page === undefined) {
|
||||
page = 1;
|
||||
}
|
||||
if (page) {
|
||||
query.append("page", (page - 1).toString());
|
||||
}
|
||||
return novuApiFetch<IGetMessagesData>(`/messages?${query}`);
|
||||
}
|
||||
|
||||
export interface IGetTemplatesData {
|
||||
page: number;
|
||||
totalCount: number;
|
||||
pageSize: number;
|
||||
data: NotificationTemplateDto[];
|
||||
}
|
||||
async function getNotificationTemplates({ limit, page }: { limit?: number; page?: number }) {
|
||||
const query = new URLSearchParams();
|
||||
if (limit) query.append("limit", String(limit));
|
||||
if (page) query.append("page", String(page));
|
||||
return novuApiFetch<IGetTemplatesData>(`/notification-templates?${query}`);
|
||||
}
|
||||
|
||||
// interface ICreateNotificationTemplateArgs {
|
||||
// name: string;
|
||||
// notificationGroupId: string;
|
||||
// tags?: string[];
|
||||
// description?: string;
|
||||
// steps?: {
|
||||
// template: {
|
||||
// type: "in_app" | "email" | "sms" | "chat" | "push" | "digest" | "trigger" | "delay";
|
||||
// variables: {
|
||||
// type: "String";
|
||||
// name: string;
|
||||
// defaultValue: string;
|
||||
// required: boolean;
|
||||
// }[];
|
||||
// content: string;
|
||||
// };
|
||||
// }[];
|
||||
// active?: boolean;
|
||||
// draft?: boolean;
|
||||
// critical?: boolean;
|
||||
// preferenceSettings?: IPreferenceChannels;
|
||||
// }
|
||||
// async function createNotificationTemplate(data: ICreateNotificationTemplateArgs) {
|
||||
// const novu = getClient();
|
||||
// if (!novu) {
|
||||
// return;
|
||||
// }
|
||||
// const response = await novu.notificationTemplates.create(data);
|
||||
// return response.data as NotificationTemplateDto;
|
||||
// }
|
||||
|
||||
export interface IGetIntegrationsData {
|
||||
data: NotificationIntegrationDto[];
|
||||
}
|
||||
async function getIntegrations() {
|
||||
return novuApiFetch<IGetIntegrationsData>("/integrations");
|
||||
}
|
||||
|
||||
type NotificationAttachmentChannel = "in_app" | "email" | "sms" | "chat" | "push" | "digest" | "trigger" | "delay";
|
||||
interface IAttachmentOptions {
|
||||
mime: string;
|
||||
file: Buffer;
|
||||
name?: string;
|
||||
channels?: NotificationAttachmentChannel[];
|
||||
}
|
||||
interface INotificationUser {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
phone: string | null;
|
||||
defaultTenantId?: string | null;
|
||||
}
|
||||
|
||||
interface INotification {
|
||||
from?: { user?: INotificationUser | null };
|
||||
message: string;
|
||||
action?: {
|
||||
title?: string;
|
||||
url: string;
|
||||
};
|
||||
data?: { [key: string]: string | string[] | boolean | number | undefined | IAttachmentOptions | IAttachmentOptions[] | Record<string, unknown> };
|
||||
attachments?: IAttachmentOptions[];
|
||||
}
|
||||
|
||||
function getNotificationSourceKey(channel: string, notification: INotification): string | undefined {
|
||||
const directSourceKey = typeof notification.data?.sourceKey === "string" ? notification.data.sourceKey : undefined;
|
||||
const notificationSourceKey = typeof notification.data?.notificationSourceKey === "string" ? notification.data.notificationSourceKey : undefined;
|
||||
const normalized = (directSourceKey ?? notificationSourceKey)?.trim();
|
||||
if (normalized) {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const requestId = typeof notification.data?.requestId === "string" ? notification.data.requestId.trim() : "";
|
||||
return requestId ? `${channel}:request:${requestId}` : undefined;
|
||||
}
|
||||
|
||||
function createSkippedNotificationDelivery({
|
||||
targetTenantId,
|
||||
to,
|
||||
channel,
|
||||
reason,
|
||||
lastError,
|
||||
}: {
|
||||
targetTenantId: string;
|
||||
to: INotificationUser;
|
||||
channel: string;
|
||||
reason: string;
|
||||
lastError: string;
|
||||
}) {
|
||||
return createNotificationDelivery({
|
||||
tenantId: targetTenantId,
|
||||
userId: to.id,
|
||||
channel: "in-app",
|
||||
category: mapNotificationChannelToCategory(channel),
|
||||
messageKey: channel,
|
||||
status: "SKIPPED",
|
||||
lastError,
|
||||
payloadMetadata: {
|
||||
source: "legacy-notification-service",
|
||||
reason,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function send({
|
||||
channel,
|
||||
to,
|
||||
notification,
|
||||
tenantId,
|
||||
required = false,
|
||||
}: {
|
||||
channel: string;
|
||||
to: INotificationUser;
|
||||
notification: INotification;
|
||||
tenantId?: string | null;
|
||||
required?: boolean;
|
||||
}) {
|
||||
if (notification.from?.user?.id === to.id) {
|
||||
const isLocalDevelopmentMode = process.env.NODE_ENV === "development";
|
||||
if (!isLocalDevelopmentMode) {
|
||||
return;
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("[LOCAL DEV] Skipping sending notification to self.");
|
||||
notification.message = `[dev] ${notification.message}`;
|
||||
}
|
||||
|
||||
if (notification.from?.user?.email === to.email) {
|
||||
if (process.env.NODE_ENV !== "development") {
|
||||
return;
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("[LOCAL DEV] Skipping sending notification to self.");
|
||||
}
|
||||
if (notification.action && !notification.action?.title) {
|
||||
notification.action.title = "View";
|
||||
}
|
||||
|
||||
const targetTenantId = tenantId ?? (typeof notification.data?.tenantId === "string" ? notification.data.tenantId : undefined) ?? to.defaultTenantId;
|
||||
if (!targetTenantId) {
|
||||
const message = "Notification delivery requires tenantId.";
|
||||
if (process.env.NODE_ENV !== "test") {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(`[NotificationService.send()] ${message}`);
|
||||
}
|
||||
if (required) {
|
||||
throw new Error(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const queued = await withNotificationQueue(process.env as RedisConnectionEnv, async (queue) => {
|
||||
const descriptor = buildNotificationJob({
|
||||
tenantId: targetTenantId,
|
||||
userId: to.id,
|
||||
email: to.email,
|
||||
channel: "in-app",
|
||||
category: mapNotificationChannelToCategory(channel),
|
||||
messageKey: channel,
|
||||
sourceKey: getNotificationSourceKey(channel, notification),
|
||||
metadata: {
|
||||
source: "legacy-notification-service",
|
||||
...(notification.action?.url ? { actionUrl: notification.action.url } : {}),
|
||||
...(notification.message ? { message: notification.message } : {}),
|
||||
},
|
||||
templateData: {
|
||||
...notification.data,
|
||||
from: notification.from,
|
||||
message: notification.message,
|
||||
action: notification.action,
|
||||
attachments: notification.attachments,
|
||||
},
|
||||
});
|
||||
return enqueueJob(queue, descriptor, { tenantId: targetTenantId });
|
||||
});
|
||||
if (!queued && required) {
|
||||
throw new Error("Notification queue is not configured.");
|
||||
}
|
||||
if (!queued) {
|
||||
return createSkippedNotificationDelivery({
|
||||
targetTenantId,
|
||||
to,
|
||||
channel,
|
||||
reason: "queue-not-configured",
|
||||
lastError: "Notification queue is not configured.",
|
||||
});
|
||||
}
|
||||
return queued;
|
||||
} catch (e: any) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
const redactedMessage = redactNotificationDiagnosticText(message);
|
||||
// eslint-disable-next-line no-console
|
||||
console.error("[NotificationService.send()] Error: " + redactedMessage);
|
||||
if (required) {
|
||||
throw new Error(redactedMessage);
|
||||
}
|
||||
return createSkippedNotificationDelivery({
|
||||
targetTenantId,
|
||||
to,
|
||||
channel,
|
||||
reason: "queue-enqueue-failed",
|
||||
lastError: redactedMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function mapNotificationChannelToCategory(channel: string) {
|
||||
if (channel === "admin-subscriptions") {
|
||||
return "billing";
|
||||
}
|
||||
if (channel.startsWith("admin-")) {
|
||||
return "team";
|
||||
}
|
||||
if (channel === "my-rows" || channel === "roles") {
|
||||
return "team";
|
||||
}
|
||||
return "default";
|
||||
}
|
||||
|
||||
async function sendToRoles({ channel, notification, tenantId }: { channel: NotificationChannel; tenantId?: string | null; notification: INotification }) {
|
||||
const notificationChannel = NotificationChannels.find((f) => f.name === channel);
|
||||
if (!notificationChannel?.roles) {
|
||||
return;
|
||||
}
|
||||
const allRoles = await getRolesByName(notificationChannel.roles);
|
||||
const adminRoles = allRoles.filter((f) => f.type === "admin");
|
||||
const appRoles = allRoles.filter((f) => f.type === "app");
|
||||
|
||||
const sentToUsers: string[] = [];
|
||||
|
||||
const adminUsersInRoles = await getAdminUsersInRoles(adminRoles.map((m) => m.id));
|
||||
await Promise.all(
|
||||
adminUsersInRoles.map(async (adminUser) => {
|
||||
if (sentToUsers.includes(adminUser.id)) {
|
||||
return;
|
||||
}
|
||||
sentToUsers.push(adminUser.id);
|
||||
await send({ channel: notificationChannel.name, to: adminUser, tenantId: tenantId ?? adminUser.defaultTenantId, notification });
|
||||
})
|
||||
);
|
||||
|
||||
if (tenantId) {
|
||||
const tenantUserRoles = await getUsersRolesInTenant(tenantId);
|
||||
await Promise.all(
|
||||
appRoles.map(async (role) => {
|
||||
const usersInRole = tenantUserRoles.filter((f) => f.roleId === role.id);
|
||||
return await Promise.all(
|
||||
usersInRole.map(async ({ user }) => {
|
||||
if (sentToUsers.includes(user.id)) {
|
||||
return;
|
||||
}
|
||||
sentToUsers.push(user.id);
|
||||
return await send({ channel: notificationChannel.name, to: user, tenantId, notification });
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteNotificationTemplate(id: string) {
|
||||
await novuApiFetch(`/notification-templates/${id}/status`, { method: "PATCH", body: JSON.stringify({ active: false }) });
|
||||
return novuApiFetch(`/notification-templates/${id}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export default {
|
||||
getSubscribers,
|
||||
getMessages,
|
||||
getIntegrations,
|
||||
getNotificationTemplates,
|
||||
// createNotificationTemplate,
|
||||
deleteNotificationTemplate,
|
||||
send,
|
||||
sendToRoles,
|
||||
};
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { NotificationChannels } from "./NotificationChannels";
|
||||
|
||||
describe("NotificationChannels", () => {
|
||||
it("uses translation keys for visible channel descriptions", () => {
|
||||
for (const channel of NotificationChannels) {
|
||||
expect(channel.descriptionKey).toBe(`notifications.admin.channelDescriptions.${channel.name}`);
|
||||
expect(channel).not.toHaveProperty("description");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
|
||||
|
||||
const NotificationChannelTypes = [
|
||||
"admin-accounts",
|
||||
"admin-users",
|
||||
"admin-subscriptions",
|
||||
"admin-api-keys",
|
||||
"admin-emails",
|
||||
"admin-groups",
|
||||
"admin-linked-accounts",
|
||||
"admin-account-members",
|
||||
"admin-onboarding",
|
||||
"admin-rows",
|
||||
"roles",
|
||||
"my-rows",
|
||||
] as const;
|
||||
export type NotificationChannel = typeof NotificationChannelTypes[number];
|
||||
|
||||
export interface NotificationChannelDto {
|
||||
name: NotificationChannel;
|
||||
descriptionKey: `notifications.admin.channelDescriptions.${NotificationChannel}`;
|
||||
roles?: string[];
|
||||
}
|
||||
|
||||
export const NotificationChannels: NotificationChannelDto[] = [
|
||||
{
|
||||
name: "admin-accounts",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-accounts",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-users",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-users",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-subscriptions",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-subscriptions",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-api-keys",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-api-keys",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-emails",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-emails",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-groups",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-groups",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-linked-accounts",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-linked-accounts",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-account-members",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-account-members",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-onboarding",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-onboarding",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "admin-rows",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.admin-rows",
|
||||
roles: [DefaultAdminRoles.SuperAdmin],
|
||||
},
|
||||
{
|
||||
name: "roles",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.roles",
|
||||
roles: [DefaultAppRoles.SuperUser],
|
||||
},
|
||||
{
|
||||
name: "my-rows",
|
||||
descriptionKey: "notifications.admin.channelDescriptions.my-rows",
|
||||
},
|
||||
];
|
||||
Reference in new issue
Block a user