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
34 changes: 34 additions & 0 deletions app/api/v1/milady/google/calendar/calendars/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { miladyGoogleRouteDeps } from "@/lib/services/milady-google-route-deps";

export const dynamic = "force-dynamic";
export const maxDuration = 30;

export async function GET(request: NextRequest) {
try {
const { user } = await miladyGoogleRouteDeps.requireAuthOrApiKeyWithOrg(request);
const rawSide = request.nextUrl.searchParams.get("side");
if (rawSide !== null && rawSide !== "owner" && rawSide !== "agent") {
return NextResponse.json({ error: "side must be owner or agent." }, { status: 400 });
}

return NextResponse.json(
await miladyGoogleRouteDeps.listManagedGoogleCalendars({
organizationId: user.organization_id,
userId: user.id,
side: rawSide === "agent" ? "agent" : "owner",
}),
);
} catch (error) {
if (error instanceof miladyGoogleRouteDeps.MiladyGoogleConnectorError) {
return NextResponse.json({ error: error.message }, { status: error.status });
}
return NextResponse.json(
{
error: error instanceof Error ? error.message : "Failed to list Google calendars.",
},
{ status: 500 },
);
}
}
73 changes: 73 additions & 0 deletions packages/lib/services/milady-google-connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from "@/lib/utils/google-mcp-shared";

