const NOTION_BASE = "https://api.notion.com/v1"; const TIMEOUT_MS = 10_000; export interface NotionProject { id: string; name: string; } function headers(token: string) { return { Authorization: `Bearer ${token}`, "Notion-Version": "2022-06-28", "Content-Type": "application/json", }; } function fetchWithTimeout(url: string, options: RequestInit): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), TIMEOUT_MS); return fetch(url, { ...options, signal: controller.signal }).finally(() => clearTimeout(timer)); } const BOOK_COLOR: Record = { green: "📗", blue: "📘", orange: "📙", red: "📕", yellow: "📒", pink: "📔", purple: "📓", }; const ICON_NAME: Record = { graduate: "🎓", science: "🔬", gears: "⚙️", comment: "💬", building: "🏢", chart: "📊", code: "💻", document: "📄", flag: "🚩", globe: "🌐", home: "🏠", link: "🔗", music: "🎵", person: "👤", phone: "📞", pin: "📌", rocket: "🚀", star: "⭐", tag: "🏷️", target: "🎯", }; function notionIconToEmoji(page: any): string { const icon = page?.icon; if (!icon) return ""; if (icon.type === "emoji") return icon.emoji as string; if (icon.type === "icon") { const { name, color } = icon.icon ?? {}; if (name === "book") return BOOK_COLOR[color] ?? "📚"; if (name === "skip-forward") return "⏭"; return ICON_NAME[name] ?? ""; } return ""; } export interface NotionUser { id: string; name: string; } export async function fetchUsers(token: string): Promise { const resp = await fetchWithTimeout(`${NOTION_BASE}/users`, { headers: headers(token), }); if (!resp.ok) throw new Error(`Failed to fetch users: ${resp.status}`); const data = (await resp.json()) as { results: any[] }; return data.results .filter((u: any) => u.type === "person" && u.person?.email) .map((u: any) => ({ id: u.id as string, name: u.name as string })) .sort((a, b) => a.name.localeCompare(b.name)); } export async function fetchProjects(token: string, dbId: string): Promise { const results: NotionProject[] = []; let cursor: string | undefined; do { const body: Record = { page_size: 100, sorts: [{ property: "Project name", direction: "ascending" }], }; if (cursor) body.start_cursor = cursor; const resp = await fetchWithTimeout(`${NOTION_BASE}/databases/${dbId}/query`, { method: "POST", headers: headers(token), body: JSON.stringify(body), }); if (!resp.ok) throw new Error(`Notion error ${resp.status}`); const data = (await resp.json()) as { results: unknown[]; has_more: boolean; next_cursor: string | null }; for (const page of data.results as any[]) { const titleArr: any[] = page.properties?.["Project name"]?.title ?? []; const title = titleArr.map((t: any) => t.plain_text).join("").trim() || "Untitled"; const emoji = notionIconToEmoji(page); results.push({ id: page.id as string, name: emoji ? `${emoji} ${title}` : title }); } cursor = data.has_more && data.next_cursor ? data.next_cursor : undefined; } while (cursor); return results; } export async function startTimer( token: string, timingDbId: string, projectId: string, projectName: string, userId: string ): Promise { const now = new Date().toISOString(); const resp = await fetchWithTimeout(`${NOTION_BASE}/pages`, { method: "POST", headers: headers(token), body: JSON.stringify({ parent: { database_id: timingDbId }, icon: { type: "emoji", emoji: "⏱️" }, properties: { Name: { title: [{ text: { content: "Timer Task" } }] }, "Start Time": { date: { start: now } }, Projects: { relation: [{ id: projectId }] }, Status: { status: { name: "Running" } }, Responsible: { people: [{ object: "user", id: userId }] }, }, }), }); if (!resp.ok) throw new Error(`Failed to start timer: ${resp.status}`); const data = (await resp.json()) as { id: string }; return data.id; } export async function stopTimer(token: string, entryId: string): Promise { const now = new Date().toISOString(); const resp = await fetchWithTimeout(`${NOTION_BASE}/pages/${entryId}`, { method: "PATCH", headers: headers(token), body: JSON.stringify({ properties: { "End Time": { date: { start: now } }, Status: { status: { name: "Stopped" } }, }, }), }); if (!resp.ok) throw new Error(`Failed to stop timer: ${resp.status}`); }