Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+46
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildChatMessageDiscoveryVM } from "@hivegrid/view-models";
|
||||
|
||||
import { mergeChatMessageDiscoveryPages } from "./ChatMessageDiscoveryRouteView";
|
||||
|
||||
const hrefs = { chat: "/demo/chat", search: "/demo/chat/search", mentions: "/demo/chat/mentions" } as const;
|
||||
|
||||
function row(id: string) {
|
||||
return {
|
||||
id,
|
||||
chatId: "chat_1",
|
||||
channelKind: "group" as const,
|
||||
channelTitle: "Montage",
|
||||
authorLabel: "Ada Lovelace",
|
||||
authorAvatar: { imageUrl: null, fallbackLabel: "AL" },
|
||||
body: `Message ${id}`,
|
||||
createdAtIso: "2026-07-16T11:00:00.000Z",
|
||||
detailHref: `/demo/chat/chat_1?message=${id}`,
|
||||
isThreadReply: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("chat message discovery pagination", () => {
|
||||
it("appends cursor pages once and keeps the incoming next cursor", () => {
|
||||
const first = buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [row("m2")], nextCursor: "cursor_2", hrefs });
|
||||
const second = buildChatMessageDiscoveryVM({
|
||||
mode: "search",
|
||||
query: "heat",
|
||||
rows: [row("m2"), row("m1")],
|
||||
nextCursor: null,
|
||||
hrefs,
|
||||
});
|
||||
|
||||
const merged = mergeChatMessageDiscoveryPages(first, second);
|
||||
expect(merged.status === "ready" && merged.data.rows.map(({ id }) => id)).toEqual(["m2", "m1"]);
|
||||
expect(merged.status === "ready" && merged.data.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("does not mix pages from different queries", () => {
|
||||
const first = buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [row("m2")], hrefs });
|
||||
const other = buildChatMessageDiscoveryVM({ mode: "search", query: "solar", rows: [row("m1")], hrefs });
|
||||
|
||||
expect(mergeChatMessageDiscoveryPages(first, other)).toEqual(other);
|
||||
});
|
||||
});
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useFetcher, useNavigate, useRevalidator } from "react-router";
|
||||
import type { ChatMessageDiscoveryData, ChatMessageDiscoveryVM } from "@hivegrid/view-models";
|
||||
|
||||
import { ChatMessageDiscoveryPage } from "~/components/screens/chat/ChatMessageDiscoveryPage";
|
||||
|
||||
import type { ChatMessageDiscoveryLoaderData } from "./chatMessageDiscoveryRouteTypes";
|
||||
|
||||
const QUERY_DEBOUNCE_MS = 250;
|
||||
|
||||
export function ChatMessageDiscoveryRouteView({ data }: { readonly data: ChatMessageDiscoveryLoaderData }) {
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
const pageFetcher = useFetcher<ChatMessageDiscoveryLoaderData>();
|
||||
const requestedCursor = useRef<string | null>(null);
|
||||
const queryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [display, setDisplay] = useState<{ readonly source: ChatMessageDiscoveryVM; readonly vm: ChatMessageDiscoveryVM }>({
|
||||
source: data.vm,
|
||||
vm: data.vm,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
requestedCursor.current = null;
|
||||
setDisplay({ source: data.vm, vm: data.vm });
|
||||
}, [data.vm]);
|
||||
useEffect(() => {
|
||||
if (pageFetcher.state !== "idle" || !requestedCursor.current || !pageFetcher.data) return;
|
||||
const requested = requestedCursor.current;
|
||||
requestedCursor.current = null;
|
||||
if (pageFetcher.data.pageCursor !== requested || !sameDiscovery(data.vm, pageFetcher.data.vm)) return;
|
||||
setDisplay((current) => ({ source: data.vm, vm: mergePages(current.source === data.vm ? current.vm : data.vm, pageFetcher.data!.vm) }));
|
||||
}, [data.vm, pageFetcher.data, pageFetcher.state]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (queryTimer.current) clearTimeout(queryTimer.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const vm = display.source === data.vm ? display.vm : data.vm;
|
||||
const navigateToQuery = useCallback(
|
||||
(query: string) => {
|
||||
const params = new URLSearchParams();
|
||||
const normalized = query.trim().slice(0, 200);
|
||||
if (normalized) params.set("q", normalized);
|
||||
void navigate(`${discoveryBasePath(data.vm)}${params.size ? `?${params.toString()}` : ""}`, { replace: true });
|
||||
},
|
||||
[data.vm, navigate]
|
||||
);
|
||||
|
||||
return (
|
||||
<ChatMessageDiscoveryPage
|
||||
vm={vm}
|
||||
actions={{
|
||||
onBack: (href) => void navigate(href),
|
||||
onSwitchMode: (href) => void navigate(href),
|
||||
onOpenResult: (row) => void navigate(row.detailHref),
|
||||
onQueryChange: (query) => {
|
||||
setDisplay((current) => ({ source: current.source, vm: withQuery(current.source, query) }));
|
||||
if (queryTimer.current) clearTimeout(queryTimer.current);
|
||||
queryTimer.current = setTimeout(() => {
|
||||
queryTimer.current = null;
|
||||
navigateToQuery(query);
|
||||
}, QUERY_DEBOUNCE_MS);
|
||||
},
|
||||
onLoadMore: (cursor) => {
|
||||
if (pageFetcher.state !== "idle" || requestedCursor.current) return;
|
||||
requestedCursor.current = cursor;
|
||||
const ready = readyData(vm);
|
||||
const params = new URLSearchParams({ cursor });
|
||||
if (ready?.mode === "search" && ready.query) params.set("q", ready.query);
|
||||
void pageFetcher.load(`${discoveryBasePath(vm)}?${params.toString()}`);
|
||||
},
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function mergeChatMessageDiscoveryPages(current: ChatMessageDiscoveryVM, incoming: ChatMessageDiscoveryVM): ChatMessageDiscoveryVM {
|
||||
if (!sameDiscovery(current, incoming) || current.status !== "ready" || incoming.status !== "ready") return incoming;
|
||||
const rows = new Map(current.data.rows.map((row) => [row.id, row]));
|
||||
for (const row of incoming.data.rows) rows.set(row.id, row);
|
||||
return { ...incoming, data: { ...incoming.data, rows: [...rows.values()] } };
|
||||
}
|
||||
|
||||
function mergePages(current: ChatMessageDiscoveryVM, incoming: ChatMessageDiscoveryVM): ChatMessageDiscoveryVM {
|
||||
return mergeChatMessageDiscoveryPages(current, incoming);
|
||||
}
|
||||
|
||||
function sameDiscovery(left: ChatMessageDiscoveryVM, right: ChatMessageDiscoveryVM): boolean {
|
||||
return left.status === "ready" && right.status === "ready" && left.data.mode === right.data.mode && left.data.query === right.data.query;
|
||||
}
|
||||
|
||||
function withQuery(vm: ChatMessageDiscoveryVM, query: string): ChatMessageDiscoveryVM {
|
||||
if (vm.status !== "ready" || vm.data.mode !== "search") return vm;
|
||||
if (query === vm.data.query) return vm;
|
||||
return { ...vm, data: { ...vm.data, query, rows: [], nextCursor: null } };
|
||||
}
|
||||
|
||||
function discoveryBasePath(vm: ChatMessageDiscoveryVM): string {
|
||||
const data = readyData(vm);
|
||||
return data?.mode === "mentions" ? (data.hrefs.mentions) : (data?.hrefs.search ?? "");
|
||||
}
|
||||
|
||||
function readyData(vm: ChatMessageDiscoveryVM): ChatMessageDiscoveryData | null {
|
||||
return vm.status === "ready" ? vm.data : null;
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
requireAuth: vi.fn(),
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
tenantHasModule: vi.fn(),
|
||||
getPermissionsByUser: vi.fn(),
|
||||
membership: { id: "tenant-user-1" } as { id: string } | null,
|
||||
tx: {
|
||||
tenantUser: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...args: unknown[]) => mocks.requireAuth(...args) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
|
||||
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args) }));
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ getPermissionsByUser: (...args: unknown[]) => mocks.getPermissionsByUser(...args) }));
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
|
||||
import {
|
||||
chatHasPermission,
|
||||
loadChatContext,
|
||||
requireChatChannelAdminAccess,
|
||||
requireChatChannelReadAccess,
|
||||
requireChatChannelWriteAccess,
|
||||
requireChatPermission,
|
||||
type ChatChannelAccessSnapshot,
|
||||
type ChatRouteContext,
|
||||
} from "./chatAccess.server";
|
||||
|
||||
const activeMember: ChatChannelAccessSnapshot = {
|
||||
isActiveMember: true,
|
||||
isChannelAdmin: false,
|
||||
isArchived: false,
|
||||
};
|
||||
|
||||
function context(permissions: readonly string[]): ChatRouteContext {
|
||||
return {
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
tenantUserId: "tenant-user-1",
|
||||
permissions,
|
||||
hasModule: true,
|
||||
};
|
||||
}
|
||||
|
||||
describe("chat access", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.requireAuth.mockResolvedValue(undefined);
|
||||
mocks.getTenantIdFromUrl.mockResolvedValue("tenant-1");
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user-1" });
|
||||
mocks.tenantHasModule.mockResolvedValue(true);
|
||||
mocks.getPermissionsByUser.mockResolvedValue([CHAT_PERMISSIONS.readOwnChannels]);
|
||||
mocks.tx.tenantUser.findFirst.mockImplementation(async () => mocks.membership);
|
||||
mocks.membership = { id: "tenant-user-1" };
|
||||
});
|
||||
|
||||
it("loads an authenticated, tenant-scoped module context", async () => {
|
||||
const request = new Request("http://app.localhost/acme/chat");
|
||||
await expect(loadChatContext({ request, params: { tenant: "acme" } })).resolves.toEqual({
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
tenantUserId: "tenant-user-1",
|
||||
permissions: [CHAT_PERMISSIONS.readOwnChannels],
|
||||
hasModule: true,
|
||||
});
|
||||
expect(mocks.tenantHasModule).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1", moduleKey: "chat" });
|
||||
expect(mocks.tx.tenantUser.findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
user: { active: true },
|
||||
tenant: { active: true },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed when the chat module is disabled", async () => {
|
||||
mocks.tenantHasModule.mockResolvedValue(false);
|
||||
const request = new Request("http://app.localhost/acme/chat");
|
||||
|
||||
await expect(loadChatContext({ request, params: { tenant: "acme" } })).rejects.toBeInstanceOf(CatalogError);
|
||||
});
|
||||
|
||||
it("rejects a session without an active tenant membership", async () => {
|
||||
mocks.membership = null;
|
||||
await expect(loadChatContext({ request: new Request("http://app.localhost/acme/chat"), params: { tenant: "acme" } })).rejects.toBeInstanceOf(CatalogError);
|
||||
});
|
||||
|
||||
it("requires exact permissions without making chat.admin an audit capability", () => {
|
||||
const admin = context([CHAT_PERMISSIONS.admin]);
|
||||
expect(chatHasPermission(admin, CHAT_PERMISSIONS.admin)).toBe(true);
|
||||
expect(chatHasPermission(admin, CHAT_PERMISSIONS.readAllChannels)).toBe(false);
|
||||
expect(() => requireChatPermission(admin, CHAT_PERMISSIONS.readAllChannels)).toThrow(CatalogError);
|
||||
});
|
||||
|
||||
it("allows active members to read and keeps audit reads behind the dedicated audit-session service", () => {
|
||||
expect(requireChatChannelReadAccess(context([CHAT_PERMISSIONS.readOwnChannels]), activeMember)).toBe("member");
|
||||
|
||||
const outsider = { ...activeMember, isActiveMember: false };
|
||||
expect(() => requireChatChannelReadAccess(context([CHAT_PERMISSIONS.readAllChannels]), outsider)).toThrow(CatalogError);
|
||||
expect(() => requireChatChannelReadAccess(context([CHAT_PERMISSIONS.admin]), outsider)).toThrow(CatalogError);
|
||||
});
|
||||
|
||||
it("never lets audit mode or archived membership write", () => {
|
||||
const auditOnly = context([CHAT_PERMISSIONS.readAllChannels]);
|
||||
expect(() => requireChatChannelWriteAccess(auditOnly, { ...activeMember, isActiveMember: false })).toThrow(CatalogError);
|
||||
expect(() => requireChatChannelWriteAccess(context([CHAT_PERMISSIONS.write]), { ...activeMember, isArchived: true })).toThrow(CatalogError);
|
||||
expect(requireChatChannelWriteAccess(context([CHAT_PERMISSIONS.write]), activeMember)).toMatchObject({ userId: "user-1" });
|
||||
});
|
||||
|
||||
it("allows channel admins only as members while global chat admins override membership", () => {
|
||||
expect(requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels]), { ...activeMember, isChannelAdmin: true })).toMatchObject({
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.admin]), activeMember)).toMatchObject({
|
||||
userId: "user-1",
|
||||
});
|
||||
expect(
|
||||
requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.admin]), {
|
||||
...activeMember,
|
||||
isActiveMember: false,
|
||||
})
|
||||
).toMatchObject({ userId: "user-1" });
|
||||
expect(() => requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels]), activeMember)).toThrow(CatalogError);
|
||||
});
|
||||
});
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import { CHAT_PERMISSIONS, type ChatPermission } from "@hivegrid/chat";
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
|
||||
import { CHAT_MODULE_KEY } from "./chatRoutePaths";
|
||||
|
||||
export type ChatRouteContext = {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
tenantUserId: string;
|
||||
permissions: readonly string[];
|
||||
hasModule: true;
|
||||
};
|
||||
|
||||
export type ChatChannelAccessSnapshot = {
|
||||
isActiveMember: boolean;
|
||||
isChannelAdmin: boolean;
|
||||
isArchived: boolean;
|
||||
};
|
||||
|
||||
export type ChatChannelReadMode = "member";
|
||||
|
||||
export async function loadChatContext({ request, params }: { request: Request; params: Record<string, string | undefined> }): Promise<ChatRouteContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
|
||||
const [hasModule, permissions, membership] = await Promise.all([
|
||||
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: CHAT_MODULE_KEY }),
|
||||
getPermissionsByUser(userInfo.userId, tenantId),
|
||||
withTenantRLS(tenantId, (tx) =>
|
||||
tx.tenantUser.findFirst({
|
||||
where: {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
status: TenantUserStatus.ACTIVE,
|
||||
user: { active: true },
|
||||
tenant: { active: true },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
),
|
||||
]);
|
||||
|
||||
if (!membership || !hasModule) {
|
||||
throw new CatalogError(foundationErrors.notFound, !hasModule ? { module: CHAT_MODULE_KEY } : undefined);
|
||||
}
|
||||
|
||||
return {
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
tenantUserId: membership.id,
|
||||
permissions,
|
||||
hasModule: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function chatHasPermission(ctx: ChatRouteContext, permission: ChatPermission): boolean {
|
||||
return ctx.permissions.includes(permission);
|
||||
}
|
||||
|
||||
export function requireChatPermission(ctx: ChatRouteContext, permission: ChatPermission): ChatRouteContext {
|
||||
if (!chatHasPermission(ctx, permission)) {
|
||||
throw new CatalogError(foundationErrors.notFound, { permission });
|
||||
}
|
||||
|
||||
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export function requireChatChannelReadAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatChannelReadMode {
|
||||
if (channel.isActiveMember && chatHasPermission(ctx, CHAT_PERMISSIONS.readOwnChannels)) {
|
||||
return "member";
|
||||
}
|
||||
|
||||
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
|
||||
}
|
||||
|
||||
export function requireChatChannelWriteAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatRouteContext {
|
||||
if (channel.isActiveMember && !channel.isArchived && chatHasPermission(ctx, CHAT_PERMISSIONS.write)) {
|
||||
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, CHAT_PERMISSIONS.write);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
|
||||
}
|
||||
|
||||
export function requireChatChannelAdminAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatRouteContext {
|
||||
if (chatHasPermission(ctx, CHAT_PERMISSIONS.admin)) {
|
||||
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, CHAT_PERMISSIONS.admin);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
if (channel.isActiveMember && channel.isChannelAdmin && chatHasPermission(ctx, CHAT_PERMISSIONS.readOwnChannels)) {
|
||||
return ctx;
|
||||
}
|
||||
|
||||
throw new CatalogError(foundationErrors.notFound, { chat: "not-administerable" });
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
chatChannelListFilterHref,
|
||||
chatChannelListPageHref,
|
||||
normalizeChatChannelQuery,
|
||||
parseChatChannelListCursor,
|
||||
parseChatChannelListFilter,
|
||||
} from "./chatListFilter";
|
||||
|
||||
describe("chat list filter", () => {
|
||||
it("parses supported filters and rejects unknown views", () => {
|
||||
expect(parseChatChannelListFilter(new URL("https://app.test/demo/chat?q=%20Montage%20&view=unread&archived=1"))).toEqual({
|
||||
query: "Montage",
|
||||
view: "unread",
|
||||
showArchived: true,
|
||||
});
|
||||
expect(parseChatChannelListFilter(new URL("https://app.test/demo/chat?view=admin"))).toEqual({
|
||||
query: "",
|
||||
view: "all",
|
||||
showArchived: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("serializes only non-default filter state", () => {
|
||||
expect(chatChannelListFilterHref("demo", { query: "", view: "all", showArchived: false })).toBe("/demo/chat");
|
||||
expect(chatChannelListFilterHref("demo", { query: "Ada", view: "direct", showArchived: true })).toBe("/demo/chat?q=Ada&view=direct&archived=1");
|
||||
});
|
||||
|
||||
it("round-trips a page cursor while filter navigation resets it", () => {
|
||||
const filter = { query: "Ada", view: "direct" as const, showArchived: true };
|
||||
const href = chatChannelListPageHref("demo", filter, "cursor.page_2");
|
||||
const url = new URL(href, "https://app.test");
|
||||
|
||||
expect(parseChatChannelListCursor(url)).toBe("cursor.page_2");
|
||||
expect(chatChannelListFilterHref("demo", filter)).toBe("/demo/chat?q=Ada&view=direct&archived=1");
|
||||
expect(chatChannelListFilterHref("demo", parseChatChannelListFilter(url))).not.toContain("cursor");
|
||||
});
|
||||
|
||||
it("treats an empty page cursor as absent", () => {
|
||||
expect(parseChatChannelListCursor(new URL("https://app.test/demo/chat?cursor=%20%20"))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses the same bounded query normalization for local and URL state", () => {
|
||||
expect(normalizeChatChannelQuery(" Montage ")).toBe("Montage");
|
||||
expect(normalizeChatChannelQuery("x".repeat(250))).toHaveLength(200);
|
||||
});
|
||||
});
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { chatChannelListViewSchema, type ChatChannelListFilterState } from "@hivegrid/view-models";
|
||||
|
||||
const MAX_CHANNEL_QUERY_LENGTH = 200;
|
||||
const MAX_CHANNEL_CURSOR_LENGTH = 2_048;
|
||||
|
||||
export function parseChatChannelListFilter(url: URL): ChatChannelListFilterState {
|
||||
const parsedView = chatChannelListViewSchema.safeParse(url.searchParams.get("view") ?? "all");
|
||||
const showArchivedValue = url.searchParams.get("archived");
|
||||
return {
|
||||
query: normalizeChatChannelQuery(url.searchParams.get("q") ?? ""),
|
||||
view: parsedView.success ? parsedView.data : "all",
|
||||
showArchived: showArchivedValue === "1" || showArchivedValue === "true",
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeChatChannelQuery(query: string): string {
|
||||
return query.trim().slice(0, MAX_CHANNEL_QUERY_LENGTH);
|
||||
}
|
||||
|
||||
export function chatChannelListFilterHref(tenantSlug: string, filter: ChatChannelListFilterState): string {
|
||||
return chatChannelListPageHref(tenantSlug, filter);
|
||||
}
|
||||
|
||||
export function parseChatChannelListCursor(url: URL): string | undefined {
|
||||
const cursor = url.searchParams.get("cursor")?.trim();
|
||||
if (!cursor) return undefined;
|
||||
return cursor.slice(0, MAX_CHANNEL_CURSOR_LENGTH);
|
||||
}
|
||||
|
||||
export function chatChannelListPageHref(tenantSlug: string, filter: ChatChannelListFilterState, cursor?: string): string {
|
||||
const params = new URLSearchParams();
|
||||
const query = normalizeChatChannelQuery(filter.query);
|
||||
if (query) params.set("q", query);
|
||||
if (filter.view !== "all") params.set("view", filter.view);
|
||||
if (filter.showArchived) params.set("archived", "1");
|
||||
const normalizedCursor = cursor?.trim().slice(0, MAX_CHANNEL_CURSOR_LENGTH);
|
||||
if (normalizedCursor) params.set("cursor", normalizedCursor);
|
||||
const search = params.toString();
|
||||
return `/${encodeURIComponent(tenantSlug)}/chat${search ? `?${search}` : ""}`;
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { buildChatChannelListVM, type ChatChannelListFilterState, type ChatChannelListRowInput } from "@hivegrid/view-models";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { mergeChatChannelListPages, sameChatChannelListFilter } from "./chatListPagination";
|
||||
|
||||
const DEFAULT_FILTER: ChatChannelListFilterState = { query: "", view: "all", showArchived: false };
|
||||
|
||||
function row(id: string, unreadCount: number): ChatChannelListRowInput {
|
||||
return {
|
||||
id,
|
||||
kind: "group",
|
||||
title: id,
|
||||
subtitle: null,
|
||||
detailHref: `/demo/chat/${id}`,
|
||||
avatar: { imageUrl: null, fallbackLabel: id.slice(0, 1) },
|
||||
project: null,
|
||||
lastMessage: null,
|
||||
typingLabels: [],
|
||||
unreadCount,
|
||||
hasMention: unreadCount > 1,
|
||||
isPinned: false,
|
||||
isPrivate: false,
|
||||
notificationPreference: "all_messages",
|
||||
archivedAtIso: null,
|
||||
memberCount: 2,
|
||||
canManage: false,
|
||||
};
|
||||
}
|
||||
|
||||
function page(rows: readonly ChatChannelListRowInput[], nextCursor: string | null, filter = DEFAULT_FILTER) {
|
||||
return buildChatChannelListVM({
|
||||
rows,
|
||||
discoverRows: [],
|
||||
filter,
|
||||
permissions: {
|
||||
canWrite: false,
|
||||
canCreateGroup: false,
|
||||
canCreateDm: false,
|
||||
canDiscover: false,
|
||||
canViewMentions: false,
|
||||
canSearch: true,
|
||||
canViewArchived: true,
|
||||
canAdmin: false,
|
||||
},
|
||||
hrefs: {
|
||||
newChannel: "/demo/chat/new",
|
||||
newDm: "/demo/chat/new?kind=dm",
|
||||
search: "/demo/chat/search",
|
||||
mentions: "/demo/chat/mentions",
|
||||
archived: "/demo/chat?archived=1",
|
||||
},
|
||||
totals: {
|
||||
unread: rows.reduce((total, entry) => total + entry.unreadCount, 0),
|
||||
mentions: rows.filter((entry) => entry.hasMention).length,
|
||||
},
|
||||
nextCursor,
|
||||
});
|
||||
}
|
||||
|
||||
describe("chat list pagination", () => {
|
||||
it("appends in server order, refreshes duplicate boundary rows, and adopts the incoming cursor", () => {
|
||||
const merged = mergeChatChannelListPages(page([row("chat_1", 1), row("chat_2", 0)], "cursor_2"), page([row("chat_2", 3), row("chat_3", 2)], null));
|
||||
|
||||
expect(merged.status).toBe("ready");
|
||||
if (merged.status !== "ready") return;
|
||||
expect(merged.data.rows.map((entry) => [entry.id, entry.unreadCount])).toEqual([
|
||||
["chat_1", 1],
|
||||
["chat_2", 3],
|
||||
["chat_3", 2],
|
||||
]);
|
||||
expect(merged.data.totals).toEqual({ unread: 6, mentions: 2 });
|
||||
expect(merged.data.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("resets to the incoming page when the normalized server filter changes", () => {
|
||||
const unreadFilter = { ...DEFAULT_FILTER, view: "unread" as const };
|
||||
const reset = mergeChatChannelListPages(page([row("chat_old", 1)], "old_cursor"), page([row("chat_new", 2)], "new_cursor", unreadFilter));
|
||||
|
||||
expect(sameChatChannelListFilter(DEFAULT_FILTER, unreadFilter)).toBe(false);
|
||||
expect(reset.status).toBe("ready");
|
||||
if (reset.status !== "ready") return;
|
||||
expect(reset.data.rows.map((entry) => entry.id)).toEqual(["chat_new"]);
|
||||
expect(reset.data.filter).toEqual(unreadFilter);
|
||||
expect(reset.data.nextCursor).toBe("new_cursor");
|
||||
});
|
||||
});
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import type { ChatChannelListFilterState, ChatChannelListRowVM, ChatChannelListVM } from "@hivegrid/view-models";
|
||||
|
||||
export function sameChatChannelListFilter(left: ChatChannelListFilterState, right: ChatChannelListFilterState): boolean {
|
||||
return left.query === right.query && left.view === right.view && left.showArchived === right.showArchived;
|
||||
}
|
||||
|
||||
/** Appends one server-filtered keyset page without changing the server order.
|
||||
* Repeated boundary rows are refreshed in place and never rendered twice. */
|
||||
export function mergeChatChannelListPages(current: ChatChannelListVM, incoming: ChatChannelListVM): ChatChannelListVM {
|
||||
if (incoming.status !== "ready") return current;
|
||||
if (current.status !== "ready" || !sameChatChannelListFilter(current.data.filter, incoming.data.filter)) return incoming;
|
||||
|
||||
const rowsById = new Map<string, ChatChannelListRowVM>(current.data.rows.map((row) => [row.id, row]));
|
||||
for (const row of incoming.data.rows) rowsById.set(row.id, row);
|
||||
const rows = [...rowsById.values()];
|
||||
|
||||
return {
|
||||
...current,
|
||||
data: {
|
||||
...current.data,
|
||||
rows,
|
||||
totals: {
|
||||
unread: rows.reduce((total, row) => total + row.unreadCount, 0),
|
||||
mentions: rows.filter((row) => row.hasMention).length,
|
||||
},
|
||||
nextCursor: incoming.data.nextCursor,
|
||||
},
|
||||
};
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
|
||||
import { buildChatMessageDiscoveryVM } from "@hivegrid/view-models";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getTranslations: vi.fn(),
|
||||
loadContext: vi.fn(),
|
||||
loadDiscovery: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("./chatAccess.server", () => ({ loadChatContext: (...args: unknown[]) => mocks.loadContext(...args) }));
|
||||
vi.mock("~/modules/chat/services/ChatMessageDiscoveryService.server", () => ({
|
||||
loadChatMessageDiscovery: (...args: unknown[]) => mocks.loadDiscovery(...args),
|
||||
}));
|
||||
|
||||
import { loadChatMessageDiscoveryRoute } from "./chatMessageDiscoveryLoader.server";
|
||||
|
||||
const context = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "viewer_1",
|
||||
tenantUserId: "tenant_user_1",
|
||||
permissions: [CHAT_PERMISSIONS.readOwnChannels],
|
||||
hasModule: true,
|
||||
} as const;
|
||||
const hrefs = { chat: "/demo/chat", search: "/demo/chat/search", mentions: "/demo/chat/mentions" } as const;
|
||||
|
||||
describe("chat message discovery route loader", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getTranslations.mockResolvedValue({ t: (key: string) => `t:${key}` });
|
||||
mocks.loadContext.mockResolvedValue(context);
|
||||
mocks.loadDiscovery.mockResolvedValue(buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [], hrefs }));
|
||||
});
|
||||
|
||||
it("normalizes search query and forwards the opaque cursor", async () => {
|
||||
const request = new Request("http://app.localhost:3000/demo/chat/search?q=%20heat%20&cursor=cursor_1");
|
||||
const result = await loadChatMessageDiscoveryRoute({ request, params: { tenant: "demo" }, context: {} } as never, "search");
|
||||
|
||||
expect(mocks.loadDiscovery).toHaveBeenCalledWith({
|
||||
context,
|
||||
tenantSlug: "demo",
|
||||
mode: "search",
|
||||
query: "heat",
|
||||
beforeCursor: "cursor_1",
|
||||
limit: 30,
|
||||
labels: {
|
||||
directMessage: "t:chat.channel.fallback.directMessage",
|
||||
unnamedGroup: "t:chat.channel.fallback.group",
|
||||
unnamedProject: "t:chat.channel.fallback.project",
|
||||
unknownUser: "t:chat.participant.unknown",
|
||||
},
|
||||
});
|
||||
expect(result.pageCursor).toBe("cursor_1");
|
||||
expect(result.title).toContain("t:chat.messageDiscovery.search.title");
|
||||
});
|
||||
|
||||
it("keeps mentions query-free even when the URL contains q", async () => {
|
||||
mocks.loadDiscovery.mockResolvedValue(buildChatMessageDiscoveryVM({ mode: "mentions", rows: [], hrefs }));
|
||||
const request = new Request("http://app.localhost:3000/demo/chat/mentions?q=ignored");
|
||||
|
||||
await loadChatMessageDiscoveryRoute({ request, params: { tenant: "demo" }, context: {} } as never, "mentions");
|
||||
|
||||
expect(mocks.loadDiscovery).toHaveBeenCalledWith(expect.not.objectContaining({ query: expect.anything() }));
|
||||
});
|
||||
});
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import type { ChatMessageDiscoveryMode } from "@hivegrid/view-models";
|
||||
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { loadChatMessageDiscovery } from "~/modules/chat/services/ChatMessageDiscoveryService.server";
|
||||
|
||||
import { loadChatContext } from "./chatAccess.server";
|
||||
import type { ChatMessageDiscoveryLoaderData } from "./chatMessageDiscoveryRouteTypes";
|
||||
|
||||
const PAGE_LIMIT = 30;
|
||||
|
||||
export async function loadChatMessageDiscoveryRoute(
|
||||
args: LoaderFunctionArgs,
|
||||
mode: ChatMessageDiscoveryMode
|
||||
): Promise<ChatMessageDiscoveryLoaderData> {
|
||||
const [{ t }, context] = await Promise.all([getTranslations(args.request), loadChatContext(args)]);
|
||||
const url = new URL(args.request.url);
|
||||
const tenantSlug = args.params.tenant ?? "";
|
||||
const pageCursor = normalizeCursor(url.searchParams.get("cursor"));
|
||||
const query = mode === "search" ? normalizeQuery(url.searchParams.get("q")) : undefined;
|
||||
const vm = await loadChatMessageDiscovery({
|
||||
context,
|
||||
tenantSlug,
|
||||
mode,
|
||||
...(query !== undefined ? { query } : {}),
|
||||
...(pageCursor ? { beforeCursor: pageCursor } : {}),
|
||||
limit: PAGE_LIMIT,
|
||||
labels: {
|
||||
directMessage: t("chat.channel.fallback.directMessage"),
|
||||
unnamedGroup: t("chat.channel.fallback.group"),
|
||||
unnamedProject: t("chat.channel.fallback.project"),
|
||||
unknownUser: t("chat.participant.unknown"),
|
||||
},
|
||||
});
|
||||
return {
|
||||
title: `${t(mode === "search" ? "chat.messageDiscovery.search.title" : "chat.messageDiscovery.mentions.title")} | ${process.env.APP_NAME}`,
|
||||
tenantSlug,
|
||||
pageCursor,
|
||||
vm,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(value: string | null): string {
|
||||
return (value ?? "").trim().slice(0, 200);
|
||||
}
|
||||
|
||||
function normalizeCursor(value: string | null): string | null {
|
||||
const normalized = value?.trim() ?? "";
|
||||
return normalized ? normalized.slice(0, 2_048) : null;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import type { ChatMessageDiscoveryVM } from "@hivegrid/view-models";
|
||||
|
||||
export type ChatMessageDiscoveryLoaderData = Readonly<{
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
pageCursor: string | null;
|
||||
vm: ChatMessageDiscoveryVM;
|
||||
}>;
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CHAT_MODULE_KEY,
|
||||
chatArchivedPath,
|
||||
chatAuditAttachmentPath,
|
||||
chatAuditPath,
|
||||
chatChannelInfoPath,
|
||||
chatChannelPath,
|
||||
chatChannelSettingsPath,
|
||||
chatFilesPath,
|
||||
chatIndexPath,
|
||||
chatMentionsPath,
|
||||
chatNewPath,
|
||||
chatNotFoundResponse,
|
||||
chatPinnedPath,
|
||||
chatSearchPath,
|
||||
chatThreadPath,
|
||||
} from "./chatRoutePaths";
|
||||
|
||||
describe("chat route paths", () => {
|
||||
it("uses the canonical chat module key and tenant-scoped collection paths", () => {
|
||||
expect(CHAT_MODULE_KEY).toBe("chat");
|
||||
expect(chatIndexPath("acme")).toBe("/acme/chat");
|
||||
expect(chatNewPath("acme")).toBe("/acme/chat/new");
|
||||
expect(chatMentionsPath("acme")).toBe("/acme/chat/mentions");
|
||||
expect(chatSearchPath("acme")).toBe("/acme/chat/search");
|
||||
expect(chatArchivedPath("acme")).toBe("/acme/chat/archived");
|
||||
});
|
||||
|
||||
it("builds channel, thread, pin, and file paths without changing identifiers", () => {
|
||||
expect(chatChannelPath("acme", "chat_1")).toBe("/acme/chat/chat_1");
|
||||
expect(chatChannelSettingsPath("acme", "chat_1")).toBe("/acme/chat/chat_1/settings");
|
||||
expect(chatChannelInfoPath("acme", "chat_1")).toBe("/acme/chat/chat_1/info");
|
||||
expect(chatThreadPath("acme", "chat_1", "thread_1")).toBe("/acme/chat/chat_1/thread/thread_1");
|
||||
expect(chatPinnedPath("acme", "chat_1")).toBe("/acme/chat/chat_1/pinned");
|
||||
expect(chatFilesPath("acme", "chat_1")).toBe("/acme/chat/chat_1/files");
|
||||
});
|
||||
|
||||
it("uses the compliance hub for audit screens while keeping the published attachment endpoint stable", () => {
|
||||
expect(chatAuditPath("acme")).toBe("/acme/settings/compliance/chat");
|
||||
expect(chatAuditAttachmentPath("acme", "chat/1", "file/1", "preview")).toBe(
|
||||
"/acme/settings/chat/audit/chat%2F1/attachments/file%2F1/preview"
|
||||
);
|
||||
});
|
||||
|
||||
it("provides the standard opaque not-found response", async () => {
|
||||
const response = chatNotFoundResponse();
|
||||
expect(response.status).toBe(404);
|
||||
expect(await response.text()).toBe("Not Found");
|
||||
});
|
||||
});
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
export const CHAT_MODULE_KEY = "chat";
|
||||
|
||||
export function chatIndexPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/chat`;
|
||||
}
|
||||
|
||||
export function chatNewPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/chat/new`;
|
||||
}
|
||||
|
||||
export function chatMentionsPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/chat/mentions`;
|
||||
}
|
||||
|
||||
export function chatSearchPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/chat/search`;
|
||||
}
|
||||
|
||||
export function chatArchivedPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/chat/archived`;
|
||||
}
|
||||
|
||||
export function chatChannelPath(tenantSlug: string, chatId: string): string {
|
||||
return `/${tenantSlug}/chat/${chatId}`;
|
||||
}
|
||||
|
||||
export function chatChannelSettingsPath(tenantSlug: string, chatId: string): string {
|
||||
return `/${tenantSlug}/chat/${chatId}/settings`;
|
||||
}
|
||||
|
||||
export function chatChannelInfoPath(tenantSlug: string, chatId: string): string {
|
||||
return `/${tenantSlug}/chat/${chatId}/info`;
|
||||
}
|
||||
|
||||
export function chatThreadPath(tenantSlug: string, chatId: string, threadId: string): string {
|
||||
return `/${tenantSlug}/chat/${chatId}/thread/${threadId}`;
|
||||
}
|
||||
|
||||
export function chatPinnedPath(tenantSlug: string, chatId: string): string {
|
||||
return `/${tenantSlug}/chat/${chatId}/pinned`;
|
||||
}
|
||||
|
||||
export function chatFilesPath(tenantSlug: string, chatId: string): string {
|
||||
return `/${tenantSlug}/chat/${chatId}/files`;
|
||||
}
|
||||
|
||||
export function chatAuditPath(tenantSlug: string): string {
|
||||
return `/${tenantSlug}/settings/compliance/chat`;
|
||||
}
|
||||
|
||||
export function chatAuditAttachmentPath(
|
||||
tenantSlug: string,
|
||||
chatId: string,
|
||||
fileId: string,
|
||||
variant: "original" | "preview"
|
||||
): string {
|
||||
return `/${tenantSlug}/settings/chat/audit/${encodeURIComponent(chatId)}/attachments/${encodeURIComponent(fileId)}/${variant}`;
|
||||
}
|
||||
|
||||
export function chatNotFoundResponse(): Response {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
Reference in new issue
Block a user