const GOOGLE_CALENDAR_EVENTS_ENDPOINT = "https://www.googleapis.com/calendar/v3/calendars";
const GOOGLE_CALENDAR_LIST_ENDPOINT = "https://www.googleapis.com/calendar/v3/users/me/calendarList";
const GOOGLE_GMAIL_MESSAGES_ENDPOINT = "https://gmail.googleapis.com/gmail/v1/users/me/messages";
const GOOGLE_GMAIL_SEND_ENDPOINT = `${GOOGLE_GMAIL_MESSAGES_ENDPOINT}/send`;
const DEFAULT_GOOGLE_CONNECTOR_CAPABILITIES = [
Expand Down Expand Up @@ -84,6 +85,18 @@ export interface ManagedGoogleCalendarEvent {
metadata: Record<string, unknown>;
}

export interface ManagedGoogleCalendarSummary {
calendarId: string;
summary: string;
description: string | null;
primary: boolean;
accessRole: string;
backgroundColor: string | null;
foregroundColor: string | null;
timeZone: string | null;
selected: boolean;
}

export interface ManagedGoogleGmailMessage {
externalId: string;
threadId: string;
Expand Down Expand Up @@ -166,6 +179,21 @@ type GoogleCalendarApiEvent = {
};
};

type GoogleCalendarListApiEntry = {
id?: string;
summary?: string;
summaryOverride?: string;
description?: string;
primary?: boolean;
accessRole?: string;
backgroundColor?: string;
foregroundColor?: string;
timeZone?: string;
selected?: boolean;
deleted?: boolean;
hidden?: boolean;
};

type GoogleGmailMetadataHeader = {
name?: string;
value?: string;
Expand Down Expand Up @@ -1066,6 +1094,51 @@ export async function fetchManagedGoogleCalendarFeed(args: {
};
}

export async function listManagedGoogleCalendars(args: {
organizationId: string;
userId: string;
side: OAuthConnectionRole;
}): Promise<ManagedGoogleCalendarSummary[]> {
const params = new URLSearchParams({
minAccessRole: "reader",
showDeleted: "false",
showHidden: "false",
fields:
"items(id,summary,summaryOverride,description,primary,accessRole,backgroundColor,foregroundColor,timeZone,selected,deleted,hidden)",
});

const response = await googleFetch({
organizationId: args.organizationId,
userId: args.userId,
side: args.side,
url: `${GOOGLE_CALENDAR_LIST_ENDPOINT}?${params.toString()}`,
});
const parsed = (await response.json()) as {
items?: GoogleCalendarListApiEntry[];
};

const calendars: ManagedGoogleCalendarSummary[] = [];
for (const item of parsed.items ?? []) {
if (item.deleted || item.hidden) continue;
const calendarId = item.id?.trim();
if (!calendarId) continue;
calendars.push({
calendarId,
summary:
item.summaryOverride?.trim() || item.summary?.trim() || calendarId,
description: item.description?.trim() || null,
primary: Boolean(item.primary),
accessRole: item.accessRole?.trim() || "reader",
backgroundColor: item.backgroundColor?.trim() || null,
foregroundColor: item.foregroundColor?.trim() || null,
timeZone: item.timeZone?.trim() || null,
selected: item.selected !== false,
});
}

return calendars;
}

export async function createManagedGoogleCalendarEvent(args: {
organizationId: string;
userId: string;
Expand Down
2 changes: 2 additions & 0 deletions packages/lib/services/milady-google-route-deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
fetchManagedGoogleGmailTriage,
getManagedGoogleConnectorStatus,
initiateManagedGoogleConnection,
listManagedGoogleCalendars,
listManagedGoogleConnectorAccounts,
MiladyGoogleConnectorError,
readManagedGoogleGmailMessage,
Expand All @@ -20,6 +21,7 @@ export const miladyGoogleRouteDeps = {
requireAuthOrApiKeyWithOrg,
getManagedGoogleConnectorStatus,
listManagedGoogleConnectorAccounts,
listManagedGoogleCalendars,
initiateManagedGoogleConnection,
disconnectManagedGoogleConnection,
fetchManagedGoogleCalendarFeed,
Expand Down
111 changes: 111 additions & 0 deletions packages/tests/unit/milady-google-calendar-calendars-route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { NextRequest } from "next/server";

const requireAuthOrApiKeyWithOrg = mock(async () => ({
user: {
id: "user-1",
organization_id: "org-1",
},
}));

const listManagedGoogleCalendars = mock(async () => [
{
calendarId: "quinn@example.com",
summary: "Quinn",
description: null,
primary: false,
accessRole: "owner",
backgroundColor: "#16a34a",
foregroundColor: "#ffffff",
timeZone: "America/New_York",
selected: true,
},
]);

async function importRoute() {
mock.module("@/lib/services/milady-google-route-deps", () => ({
miladyGoogleRouteDeps: {
requireAuthOrApiKeyWithOrg,
listManagedGoogleCalendars,
MiladyGoogleConnectorError: class extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
this.name = "MiladyGoogleConnectorError";
}
},
},
}));

return import(
new URL("../../../app/api/v1/milady/google/calendar/calendars/route.ts?test=" + Date.now(), import.meta.url).href
);
}

describe("managed Google calendar calendars route", () => {
beforeEach(() => {
mock.restore();
requireAuthOrApiKeyWithOrg.mockReset();
listManagedGoogleCalendars.mockReset();
requireAuthOrApiKeyWithOrg.mockResolvedValue({
user: {
id: "user-1",
organization_id: "org-1",
},
});
listManagedGoogleCalendars.mockResolvedValue([
{
calendarId: "quinn@example.com",
summary: "Quinn",
description: null,
primary: false,
accessRole: "owner",
backgroundColor: "#16a34a",
foregroundColor: "#ffffff",
timeZone: "America/New_York",
selected: true,
},
]);
});

afterEach(() => {
mock.restore();
});

test("returns managed calendars for the requested side", async () => {
const { GET } = await importRoute();

const response = await GET(
new NextRequest("https://example.com/api/v1/milady/google/calendar/calendars?side=owner"),
);

expect(requireAuthOrApiKeyWithOrg).toHaveBeenCalledTimes(1);
expect(listManagedGoogleCalendars).toHaveBeenCalledWith({
organizationId: "org-1",
userId: "user-1",
side: "owner",
});
expect(response.status).toBe(200);
expect(await response.json()).toEqual([
expect.objectContaining({
calendarId: "quinn@example.com",
summary: "Quinn",
}),
]);
});

test("rejects invalid side values", async () => {
const { GET } = await importRoute();

const response = await GET(
new NextRequest("https://example.com/api/v1/milady/google/calendar/calendars?side=bad"),
);

expect(response.status).toBe(400);
expect(await response.json()).toEqual({
error: "side must be owner or agent.",
});
});
});