Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions apps/backend/src/lib/data/notifications/items.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, expect, mock, test } from "bun:test";

const notifications = [
{ id: "own-item", topicId: "own-topic", status: "received" },
{ id: "foreign-item", topicId: "foreign-topic", status: "received" },
];
const updates: Array<{ id: string; data: Record<string, unknown> }> = [];

const fakePB = {
collection(name: string) {
return {
async getFullList({ filter }: { filter: string }) {
if (name === "notificationTopics") {
return [{ id: "own-topic", userId: "user-a" }];
}
if (name === "notificationItems") {
const topicIds = [...filter.matchAll(/topicId="([^"]+)"/g)].map((match) => match[1]);
return notifications.filter((item) => topicIds.includes(item.topicId));
}
throw new Error(`Unexpected collection: ${name}`);
},
async update(id: string, data: Record<string, unknown>) {
updates.push({ id, data });
const item = notifications.find((record) => record.id === id);
if (item) item.status = String(data.status);
return item;
},
};
},
};

mock.module("../../pb/pocketbase", () => ({
getSuperuserPB: async () => fakePB,
}));
mock.module("./publish", () => ({ queueNotificationForForwarding: async () => {} }));

const { markNotificationsAsRead } = await import("./items");

describe("markNotificationsAsRead", () => {
test("marks a user's requested notification read without changing a foreign notification", async () => {
updates.length = 0;
notifications[0].status = "received";
notifications[1].status = "received";

await markNotificationsAsRead("user-a", ["own-item", "foreign-item"]);

expect(updates).toEqual([{ id: "own-item", data: { status: "read" } }]);
expect(notifications[0].status).toBe("read");
expect(notifications[1].status).toBe("received");
});

test("with no IDs, marks all unread notifications in the user's topics read", async () => {
updates.length = 0;
notifications[0].status = "received";
notifications[1].status = "received";

await markNotificationsAsRead("user-a", []);

expect(updates).toEqual([{ id: "own-item", data: { status: "read" } }]);
expect(notifications[0].status).toBe("read");
expect(notifications[1].status).toBe("received");
});
});
36 changes: 19 additions & 17 deletions apps/backend/src/lib/data/notifications/items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,25 +158,27 @@ export async function sendTestNotification(userId: string, topicId: string) {

export async function markNotificationsAsRead(userId: string, ids: string[]) {
const pb = await getSuperuserPB();
let targetIds = ids;
const topics = (await pb.collection("notificationTopics").getFullList({
filter: `userId="${userId}"`,
})) as Array<NotificationTopicsResponse>;
const topicIds = topics.map((topic) => topic.id);

if (topicIds.length === 0) {
return null;
}

// Scope records to the user's topics before considering caller-supplied IDs.
// The superuser client bypasses PocketBase rules, so IDs alone are not an
// authorization check.
const topicFilter = topicIds.map((id) => `topicId="${id}"`).join(" || ");
const items = (await pb.collection("notificationItems").getFullList({ filter: topicFilter })) as Array<NotificationItemsResponse>;
const requestedIds = new Set(ids);
const targetIds = items
.filter((item) => ids.length === 0 ? item.status !== "read" : requestedIds.has(item.id))
.map((item) => item.id);

if (targetIds.length === 0) {
const topics = (await pb.collection("notificationTopics").getFullList({
filter: `userId="${userId}"`,
})) as Array<NotificationTopicsResponse>;
const topicIds = topics.map((topic) => topic.id);

if (topicIds.length === 0) {
return null;
}

const filter = topicIds.map((id) => `topicId="${id}"`).join(" || ");
const items = (await pb.collection("notificationItems").getFullList({ filter, sort: "-created" })) as Array<NotificationItemsResponse>;
targetIds = items.filter((item) => item.status !== "read").map((item) => item.id);

if (targetIds.length === 0) {
return null;
}
return null;
}

await Promise.allSettled(
Expand Down
43 changes: 43 additions & 0 deletions apps/backend/src/routes/integrations.caldav.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, expect, test } from "bun:test";

import { getCalDavEventsForIntegration } from "./integrations.route";

describe("CalDAV integration events", () => {
test("uses the integration wrapper and persists local data through the authenticated session", async () => {
const environment = { CALDAV_URL: "https://calendar.example/dav" };
const localData = { calendarUrl: "/calendar/" };
const updatedLocalData = { ...localData, syncToken: "next-token" };
const updates: Array<{ id: string; body: unknown }> = [];
const pb = {
collection(name: string) {
expect(name).toBe("integrations");
return {
async update(id: string, body: unknown) {
updates.push({ id, body });
},
};
},
};
const eventCalls: unknown[][] = [];
const getEvents = async (...args: any[]) => {
eventCalls.push(args);
await args[2](updatedLocalData);
return [{ id: "event-1" }];
};

const events = await getCalDavEventsForIntegration(
{ integration: { environment, localData } },
"owned-integration-id",
pb,
getEvents as any,
);

expect(eventCalls[0]?.[0]).toBe(environment);
expect(eventCalls[0]?.[1]).toBe(localData);
expect(events).toEqual([{ id: "event-1" }]);
expect(updates).toEqual([{
id: "owned-integration-id",
body: { localData: updatedLocalData },
}]);
});
});
32 changes: 25 additions & 7 deletions apps/backend/src/routes/integrations.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,17 +388,13 @@ integrationsRoute
) => pb.collection("integrations").update(id, { localData });

if (integrationId) {
const integration = await getIntegration(userId, integrationId);
if (!integration) {
const result = await getIntegration(userId, integrationId);
if (!result?.integration) {
throw new ApiActionError("Integration not found", 404, {
error: "Not found",
});
}
const events = await getUpcomingEvents(
(integration as any).environment,
(integration as any).localData,
(ld) => updateLocalData(integrationId, ld).then(() => undefined),
);
const events = await getCalDavEventsForIntegration(result, integrationId, pb);
return { events };
}

Expand All @@ -425,6 +421,28 @@ integrationsRoute

export default integrationsRoute;

export async function getCalDavEventsForIntegration(
result: {
integration: {
environment: Record<string, string>;
localData?: Record<string, unknown>;
};
},
integrationId: string,
pb: any,
getEvents: typeof getUpcomingEvents = getUpcomingEvents,
) {
const integration = result.integration;
return getEvents(
integration.environment,
integration.localData,
(localData) =>
pb.collection("integrations")
.update(integrationId, { localData })
.then(() => undefined),
);
}

// --- Types ---

type ResolveConsumerDataOpts = {
Expand Down
Loading