Email for professionals and teams
Add scheduled tab #97
Hieu Nguyen (Jack)4b31136ac771
diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsxindex 1d5929d..beee9b1 100644--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx@@ -18,6 +18,8 @@ import { PreviousMessage } from "@/components/previous-message";import { ConversationThread } from "@/components/messages/conversation-thread";import { MessageDetailNavigation } from "@/components/messages/message-detail-navigation";import { MessageReadingHeaderButton } from "@/components/messages/message-reading-header-button";+import { ScheduledSendBanner } from "@/components/messages/scheduled-send-banner";+import { formatScheduledSendTime } from "@/components/messages/scheduled-send-utils";import { QuotedEmailToggle } from "@/components/messages/quoted-email-toggle";import { ThreadMessageActions } from "@/components/messages/thread-message-actions";import { useMessageThread } from "@/components/messages/use-message-thread";@@ -108,7 +110,7 @@ export default function MessageDetailPage() {);}- const { message, body, attachments = [] } = data;+ const { message, body, attachments = [], scheduledAt } = data;const currentThreadMessage = {...message,textBody: body?.textBody ?? null,@@ -259,7 +261,9 @@ export default function MessageDetailPage() {</div><div className="flex shrink-0 items-center gap-2"><p className="text-xs">- {formatUserDate(message.createdAt, { month: "short", day: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" })}+ {scheduledAt+ ? formatScheduledSendTime(scheduledAt, t)+ : formatUserDate(message.createdAt, { month: "short", day: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" })}</p><ThreadMessageActionsmessage={currentThreadMessage}@@ -270,6 +274,7 @@ export default function MessageDetailPage() {/></div></div>+ {scheduledAt && <div className="pl-10"><ScheduledSendBanner messageId={message.id} scheduledAt={scheduledAt} /></div>}<div className="prose max-w-none pl-16 text-neutral-900">{htmlBody ? (<EmailHtmlRenderer key={message.id} className="mx-auto" html={htmlBody} />diff --git a/src/app/(dashboard)/inbox/[messageId]/types.d.ts b/src/app/(dashboard)/inbox/[messageId]/types.d.tsindex ed098ff..fad3cf8 100644--- a/src/app/(dashboard)/inbox/[messageId]/types.d.ts+++ b/src/app/(dashboard)/inbox/[messageId]/types.d.ts@@ -9,6 +9,8 @@ export type MessageDetailResponse = {} | null;attachments?: MessageAttachment[];unsubscribeUrl?: string | null;+ /** ISO time a queued message is waiting to be sent, when it is a scheduled send. */+ scheduledAt?: string | null;error?: string;};diff --git a/src/app/(dashboard)/scheduled/[messageId]/page.tsx b/src/app/(dashboard)/scheduled/[messageId]/page.tsxnew file mode 100644index 0000000..155292d--- /dev/null+++ b/src/app/(dashboard)/scheduled/[messageId]/page.tsx@@ -0,0 +1,3 @@+import Page from "@/app/(dashboard)/inbox/[messageId]/page"++export default Page;\ No newline at end of filediff --git a/src/app/(dashboard)/scheduled/layout.tsx b/src/app/(dashboard)/scheduled/layout.tsxnew file mode 100644index 0000000..4b1c9e2--- /dev/null+++ b/src/app/(dashboard)/scheduled/layout.tsx@@ -0,0 +1,16 @@+"use client";++import { scheduledFolderConfig } from "@/components/messages/message-folder-configs";+import { MessageSplitLayout } from "@/components/messages/message-split-layout";++export default function ScheduledLayout({+ children,+}: {+ children: React.ReactNode;+}) {+ return (+ <MessageSplitLayout config={scheduledFolderConfig}>+ {children}+ </MessageSplitLayout>+ );+}diff --git a/src/app/(dashboard)/scheduled/page.tsx b/src/app/(dashboard)/scheduled/page.tsxnew file mode 100644index 0000000..9d4a14a--- /dev/null+++ b/src/app/(dashboard)/scheduled/page.tsx@@ -0,0 +1,8 @@+"use client";++import { scheduledFolderConfig } from "@/components/messages/message-folder-configs";+import { MessageFolderPage } from "@/components/messages/message-folder-page";++export default function ScheduledPage() {+ return <MessageFolderPage config={scheduledFolderConfig} />;+}diff --git a/src/app/api/messages/[messageId]/cancel-schedule/route.ts b/src/app/api/messages/[messageId]/cancel-schedule/route.tsnew file mode 100644index 0000000..d9262d1--- /dev/null+++ b/src/app/api/messages/[messageId]/cancel-schedule/route.ts@@ -0,0 +1,52 @@+import { and, eq, isNotNull } from "drizzle-orm";+import { NextResponse } from "next/server";+import { getDb } from "@/db";+import { messages, outboundJobs } from "@/db/schema";+import { getCurrentUser } from "@/lib/auth/cookies";+import { getEnv } from "@/lib/cloudflare";+import { getMailboxAccessLevel } from "@/lib/mailboxes/access";++/**+ * Cancels a scheduled send and returns the message to Drafts. Deleting the job is+ * what stops delivery: the queue consumer skips messages whose job is gone.+ */+export async function POST(+ request: Request,+ { params }: { params: Promise<{ messageId: string }> },+) {+ const { messageId } = await params;+ const env = getEnv();+ const user = await getCurrentUser(env, request);+ if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });++ const db = getDb(env);+ const [message] = await db+ .select({ id: messages.id, mailboxId: messages.mailboxId, direction: messages.direction, status: messages.status })+ .from(messages)+ .where(eq(messages.id, messageId))+ .limit(1);+ if (!message?.mailboxId) return NextResponse.json({ error: "Message not found" }, { status: 404 });++ const access = await getMailboxAccessLevel(db, user, message.mailboxId);+ if (!access?.canRead) return NextResponse.json({ error: "Message not found" }, { status: 404 });+ if (!access.canSendAs && !access.canSendOnBehalf) {+ return NextResponse.json({ error: "You cannot cancel sends from this mailbox" }, { status: 403 });+ }++ const [job] = await db+ .select({ id: outboundJobs.id })+ .from(outboundJobs)+ .where(and(+ eq(outboundJobs.messageId, message.id),+ eq(outboundJobs.status, "queued"),+ isNotNull(outboundJobs.scheduledAt),+ ))+ .limit(1);+ if (message.direction !== "outbound" || message.status !== "queued" || !job) {+ return NextResponse.json({ error: "This message is not scheduled" }, { status: 409 });+ }++ await db.delete(outboundJobs).where(eq(outboundJobs.id, job.id));+ await db.update(messages).set({ status: "draft" }).where(eq(messages.id, message.id));+ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/messages/counts/route.ts b/src/app/api/messages/counts/route.tsindex 73b6f9d..2dd1afe 100644--- a/src/app/api/messages/counts/route.ts+++ b/src/app/api/messages/counts/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/db";import { messages } from "@/db/schema";import { getCurrentUser } from "@/lib/auth/cookies";import { getEnv } from "@/lib/cloudflare";+import { scheduledMessageCondition } from "@/lib/email/scheduled";import { buildMessageCounts } from "./utils";import { getMailboxAccessLevel, listAccessibleMailboxIds } from "@/lib/mailboxes/access";@@ -58,5 +59,12 @@ export async function GET(request: Request) {messages.snoozedUntil,);- return NextResponse.json({ counts: buildMessageCounts(rows) });+ const [scheduledRow] = await db+ .select({ total: count() })+ .from(messages)+ .where(and(...conditions, scheduledMessageCondition(db)));+ const counts = buildMessageCounts(rows);+ counts.folders.scheduled.total = scheduledRow?.total ?? 0;++ return NextResponse.json({ counts });}diff --git a/src/app/api/messages/counts/utils.ts b/src/app/api/messages/counts/utils.tsindex 604bc42..00a6065 100644--- a/src/app/api/messages/counts/utils.ts+++ b/src/app/api/messages/counts/utils.ts@@ -18,6 +18,7 @@ export function createEmptyFolderCounts(): MessageCounts["folders"] {starred: { total: 0, unread: 0 },snoozed: { total: 0, unread: 0 },sent: { total: 0, unread: 0 },+ scheduled: { total: 0, unread: 0 },drafts: { total: 0, unread: 0 },archived: { total: 0, unread: 0 },spam: { total: 0, unread: 0 },diff --git a/src/app/api/messages/navigation/route.ts b/src/app/api/messages/navigation/route.tsindex 4bd0ba0..cd57e78 100644--- a/src/app/api/messages/navigation/route.ts+++ b/src/app/api/messages/navigation/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server";import { and, desc, eq, gt, inArray, isNull, lte, or } from "drizzle-orm";import type { SQL } from "drizzle-orm";+import { scheduledMessageCondition } from "@/lib/email/scheduled";import { getDb } from "@/db";import { messages } from "@/db/schema";import { getCurrentUser } from "@/lib/auth/cookies";@@ -9,7 +10,7 @@ import { getMailboxAccessLevel, listAccessibleMailboxIds } from "@/lib/mailboxesimport type { MessageFolder } from "@/hooks/types";import type { MessageNavigationEntry } from "./types";-const folders: MessageFolder[] = ["inbox", "starred", "snoozed", "sent", "archived", "spam", "trash"];+const folders: MessageFolder[] = ["inbox", "starred", "snoozed", "sent", "scheduled", "archived", "spam", "trash"];export async function GET(request: Request) {const env = getEnv();@@ -54,6 +55,8 @@ export async function GET(request: Request) {} else if (folder === "sent") {conditions.push(eq(messages.direction, "outbound"));conditions.push(eq(messages.status, "sent"));+ } else if (folder === "scheduled") {+ conditions.push(scheduledMessageCondition(db));} else {conditions.push(eq(messages.status, folder));}diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.tsindex 899d6bc..d61cab2 100644--- a/src/app/api/messages/route.ts+++ b/src/app/api/messages/route.ts@@ -4,13 +4,14 @@ import type { SQL } from "drizzle-orm";import { getEnv } from "@/lib/cloudflare";import { getCurrentUser } from "@/lib/auth/cookies";import { getDb } from "@/db";-import { messages } from "@/db/schema";+import { messages, outboundJobs } from "@/db/schema";import { getContactDisplayNameMap } from "@/lib/contacts/service";import { getFirstEmailAddressEntry, normalizeEmailAddress } from "@/lib/email/address";import { getMailboxAccessLevel, listAccessibleMailboxes } from "@/lib/mailboxes/access";import { tracksAccountIdentity } from "@/lib/profile/identity-utils";import { buildSearchConditions } from "@/lib/search/conditions";import { getRequestTimeZone } from "@/lib/time/utils";+import { scheduledMessageCondition } from "@/lib/email/scheduled";import { getMessageListColumns, loadConversationPage } from "./utils";import type { ListMessage } from "./types";@@ -31,6 +32,7 @@ export async function GET(request: Request) {const read = url.searchParams.get("read");const starred = url.searchParams.get("starred");const snoozed = url.searchParams.get("snoozed");+ const scheduled = url.searchParams.get("scheduled");const limit = Math.min(Number(url.searchParams.get("limit") ?? 50), 100);const offset = Math.max(Number(url.searchParams.get("offset") ?? 0), 0);// Conversation view: one row per thread, represented by its newest message@@ -77,6 +79,9 @@ export async function GET(request: Request) {conditions.push(isNull(messages.folderId));conditions.push(gt(messages.snoozedUntil, new Date()));}+ if (scheduled === "true") {+ conditions.push(scheduledMessageCondition(db));+ }if (read === "read") {conditions.push(eq(messages.read, true));}@@ -154,6 +159,16 @@ export async function GET(request: Request) {if (row.threadId) threadCounts.set(row.threadId, { total: row.total, unread: Number(row.unread ?? 0) });}}+ const scheduledAtByMessageId = new Map<string, string>();+ if (scheduled === "true" && rows.length > 0) {+ const jobs = await db+ .select({ messageId: outboundJobs.messageId, scheduledAt: outboundJobs.scheduledAt })+ .from(outboundJobs)+ .where(and(inArray(outboundJobs.messageId, rows.map((row) => row.id)), eq(outboundJobs.status, "queued"), isNotNull(outboundJobs.scheduledAt)));+ for (const job of jobs) {+ if (job.messageId && job.scheduledAt) scheduledAtByMessageId.set(job.messageId, job.scheduledAt.toISOString());+ }+ }const mailboxNameMap = new Map(accessibleMailboxes.map((mailbox) => [mailbox.id,@@ -185,6 +200,7 @@ export async function GET(request: Request) {return {...message,snippet: message.snippet,+ ...(scheduledAtByMessageId.has(message.id) ? { scheduledAt: scheduledAtByMessageId.get(message.id) } : {}),fromContactName:(message.direction === "outbound" ? accountName : null) ??contactMap?.get(normalizeEmailAddress(message.fromAddr)) ??diff --git a/src/app/globals.css b/src/app/globals.cssindex 0fc318a..6aa2838 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -458,7 +458,8 @@ button {.dark .bg-\[\#f6f8fc\], .dark .bg-\[\#f7f9fc\] { background-color: #202124; }.dark .bg-\[\#f2f6fc\], .dark .bg-\[\#f1f4fa\], .dark .bg-\[\#f0f3f9\] { background-color: #303134; }.dark .bg-\[\#eef3fb\], .dark .bg-\[\#eaf1fb\], .dark .bg-\[\#e6ecf6\] { background-color: #383a3e; }-.dark .hover\:bg-\[\#f2f6fc\]:hover { background-color: #35363a; }+.dark .hover\:bg-\[\#f2f6fc\]:hover,+.dark .bg-\[\#f2f6fc\] { background-color: #35363a; }.dark .hover\:bg-\[\#e6ecf6\]:hover { background-color: #3c4043; }/* Soft shadows turn dark */.dark .shadow-neutral-200, .dark .shadow-neutral-300 { --tw-shadow-color: rgb(0 0 0 / 0.6); }diff --git a/src/components/components-nav-utils.ts b/src/components/components-nav-utils.tsindex 680f0f3..58d5cb0 100644--- a/src/components/components-nav-utils.ts+++ b/src/components/components-nav-utils.ts@@ -4,7 +4,7 @@ import type { MessageFolder } from "@/hooks/types";export async function preloadMailboxPage(href: string, mailboxId?: string) {const customFolderMatch = href.match(/^\/folders\/([^/]+)$/);const folder = (customFolderMatch ? "inbox" : href.slice(1)) as MessageFolder;- const supportedFolders: MessageFolder[] = ["inbox", "starred", "snoozed", "sent", "drafts", "archived", "spam", "trash"];+ const supportedFolders: MessageFolder[] = ["inbox", "starred", "snoozed", "sent", "scheduled", "drafts", "archived", "spam", "trash"];if (!supportedFolders.includes(folder)) return;const params = getMessageQueryParams(diff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsxindex 4c0434a..dd3f549 100644--- a/src/components/dashboard-nav.tsx+++ b/src/components/dashboard-nav.tsx@@ -8,6 +8,7 @@ import { useEffect, useState } from "react";import { usePathname } from "next/navigation";import {Archive,+ CalendarClock,Clock,FileText,Folder,@@ -61,6 +62,7 @@ const links = [{ href: "/starred", labelKey: "navigation.starred", icon: Star, preloadMessages: true },{ href: "/snoozed", labelKey: "navigation.snoozed", icon: Clock, preloadMessages: true },{ href: "/sent", labelKey: "navigation.sent", icon: Send, preloadMessages: true },+ { href: "/scheduled", labelKey: "navigation.scheduled", icon: CalendarClock, preloadMessages: true },{ href: "/drafts", labelKey: "navigation.drafts", icon: FileText, preloadMessages: true },{href: "/archived",@@ -108,7 +110,7 @@ export function DashboardNav({ className }: { className?: string }) {useState<FolderColor>(DEFAULT_FOLDER_COLOR);const [addingFolder, setAddingFolder] = useState(false);const [folderDialogOpen, setFolderDialogOpen] = useState(false);- const linksWithCounts: NavLink[] = links.map(({ labelKey, ...rest }): NavLink => {+ const linksWithCounts: NavLink[] = links.filter((link) => link.href !== "/scheduled" || counts.folders.scheduled.total > 0).map(({ labelKey, ...rest }): NavLink => {const link = { ...rest, label: t(labelKey) };if (link.href === "/inbox") {return { ...link, count: getFolderNavCount("inbox", counts.folders) };@@ -122,6 +124,9 @@ export function DashboardNav({ className }: { className?: string }) {if (link.href === "/sent") {return { ...link, count: getFolderNavCount("sent", counts.folders) };}+ if (link.href === "/scheduled") {+ return { ...link, count: counts.folders.scheduled.total };+ }if (link.href === "/drafts") {return { ...link, count: getFolderNavCount("drafts", counts.folders) };}diff --git a/src/components/messages/message-folder-configs.ts b/src/components/messages/message-folder-configs.tsindex 7307c21..d086f25 100644--- a/src/components/messages/message-folder-configs.ts+++ b/src/components/messages/message-folder-configs.ts@@ -1,4 +1,4 @@-import { Archive, Clock, MailOpen, Send, ShieldAlert, Star, Trash2 } from "lucide-react";+import { Archive, Clock, CalendarClock, MailOpen, Send, ShieldAlert, Star, Trash2 } from "lucide-react";import type { MessageFolderConfig } from "./types";export const inboxFolderConfig: MessageFolderConfig = {@@ -47,6 +47,17 @@ export const sentFolderConfig: MessageFolderConfig = {badgeVariant: "outline",};+export const scheduledFolderConfig: MessageFolderConfig = {+ folder: "scheduled",+ title: "Scheduled",+ titleKey: "navigation.scheduled",+ emptyTextKey: "folder.empty.scheduled",+ emptyText: "No scheduled emails",+ hrefPrefix: "/scheduled",+ icon: CalendarClock,+ badgeVariant: "outline",+};+export const archivedFolderConfig: MessageFolderConfig = {folder: "archived",title: "Archived",diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsxindex 91408a2..77568a2 100644--- a/src/components/messages/message-folder-page.tsx+++ b/src/components/messages/message-folder-page.tsx@@ -11,6 +11,7 @@ import { Tooltip } from "@/components/ui/tooltip";import { useMailSearch } from "@/components/mail-search/mail-search-context";import { useSelectedMailbox } from "@/components/mailbox-provider";import { usePageLoading } from "@/components/page-loading";+import { formatScheduledSendTime } from "./scheduled-send-utils";import { useIsMobile } from "@/components/sidebar-mobile-utils";import { useMessageCounts } from "@/hooks/use-message-counts";import { useMessages } from "@/hooks/use-messages";@@ -149,7 +150,7 @@ function MessageListRow({)}</span><span className={clsx(unread ?"font-medium":"text-neutral-400","shrink-0 text-[11px]")}>- {formatMessageListTimestamp(message.createdAt)}+ {message.scheduledAt ? formatScheduledSendTime(message.scheduledAt, t) : formatMessageListTimestamp(message.createdAt)}</span></span><span@@ -186,7 +187,7 @@ function MessageListRow({}const className =- `group relative grid min-h-12 w-full grid-cols-[24px_32px_minmax(160px,260px)_1fr_auto] items-center gap-3 px-6 text-left text-sm hover:z-10 hover:bg-[#f2f6fc] hover:shadow-sm ${active || selected ? "bg-blue-50" : ""+ `group relative grid min-h-12 w-full grid-cols-[24px_32px_minmax(160px,80px)_1fr_auto] items-center gap-3 px-6 text-left text-sm hover:z-10 hover:bg-[#f2f6fc] hover:shadow-sm ${active || selected ? "bg-blue-50" : ""} ${draggable ? "cursor-grab active:cursor-grabbing" : ""}`;const content = (<>@@ -228,7 +229,7 @@ function MessageListRow({className={`min-w-[96px] whitespace-nowrap text-right text-xs group-hover:opacity-0 ${unread ? "font-semibold text-neutral-800" : "text-neutral-500"}`}>- {formatMessageListTimestamp(message.createdAt)}+ {message.scheduledAt ? formatScheduledSendTime(message.scheduledAt, t) : formatMessageListTimestamp(message.createdAt)}</time></>);diff --git a/src/components/messages/message-list-row-actions.tsx b/src/components/messages/message-list-row-actions.tsxindex c226512..2dc88d2 100644--- a/src/components/messages/message-list-row-actions.tsx+++ b/src/components/messages/message-list-row-actions.tsx@@ -36,7 +36,7 @@ export function MessageListRowActions({ message, onAction }: MessageListRowActioreturn (<>- <div className="pointer-events-none absolute right-6 top-1/2 z-10 flex -translate-y-1/2 items-center gap-1 pl-3 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 bg-[#f2f6fc]">+ <div className="pointer-events-none absolute right-6 top-1/2 z-10 flex -translate-y-1/2 items-center gap-1 pl-3 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 bg-[#f2f6fc] dark:bg-[#f2f6fc]"><Tooltip label={t("common.archive")}><Button type="button" variant="ghost" size="sm" onClick={() => void onAction("archive")} aria-label={t("common.archive")}><Archive className="h-4 w-4" />diff --git a/src/components/messages/scheduled-send-banner.tsx b/src/components/messages/scheduled-send-banner.tsxnew file mode 100644index 0000000..63a53cf--- /dev/null+++ b/src/components/messages/scheduled-send-banner.tsx@@ -0,0 +1,45 @@+"use client";++import { useState } from "react";+import { useRouter } from "next/navigation";+import { CalendarClock } from "lucide-react";+import { useLanguage } from "@/components/language-provider";+import { authFetch } from "@/lib/auth/client";+import { clearMessageDetailCache } from "@/lib/messages/detail-cache";+import { formatScheduledSendTime } from "./scheduled-send-utils";++/** Shown above a scheduled message; cancelling returns it to Drafts. */+export function ScheduledSendBanner({ messageId, scheduledAt }: { messageId: string; scheduledAt: string }) {+ const { t } = useLanguage();+ const router = useRouter();+ const [cancelling, setCancelling] = useState(false);++ async function cancelSend() {+ setCancelling(true);+ try {+ const response = await authFetch(`/api/messages/${messageId}/cancel-schedule`, { method: "POST" });+ if (!response.ok) throw new Error("Unable to cancel");+ clearMessageDetailCache();+ window.dispatchEvent(new Event("mailflare:messages-changed"));+ router.push("/drafts");+ } catch {+ window.alert(t("schedule.cancelFailed"));+ setCancelling(false);+ }+ }++ return (+ <div className="mx-6 mb-2 flex items-center gap-3 rounded-lg bg-neutral-100 px-4 py-3 text-sm text-neutral-600">+ <CalendarClock className="h-5 w-5 shrink-0 text-neutral-500" />+ <span className="min-w-0 flex-1">{t("schedule.sendScheduledFor", { when: formatScheduledSendTime(scheduledAt, t) })}</span>+ <button+ type="button"+ onClick={() => void cancelSend()}+ disabled={cancelling}+ className="shrink-0 font-medium text-blue-600 hover:underline disabled:opacity-50"+ >+ {t("schedule.cancelSend")}+ </button>+ </div>+ );+}diff --git a/src/components/messages/scheduled-send-utils.ts b/src/components/messages/scheduled-send-utils.tsnew file mode 100644index 0000000..9f2670b--- /dev/null+++ b/src/components/messages/scheduled-send-utils.ts@@ -0,0 +1,22 @@+import { formatUserDate, getUserTimeZone, zonedDateFields } from "@/lib/time/utils";+import type { Translator } from "@/lib/i18n/utils";++const DAY_MS = 24 * 60 * 60 * 1000;++/** "Today, 8:00 AM", "Tomorrow, 8:00 AM", "Friday, 8:00 AM" within a week, otherwise the date. */+export function formatScheduledSendTime(value: Date | string, t: Translator, now = new Date()): string {+ const date = new Date(value);+ const zone = getUserTimeZone();+ const startOfDay = (input: Date) => {+ const fields = zonedDateFields(input, zone);+ fields.setUTCHours(0, 0, 0, 0);+ return fields.getTime();+ };+ const days = Math.round((startOfDay(date) - startOfDay(now)) / DAY_MS);+ const time = formatUserDate(date, { hour: "numeric", minute: "2-digit" });+ if (days === 0) return t("schedule.todayAt", { time });+ if (days === 1) return t("schedule.tomorrowAt", { time });+ if (days >= 2 && days <= 7) return formatUserDate(date, { weekday: "long", hour: "numeric", minute: "2-digit" });+ const sameYear = zonedDateFields(date, zone).getUTCFullYear() === zonedDateFields(now, zone).getUTCFullYear();+ return formatUserDate(date, { month: "short", day: "numeric", ...(sameYear ? {} : { year: "numeric" }), hour: "numeric", minute: "2-digit" });+}diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.tsindex c5e2b22..8d37187 100644--- a/src/components/messages/utils.ts+++ b/src/components/messages/utils.ts@@ -18,7 +18,7 @@ export function getMessageParty(t: Translator = defaultTranslator,) {if (folder === "drafts") return t("list.draft");- if (folder === "sent") return formatRecipientSummary(message.toAddr, message.toContactName, t);+ if (folder === "sent" || folder === "scheduled") return formatRecipientSummary(message.toAddr, message.toContactName, t);if (message.direction === "outbound" && currentAccountName) return currentAccountName;return message.fromContactName ?? (message.fromAddr ? getEmailDisplayName(message.fromAddr) : t("list.unknownSender"));}diff --git a/src/hooks/types.d.ts b/src/hooks/types.d.tsindex 854f5af..e29e681 100644--- a/src/hooks/types.d.ts+++ b/src/hooks/types.d.ts@@ -1,6 +1,6 @@export type MessageStatus = "received" | "sent" | "draft" | "queued" | "failed" | "archived" | "trash" | "spam";-export type MessageFolder = "inbox" | "starred" | "snoozed" | "sent" | "drafts" | "archived" | "trash" | "spam";+export type MessageFolder = "inbox" | "starred" | "snoozed" | "sent" | "scheduled" | "drafts" | "archived" | "trash" | "spam";export type MessageDirection = "inbound" | "outbound";@@ -27,6 +27,8 @@ export type Message = {read: boolean;starred: boolean;snoozedUntil?: string | null;+ /** When a scheduled send will go out; set on rows in the Scheduled list. */+ scheduledAt?: string | null;threadId: string | null;inReplyTo?: string | null;references?: string | null;diff --git a/src/hooks/use-message-counts.ts b/src/hooks/use-message-counts.tsindex ef28244..3d58a83 100644--- a/src/hooks/use-message-counts.ts+++ b/src/hooks/use-message-counts.ts@@ -10,6 +10,7 @@ const emptyCounts: MessageCounts = {starred: { total: 0, unread: 0 },snoozed: { total: 0, unread: 0 },sent: { total: 0, unread: 0 },+ scheduled: { total: 0, unread: 0 },drafts: { total: 0, unread: 0 },archived: { total: 0, unread: 0 },spam: { total: 0, unread: 0 },diff --git a/src/hooks/utils.ts b/src/hooks/utils.tsindex 9bc18b5..cc26435 100644--- a/src/hooks/utils.ts+++ b/src/hooks/utils.ts@@ -40,6 +40,11 @@ export function getMessageQueryParams(params.set("status", "sent");}+ if (folder === "scheduled") {+ params.set("direction", "outbound");+ params.set("scheduled", "true");+ }+if (folder === "drafts") {params.set("direction", "outbound");params.set("status", "draft");diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.tsindex 43cabd5..93c1f85 100644--- a/src/lib/email/inbound.ts+++ b/src/lib/email/inbound.ts@@ -1,6 +1,6 @@-import { and, eq } from "drizzle-orm";+import { and, eq, isNotNull } from "drizzle-orm";import { getDb } from "@/db";-import { messages, users } from "@/db/schema";+import { messages, outboundJobs, users } from "@/db/schema";import { newId } from "@/lib/ids";import { buildSnippet, parseRawMime } from "@/lib/email/parse";import { resolveInboundAddress, resolveInboxRuleDestination } from "@/lib/email/routing";@@ -268,7 +268,20 @@ export async function getMessageWithBody(env: CloudflareEnv, userId: string, mesconst contactNames = await getMessageContactNames(env, userId, message.fromAddr, message.toAddr);const attachments = await listMessageAttachments(env, messageId);const unsubscribeUrl = await getUnsubscribeUrlFromRawR2Key(env, message.rawR2Key);- return { message: { ...message, ...contactNames }, body: message, attachments, unsubscribeUrl };+ const [scheduledJob] = message.direction === "outbound" && message.status === "queued"+ ? await db+ .select({ scheduledAt: outboundJobs.scheduledAt })+ .from(outboundJobs)+ .where(and(eq(outboundJobs.messageId, messageId), eq(outboundJobs.status, "queued"), isNotNull(outboundJobs.scheduledAt)))+ .limit(1)+ : [];+ return {+ message: { ...message, ...contactNames },+ body: message,+ attachments,+ unsubscribeUrl,+ scheduledAt: scheduledJob?.scheduledAt?.toISOString() ?? null,+ };}export async function getMessageWithBodyForUser(env: CloudflareEnv, user: SessionUser, messageId: string) {diff --git a/src/lib/email/scheduled.ts b/src/lib/email/scheduled.tsnew file mode 100644index 0000000..b93dc97--- /dev/null+++ b/src/lib/email/scheduled.ts@@ -0,0 +1,18 @@+import { and, eq, exists, isNotNull } from "drizzle-orm";+import type { SQL } from "drizzle-orm";+import { getDb } from "@/db";+import { messages, outboundJobs } from "@/db/schema";++/** Matches outbound messages whose send job is still waiting for its scheduled time. */+export function scheduledMessageCondition(db: ReturnType<typeof getDb>): SQL {+ return and(+ eq(messages.direction, "outbound"),+ eq(messages.status, "queued"),+ exists(+ db+ .select({ id: outboundJobs.id })+ .from(outboundJobs)+ .where(and(eq(outboundJobs.messageId, messages.id), eq(outboundJobs.status, "queued"), isNotNull(outboundJobs.scheduledAt))),+ ),+ )!;+}diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.jsonindex dab37f4..d94a2d8 100644--- a/src/lib/i18n/en.json+++ b/src/lib/i18n/en.json@@ -4,6 +4,7 @@"navigation.starred": "Starred","navigation.snoozed": "Snoozed","navigation.sent": "Sent",+ "navigation.scheduled": "Scheduled","navigation.drafts": "Drafts","navigation.archived": "Archived","navigation.spam": "Spam",@@ -130,6 +131,7 @@"shortcut.reportSpam": "Report Spam","shortcut.backToList": "Back to List","folder.empty.inbox": "No emails",+ "folder.empty.scheduled": "No scheduled emails","folder.empty.starred": "No starred emails","folder.empty.snoozed": "No snoozed emails","folder.empty.archived": "No archived emails",@@ -229,6 +231,11 @@"editor.insertLink": "Insert link","editor.clearFormatting": "Clear formatting","editor.apply": "Apply",+ "schedule.todayAt": "Today, {time}",+ "schedule.tomorrowAt": "Tomorrow, {time}",+ "schedule.sendScheduledFor": "Send scheduled for {when}",+ "schedule.cancelSend": "Cancel send",+ "schedule.cancelFailed": "Unable to cancel the scheduled send.","schedule.optionsLabel": "Schedule send options","schedule.heading": "Schedule","schedule.clear": "Clear schedule",diff --git a/src/lib/messages/detail-cache-types.d.ts b/src/lib/messages/detail-cache-types.d.tsindex e286540..3d8e710 100644--- a/src/lib/messages/detail-cache-types.d.ts+++ b/src/lib/messages/detail-cache-types.d.ts@@ -13,5 +13,6 @@ export type CachedMessageDetail = {type: string;}>;unsubscribeUrl?: string | null;+ scheduledAt?: string | null;error?: string;};