Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(email-service): Hexify create draft endpoint (#1757)
Evan Hutnike9518e8c54db
diff --git a/js/app/justfile b/js/app/justfileindex b249bb33e9..6f6b68bc10 100644--- a/js/app/justfile+++ b/js/app/justfile@@ -15,6 +15,9 @@ local-dss:local-search:cd packages/app && VITE_LOCAL_SERVERS='search-service' bun run --bun dev+local-email:+ cd packages/app && VITE_LOCAL_SERVERS='email-service' bun run --bun dev+build-dev:cd packages/app && MODE=development NODE_ENV=production bun run --bun builddiff --git a/js/app/packages/block-email/component/BaseInput.tsx b/js/app/packages/block-email/component/BaseInput.tsxindex d43dc93e7d..f31e4d1a9a 100644--- a/js/app/packages/block-email/component/BaseInput.tsx+++ b/js/app/packages/block-email/component/BaseInput.tsx@@ -615,27 +615,6 @@ export function BaseInput(props: {return;}- let linkId: string | undefined = currentThread?.link_id;- if (newMessage || !linkId) {- if (emailLinksQuery.isPending) {- return;- }-- if (emailLinksQuery.isError) {- logger.error(- new Error('Failed to save email draft: could not load email links')- );- return;- }-- const linksData = emailLinksQuery.data;- if (!linksData || linksData.links.length === 0) {- logger.error(new Error('Failed to save email draft: no links found'));- return;- }- linkId = linksData.links[0].id;- }-const existingDraft = savedDraftId() !== undefined;// If there's an existing draft, we should send the sendTime so that the send time@@ -646,7 +625,6 @@ export function BaseInput(props: {draft: {...draftToSave,db_id: savedDraftId(),- link_id: linkId!,provider_thread_id: currentThread?.provider_id,thread_db_id: currentThread?.db_id,},diff --git a/js/app/packages/block-email/component/Compose.tsx b/js/app/packages/block-email/component/Compose.tsxindex 46cccab551..4adea122a7 100644--- a/js/app/packages/block-email/component/Compose.tsx+++ b/js/app/packages/block-email/component/Compose.tsx@@ -257,14 +257,6 @@ export function EmailCompose(props: EmailComposeProps) {return;}- const linkID = link()?.id;- if (!linkID || hasLinkError()) {- logger.error(- new Error('Failed to save email draft: could not load email links')- );- return;- }-const existingDraft = currentDraftID() !== undefined;// If there's an existing draft, we should send the sendTime so that the send time@@ -275,7 +267,6 @@ export function EmailCompose(props: EmailComposeProps) {draft: {...draftToSave,db_id: currentDraftID(),- link_id: linkID,},sendTime,});diff --git a/js/app/packages/block-email/signal/emailDraft.ts b/js/app/packages/block-email/signal/emailDraft.tsindex 215101b840..8acc628c6f 100644--- a/js/app/packages/block-email/signal/emailDraft.ts+++ b/js/app/packages/block-email/signal/emailDraft.ts@@ -1,13 +1,15 @@import { isErr } from '@core/util/maybeResult';import { logger } from '@observability/logger';import { emailClient } from '@service-email/client';-import type { MessageToSendDbId } from '@service-email/generated/schemas';-import type { MessageToSend } from '@service-email/generated/schemas/messageToSend';+import type {+ ApiDraftInput,+ ApiDraftOutputDbId,+} from '@service-email/generated/schemas';export async function saveEmailDraft(- draft: MessageToSend,+ draft: ApiDraftInput,sendTime?: Date | null-): Promise<MessageToSendDbId | false> {+): Promise<ApiDraftOutputDbId | false> {const createRes = await emailClient.createDraft({draft,send_time: sendTime?.toISOString() ?? null,diff --git a/js/app/packages/core/constant/servers.ts b/js/app/packages/core/constant/servers.tsindex a26198368e..6ac4f9c443 100644--- a/js/app/packages/core/constant/servers.ts+++ b/js/app/packages/core/constant/servers.ts@@ -9,7 +9,7 @@ const serverHostLocal: Servers = {'static-file': 'http://localhost:8100','unfurl-service': 'http://localhost:8095',contacts: 'http://localhost:8083',- 'email-service': 'http://localhost:8087',+ 'email-service': 'http://localhost:8094','image-proxy-service': 'http://localhost:8097',} as const;diff --git a/js/app/packages/queries/email/draft.ts b/js/app/packages/queries/email/draft.tsindex dfe6c18452..74c833ef00 100644--- a/js/app/packages/queries/email/draft.ts+++ b/js/app/packages/queries/email/draft.ts@@ -2,8 +2,8 @@ import { toast } from '@core/component/Toast/Toast';import { throwOnErr } from '@core/util/maybeResult';import { emailClient } from '@service-email/client';import type {+ ApiDraftInput,CreateDraftResponse,- MessageToSend,} from '@service-email/generated/schemas';import { useMutation } from '@tanstack/solid-query';import { queryClient } from '../client';@@ -12,7 +12,7 @@ import { emailKeys } from './keys';import { invalidateSoupEntity, invalidateAllSoup } from '@queries/soup/cache';type CreateDraftParams = {- draft: MessageToSend;+ draft: ApiDraftInput;sendTime?: Date | null;};diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.tsindex 4836f29e52..8af0649c33 100644--- a/js/app/packages/service-clients/service-email/generated/client.ts+++ b/js/app/packages/service-clients/service-email/generated/client.ts@@ -446,9 +446,9 @@ export type createDraftResponse400 = {status: 400;};-export type createDraftResponse401 = {+export type createDraftResponse404 = {data: ErrorResponse;- status: 401;+ status: 404;};export type createDraftResponse500 = {@@ -461,7 +461,7 @@ export type createDraftResponseSuccess = createDraftResponse201 & {};export type createDraftResponseError = (| createDraftResponse400- | createDraftResponse401+ | createDraftResponse404| createDraftResponse500) & {headers: Headers;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfo.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfo.tsnew file mode 100644index 0000000000..d66bf4f213--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfo.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftContactInfoName } from './apiDraftContactInfoName';+import type { ApiDraftContactInfoPhotoUrl } from './apiDraftContactInfoPhotoUrl';++/**+ * Contact info for draft request/response (backward-compatible with MessageToSend shape).+ */+export interface ApiDraftContactInfo {+ /** Email address. */+ email: string;+ /** Display name. */+ name?: ApiDraftContactInfoName;+ /** Profile photo URL. */+ photo_url?: ApiDraftContactInfoPhotoUrl;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfoName.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfoName.tsnew file mode 100644index 0000000000..63b0b770a6--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfoName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display name.+ */+export type ApiDraftContactInfoName = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfoPhotoUrl.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfoPhotoUrl.tsnew file mode 100644index 0000000000..dc8a732928--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftContactInfoPhotoUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Profile photo URL.+ */+export type ApiDraftContactInfoPhotoUrl = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInput.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInput.tsnew file mode 100644index 0000000000..0701fed07e--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInput.ts@@ -0,0 +1,49 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftInputBcc } from './apiDraftInputBcc';+import type { ApiDraftInputBodyHtml } from './apiDraftInputBodyHtml';+import type { ApiDraftInputBodyMacro } from './apiDraftInputBodyMacro';+import type { ApiDraftInputBodyText } from './apiDraftInputBodyText';+import type { ApiDraftInputCc } from './apiDraftInputCc';+import type { ApiDraftInputDbId } from './apiDraftInputDbId';+import type { ApiDraftInputHeadersJson } from './apiDraftInputHeadersJson';+import type { ApiDraftInputProviderId } from './apiDraftInputProviderId';+import type { ApiDraftInputProviderThreadId } from './apiDraftInputProviderThreadId';+import type { ApiDraftInputReplyingToId } from './apiDraftInputReplyingToId';+import type { ApiDraftInputThreadDbId } from './apiDraftInputThreadDbId';+import type { ApiDraftInputTo } from './apiDraftInputTo';++/**+ * The draft input matching the current `MessageToSend` JSON shape for backward compat.+ */+export interface ApiDraftInput {+ /** Bcc recipients. */+ bcc?: ApiDraftInputBcc;+ /** HTML body (base64 URL_SAFE_NO_PAD encoded). */+ body_html?: ApiDraftInputBodyHtml;+ /** Macro body format. */+ body_macro?: ApiDraftInputBodyMacro;+ /** Plain text body. */+ body_text?: ApiDraftInputBodyText;+ /** Cc recipients. */+ cc?: ApiDraftInputCc;+ /** Existing message DB ID (for updating an existing draft). */+ db_id?: ApiDraftInputDbId;+ headers_json?: ApiDraftInputHeadersJson;+ /** Provider message ID. */+ provider_id?: ApiDraftInputProviderId;+ /** Provider thread ID. */+ provider_thread_id?: ApiDraftInputProviderThreadId;+ /** ID of the message this draft is replying to. */+ replying_to_id?: ApiDraftInputReplyingToId;+ /** Subject line. */+ subject: string;+ /** Thread DB ID. */+ thread_db_id?: ApiDraftInputThreadDbId;+ /** To recipients. */+ to?: ApiDraftInputTo;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBcc.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBcc.tsnew file mode 100644index 0000000000..b9e56fb6b2--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBcc.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftContactInfo } from './apiDraftContactInfo';++/**+ * Bcc recipients.+ */+export type ApiDraftInputBcc = ApiDraftContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyHtml.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyHtml.tsnew file mode 100644index 0000000000..d635e9be94--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyHtml.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * HTML body (base64 URL_SAFE_NO_PAD encoded).+ */+export type ApiDraftInputBodyHtml = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyMacro.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyMacro.tsnew file mode 100644index 0000000000..c0b5bd545d--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyMacro.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Macro body format.+ */+export type ApiDraftInputBodyMacro = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyText.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyText.tsnew file mode 100644index 0000000000..223d1cedb1--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputBodyText.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Plain text body.+ */+export type ApiDraftInputBodyText = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputCc.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputCc.tsnew file mode 100644index 0000000000..33f5881125--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputCc.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftContactInfo } from './apiDraftContactInfo';++/**+ * Cc recipients.+ */+export type ApiDraftInputCc = ApiDraftContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputDbId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputDbId.tsnew file mode 100644index 0000000000..f05e083acf--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputDbId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Existing message DB ID (for updating an existing draft).+ */+export type ApiDraftInputDbId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputHeadersJson.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputHeadersJson.tsnew file mode 100644index 0000000000..c43a92fe12--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputHeadersJson.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { Value } from './value';++export type ApiDraftInputHeadersJson = null | Value;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputProviderId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputProviderId.tsnew file mode 100644index 0000000000..a7f8ef8bbd--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputProviderId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider message ID.+ */+export type ApiDraftInputProviderId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputProviderThreadId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputProviderThreadId.tsnew file mode 100644index 0000000000..f7dbb6cf98--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputProviderThreadId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider thread ID.+ */+export type ApiDraftInputProviderThreadId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputReplyingToId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputReplyingToId.tsnew file mode 100644index 0000000000..11645d13d9--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputReplyingToId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * ID of the message this draft is replying to.+ */+export type ApiDraftInputReplyingToId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputThreadDbId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputThreadDbId.tsnew file mode 100644index 0000000000..935b94554e--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputThreadDbId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Thread DB ID.+ */+export type ApiDraftInputThreadDbId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputTo.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputTo.tsnew file mode 100644index 0000000000..1675c90e83--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftInputTo.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftContactInfo } from './apiDraftContactInfo';++/**+ * To recipients.+ */+export type ApiDraftInputTo = ApiDraftContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutput.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutput.tsnew file mode 100644index 0000000000..6fb0c71140--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutput.ts@@ -0,0 +1,54 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftOutputBcc } from './apiDraftOutputBcc';+import type { ApiDraftOutputBodyHtml } from './apiDraftOutputBodyHtml';+import type { ApiDraftOutputBodyMacro } from './apiDraftOutputBodyMacro';+import type { ApiDraftOutputBodyText } from './apiDraftOutputBodyText';+import type { ApiDraftOutputCc } from './apiDraftOutputCc';+import type { ApiDraftOutputDbId } from './apiDraftOutputDbId';+import type { ApiDraftOutputHeadersJson } from './apiDraftOutputHeadersJson';+import type { ApiDraftOutputProviderId } from './apiDraftOutputProviderId';+import type { ApiDraftOutputProviderThreadId } from './apiDraftOutputProviderThreadId';+import type { ApiDraftOutputReplyingToId } from './apiDraftOutputReplyingToId';+import type { ApiDraftOutputSendTime } from './apiDraftOutputSendTime';+import type { ApiDraftOutputThreadDbId } from './apiDraftOutputThreadDbId';+import type { ApiDraftOutputTo } from './apiDraftOutputTo';++/**+ * The draft output matching the current `MessageToSend` JSON shape for backward compat.+ */+export interface ApiDraftOutput {+ /** Bcc recipients. */+ bcc?: ApiDraftOutputBcc;+ /** HTML body (decoded). */+ body_html?: ApiDraftOutputBodyHtml;+ /** Macro body. */+ body_macro?: ApiDraftOutputBodyMacro;+ /** Plain text body. */+ body_text?: ApiDraftOutputBodyText;+ /** Cc recipients. */+ cc?: ApiDraftOutputCc;+ /** Message DB ID. */+ db_id?: ApiDraftOutputDbId;+ headers_json?: ApiDraftOutputHeadersJson;+ /** Link ID. */+ link_id: string;+ /** Provider message ID. */+ provider_id?: ApiDraftOutputProviderId;+ /** Provider thread ID. */+ provider_thread_id?: ApiDraftOutputProviderThreadId;+ /** ID of the message this draft is replying to. */+ replying_to_id?: ApiDraftOutputReplyingToId;+ /** Send time. */+ send_time?: ApiDraftOutputSendTime;+ /** Subject line. */+ subject: string;+ /** Thread DB ID. */+ thread_db_id?: ApiDraftOutputThreadDbId;+ /** To recipients. */+ to?: ApiDraftOutputTo;+}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBcc.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBcc.tsnew file mode 100644index 0000000000..cdde8918b3--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBcc.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftContactInfo } from './apiDraftContactInfo';++/**+ * Bcc recipients.+ */+export type ApiDraftOutputBcc = ApiDraftContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyHtml.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyHtml.tsnew file mode 100644index 0000000000..6caf8df1c2--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyHtml.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * HTML body (decoded).+ */+export type ApiDraftOutputBodyHtml = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyMacro.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyMacro.tsnew file mode 100644index 0000000000..a967dea96d--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyMacro.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Macro body.+ */+export type ApiDraftOutputBodyMacro = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyText.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyText.tsnew file mode 100644index 0000000000..a03860ba95--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputBodyText.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Plain text body.+ */+export type ApiDraftOutputBodyText = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputCc.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputCc.tsnew file mode 100644index 0000000000..dace725337--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputCc.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftContactInfo } from './apiDraftContactInfo';++/**+ * Cc recipients.+ */+export type ApiDraftOutputCc = ApiDraftContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputDbId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputDbId.tsnew file mode 100644index 0000000000..ef5090d2af--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputDbId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Message DB ID.+ */+export type ApiDraftOutputDbId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputHeadersJson.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputHeadersJson.tsnew file mode 100644index 0000000000..105ee7ea73--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputHeadersJson.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { Value } from './value';++export type ApiDraftOutputHeadersJson = null | Value;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputProviderId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputProviderId.tsnew file mode 100644index 0000000000..01885b5d54--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputProviderId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider message ID.+ */+export type ApiDraftOutputProviderId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputProviderThreadId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputProviderThreadId.tsnew file mode 100644index 0000000000..2755b346fc--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputProviderThreadId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Provider thread ID.+ */+export type ApiDraftOutputProviderThreadId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputReplyingToId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputReplyingToId.tsnew file mode 100644index 0000000000..a2e6c13ffc--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputReplyingToId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * ID of the message this draft is replying to.+ */+export type ApiDraftOutputReplyingToId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputSendTime.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputSendTime.tsnew file mode 100644index 0000000000..bdcfa450af--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputSendTime.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Send time.+ */+export type ApiDraftOutputSendTime = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputThreadDbId.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputThreadDbId.tsnew file mode 100644index 0000000000..002258d809--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputThreadDbId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Thread DB ID.+ */+export type ApiDraftOutputThreadDbId = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputTo.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputTo.tsnew file mode 100644index 0000000000..4a7351e85c--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiDraftOutputTo.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiDraftContactInfo } from './apiDraftContactInfo';++/**+ * To recipients.+ */+export type ApiDraftOutputTo = ApiDraftContactInfo[] | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequest.ts b/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequest.tsindex acef742563..347e265569 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequest.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequest.ts@@ -4,14 +4,15 @@* email_service* OpenAPI spec version: 0.1.0*/-+import type { ApiDraftInput } from './apiDraftInput';import type { CreateDraftRequestSendTime } from './createDraftRequestSendTime';-import type { MessageToSend } from './messageToSend';/**- * The request passed to send a message+ * Request body for creating a draft.*/export interface CreateDraftRequest {- draft: MessageToSend;+ /** The draft content. */+ draft: ApiDraftInput;+ /** Scheduled send time. */send_time?: CreateDraftRequestSendTime;}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequestSendTime.ts b/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequestSendTime.tsindex 961611b1d5..420013be27 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequestSendTime.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/createDraftRequestSendTime.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/+/**+ * Scheduled send time.+ */export type CreateDraftRequestSendTime = string | null;diff --git a/js/app/packages/service-clients/service-email/generated/schemas/createDraftResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/createDraftResponse.tsindex ebde2179de..65feb6d1d9 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/createDraftResponse.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/createDraftResponse.ts@@ -4,8 +4,12 @@* email_service* OpenAPI spec version: 0.1.0*/-import type { MessageToSend } from './messageToSend';+import type { ApiDraftOutput } from './apiDraftOutput';+/**+ * Response body for creating a draft.+ */export interface CreateDraftResponse {- draft: MessageToSend;+ /** The created draft. */+ draft: ApiDraftOutput;}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.tsindex 49ab056bb1..e6cae642b7 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts@@ -32,6 +32,36 @@ export * from './apiContactInfoName';export * from './apiContactInfoPhotoUrl';export * from './apiContactName';export * from './apiContactSfsPhotoUrl';+export * from './apiDraftContactInfo';+export * from './apiDraftContactInfoName';+export * from './apiDraftContactInfoPhotoUrl';+export * from './apiDraftInput';+export * from './apiDraftInputBcc';+export * from './apiDraftInputBodyHtml';+export * from './apiDraftInputBodyMacro';+export * from './apiDraftInputBodyText';+export * from './apiDraftInputCc';+export * from './apiDraftInputDbId';+export * from './apiDraftInputHeadersJson';+export * from './apiDraftInputProviderId';+export * from './apiDraftInputProviderThreadId';+export * from './apiDraftInputReplyingToId';+export * from './apiDraftInputThreadDbId';+export * from './apiDraftInputTo';+export * from './apiDraftOutput';+export * from './apiDraftOutputBcc';+export * from './apiDraftOutputBodyHtml';+export * from './apiDraftOutputBodyMacro';+export * from './apiDraftOutputBodyText';+export * from './apiDraftOutputCc';+export * from './apiDraftOutputDbId';+export * from './apiDraftOutputHeadersJson';+export * from './apiDraftOutputProviderId';+export * from './apiDraftOutputProviderThreadId';+export * from './apiDraftOutputReplyingToId';+export * from './apiDraftOutputSendTime';+export * from './apiDraftOutputThreadDbId';+export * from './apiDraftOutputTo';export * from './apiLabel';export * from './apiLabelListVisibility';export * from './apiLabelType';diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex 2abf3a1c01..5073813633 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -406,7 +406,7 @@}}},- "401": {+ "404": {"description": "","content": {"application/json": {@@ -2389,6 +2389,191 @@}}},+ "ApiDraftContactInfo": {+ "type": "object",+ "description": "Contact info for draft request/response (backward-compatible with MessageToSend shape).",+ "required": ["email"],+ "properties": {+ "email": {+ "type": "string",+ "description": "Email address."+ },+ "name": {+ "type": ["string", "null"],+ "description": "Display name."+ },+ "photo_url": {+ "type": ["string", "null"],+ "description": "Profile photo URL."+ }+ }+ },+ "ApiDraftInput": {+ "type": "object",+ "description": "The draft input matching the current `MessageToSend` JSON shape for backward compat.",+ "required": ["subject"],+ "properties": {+ "bcc": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ApiDraftContactInfo"+ },+ "description": "Bcc recipients."+ },+ "body_html": {+ "type": ["string", "null"],+ "description": "HTML body (base64 URL_SAFE_NO_PAD encoded)."+ },+ "body_macro": {+ "type": ["string", "null"],+ "description": "Macro body format."+ },+ "body_text": {+ "type": ["string", "null"],+ "description": "Plain text body."+ },+ "cc": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ApiDraftContactInfo"+ },+ "description": "Cc recipients."+ },+ "db_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Existing message DB ID (for updating an existing draft)."+ },+ "headers_json": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/Value",+ "description": "Headers JSON."+ }+ ]+ },+ "provider_id": {+ "type": ["string", "null"],+ "description": "Provider message ID."+ },+ "provider_thread_id": {+ "type": ["string", "null"],+ "description": "Provider thread ID."+ },+ "replying_to_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "ID of the message this draft is replying to."+ },+ "subject": {+ "type": "string",+ "description": "Subject line."+ },+ "thread_db_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Thread DB ID."+ },+ "to": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ApiDraftContactInfo"+ },+ "description": "To recipients."+ }+ }+ },+ "ApiDraftOutput": {+ "type": "object",+ "description": "The draft output matching the current `MessageToSend` JSON shape for backward compat.",+ "required": ["link_id", "subject"],+ "properties": {+ "bcc": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ApiDraftContactInfo"+ },+ "description": "Bcc recipients."+ },+ "body_html": {+ "type": ["string", "null"],+ "description": "HTML body (decoded)."+ },+ "body_macro": {+ "type": ["string", "null"],+ "description": "Macro body."+ },+ "body_text": {+ "type": ["string", "null"],+ "description": "Plain text body."+ },+ "cc": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ApiDraftContactInfo"+ },+ "description": "Cc recipients."+ },+ "db_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Message DB ID."+ },+ "headers_json": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/Value",+ "description": "Headers JSON."+ }+ ]+ },+ "link_id": {+ "type": "string",+ "format": "uuid",+ "description": "Link ID."+ },+ "provider_id": {+ "type": ["string", "null"],+ "description": "Provider message ID."+ },+ "provider_thread_id": {+ "type": ["string", "null"],+ "description": "Provider thread ID."+ },+ "replying_to_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "ID of the message this draft is replying to."+ },+ "send_time": {+ "type": ["string", "null"],+ "format": "date-time",+ "description": "Send time."+ },+ "subject": {+ "type": "string",+ "description": "Subject line."+ },+ "thread_db_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Thread DB ID."+ },+ "to": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ApiDraftContactInfo"+ },+ "description": "To recipients."+ }+ }+ },"ApiLabel": {"type": "object","required": [@@ -3168,24 +3353,28 @@},"CreateDraftRequest": {"type": "object",- "description": "The request passed to send a message",+ "description": "Request body for creating a draft.","required": ["draft"],"properties": {"draft": {- "$ref": "#/components/schemas/MessageToSend"+ "$ref": "#/components/schemas/ApiDraftInput",+ "description": "The draft content."},"send_time": {"type": ["string", "null"],- "format": "date-time"+ "format": "date-time",+ "description": "Scheduled send time."}}},"CreateDraftResponse": {"type": "object",+ "description": "Response body for creating a draft.","required": ["draft"],"properties": {"draft": {- "$ref": "#/components/schemas/MessageToSend"+ "$ref": "#/components/schemas/ApiDraftOutput",+ "description": "The created draft."}}},diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 63c1af17e5..ef801984dd 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3298,6 +3298,7 @@ dependencies = ["anyhow","axum","axum-extra",+ "base64 0.22.1","chrono","doppleganger","either",@@ -3309,6 +3310,7 @@ dependencies = ["item_filters","macro_db_migrator","macro_user_id",+ "macro_uuid","model-entity","model-error-response","model_user",diff --git a/rust/cloud-storage/email/.sqlx/query-2e5e76597cf6fe734978fef0762c7c86aeba3b076e8684a85696045ed3a4636e.json b/rust/cloud-storage/email/.sqlx/query-2e5e76597cf6fe734978fef0762c7c86aeba3b076e8684a85696045ed3a4636e.jsonnew file mode 100644index 0000000000..7c3172354d--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-2e5e76597cf6fe734978fef0762c7c86aeba3b076e8684a85696045ed3a4636e.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM email_scheduled_messages\n WHERE link_id = $1 AND message_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "2e5e76597cf6fe734978fef0762c7c86aeba3b076e8684a85696045ed3a4636e"+}diff --git a/rust/cloud-storage/email/.sqlx/query-359a16ea19cd02675cf7f6ffb815f76ad39c5aca7b6503ae8e43ebd1cc5d733f.json b/rust/cloud-storage/email/.sqlx/query-359a16ea19cd02675cf7f6ffb815f76ad39c5aca7b6503ae8e43ebd1cc5d733f.jsonnew file mode 100644index 0000000000..f99ce906c2--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-359a16ea19cd02675cf7f6ffb815f76ad39c5aca7b6503ae8e43ebd1cc5d733f.json@@ -0,0 +1,31 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_contacts (id, link_id, email_address, name)\n SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::text[])\n ON CONFLICT (link_id, email_address) DO NOTHING\n RETURNING id, email_address\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_address",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "UuidArray",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "359a16ea19cd02675cf7f6ffb815f76ad39c5aca7b6503ae8e43ebd1cc5d733f"+}diff --git a/rust/cloud-storage/email/.sqlx/query-37c7a9fd9f1156ce7de8a691fab1d33b9b50bd1e3525338b49991091df258321.json b/rust/cloud-storage/email/.sqlx/query-37c7a9fd9f1156ce7de8a691fab1d33b9b50bd1e3525338b49991091df258321.jsonnew file mode 100644index 0000000000..cf6201e995--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-37c7a9fd9f1156ce7de8a691fab1d33b9b50bd1e3525338b49991091df258321.json@@ -0,0 +1,53 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n m.id,\n m.thread_id,\n m.provider_thread_id,\n m.headers_jsonb,\n m.is_sent,\n m.is_draft\n FROM email_messages m\n WHERE m.id = $1 AND m.link_id = $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "thread_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "provider_thread_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "headers_jsonb",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 4,+ "name": "is_sent",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "is_draft",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "37c7a9fd9f1156ce7de8a691fab1d33b9b50bd1e3525338b49991091df258321"+}diff --git a/rust/cloud-storage/email/.sqlx/query-3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd.json b/rust/cloud-storage/email/.sqlx/query-3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd.jsonnew file mode 100644index 0000000000..3de2090f48--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd.json@@ -0,0 +1,33 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_messages (\n id, provider_id, link_id, thread_id, provider_thread_id,\n replying_to_id, subject, from_contact_id, sent_at,\n has_attachments, is_read, is_starred, is_sent, is_draft,\n body_text, body_html_sanitized, body_macro, headers_jsonb,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n ON CONFLICT (id) DO UPDATE SET\n provider_id = EXCLUDED.provider_id,\n thread_id = EXCLUDED.thread_id,\n provider_thread_id = EXCLUDED.provider_thread_id,\n replying_to_id = EXCLUDED.replying_to_id,\n subject = EXCLUDED.subject,\n from_contact_id = EXCLUDED.from_contact_id,\n sent_at = EXCLUDED.sent_at,\n has_attachments = EXCLUDED.has_attachments,\n is_read = EXCLUDED.is_read,\n is_starred = EXCLUDED.is_starred,\n is_sent = EXCLUDED.is_sent,\n is_draft = EXCLUDED.is_draft,\n body_text = EXCLUDED.body_text,\n body_html_sanitized = EXCLUDED.body_html_sanitized,\n body_macro = EXCLUDED.body_macro,\n headers_jsonb = EXCLUDED.headers_jsonb,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Uuid",+ "Text",+ "Uuid",+ "Text",+ "Uuid",+ "Timestamptz",+ "Bool",+ "Bool",+ "Bool",+ "Bool",+ "Bool",+ "Text",+ "Text",+ "Text",+ "Jsonb",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "3b147b8bcb7d08a87729fc68c562ea545e65d41bd61891ed3aad8eda3c4d90dd"+}diff --git a/rust/cloud-storage/email/.sqlx/query-44682e65711eb45a1dbec725646b7b0e02ced66e66f2d985f3da2d3eb7ad8c60.json b/rust/cloud-storage/email/.sqlx/query-44682e65711eb45a1dbec725646b7b0e02ced66e66f2d985f3da2d3eb7ad8c60.jsonnew file mode 100644index 0000000000..2bb459c23a--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-44682e65711eb45a1dbec725646b7b0e02ced66e66f2d985f3da2d3eb7ad8c60.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT ml.message_id, el.provider_label_id\n FROM email_message_labels ml\n JOIN email_labels el ON el.id = ml.label_id\n WHERE ml.message_id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "message_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "provider_label_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "44682e65711eb45a1dbec725646b7b0e02ced66e66f2d985f3da2d3eb7ad8c60"+}diff --git a/rust/cloud-storage/email/.sqlx/query-4b75a017d1bfeb600d0b75c58220b27c51a57253d0d82c55793eb5b0852d476f.json b/rust/cloud-storage/email/.sqlx/query-4b75a017d1bfeb600d0b75c58220b27c51a57253d0d82c55793eb5b0852d476f.jsonnew file mode 100644index 0000000000..a8c8857eae--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-4b75a017d1bfeb600d0b75c58220b27c51a57253d0d82c55793eb5b0852d476f.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_contacts\n SET name = data.name, updated_at = now()\n FROM (SELECT unnest($1::uuid[]) as id, unnest($2::text[]) as name) as data\n WHERE email_contacts.id = data.id\n AND email_contacts.name IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "4b75a017d1bfeb600d0b75c58220b27c51a57253d0d82c55793eb5b0852d476f"+}diff --git a/rust/cloud-storage/email/.sqlx/query-58b8b566779518776b13cabdb3498ac55b426b0493e769ea607618db7e246a71.json b/rust/cloud-storage/email/.sqlx/query-58b8b566779518776b13cabdb3498ac55b426b0493e769ea607618db7e246a71.jsonnew file mode 100644index 0000000000..2a84c80297--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-58b8b566779518776b13cabdb3498ac55b426b0493e769ea607618db7e246a71.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_scheduled_messages (\n link_id, message_id, send_time, sent,\n created_at, updated_at\n )\n VALUES ($1, $2, $3, $4, NOW(), NOW())\n ON CONFLICT (link_id, message_id) DO UPDATE SET\n send_time = EXCLUDED.send_time,\n sent = EXCLUDED.sent,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Timestamptz",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "58b8b566779518776b13cabdb3498ac55b426b0493e769ea607618db7e246a71"+}diff --git a/rust/cloud-storage/email/.sqlx/query-5df7eb0451abdb0810c1329807dab9213313858eceaea2015c5e6d584d2f168d.json b/rust/cloud-storage/email/.sqlx/query-5df7eb0451abdb0810c1329807dab9213313858eceaea2015c5e6d584d2f168d.jsonnew file mode 100644index 0000000000..cf67130e20--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-5df7eb0451abdb0810c1329807dab9213313858eceaea2015c5e6d584d2f168d.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_user_history (link_id, thread_id, created_at, updated_at)\n VALUES ($1, $2, NOW(), NOW())\n ON CONFLICT (link_id, thread_id)\n DO UPDATE SET\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "5df7eb0451abdb0810c1329807dab9213313858eceaea2015c5e6d584d2f168d"+}diff --git a/rust/cloud-storage/email/.sqlx/query-6c022c7b1e5e5faf6f388528436453738aa66c36c46313ca18c7570b406553f6.json b/rust/cloud-storage/email/.sqlx/query-6c022c7b1e5e5faf6f388528436453738aa66c36c46313ca18c7570b406553f6.jsonnew file mode 100644index 0000000000..2f59f37298--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-6c022c7b1e5e5faf6f388528436453738aa66c36c46313ca18c7570b406553f6.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_threads\n SET\n inbox_visible = $1,\n is_read = $2,\n latest_inbound_message_ts = $3,\n latest_outbound_message_ts = $4,\n latest_non_spam_message_ts = $5,\n updated_at = NOW()\n WHERE\n id = $6 AND\n link_id = $7\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Bool",+ "Bool",+ "Timestamptz",+ "Timestamptz",+ "Timestamptz",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "6c022c7b1e5e5faf6f388528436453738aa66c36c46313ca18c7570b406553f6"+}diff --git a/rust/cloud-storage/email/.sqlx/query-74132c6b056f693ac364bd5d70a40d81ccd384ffc21881d7c162895cb7d11647.json b/rust/cloud-storage/email/.sqlx/query-74132c6b056f693ac364bd5d70a40d81ccd384ffc21881d7c162895cb7d11647.jsonnew file mode 100644index 0000000000..eddca4f0fd--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-74132c6b056f693ac364bd5d70a40d81ccd384ffc21881d7c162895cb7d11647.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, email_address\n FROM email_contacts\n WHERE link_id = $1 AND email_address = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_address",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "74132c6b056f693ac364bd5d70a40d81ccd384ffc21881d7c162895cb7d11647"+}diff --git a/rust/cloud-storage/email/.sqlx/query-88cb2c1126909dabe0cc1846ca2733ab98724d4b89d409fa770209d4d7627654.json b/rust/cloud-storage/email/.sqlx/query-88cb2c1126909dabe0cc1846ca2733ab98724d4b89d409fa770209d4d7627654.jsonnew file mode 100644index 0000000000..566b687721--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-88cb2c1126909dabe0cc1846ca2733ab98724d4b89d409fa770209d4d7627654.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_message_recipients (message_id, contact_id, name, recipient_type)\n SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::email_recipient_type[])\n ON CONFLICT (message_id, contact_id, recipient_type) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "UuidArray",+ "TextArray",+ {+ "Custom": {+ "name": "email_recipient_type[]",+ "kind": {+ "Array": {+ "Custom": {+ "name": "email_recipient_type",+ "kind": {+ "Enum": [+ "TO",+ "CC",+ "BCC"+ ]+ }+ }+ }+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "88cb2c1126909dabe0cc1846ca2733ab98724d4b89d409fa770209d4d7627654"+}diff --git a/rust/cloud-storage/email/.sqlx/query-b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d.json b/rust/cloud-storage/email/.sqlx/query-b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d.jsonnew file mode 100644index 0000000000..f91da73bfc--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, email_address\n FROM email_contacts\n WHERE link_id = $1 AND email_address = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_address",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "b0c4750b13bbd3de768ac09f971094ac7f53c161f7054083964f472fa01dd83d"+}diff --git a/rust/cloud-storage/email/.sqlx/query-b4d3994adddd1a4b1c769cf01690bedbf26640fdfad218b4dca813bdcee08a5a.json b/rust/cloud-storage/email/.sqlx/query-b4d3994adddd1a4b1c769cf01690bedbf26640fdfad218b4dca813bdcee08a5a.jsonnew file mode 100644index 0000000000..765e4bd327--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-b4d3994adddd1a4b1c769cf01690bedbf26640fdfad218b4dca813bdcee08a5a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT DISTINCT emr.message_id\n FROM email_message_recipients emr\n JOIN email_messages m ON m.id = emr.message_id\n WHERE emr.message_id = ANY($1)\n AND m.from_contact_id IS NOT NULL\n AND emr.contact_id = m.from_contact_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "message_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b4d3994adddd1a4b1c769cf01690bedbf26640fdfad218b4dca813bdcee08a5a"+}diff --git a/rust/cloud-storage/email/.sqlx/query-b8eb30360d1232b36214b17758d8c7d897251a93c7d56b310a2fc6f026fdbea9.json b/rust/cloud-storage/email/.sqlx/query-b8eb30360d1232b36214b17758d8c7d897251a93c7d56b310a2fc6f026fdbea9.jsonnew file mode 100644index 0000000000..331e15bd4e--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-b8eb30360d1232b36214b17758d8c7d897251a93c7d56b310a2fc6f026fdbea9.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM email_message_recipients\n WHERE message_id = $1\n AND (contact_id, recipient_type) NOT IN (\n SELECT contact_id, recipient_type\n FROM unnest($2::uuid[], $3::email_recipient_type[])\n AS t(contact_id, recipient_type)\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray",+ {+ "Custom": {+ "name": "email_recipient_type[]",+ "kind": {+ "Array": {+ "Custom": {+ "name": "email_recipient_type",+ "kind": {+ "Enum": [+ "TO",+ "CC",+ "BCC"+ ]+ }+ }+ }+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "b8eb30360d1232b36214b17758d8c7d897251a93c7d56b310a2fc6f026fdbea9"+}diff --git a/rust/cloud-storage/email/.sqlx/query-c33f85b35573916eb380c8b6069939087fbd3b34b296b546a34cdfc3e7c9eee0.json b/rust/cloud-storage/email/.sqlx/query-c33f85b35573916eb380c8b6069939087fbd3b34b296b546a34cdfc3e7c9eee0.jsonnew file mode 100644index 0000000000..9da8336f8e--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-c33f85b35573916eb380c8b6069939087fbd3b34b296b546a34cdfc3e7c9eee0.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM email_message_recipients\n WHERE message_id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "c33f85b35573916eb380c8b6069939087fbd3b34b296b546a34cdfc3e7c9eee0"+}diff --git a/rust/cloud-storage/email/.sqlx/query-c3f8291d5ce84fb1eb463eaa0f0aed0c3ac2ed1297f345941cc8c2bfdcadedd5.json b/rust/cloud-storage/email/.sqlx/query-c3f8291d5ce84fb1eb463eaa0f0aed0c3ac2ed1297f345941cc8c2bfdcadedd5.jsonnew file mode 100644index 0000000000..d93442c86c--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-c3f8291d5ce84fb1eb463eaa0f0aed0c3ac2ed1297f345941cc8c2bfdcadedd5.json@@ -0,0 +1,53 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n m.id,\n m.thread_id,\n m.provider_thread_id,\n m.headers_jsonb,\n m.is_sent,\n m.is_draft\n FROM email_messages m\n WHERE m.link_id = $1\n AND m.is_draft = true\n AND jsonb_path_exists(\n m.headers_jsonb,\n '$[*] ? (@.\"Macro-In-Reply-To\" == $macro_uuid)'::jsonpath,\n jsonb_build_object('macro_uuid', $2::text)\n )\n ORDER BY m.created_at DESC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "thread_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "provider_thread_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "headers_jsonb",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 4,+ "name": "is_sent",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "is_draft",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "c3f8291d5ce84fb1eb463eaa0f0aed0c3ac2ed1297f345941cc8c2bfdcadedd5"+}diff --git a/rust/cloud-storage/email/.sqlx/query-e7e9e2db72c9bf45273b0cfe11057a5dbce790572f2420457e24b0fd498c2024.json b/rust/cloud-storage/email/.sqlx/query-e7e9e2db72c9bf45273b0cfe11057a5dbce790572f2420457e24b0fd498c2024.jsonnew file mode 100644index 0000000000..5d51a7025e--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-e7e9e2db72c9bf45273b0cfe11057a5dbce790572f2420457e24b0fd498c2024.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read,\n latest_inbound_message_ts, latest_outbound_message_ts,\n latest_non_spam_message_ts)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (link_id, provider_id) WHERE provider_id IS NOT NULL DO UPDATE\n SET\n latest_inbound_message_ts = EXCLUDED.latest_inbound_message_ts,\n updated_at = NOW()\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Uuid",+ "Bool",+ "Bool",+ "Timestamptz",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e7e9e2db72c9bf45273b0cfe11057a5dbce790572f2420457e24b0fd498c2024"+}diff --git a/rust/cloud-storage/email/.sqlx/query-fc6df4dc3c0f82de02b70975338d7455df93799b12af38d50bb85d81391861c3.json b/rust/cloud-storage/email/.sqlx/query-fc6df4dc3c0f82de02b70975338d7455df93799b12af38d50bb85d81391861c3.jsonnew file mode 100644index 0000000000..ca1b2f5d86--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-fc6df4dc3c0f82de02b70975338d7455df93799b12af38d50bb85d81391861c3.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id, is_draft, is_sent, is_read, provider_id,\n internal_date_ts, updated_at\n FROM email_messages\n WHERE thread_id = $1\n ORDER BY internal_date_ts DESC NULLS LAST\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "is_draft",+ "type_info": "Bool"+ },+ {+ "ordinal": 2,+ "name": "is_sent",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "is_read",+ "type_info": "Bool"+ },+ {+ "ordinal": 4,+ "name": "provider_id",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "internal_date_ts",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ true,+ true,+ false+ ]+ },+ "hash": "fc6df4dc3c0f82de02b70975338d7455df93799b12af38d50bb85d81391861c3"+}diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.tomlindex a9fe34215c..c065466835 100644--- a/rust/cloud-storage/email/Cargo.toml+++ b/rust/cloud-storage/email/Cargo.toml@@ -21,6 +21,7 @@ ports = ["dep:tokio", "frecency/ports"][dependencies]anyhow = { workspace = true }+base64 = { workspace = true }entity_access = { path = "../entity_access" }futures = { workspace = true }axum = { workspace = true, optional = true }@@ -33,6 +34,7 @@ filter_ast = { path = "../filter_ast" }frecency = { path = "../frecency" }item_filters = { path = "../item_filters" }macro_user_id = { path = "../macro_user_id" }+macro_uuid = { path = "../macro_uuid" }model-entity = { path = "../model-entity" }model-error-response = { path = "../model-error-response", optional = true }model_user = { path = "../model_user", optional = true }diff --git a/rust/cloud-storage/email/fixtures/email_draft.sql b/rust/cloud-storage/email/fixtures/email_draft.sqlnew file mode 100644index 0000000000..ecc33fd7df--- /dev/null+++ b/rust/cloud-storage/email/fixtures/email_draft.sql@@ -0,0 +1,62 @@+-- Fixture for testing draft-related repo methods:+-- get_simple_message, get_draft_replying_to, upsert_contacts, insert_draft_message++-- Insert test link+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL', true, NOW(), NOW());++-- Insert contacts+INSERT INTO email_contacts (id, link_id, email_address, name, sfs_photo_url, created_at, updated_at)+VALUES+ ('c0000001-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Alice Smith', NULL, NOW(), NOW()),+ ('c0000002-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Bob Jones', NULL, NOW(), NOW()),+ ('c0000003-0000-0000-0000-000000000003', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', NULL, NULL, NOW(), NOW());++-- Insert labels (needed for thread metadata update)+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)+VALUES+ ('bb000001-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),+ ('bb000002-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'SENT', 'SENT', 'Show', 'LabelShow', 'System', NOW());++-- Insert threads+INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES+ ('11111111-1111-1111-1111-111111111111', 'provider-thread-1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, false, NOW(), NOW()),+ ('22222222-2222-2222-2222-222222222222', 'provider-thread-2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', true, true, NOW(), NOW());++-- msg1: A regular sent message in thread 1 (for get_simple_message and replying_to tests)+INSERT INTO email_messages (id, provider_id, thread_id, provider_thread_id, link_id, from_contact_id, subject, is_read, is_sent, is_draft, has_attachments, internal_date_ts, created_at, updated_at)+VALUES+ ('ee000001-0000-0000-0000-000000000001', 'provider-msg-1', '11111111-1111-1111-1111-111111111111', 'provider-thread-1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',+ 'c0000001-0000-0000-0000-000000000001', 'Hello World', true, true, false, false, '2025-01-10 10:00:00+00', '2025-01-10 10:00:00+00', '2025-01-10 10:00:00+00');++-- msg1 has INBOX + SENT labels+INSERT INTO email_message_labels (message_id, label_id)+VALUES+ ('ee000001-0000-0000-0000-000000000001', 'bb000001-0000-0000-0000-000000000001'),+ ('ee000001-0000-0000-0000-000000000001', 'bb000002-0000-0000-0000-000000000002');++-- msg1 has recipients: bob=TO+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type, name)+VALUES+ ('ee000001-0000-0000-0000-000000000001', 'c0000002-0000-0000-0000-000000000002', 'TO', NULL);++-- msg2: A draft in thread 1 replying to msg1, identified by Macro-In-Reply-To header+INSERT INTO email_messages (id, thread_id, provider_thread_id, link_id, from_contact_id, replying_to_id, subject, is_read, is_sent, is_draft, has_attachments, headers_jsonb, created_at, updated_at)+VALUES+ ('ee000002-0000-0000-0000-000000000002', '11111111-1111-1111-1111-111111111111', 'provider-thread-1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',+ 'c0000001-0000-0000-0000-000000000001', 'ee000001-0000-0000-0000-000000000001', 'Re: Hello World', true, false, true, false,+ '[{"Macro-In-Reply-To": "ee000001-0000-0000-0000-000000000001"}]',+ '2025-01-11 10:00:00+00', '2025-01-11 10:00:00+00');++-- msg3: A regular message in thread 2 (for testing draft insert into existing thread)+INSERT INTO email_messages (id, provider_id, thread_id, provider_thread_id, link_id, from_contact_id, subject, is_read, is_sent, is_draft, has_attachments, internal_date_ts, created_at, updated_at)+VALUES+ ('ee000003-0000-0000-0000-000000000003', 'provider-msg-3', '22222222-2222-2222-2222-222222222222', 'provider-thread-2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',+ 'c0000002-0000-0000-0000-000000000002', 'Different thread', true, false, false, false, '2025-02-01 12:00:00+00', '2025-02-01 12:00:00+00', '2025-02-01 12:00:00+00');++-- msg3 has INBOX label+INSERT INTO email_message_labels (message_id, label_id)+VALUES+ ('ee000003-0000-0000-0000-000000000003', 'bb000001-0000-0000-0000-000000000001');diff --git a/rust/cloud-storage/email/src/domain/models/draft.rs b/rust/cloud-storage/email/src/domain/models/draft.rsnew file mode 100644index 0000000000..9bc3066acf--- /dev/null+++ b/rust/cloud-storage/email/src/domain/models/draft.rs@@ -0,0 +1,125 @@+use chrono::{DateTime, Utc};+use serde_json::Value as JsonValue;+use uuid::Uuid;++use super::contact::{ContactInfo, RecipientType};++/// Input for creating a draft message. Mirrors the fields from `MessageToSend`.+#[derive(Debug, Clone)]+pub struct CreateDraftInput {+ /// Existing message DB ID (for updating an existing draft).+ pub db_id: Option<Uuid>,+ /// Provider message ID.+ pub provider_id: Option<String>,+ /// ID of the message this draft is replying to.+ pub replying_to_id: Option<Uuid>,+ /// Provider thread ID.+ pub provider_thread_id: Option<String>,+ /// Thread DB ID (set if this draft belongs to an existing thread).+ pub thread_db_id: Option<Uuid>,+ /// Subject line of the draft.+ pub subject: String,+ /// To recipients.+ pub to: Vec<ContactInfo>,+ /// Cc recipients.+ pub cc: Vec<ContactInfo>,+ /// Bcc recipients.+ pub bcc: Vec<ContactInfo>,+ /// Plain text body.+ pub body_text: Option<String>,+ /// HTML body (base64 encoded from the client, decoded before storage).+ pub body_html: Option<String>,+ /// Macro-specific body format.+ pub body_macro: Option<String>,+ /// Headers JSON (e.g. Macro-In-Reply-To).+ pub headers_json: Option<JsonValue>,+ /// Scheduled send time.+ pub send_time: Option<DateTime<Utc>>,+}++/// Simplified message info used for validation queries.+#[derive(Debug, Clone)]+pub struct SimpleMessageInfo {+ /// Database ID of the message.+ pub db_id: Uuid,+ /// Thread database ID.+ pub thread_db_id: Uuid,+ /// Provider thread ID.+ pub provider_thread_id: Option<String>,+ /// Headers JSON.+ pub headers_json: Option<JsonValue>,+ /// Whether the message has been sent.+ pub is_sent: bool,+ /// Whether the message is a draft.+ pub is_draft: bool,+}++/// The result of creating a draft.+#[derive(Debug, Clone)]+pub struct CreatedDraft {+ /// The assigned or existing message DB ID.+ pub db_id: Uuid,+ /// Provider message ID.+ pub provider_id: Option<String>,+ /// ID of the message this draft is replying to.+ pub replying_to_id: Option<Uuid>,+ /// Provider thread ID.+ pub provider_thread_id: Option<String>,+ /// Thread DB ID.+ pub thread_db_id: Uuid,+ /// Link ID.+ pub link_id: Uuid,+ /// Subject.+ pub subject: String,+ /// To recipients.+ pub to: Vec<ContactInfo>,+ /// Cc recipients.+ pub cc: Vec<ContactInfo>,+ /// Bcc recipients.+ pub bcc: Vec<ContactInfo>,+ /// Plain text body.+ pub body_text: Option<String>,+ /// HTML body (decoded).+ pub body_html: Option<String>,+ /// Macro body.+ pub body_macro: Option<String>,+ /// Headers JSON.+ pub headers_json: Option<JsonValue>,+ /// Scheduled send time.+ pub send_time: Option<DateTime<Utc>>,+}++/// Parsed from/to/cc/bcc addresses for contact upsert.+#[derive(Debug, Clone)]+pub struct ParsedAddresses {+ /// The from email address.+ pub from_email: String,+ /// The from display name.+ pub from_name: Option<String>,+ /// To recipients.+ pub to: Vec<ContactInfo>,+ /// Cc recipients.+ pub cc: Vec<ContactInfo>,+ /// Bcc recipients.+ pub bcc: Vec<ContactInfo>,+}++/// Result of upserting contacts for a draft.+#[derive(Debug, Clone)]+pub struct UpsertedContacts {+ /// The contact ID of the sender.+ pub from_contact_id: Option<Uuid>,+ /// The upserted recipients.+ pub recipients: Vec<UpsertedRecipient>,+}++/// A single upserted recipient.+#[derive(Debug, Clone)]+pub struct UpsertedRecipient {+ /// Contact ID.+ pub contact_id: Uuid,+ /// Display name.+ pub name: Option<String>,+ /// Recipient type (to, cc, bcc).+ pub recipient_type: RecipientType,+}diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rsindex 326d4d103a..c10a190686 100644--- a/rust/cloud-storage/email/src/domain/models/error.rs+++ b/rust/cloud-storage/email/src/domain/models/error.rs@@ -1,10 +1,29 @@use frecency::domain::models::FrecencyQueryErr;use thiserror::Error;+use uuid::Uuid;+/// Errors that can occur in the email domain.#[derive(Debug, Error)]pub enum EmailErr {+ /// A repository/infrastructure error.#[error(transparent)]RepoErr(#[from] anyhow::Error),+ /// A frecency query error.#[error(transparent)]Frecency(#[from] FrecencyQueryErr),+ /// The referenced message was not found.+ #[error("Message with id {0} not found")]+ MessageNotFound(Uuid),+ /// The referenced message has already been sent and cannot be modified.+ #[error("Message with id {0} has already been sent")]+ MessageAlreadySent(Uuid),+ /// Cannot reply to a draft message.+ #[error("Cannot reply to a draft")]+ CannotReplyToDraft,+ /// Failed to decode base64 body content.+ #[error("Failed to decode base64 HTML body")]+ Base64DecodeError(#[from] base64::DecodeError),+ /// Decoded bytes are not valid UTF-8.+ #[error("Failed to convert decoded HTML body to UTF-8")]+ Utf8Error(#[from] std::string::FromUtf8Error),}diff --git a/rust/cloud-storage/email/src/domain/models/mod.rs b/rust/cloud-storage/email/src/domain/models/mod.rsindex adaa368471..7c648e13b1 100644--- a/rust/cloud-storage/email/src/domain/models/mod.rs+++ b/rust/cloud-storage/email/src/domain/models/mod.rs@@ -1,5 +1,6 @@pub mod attachment;pub mod contact;+pub mod draft;pub mod error;pub mod label;pub mod link;@@ -12,6 +13,10 @@ mod tests;pub use attachment::{Attachment, AttachmentDraft, AttachmentForwarded, MessageAttachment};pub use contact::{Contact, ContactInfo, RecipientType};+pub use draft::{+ CreateDraftInput, CreatedDraft, ParsedAddresses, SimpleMessageInfo, UpsertedContacts,+ UpsertedRecipient,+};pub use error::EmailErr;pub use label::{Label, LabelListVisibility, LabelType, MessageLabel, MessageListVisibility};pub use link::{Link, UserProvider};diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rsindex 02ffe20c34..d1240df57a 100644--- a/rust/cloud-storage/email/src/domain/ports.rs+++ b/rust/cloud-storage/email/src/domain/ports.rs@@ -1,8 +1,8 @@use crate::domain::models::{- Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailErr,- EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest, Label, Link,- MessageAttachment, MessageLabel, MessageRow, PreviewCursorQuery, RecipientType, Thread,- ThreadRow, UserProvider,+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,+ CreatedDraft, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest,+ Label, Link, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses, PreviewCursorQuery,+ RecipientType, SimpleMessageInfo, Thread, ThreadRow, UpsertedContacts, UserProvider,};use chrono::{DateTime, Utc};use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};@@ -100,6 +100,42 @@ pub trait EmailRepo: Send + Sync + 'static {&self,message_ids: &[Uuid],) -> impl Future<Output = Result<HashMap<Uuid, DateTime<Utc>>, Self::Err>> + Send;++ /// Fetch a simplified message by its DB ID and link ID (for validation).+ fn get_simple_message(+ &self,+ message_id: Uuid,+ link_id: Uuid,+ ) -> impl Future<Output = Result<Option<SimpleMessageInfo>, Self::Err>> + Send;++ /// Find an existing draft that replies to the given message ID.+ fn get_draft_replying_to(+ &self,+ link_id: Uuid,+ replying_to_id: Uuid,+ ) -> impl Future<Output = Result<Option<SimpleMessageInfo>, Self::Err>> + Send;++ /// Upsert contacts from the parsed addresses. Must be called outside a transaction+ /// to avoid deadlocks (contacts are shared across messages).+ fn upsert_contacts(+ &self,+ link_id: Uuid,+ addresses: ParsedAddresses,+ ) -> impl Future<Output = Result<UpsertedContacts, Self::Err>> + Send;++ /// Insert a draft message within a transaction, including thread insert (if new),+ /// recipients, scheduled message handling, thread metadata update, and user history.+ /// If `new_thread` is Some, the thread is created inside the same transaction.+ /// Returns the thread DB ID.+ fn insert_draft_message(+ &self,+ input: &CreateDraftInput,+ message_db_id: Uuid,+ thread_db_id: Uuid,+ contacts: &UpsertedContacts,+ link_id: Uuid,+ new_thread: Option<ThreadRow>,+ ) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;}pub trait EmailService: Send + Sync + 'static {@@ -126,4 +162,11 @@ pub trait EmailService: Send + Sync + 'static {offset: i64,limit: i64,) -> impl Future<Output = Result<Option<Thread>, EmailErr>> + Send;++ /// Create a draft message for the given link.+ fn create_draft(+ &self,+ link: &Link,+ input: CreateDraftInput,+ ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;}diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rsnew file mode 100644index 0000000000..7fc29935e0--- /dev/null+++ b/rust/cloud-storage/email/src/domain/service/draft.rs@@ -0,0 +1,218 @@+use crate::domain::{+ models::{+ CreateDraftInput, CreatedDraft, EmailErr, Link, ParsedAddresses, SimpleMessageInfo,+ ThreadRow,+ },+ ports::EmailRepo,+};+use base64::Engine;+use base64::engine::general_purpose::URL_SAFE_NO_PAD;+use frecency::domain::ports::FrecencyQueryService;+use uuid::Uuid;++use super::EmailServiceImpl;++impl<T, U> EmailServiceImpl<T, U>+where+ T: EmailRepo,+ U: FrecencyQueryService,+ anyhow::Error: From<T::Err>,+{+ #[tracing::instrument(err, skip(self, link, input))]+ pub(crate) async fn create_draft_impl(+ &self,+ link: &Link,+ mut input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ let link_id = link.id;++ self.validate_existing_message(link_id, &mut input).await?;++ self.validate_replying_to(link_id, &mut input).await?;++ decode_html_body(&mut input)?;++ // Build parsed addresses+ let from_email = String::from(link.email_address.clone());+ let addresses = ParsedAddresses {+ from_email: from_email.clone(),+ from_name: None,+ to: input.to.clone(),+ cc: input.cc.clone(),+ bcc: input.bcc.clone(),+ };++ // Upsert contacts (outside transaction to avoid deadlocks)+ let contacts = self+ .email_repo+ .upsert_contacts(link_id, addresses)+ .await+ .map_err(anyhow::Error::from)?;++ // Build new thread if one doesn't already exist+ let (thread_db_id, new_thread) = self.build_new_thread_if_needed(link_id, &input);++ // Generate message ID once, before insert, so the response matches the DB+ let message_db_id = input.db_id.unwrap_or_else(macro_uuid::generate_uuid_v7);+ input.db_id = Some(message_db_id);++ let thread_db_id = self+ .email_repo+ .insert_draft_message(+ &input,+ message_db_id,+ thread_db_id,+ &contacts,+ link_id,+ new_thread,+ )+ .await+ .map_err(anyhow::Error::from)?;++ Ok(CreatedDraft {+ db_id: message_db_id,+ provider_id: input.provider_id,+ replying_to_id: input.replying_to_id,+ provider_thread_id: input.provider_thread_id,+ thread_db_id,+ link_id,+ subject: input.subject,+ to: input.to,+ cc: input.cc,+ bcc: input.bcc,+ body_text: input.body_text,+ body_html: input.body_html,+ body_macro: input.body_macro,+ headers_json: input.headers_json,+ send_time: input.send_time,+ })+ }++ async fn validate_existing_message(+ &self,+ link_id: Uuid,+ input: &mut CreateDraftInput,+ ) -> Result<(), EmailErr> {+ let Some(db_id) = input.db_id else {+ return Ok(());+ };++ let msg = self+ .email_repo+ .get_simple_message(db_id, link_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(EmailErr::MessageNotFound(db_id))?;++ if msg.is_sent || !msg.is_draft {+ return Err(EmailErr::MessageAlreadySent(db_id));+ }++ input.thread_db_id = Some(msg.thread_db_id);+ input.provider_thread_id = msg.provider_thread_id;++ Ok(())+ }++ async fn validate_replying_to(+ &self,+ link_id: Uuid,+ input: &mut CreateDraftInput,+ ) -> Result<(), EmailErr> {+ let Some(replying_to_id) = input.replying_to_id else {+ return Ok(());+ };++ // Check if a draft already exists replying to this message+ if let Some(existing_draft) = self+ .email_repo+ .get_draft_replying_to(link_id, replying_to_id)+ .await+ .map_err(anyhow::Error::from)?+ {+ self.apply_existing_draft(input, existing_draft);+ } else {+ self.apply_reply_target(link_id, input, replying_to_id)+ .await?;+ }++ Ok(())+ }++ fn apply_existing_draft(+ &self,+ input: &mut CreateDraftInput,+ existing_draft: SimpleMessageInfo,+ ) {+ input.db_id = Some(existing_draft.db_id);+ input.thread_db_id = Some(existing_draft.thread_db_id);+ input.provider_thread_id = existing_draft.provider_thread_id;+ input.headers_json = existing_draft.headers_json;+ }++ async fn apply_reply_target(+ &self,+ link_id: Uuid,+ input: &mut CreateDraftInput,+ replying_to_id: Uuid,+ ) -> Result<(), EmailErr> {+ let reply_target = self+ .email_repo+ .get_simple_message(replying_to_id, link_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(EmailErr::MessageNotFound(replying_to_id))?;++ if reply_target.is_draft {+ return Err(EmailErr::CannotReplyToDraft);+ }++ input.thread_db_id = Some(reply_target.thread_db_id);+ input.provider_thread_id = reply_target.provider_thread_id;++ // Generate Macro-In-Reply-To header+ input.headers_json = Some(serde_json::json!([{+ "Macro-In-Reply-To": reply_target.db_id.to_string()+ }]));++ Ok(())+ }++ /// If the input already has a thread_db_id, return it with no new thread.+ /// Otherwise, build a ThreadRow for creation inside the transaction.+ fn build_new_thread_if_needed(+ &self,+ link_id: Uuid,+ input: &CreateDraftInput,+ ) -> (Uuid, Option<ThreadRow>) {+ if let Some(id) = input.thread_db_id {+ return (id, None);+ }++ let now = chrono::Utc::now();+ let thread = ThreadRow {+ db_id: macro_uuid::generate_uuid_v7(),+ provider_id: None,+ link_id,+ inbox_visible: false,+ is_read: true,+ latest_inbound_message_ts: None,+ latest_outbound_message_ts: None,+ latest_non_spam_message_ts: None,+ created_at: now,+ updated_at: now,+ };++ let thread_db_id = thread.db_id;+ (thread_db_id, Some(thread))+ }+}++fn decode_html_body(input: &mut CreateDraftInput) -> Result<(), EmailErr> {+ if let Some(ref html_body) = input.body_html {+ let decoded = URL_SAFE_NO_PAD.decode(html_body.as_bytes())?;+ let decoded_str = String::from_utf8(decoded)?;+ input.body_html = Some(decoded_str);+ }+ Ok(())+}diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rsnew file mode 100644index 0000000000..4ba21d8064--- /dev/null+++ b/rust/cloud-storage/email/src/domain/service/mod.rs@@ -0,0 +1,76 @@+mod draft;+mod previews;+mod thread;++use crate::domain::{+ models::{+ CreateDraftInput, CreatedDraft, EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest,+ Link, Thread,+ },+ ports::{EmailRepo, EmailService},+};+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};+use frecency::domain::ports::FrecencyQueryService;+use models_pagination::{PaginatedCursor, SimpleSortMethod};+use uuid::Uuid;++#[derive(Clone)]+pub struct EmailServiceImpl<T, U> {+ email_repo: T,+ frecency_service: U,+}++impl<T, U> EmailServiceImpl<T, U>+where+ T: EmailRepo,+ U: FrecencyQueryService,+{+ pub fn new(email_repo: T, frecency_service: U) -> EmailServiceImpl<T, U> {+ EmailServiceImpl {+ email_repo,+ frecency_service,+ }+ }+}++impl<T, U> EmailService for EmailServiceImpl<T, U>+where+ T: EmailRepo,+ U: FrecencyQueryService,+ anyhow::Error: From<T::Err>,+{+ async fn get_email_thread_previews(+ &self,+ req: GetEmailsRequest,+ ) -> Result<PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>, EmailErr>+ {+ self.get_email_thread_previews_impl(req).await+ }++ async fn get_link_by_auth_id_and_macro_id(+ &self,+ auth_id: &str,+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ ) -> Result<Option<crate::domain::models::Link>, EmailErr> {+ self.get_link_by_auth_id_and_macro_id_impl(auth_id, macro_id)+ .await+ }++ async fn get_thread_with_messages(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ offset: i64,+ limit: i64,+ ) -> Result<Option<Thread>, EmailErr> {+ self.get_thread_with_messages_impl(receipt, offset, limit)+ .await+ }++ async fn create_draft(+ &self,+ link: &Link,+ input: CreateDraftInput,+ ) -> Result<CreatedDraft, EmailErr> {+ self.create_draft_impl(link, input).await+ }+}diff --git a/rust/cloud-storage/email/src/domain/service/previews.rs b/rust/cloud-storage/email/src/domain/service/previews.rsnew file mode 100644index 0000000000..ebd676b993--- /dev/null+++ b/rust/cloud-storage/email/src/domain/service/previews.rs@@ -0,0 +1,127 @@+use crate::domain::{+ models::{+ EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery, UserProvider,+ },+ ports::EmailRepo,+};+use frecency::domain::{+ models::{AggregateId, FrecencyByIdsRequest, FrecencyData},+ ports::FrecencyQueryService,+};+use macro_user_id::cowlike::CowLike;+use model_entity::EntityType;+use models_pagination::{CollectBy, PaginateOn, PaginatedCursor, SimpleSortMethod};+use std::collections::HashMap;+use uuid::Uuid;++use super::EmailServiceImpl;++impl<T, U> EmailServiceImpl<T, U>+where+ T: EmailRepo,+ U: FrecencyQueryService,+ anyhow::Error: From<T::Err>,+{+ #[tracing::instrument(err, skip(self, req))]+ pub(crate) async fn get_email_thread_previews_impl(+ &self,+ req: GetEmailsRequest,+ ) -> Result<PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>, EmailErr>+ {+ let GetEmailsRequest {+ view,+ link_id,+ macro_id,+ limit,+ query,+ } = req;+ let sort_method = *query.sort_method();++ const MIN_PAGE: u32 = 20;+ const MAX_PAGE: u32 = 500;++ let limit = limit.unwrap_or_default().clamp(MIN_PAGE, MAX_PAGE);++ let query = PreviewCursorQuery {+ view,+ link_id,+ limit,+ query,+ };++ let previews = self+ .email_repo+ .previews_for_view_cursor(query, macro_id.copied().into_owned())+ .await+ .map_err(anyhow::Error::from)?;++ let thread_ids: Vec<Uuid> = previews.iter().map(|p| p.id).collect();++ let ids: Vec<_> = thread_ids+ .iter()+ .map(|id| EntityType::EmailThread.with_entity_string(id.to_string()))+ .collect();++ let frecency_request = FrecencyByIdsRequest {+ user_id: macro_id,+ ids: ids.as_slice(),+ };++ let (attachment_map_result, participant_result, labels_result, frecency_scores) = tokio::join!(+ self.email_repo.attachments_by_thread_ids(&thread_ids),+ self.email_repo.contacts_by_thread_ids(&thread_ids),+ self.email_repo.labels_by_thread_ids(&thread_ids),+ self.frecency_service+ .get_frecencies_by_ids(frecency_request)+ );++ let mut attachment_map = attachment_map_result+ .map_err(anyhow::Error::from)?+ .into_iter()+ .group_by(|v| v.thread_id);+ let mut participant_map = participant_result+ .map_err(anyhow::Error::from)?+ .into_iter()+ .group_by(|v| v.thread_id);+ let mut labels_map = labels_result+ .map_err(anyhow::Error::from)?+ .into_iter()+ .group_by(|v| v.thread_id);++ let mut frecency_scores_map: HashMap<AggregateId<'static>, FrecencyData> =+ frecency_scores?.into_inner();++ Ok(previews+ .into_iter()+ .map(|thread| {+ let id = AggregateId {+ user_id: thread.owner_id.clone(),+ entity: EntityType::EmailThread.with_entity_string(thread.id.to_string()),+ };++ EnrichedEmailThreadPreview {+ attachments: attachment_map.remove(&thread.id).unwrap_or_default(),+ labels: labels_map.remove(&thread.id).unwrap_or_default(),+ participants: participant_map.remove(&thread.id).unwrap_or_default(),+ frecency_score: frecency_scores_map+ .remove(&id)+ .map(|data| id.into_aggregate(data)),+ thread,+ }+ })+ .paginate_on(limit as usize, sort_method)+ .into_page())+ }++ pub(crate) async fn get_link_by_auth_id_and_macro_id_impl(+ &self,+ auth_id: &str,+ macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,+ ) -> Result<Option<crate::domain::models::Link>, EmailErr> {+ Ok(self+ .email_repo+ .link_by_fusionauth_and_macro_id(auth_id, macro_id, UserProvider::Gmail)+ .await+ .map_err(anyhow::Error::from)?)+ }+}diff --git a/rust/cloud-storage/email/src/domain/service.rs b/rust/cloud-storage/email/src/domain/service/thread.rssimilarity index 56%rename from rust/cloud-storage/email/src/domain/service.rsrename to rust/cloud-storage/email/src/domain/service/thread.rsindex 0060536765..606b5eed05 100644--- a/rust/cloud-storage/email/src/domain/service.rs+++ b/rust/cloud-storage/email/src/domain/service/thread.rs@@ -1,154 +1,24 @@use crate::domain::{assembler::{message_from_row, split_recipients, thread_from_row},- models::{- EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, Message, PreviewCursorQuery,- Thread, UserProvider,- },- ports::{EmailRepo, EmailService},+ models::{EmailErr, Message, Thread},+ ports::EmailRepo,};use entity_access::domain::models::{AccessLevel, EntityAccessReceipt, EntityPermission, ViewAccessLevel,};-use frecency::domain::{- models::{AggregateId, FrecencyByIdsRequest, FrecencyData},- ports::FrecencyQueryService,-};-use macro_user_id::cowlike::CowLike;-use model_entity::EntityType;-use models_pagination::{CollectBy, PaginateOn, PaginatedCursor, SimpleSortMethod};-use std::collections::HashMap;+use frecency::domain::ports::FrecencyQueryService;use uuid::Uuid;-#[derive(Clone)]-pub struct EmailServiceImpl<T, U> {- email_repo: T,- frecency_service: U,-}+use super::EmailServiceImpl;impl<T, U> EmailServiceImpl<T, U>-where- T: EmailRepo,- U: FrecencyQueryService,-{- pub fn new(email_repo: T, frecency_service: U) -> EmailServiceImpl<T, U> {- EmailServiceImpl {- email_repo,- frecency_service,- }- }-}--impl<T, U> EmailService for EmailServiceImpl<T, U>whereT: EmailRepo,U: FrecencyQueryService,anyhow::Error: From<T::Err>,{- #[tracing::instrument(err, skip(self, req))]- async fn get_email_thread_previews(- &self,- req: GetEmailsRequest,- ) -> Result<PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>, EmailErr>- {- let GetEmailsRequest {- view,- link_id,- macro_id,- limit,- query,- } = req;- let sort_method = *query.sort_method();-- const MIN_PAGE: u32 = 20;- const MAX_PAGE: u32 = 500;-- let limit = limit.unwrap_or_default().clamp(MIN_PAGE, MAX_PAGE);-- let query = PreviewCursorQuery {- view,- link_id,- limit,- query,- };-- let previews = self- .email_repo- .previews_for_view_cursor(query, macro_id.copied().into_owned())- .await- .map_err(anyhow::Error::from)?;-- let thread_ids: Vec<Uuid> = previews.iter().map(|p| p.id).collect();-- let ids: Vec<_> = thread_ids- .iter()- .map(|id| EntityType::EmailThread.with_entity_string(id.to_string()))- .collect();-- let frecency_request = FrecencyByIdsRequest {- user_id: macro_id,- ids: ids.as_slice(),- };-- let (attachment_map_result, participant_result, labels_result, frecency_scores) = tokio::join!(- self.email_repo.attachments_by_thread_ids(&thread_ids),- self.email_repo.contacts_by_thread_ids(&thread_ids),- self.email_repo.labels_by_thread_ids(&thread_ids),- self.frecency_service- .get_frecencies_by_ids(frecency_request)- );-- let mut attachment_map = attachment_map_result- .map_err(anyhow::Error::from)?- .into_iter()- .group_by(|v| v.thread_id);- let mut participant_map = participant_result- .map_err(anyhow::Error::from)?- .into_iter()- .group_by(|v| v.thread_id);- let mut labels_map = labels_result- .map_err(anyhow::Error::from)?- .into_iter()- .group_by(|v| v.thread_id);-- let mut frecency_scores_map: HashMap<AggregateId<'static>, FrecencyData> =- frecency_scores?.into_inner();-- Ok(previews- .into_iter()- .map(|thread| {- let id = AggregateId {- user_id: thread.owner_id.clone(),- entity: EntityType::EmailThread.with_entity_string(thread.id.to_string()),- };-- EnrichedEmailThreadPreview {- attachments: attachment_map.remove(&thread.id).unwrap_or_default(),- labels: labels_map.remove(&thread.id).unwrap_or_default(),- participants: participant_map.remove(&thread.id).unwrap_or_default(),- frecency_score: frecency_scores_map- .remove(&id)- .map(|data| id.into_aggregate(data)),- thread,- }- })- .paginate_on(limit as usize, sort_method)- .into_page())- }-- async fn get_link_by_auth_id_and_macro_id(- &self,- auth_id: &str,- macro_id: macro_user_id::user_id::MacroUserIdStr<'_>,- ) -> Result<Option<super::models::Link>, EmailErr> {- Ok(self- .email_repo- .link_by_fusionauth_and_macro_id(auth_id, macro_id, UserProvider::Gmail)- .await- .map_err(anyhow::Error::from)?)- }-#[tracing::instrument(err, skip(self, receipt))]- async fn get_thread_with_messages(+ pub(crate) async fn get_thread_with_messages_impl(&self,receipt: EntityAccessReceipt<ViewAccessLevel>,offset: i64,diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rsindex 4be9af914d..7ba834da7d 100644--- a/rust/cloud-storage/email/src/inbound/axum.rs+++ b/rust/cloud-storage/email/src/inbound/axum.rs@@ -1,9 +1,11 @@mod api_types;mod axum_impls;+mod draft_router;mod get_thread_router;mod previews_router;pub use api_types::*;pub use axum_impls::*;+pub use draft_router::*;pub use get_thread_router::*;pub use previews_router::*;diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/draft.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/draft.rsnew file mode 100644index 0000000000..66fd358e1e--- /dev/null+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/draft.rs@@ -0,0 +1,188 @@+use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use serde_json::Value as JsonValue;+use utoipa::ToSchema;+use uuid::Uuid;++use crate::domain::models::{ContactInfo, CreateDraftInput, CreatedDraft};++/// Contact info for draft request/response (backward-compatible with MessageToSend shape).+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct ApiDraftContactInfo {+ /// Email address.+ pub email: String,+ /// Display name.+ pub name: Option<String>,+ /// Profile photo URL.+ pub photo_url: Option<String>,+}++impl From<ApiDraftContactInfo> for ContactInfo {+ fn from(c: ApiDraftContactInfo) -> Self {+ ContactInfo {+ email: c.email,+ name: c.name,+ photo_url: c.photo_url,+ }+ }+}++impl From<ContactInfo> for ApiDraftContactInfo {+ fn from(c: ContactInfo) -> Self {+ ApiDraftContactInfo {+ email: c.email,+ name: c.name,+ photo_url: c.photo_url,+ }+ }+}++/// The draft input matching the current `MessageToSend` JSON shape for backward compat.+#[derive(Debug, Deserialize, ToSchema)]+pub struct ApiDraftInput {+ /// Existing message DB ID (for updating an existing draft).+ pub db_id: Option<Uuid>,+ /// Provider message ID.+ pub provider_id: Option<String>,+ /// ID of the message this draft is replying to.+ pub replying_to_id: Option<Uuid>,+ /// Provider thread ID.+ pub provider_thread_id: Option<String>,+ /// Thread DB ID.+ pub thread_db_id: Option<Uuid>,+ /// Subject line.+ pub subject: String,+ /// To recipients.+ pub to: Option<Vec<ApiDraftContactInfo>>,+ /// Cc recipients.+ pub cc: Option<Vec<ApiDraftContactInfo>>,+ /// Bcc recipients.+ pub bcc: Option<Vec<ApiDraftContactInfo>>,+ /// Plain text body.+ pub body_text: Option<String>,+ /// HTML body (base64 URL_SAFE_NO_PAD encoded).+ pub body_html: Option<String>,+ /// Macro body format.+ pub body_macro: Option<String>,+ /// Headers JSON.+ pub headers_json: Option<JsonValue>,+}++/// Request body for creating a draft.+#[derive(Debug, Deserialize, ToSchema)]+pub struct CreateDraftRequest {+ /// The draft content.+ pub draft: ApiDraftInput,+ /// Scheduled send time.+ pub send_time: Option<DateTime<Utc>>,+}++/// The draft output matching the current `MessageToSend` JSON shape for backward compat.+#[derive(Debug, Serialize, ToSchema)]+pub struct ApiDraftOutput {+ /// Message DB ID.+ pub db_id: Option<Uuid>,+ /// Provider message ID.+ pub provider_id: Option<String>,+ /// ID of the message this draft is replying to.+ pub replying_to_id: Option<Uuid>,+ /// Provider thread ID.+ pub provider_thread_id: Option<String>,+ /// Thread DB ID.+ pub thread_db_id: Option<Uuid>,+ /// Link ID.+ pub link_id: Uuid,+ /// Subject line.+ pub subject: String,+ /// To recipients.+ pub to: Option<Vec<ApiDraftContactInfo>>,+ /// Cc recipients.+ pub cc: Option<Vec<ApiDraftContactInfo>>,+ /// Bcc recipients.+ pub bcc: Option<Vec<ApiDraftContactInfo>>,+ /// Plain text body.+ pub body_text: Option<String>,+ /// HTML body (decoded).+ pub body_html: Option<String>,+ /// Macro body.+ pub body_macro: Option<String>,+ /// Headers JSON.+ pub headers_json: Option<JsonValue>,+ /// Send time.+ pub send_time: Option<DateTime<Utc>>,+}++/// Response body for creating a draft.+#[derive(Debug, Serialize, ToSchema)]+pub struct CreateDraftResponse {+ /// The created draft.+ pub draft: ApiDraftOutput,+}++impl CreateDraftRequest {+ /// Convert the API request into a domain `CreateDraftInput`.+ pub fn into_domain(self) -> CreateDraftInput {+ let draft = self.draft;++ CreateDraftInput {+ db_id: draft.db_id,+ provider_id: draft.provider_id,+ replying_to_id: draft.replying_to_id,+ provider_thread_id: draft.provider_thread_id,+ thread_db_id: draft.thread_db_id,+ subject: draft.subject,+ to: draft+ .to+ .unwrap_or_default()+ .into_iter()+ .map(ContactInfo::from)+ .collect(),+ cc: draft+ .cc+ .unwrap_or_default()+ .into_iter()+ .map(ContactInfo::from)+ .collect(),+ bcc: draft+ .bcc+ .unwrap_or_default()+ .into_iter()+ .map(ContactInfo::from)+ .collect(),+ body_text: draft.body_text,+ body_html: draft.body_html,+ body_macro: draft.body_macro,+ headers_json: draft.headers_json,+ send_time: self.send_time,+ }+ }+}++impl From<CreatedDraft> for ApiDraftOutput {+ fn from(d: CreatedDraft) -> Self {+ let to: Vec<ApiDraftContactInfo> =+ d.to.into_iter().map(ApiDraftContactInfo::from).collect();+ let cc: Vec<ApiDraftContactInfo> =+ d.cc.into_iter().map(ApiDraftContactInfo::from).collect();+ let bcc: Vec<ApiDraftContactInfo> =+ d.bcc.into_iter().map(ApiDraftContactInfo::from).collect();++ ApiDraftOutput {+ db_id: Some(d.db_id),+ provider_id: d.provider_id,+ replying_to_id: d.replying_to_id,+ provider_thread_id: d.provider_thread_id,+ thread_db_id: Some(d.thread_db_id),+ link_id: d.link_id,+ subject: d.subject,+ to: if to.is_empty() { None } else { Some(to) },+ cc: if cc.is_empty() { None } else { Some(cc) },+ bcc: if bcc.is_empty() { None } else { Some(bcc) },+ body_text: d.body_text,+ body_html: d.body_html,+ body_macro: d.body_macro,+ headers_json: d.headers_json,+ send_time: d.send_time,+ }+ }+}diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs b/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rsindex dfacafbebd..a218e1d83f 100644--- a/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs+++ b/rust/cloud-storage/email/src/inbound/axum/api_types/mod.rs@@ -1,3 +1,8 @@+mod draft;++pub use draft::{+ ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, CreateDraftRequest, CreateDraftResponse,+};mod label;mod message;mod preview;diff --git a/rust/cloud-storage/email/src/inbound/axum/draft_router.rs b/rust/cloud-storage/email/src/inbound/axum/draft_router.rsnew file mode 100644index 0000000000..d1d728edb1--- /dev/null+++ b/rust/cloud-storage/email/src/inbound/axum/draft_router.rs@@ -0,0 +1,115 @@+use std::sync::Arc;++use axum::{+ Extension, Json, Router, extract::State, http::StatusCode, response::IntoResponse,+ routing::post,+};+use model_error_response::ErrorResponse;+use thiserror::Error;++use crate::domain::{+ models::{EmailErr, Link},+ ports::EmailService,+};++use super::api_types::{CreateDraftRequest, CreateDraftResponse};++/// State for the draft router, containing only the email service.+pub struct EmailDraftRouterState<T> {+ /// The email service.+ pub service: Arc<T>,+}++impl<T> Clone for EmailDraftRouterState<T> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ }+ }+}++/// Create the draft router with a `POST /` handler.+pub fn draft_router<S, T>(state: EmailDraftRouterState<T>) -> Router<S>+where+ S: Send + Sync + 'static,+ T: EmailService,+{+ Router::new()+ .route("/", post(create_draft_handler::<T>))+ .with_state(state)+}++/// Errors from the create draft handler.+#[derive(Debug, Error)]+pub enum CreateDraftError {+ /// Validation error (bad request).+ #[error("{0}")]+ Validation(String),+ /// Not found.+ #[error("{0}")]+ NotFound(String),+ /// Internal error.+ #[error("Internal error")]+ Internal(EmailErr),+}++impl IntoResponse for CreateDraftError {+ fn into_response(self) -> axum::response::Response {+ if matches!(self, CreateDraftError::Internal(_)) {+ tracing::error!(error=?self, "create draft error");+ }++ let status = match &self {+ CreateDraftError::Validation(_) => StatusCode::BAD_REQUEST,+ CreateDraftError::NotFound(_) => StatusCode::NOT_FOUND,+ CreateDraftError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ let message = self.to_string();+ (status, Json(ErrorResponse { message: &message })).into_response()+ }+}++impl From<EmailErr> for CreateDraftError {+ fn from(err: EmailErr) -> Self {+ match &err {+ EmailErr::MessageNotFound(_) => CreateDraftError::NotFound(err.to_string()),+ EmailErr::MessageAlreadySent(_)+ | EmailErr::CannotReplyToDraft+ | EmailErr::Base64DecodeError(_)+ | EmailErr::Utf8Error(_) => CreateDraftError::Validation(err.to_string()),+ EmailErr::RepoErr(_) | EmailErr::Frecency(_) => CreateDraftError::Internal(err),+ }+ }+}++/// Create a draft.+#[utoipa::path(+ post,+ tag = "Drafts",+ path = "/email/drafts",+ operation_id = "create_draft",+ request_body = CreateDraftRequest,+ responses(+ (status = 201, body = CreateDraftResponse),+ (status = 400, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip(state, link, body))]+pub async fn create_draft_handler<T: EmailService>(+ State(state): State<EmailDraftRouterState<T>>,+ Extension(link): Extension<Link>,+ Json(body): Json<CreateDraftRequest>,+) -> Result<impl IntoResponse, CreateDraftError> {+ let input = body.into_domain();+ let draft = state.service.create_draft(&link, input).await?;++ Ok((+ StatusCode::CREATED,+ Json(CreateDraftResponse {+ draft: draft.into(),+ }),+ ))+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/contact.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/contact.rsnew file mode 100644index 0000000000..4fe9613d06--- /dev/null+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/contact.rs@@ -0,0 +1,191 @@+use crate::domain::models::{ParsedAddresses, RecipientType, UpsertedContacts, UpsertedRecipient};+use sqlx::PgPool;+use std::collections::HashMap;+use uuid::Uuid;++/// Upsert contacts from parsed addresses. Called outside a transaction to avoid deadlocks.+#[tracing::instrument(skip(pool, addresses), err)]+pub(crate) async fn upsert_contacts(+ pool: &PgPool,+ link_id: Uuid,+ addresses: ParsedAddresses,+) -> Result<UpsertedContacts, sqlx::Error> {+ // Collect all unique email addresses and normalize names+ let mut unique_map: HashMap<String, Option<String>> = HashMap::new();++ let from_lower = addresses.from_email.to_lowercase();+ let from_name_normalized =+ email_utils::normalize_contact_name(&from_lower, addresses.from_name.as_deref());+ unique_map.entry(from_lower).or_insert(from_name_normalized);++ for contact in addresses+ .to+ .iter()+ .chain(addresses.cc.iter())+ .chain(addresses.bcc.iter())+ {+ let email_lower = contact.email.to_lowercase();+ unique_map.entry(email_lower.clone()).or_insert_with(|| {+ email_utils::normalize_contact_name(&email_lower, contact.name.as_deref())+ });+ }++ if unique_map.is_empty() {+ return Ok(UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ });+ }++ let mut ids: Vec<Uuid> = Vec::with_capacity(unique_map.len());+ let mut link_ids: Vec<Uuid> = Vec::with_capacity(unique_map.len());+ let mut emails: Vec<String> = Vec::with_capacity(unique_map.len());+ let mut names: Vec<Option<String>> = Vec::with_capacity(unique_map.len());++ for (email, name) in &unique_map {+ ids.push(macro_uuid::generate_uuid_v7());+ link_ids.push(link_id);+ emails.push(email.clone());+ names.push(name.clone());+ }++ // Step 1: Fetch existing contacts+ let existing = sqlx::query!(+ r#"+ SELECT id, email_address+ FROM email_contacts+ WHERE link_id = $1 AND email_address = ANY($2)+ "#,+ link_id,+ &emails,+ )+ .fetch_all(pool)+ .await?;++ let mut email_to_id: HashMap<String, Uuid> = existing+ .into_iter()+ .map(|r| (r.email_address, r.id))+ .collect();++ // Step 2: Update names for existing contacts that don't have one yet+ let name_updates: Vec<(Uuid, String)> = unique_map+ .iter()+ .filter_map(|(email, name)| {+ name.as_ref()+ .and_then(|n| email_to_id.get(email).map(|id| (*id, n.clone())))+ })+ .collect();++ if !name_updates.is_empty() {+ let update_ids: Vec<Uuid> = name_updates.iter().map(|(id, _)| *id).collect();+ let update_names: Vec<String> = name_updates.iter().map(|(_, name)| name.clone()).collect();+ sqlx::query!(+ r#"+ UPDATE email_contacts+ SET name = data.name, updated_at = now()+ FROM (SELECT unnest($1::uuid[]) as id, unnest($2::text[]) as name) as data+ WHERE email_contacts.id = data.id+ AND email_contacts.name IS NULL+ "#,+ &update_ids,+ &update_names,+ )+ .execute(pool)+ .await?;+ }++ // Step 3: Insert new contacts+ let new_ids: Vec<Uuid> = ids+ .iter()+ .zip(emails.iter())+ .filter(|(_, e)| !email_to_id.contains_key(*e))+ .map(|(id, _)| *id)+ .collect();+ let new_link_ids: Vec<Uuid> = new_ids.iter().map(|_| link_id).collect();+ let new_emails: Vec<String> = emails+ .iter()+ .filter(|e| !email_to_id.contains_key(*e))+ .cloned()+ .collect();+ let new_names: Vec<Option<String>> = new_emails+ .iter()+ .map(|e| unique_map.get(e).cloned().flatten())+ .collect();++ if !new_emails.is_empty() {+ let inserted = sqlx::query!(+ r#"+ INSERT INTO email_contacts (id, link_id, email_address, name)+ SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::text[])+ ON CONFLICT (link_id, email_address) DO NOTHING+ RETURNING id, email_address+ "#,+ &new_ids,+ &new_link_ids,+ &new_emails,+ &new_names as &[Option<String>],+ )+ .fetch_all(pool)+ .await?;++ for row in inserted {+ email_to_id.insert(row.email_address, row.id);+ }++ // Step 4: Handle race conditions - fetch any still-missing contacts+ let still_missing: Vec<String> = new_emails+ .iter()+ .filter(|e| !email_to_id.contains_key(*e))+ .cloned()+ .collect();++ if !still_missing.is_empty() {+ let fetched = sqlx::query!(+ r#"+ SELECT id, email_address+ FROM email_contacts+ WHERE link_id = $1 AND email_address = ANY($2)+ "#,+ link_id,+ &still_missing,+ )+ .fetch_all(pool)+ .await?;++ for row in fetched {+ email_to_id.insert(row.email_address, row.id);+ }+ }+ }++ // Build the result+ let from_normalized = addresses.from_email.to_lowercase();+ let from_contact_id = email_to_id.get(&from_normalized).copied();++ let mut recipients = Vec::new();+ let recipient_groups = [+ (&addresses.to, RecipientType::To),+ (&addresses.cc, RecipientType::Cc),+ (&addresses.bcc, RecipientType::Bcc),+ ];++ for (addr_vec, kind) in &recipient_groups {+ for addr in *addr_vec {+ let normalized = addr.email.to_lowercase();+ if let Some(id) = email_to_id.get(&normalized) {+ recipients.push(UpsertedRecipient {+ contact_id: *id,+ name: addr.name.clone(),+ recipient_type: *kind,+ });+ } else {+ tracing::error!(email=%addr.email, type_=?kind, "Recipient ID missing post-upsert");+ }+ }+ }++ Ok(UpsertedContacts {+ from_contact_id,+ recipients,+ })+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rsindex 2d5ad16538..a6d96ae107 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs@@ -1,7 +1,7 @@use crate::domain::models::{Attachment, AttachmentDraft, AttachmentForwarded, ContactInfo, EmailThreadPreview, Label,LabelListVisibility, LabelType, Link, MessageAttachment, MessageLabel, MessageListVisibility,- MessageRow, RecipientType, ThreadRow,+ MessageRow, RecipientType, SimpleMessageInfo, ThreadRow,};use chrono::{DateTime, Utc};use doppleganger::{Doppleganger, Mirror};@@ -427,6 +427,29 @@ impl From<DbRecipientRow> for (uuid::Uuid, ContactInfo, RecipientType) {}}+/// DB row for a simplified message used in draft validation queries.+pub(crate) struct DbSimpleMessageRow {+ pub id: Uuid,+ pub thread_id: Uuid,+ pub provider_thread_id: Option<String>,+ pub headers_jsonb: Option<serde_json::Value>,+ pub is_sent: bool,+ pub is_draft: bool,+}++impl From<DbSimpleMessageRow> for SimpleMessageInfo {+ fn from(row: DbSimpleMessageRow) -> Self {+ Self {+ db_id: row.id,+ thread_db_id: row.thread_id,+ provider_thread_id: row.provider_thread_id,+ headers_json: row.headers_jsonb,+ is_sent: row.is_sent,+ is_draft: row.is_draft,+ }+ }+}+impl DbLink {pub(crate) fn try_into_model(self) -> Result<Link, macro_user_id::error::ParseErr> {let DbLink {diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/draft.rsnew file mode 100644index 0000000000..ba7604eb0e--- /dev/null+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/draft.rs@@ -0,0 +1,116 @@+use super::{message, thread};+use crate::domain::models::{CreateDraftInput, ThreadRow, UpsertedContacts};+use chrono::Utc;+use sqlx::PgPool;+use uuid::Uuid;++/// Insert a draft message within a transaction.+/// Includes: thread insert (if new), message upsert, scheduled message, recipients,+/// thread metadata update, and user history.+/// Returns the thread DB ID.+#[tracing::instrument(skip(pool, input, contacts, new_thread), err)]+pub(crate) async fn insert_draft_message(+ pool: &PgPool,+ input: &CreateDraftInput,+ message_db_id: Uuid,+ thread_db_id: Uuid,+ contacts: &UpsertedContacts,+ link_id: Uuid,+ new_thread: Option<ThreadRow>,+) -> Result<Uuid, sqlx::Error> {+ let mut tx = pool.begin().await?;++ let thread_db_id = if let Some(thread) = new_thread {+ thread::insert_thread(&mut tx, &thread, link_id).await?+ } else {+ thread_db_id+ };++ upsert_draft(+ &mut tx,+ input,+ message_db_id,+ thread_db_id,+ contacts.from_contact_id,+ link_id,+ )+ .await?;++ message::process_scheduled_message(&mut tx, link_id, message_db_id, input.send_time).await?;++ message::upsert_recipients(&mut tx, message_db_id, contacts).await?;++ thread::update_thread_metadata(&mut tx, thread_db_id, link_id).await?;++ thread::upsert_user_history(&mut tx, link_id, thread_db_id).await?;++ tx.commit().await?;+ Ok(thread_db_id)+}++/// Upsert a draft message row.+pub(crate) async fn upsert_draft(+ tx: &mut sqlx::PgConnection,+ input: &CreateDraftInput,+ message_db_id: Uuid,+ thread_db_id: Uuid,+ from_contact_id: Option<Uuid>,+ link_id: Uuid,+) -> Result<(), sqlx::Error> {+ let now = Utc::now();++ sqlx::query!(+ r#"+ INSERT INTO email_messages (+ id, provider_id, link_id, thread_id, provider_thread_id,+ replying_to_id, subject, from_contact_id, sent_at,+ has_attachments, is_read, is_starred, is_sent, is_draft,+ body_text, body_html_sanitized, body_macro, headers_jsonb,+ created_at, updated_at+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)+ ON CONFLICT (id) DO UPDATE SET+ provider_id = EXCLUDED.provider_id,+ thread_id = EXCLUDED.thread_id,+ provider_thread_id = EXCLUDED.provider_thread_id,+ replying_to_id = EXCLUDED.replying_to_id,+ subject = EXCLUDED.subject,+ from_contact_id = EXCLUDED.from_contact_id,+ sent_at = EXCLUDED.sent_at,+ has_attachments = EXCLUDED.has_attachments,+ is_read = EXCLUDED.is_read,+ is_starred = EXCLUDED.is_starred,+ is_sent = EXCLUDED.is_sent,+ is_draft = EXCLUDED.is_draft,+ body_text = EXCLUDED.body_text,+ body_html_sanitized = EXCLUDED.body_html_sanitized,+ body_macro = EXCLUDED.body_macro,+ headers_jsonb = EXCLUDED.headers_jsonb,+ updated_at = NOW()+ "#,+ message_db_id,+ input.provider_id,+ link_id,+ thread_db_id,+ input.provider_thread_id,+ input.replying_to_id,+ input.subject,+ from_contact_id,+ now,+ false, // has_attachments+ true, // is_read+ false, // is_starred+ false, // is_sent+ true, // is_draft (always true for drafts)+ input.body_text,+ input.body_html,+ input.body_macro,+ input.headers_json,+ now,+ now,+ )+ .execute(&mut *tx)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rsindex 8244819aab..af0119bb0e 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/message.rs@@ -1,7 +1,7 @@use crate::domain::{models::{AttachmentDraft, AttachmentForwarded, ContactInfo, MessageAttachment, MessageLabel,- RecipientType,+ RecipientType, SimpleMessageInfo, UpsertedContacts,},ports::RecipientsByMessageId,};@@ -12,7 +12,7 @@ use uuid::Uuid;use super::db_types::{DbDraftAttachmentRow, DbForwardedAttachmentRow, DbMessageAttachmentRow, DbMessageLabelRow,- DbRecipientRow, DbRecipientType, DbSenderRow,+ DbRecipientRow, DbRecipientType, DbSenderRow, DbSimpleMessageRow,};#[tracing::instrument(err, skip(pool, message_ids))]@@ -270,3 +270,185 @@ pub(super) async fn scheduled_send_times_by_message_ids(.map(|r| (r.message_id, r.send_time)).collect())}++/// Fetch a simplified message by DB ID and link ID for validation.+#[tracing::instrument(skip(pool), err)]+pub(crate) async fn get_simple_message(+ pool: &PgPool,+ message_id: Uuid,+ link_id: Uuid,+) -> Result<Option<SimpleMessageInfo>, sqlx::Error> {+ let row = sqlx::query_as!(+ DbSimpleMessageRow,+ r#"+ SELECT+ m.id,+ m.thread_id,+ m.provider_thread_id,+ m.headers_jsonb,+ m.is_sent,+ m.is_draft+ FROM email_messages m+ WHERE m.id = $1 AND m.link_id = $2+ "#,+ message_id,+ link_id,+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.map(SimpleMessageInfo::from))+}++/// Find an existing draft that replies to the given message, identified by+/// the "Macro-In-Reply-To" header value.+#[tracing::instrument(skip(pool), err)]+pub(crate) async fn get_draft_replying_to(+ pool: &PgPool,+ link_id: Uuid,+ replying_to_id: Uuid,+) -> Result<Option<SimpleMessageInfo>, sqlx::Error> {+ let row = sqlx::query_as!(+ DbSimpleMessageRow,+ r#"+ SELECT+ m.id,+ m.thread_id,+ m.provider_thread_id,+ m.headers_jsonb,+ m.is_sent,+ m.is_draft+ FROM email_messages m+ WHERE m.link_id = $1+ AND m.is_draft = true+ AND jsonb_path_exists(+ m.headers_jsonb,+ '$[*] ? (@."Macro-In-Reply-To" == $macro_uuid)'::jsonpath,+ jsonb_build_object('macro_uuid', $2::text)+ )+ ORDER BY m.created_at DESC+ LIMIT 1+ "#,+ link_id,+ replying_to_id.to_string(),+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.map(SimpleMessageInfo::from))+}++/// Upsert or delete a scheduled message based on send_time.+pub(super) async fn process_scheduled_message(+ tx: &mut sqlx::PgConnection,+ link_id: Uuid,+ message_db_id: Uuid,+ send_time: Option<DateTime<Utc>>,+) -> Result<(), sqlx::Error> {+ if let Some(send_time) = send_time {+ sqlx::query!(+ r#"+ INSERT INTO email_scheduled_messages (+ link_id, message_id, send_time, sent,+ created_at, updated_at+ )+ VALUES ($1, $2, $3, $4, NOW(), NOW())+ ON CONFLICT (link_id, message_id) DO UPDATE SET+ send_time = EXCLUDED.send_time,+ sent = EXCLUDED.sent,+ updated_at = NOW()+ "#,+ link_id,+ message_db_id,+ send_time,+ false,+ )+ .execute(&mut *tx)+ .await?;+ } else {+ sqlx::query!(+ r#"+ DELETE FROM email_scheduled_messages+ WHERE link_id = $1 AND message_id = $2+ "#,+ link_id,+ message_db_id,+ )+ .execute(&mut *tx)+ .await?;+ }+ Ok(())+}++/// Upsert message recipients, removing stale ones and inserting new ones.+pub(super) async fn upsert_recipients(+ tx: &mut sqlx::PgConnection,+ message_db_id: Uuid,+ contacts: &UpsertedContacts,+) -> Result<(), sqlx::Error> {+ if contacts.recipients.is_empty() {+ // Delete all existing recipients when the new list is empty.+ sqlx::query!(+ r#"+ DELETE FROM email_message_recipients+ WHERE message_id = $1+ "#,+ message_db_id,+ )+ .execute(&mut *tx)+ .await?;+ return Ok(());+ }++ let n = contacts.recipients.len();+ let mut message_ids: Vec<Uuid> = Vec::with_capacity(n);+ let mut contact_ids: Vec<Uuid> = Vec::with_capacity(n);+ let mut recipient_names: Vec<Option<String>> = Vec::with_capacity(n);+ let mut recipient_types: Vec<DbRecipientType> = Vec::with_capacity(n);++ for r in &contacts.recipients {+ message_ids.push(message_db_id);+ contact_ids.push(r.contact_id);+ recipient_names.push(r.name.clone());+ recipient_types.push(match r.recipient_type {+ RecipientType::To => DbRecipientType::To,+ RecipientType::Cc => DbRecipientType::Cc,+ RecipientType::Bcc => DbRecipientType::Bcc,+ });+ }++ // Delete stale recipients+ sqlx::query!(+ r#"+ DELETE FROM email_message_recipients+ WHERE message_id = $1+ AND (contact_id, recipient_type) NOT IN (+ SELECT contact_id, recipient_type+ FROM unnest($2::uuid[], $3::email_recipient_type[])+ AS t(contact_id, recipient_type)+ )+ "#,+ message_db_id,+ &contact_ids,+ &recipient_types as &[DbRecipientType],+ )+ .execute(&mut *tx)+ .await?;++ // Insert new recipients+ sqlx::query!(+ r#"+ INSERT INTO email_message_recipients (message_id, contact_id, name, recipient_type)+ SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::text[], $4::email_recipient_type[])+ ON CONFLICT (message_id, contact_id, recipient_type) DO NOTHING+ "#,+ &message_ids,+ &contact_ids,+ &recipient_names as &[Option<String>],+ &recipient_types as &[DbRecipientType],+ )+ .execute(&mut *tx)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rsindex 498e33e073..c3f7eef49c 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/mod.rs@@ -1,7 +1,8 @@use crate::domain::{models::{- Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailThreadPreview,- Label, Link, MessageAttachment, MessageLabel, MessageRow, PreviewCursorQuery, ThreadRow,+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,+ EmailThreadPreview, Label, Link, MessageAttachment, MessageLabel, MessageRow,+ ParsedAddresses, PreviewCursorQuery, SimpleMessageInfo, ThreadRow, UpsertedContacts,UserProvider,},ports::{EmailRepo, RecipientsByMessageId},@@ -12,7 +13,9 @@ use sqlx::PgPool;use std::collections::HashMap;use uuid::Uuid;+mod contact;mod db_types;+mod draft;mod dynamic;mod link;mod message;@@ -131,4 +134,49 @@ impl EmailRepo for EmailPgRepo {) -> Result<HashMap<Uuid, DateTime<Utc>>, Self::Err> {message::scheduled_send_times_by_message_ids(&self.pool, message_ids).await}++ async fn get_simple_message(+ &self,+ message_id: Uuid,+ link_id: Uuid,+ ) -> Result<Option<SimpleMessageInfo>, Self::Err> {+ message::get_simple_message(&self.pool, message_id, link_id).await+ }++ async fn get_draft_replying_to(+ &self,+ link_id: Uuid,+ replying_to_id: Uuid,+ ) -> Result<Option<SimpleMessageInfo>, Self::Err> {+ message::get_draft_replying_to(&self.pool, link_id, replying_to_id).await+ }++ async fn upsert_contacts(+ &self,+ link_id: Uuid,+ addresses: ParsedAddresses,+ ) -> Result<UpsertedContacts, Self::Err> {+ contact::upsert_contacts(&self.pool, link_id, addresses).await+ }++ async fn insert_draft_message(+ &self,+ input: &CreateDraftInput,+ message_db_id: Uuid,+ thread_db_id: Uuid,+ contacts: &UpsertedContacts,+ link_id: Uuid,+ new_thread: Option<ThreadRow>,+ ) -> Result<Uuid, Self::Err> {+ draft::insert_draft_message(+ &self.pool,+ input,+ message_db_id,+ thread_db_id,+ contacts,+ link_id,+ new_thread,+ )+ .await+ }}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rsnew file mode 100644index 0000000000..88ed520930--- /dev/null+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/draft.rs@@ -0,0 +1,684 @@+use super::*;+use crate::domain::models::{+ ContactInfo, CreateDraftInput, ParsedAddresses, RecipientType, ThreadRow, UpsertedContacts,+ UpsertedRecipient,+};+use chrono::Utc;+use sqlx::Row;++// ── get_simple_message ────────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_get_simple_message_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let result = repo.get_simple_message(msg_id, link_id).await?;++ let info = result.expect("Message should be found");+ assert_eq!(info.db_id, msg_id);+ assert_eq!(+ info.thread_db_id,+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?+ );+ assert_eq!(+ info.provider_thread_id.as_deref(),+ Some("provider-thread-1")+ );+ assert!(info.is_sent);+ assert!(!info.is_draft);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_get_simple_message_wrong_link_id(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let wrong_link = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;+ let result = repo.get_simple_message(msg_id, wrong_link).await?;++ assert!(result.is_none(), "Wrong link_id should return None");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_get_simple_message_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let missing = Uuid::parse_str("99999999-9999-9999-9999-999999999999")?;+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let result = repo.get_simple_message(missing, link_id).await?;++ assert!(result.is_none());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_get_simple_message_draft_with_headers(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let msg_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let result = repo.get_simple_message(msg_id, link_id).await?;++ let info = result.expect("Draft should be found");+ assert!(info.is_draft);+ assert!(!info.is_sent);+ assert!(info.headers_json.is_some(), "Headers should be present");++ Ok(())+}++// ── get_draft_replying_to ─────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_get_draft_replying_to_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let replying_to = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let result = repo.get_draft_replying_to(link_id, replying_to).await?;++ let info = result.expect("Should find the draft replying to msg1");+ assert_eq!(+ info.db_id,+ Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?+ );+ assert!(info.is_draft);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_get_draft_replying_to_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let no_reply = Uuid::parse_str("ee000003-0000-0000-0000-000000000003")?;+ let result = repo.get_draft_replying_to(link_id, no_reply).await?;++ assert!(result.is_none(), "No draft replies to msg3");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_get_draft_replying_to_wrong_link(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let wrong_link = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")?;+ let replying_to = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let result = repo.get_draft_replying_to(wrong_link, replying_to).await?;++ assert!(result.is_none(), "Wrong link_id should find nothing");++ Ok(())+}++// ── upsert_contacts ───────────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_contacts_existing_contacts(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let addresses = ParsedAddresses {+ from_email: "[email protected]".to_string(),+ from_name: Some("Alice Smith".to_string()),+ to: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: Some("Bob Jones".to_string()),+ photo_url: None,+ }],+ cc: vec![],+ bcc: vec![],+ };++ let result = repo.upsert_contacts(link_id, addresses).await?;++ assert!(+ result.from_contact_id.is_some(),+ "Alice should have a contact ID"+ );+ assert_eq!(+ result.from_contact_id,+ Some(Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?)+ );+ assert_eq!(result.recipients.len(), 1);+ assert_eq!(+ result.recipients[0].contact_id,+ Uuid::parse_str("c0000002-0000-0000-0000-000000000002")?+ );+ assert_eq!(result.recipients[0].recipient_type, RecipientType::To);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_contacts_new_contact(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let addresses = ParsedAddresses {+ from_email: "[email protected]".to_string(),+ from_name: None,+ to: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: Some("New User".to_string()),+ photo_url: None,+ }],+ cc: vec![],+ bcc: vec![],+ };++ let result = repo.upsert_contacts(link_id, addresses).await?;++ assert!(result.from_contact_id.is_some());+ assert_eq!(result.recipients.len(), 1);+ // New contact should have been created with a new UUID+ assert_ne!(+ result.recipients[0].contact_id,+ Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?+ );+ assert_eq!(result.recipients[0].recipient_type, RecipientType::To);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_contacts_fills_missing_name(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ // carol has no name in the fixture+ let addresses = ParsedAddresses {+ from_email: "[email protected]".to_string(),+ from_name: Some("Carol White".to_string()),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ };++ let result = repo.upsert_contacts(link_id, addresses).await?;+ assert!(result.from_contact_id.is_some());++ // Verify the name was updated using non-macro query+ let row = sqlx::query("SELECT name FROM email_contacts WHERE id = $1")+ .bind(Uuid::parse_str("c0000003-0000-0000-0000-000000000003")?)+ .fetch_one(&pool)+ .await?;++ let name: Option<String> = row.get("name");+ assert_eq!(name.as_deref(), Some("Carol White"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_contacts_mixed_to_cc_bcc(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let addresses = ParsedAddresses {+ from_email: "[email protected]".to_string(),+ from_name: None,+ to: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: None,+ photo_url: None,+ }],+ cc: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: None,+ photo_url: None,+ }],+ bcc: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: Some("BCC User".to_string()),+ photo_url: None,+ }],+ };++ let result = repo.upsert_contacts(link_id, addresses).await?;++ assert_eq!(result.recipients.len(), 3);+ assert_eq!(result.recipients[0].recipient_type, RecipientType::To);+ assert_eq!(result.recipients[1].recipient_type, RecipientType::Cc);+ assert_eq!(result.recipients[2].recipient_type, RecipientType::Bcc);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_contacts_case_insensitive(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let addresses = ParsedAddresses {+ from_email: "[email protected]".to_string(),+ from_name: None,+ to: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: None,+ photo_url: None,+ }],+ cc: vec![],+ bcc: vec![],+ };++ let result = repo.upsert_contacts(link_id, addresses).await?;++ // Should resolve to the same existing contacts despite different casing+ assert_eq!(+ result.from_contact_id,+ Some(Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?)+ );+ assert_eq!(+ result.recipients[0].contact_id,+ Uuid::parse_str("c0000002-0000-0000-0000-000000000002")?+ );++ Ok(())+}++// ── insert_draft_message ──────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_draft_message_into_existing_thread(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread_db_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;+ let message_db_id = Uuid::parse_str("dd000001-0000-0000-0000-000000000001")?;+ let from_contact_id = Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?;+ let to_contact_id = Uuid::parse_str("c0000002-0000-0000-0000-000000000002")?;++ let input = CreateDraftInput {+ db_id: None,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: Some("provider-thread-2".to_string()),+ thread_db_id: Some(thread_db_id),+ subject: "Test draft".to_string(),+ to: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: Some("Bob".to_string()),+ photo_url: None,+ }],+ cc: vec![],+ bcc: vec![],+ body_text: Some("Hello".to_string()),+ body_html: Some("<p>Hello</p>".to_string()),+ body_macro: None,+ headers_json: None,+ send_time: None,+ };++ let contacts = UpsertedContacts {+ from_contact_id: Some(from_contact_id),+ recipients: vec![UpsertedRecipient {+ contact_id: to_contact_id,+ name: Some("Bob".to_string()),+ recipient_type: RecipientType::To,+ }],+ };++ let returned_thread_id = repo+ .insert_draft_message(+ &input,+ message_db_id,+ thread_db_id,+ &contacts,+ link_id,+ None,+ )+ .await?;++ assert_eq!(returned_thread_id, thread_db_id);++ // Verify the message was inserted+ let msg = sqlx::query(+ "SELECT thread_id, subject, is_draft, body_text FROM email_messages WHERE id = $1",+ )+ .bind(message_db_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(msg.get::<Uuid, _>("thread_id"), thread_db_id);+ assert_eq!(+ msg.get::<Option<String>, _>("subject").as_deref(),+ Some("Test draft")+ );+ assert!(msg.get::<bool, _>("is_draft"));+ assert_eq!(+ msg.get::<Option<String>, _>("body_text").as_deref(),+ Some("Hello")+ );++ // Verify recipients were inserted+ let recip_count: i64 =+ sqlx::query_scalar("SELECT COUNT(*) FROM email_message_recipients WHERE message_id = $1")+ .bind(message_db_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(recip_count, 1);++ // Verify user history was upserted+ let history_count: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM email_user_history WHERE link_id = $1 AND thread_id = $2",+ )+ .bind(link_id)+ .bind(thread_db_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(history_count, 1, "User history should be created");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_draft_message_with_new_thread(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let new_thread_id = Uuid::parse_str("44444444-4444-4444-4444-444444444444")?;+ let message_db_id = Uuid::parse_str("dd000002-0000-0000-0000-000000000002")?;+ let from_contact_id = Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?;++ let input = CreateDraftInput {+ db_id: None,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id: None,+ subject: "Brand new thread draft".to_string(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: Some("New thread body".to_string()),+ body_html: None,+ body_macro: None,+ headers_json: None,+ send_time: None,+ };++ let contacts = UpsertedContacts {+ from_contact_id: Some(from_contact_id),+ recipients: vec![],+ };++ let new_thread = ThreadRow {+ db_id: new_thread_id,+ provider_id: None,+ link_id,+ inbox_visible: true,+ is_read: true,+ latest_inbound_message_ts: None,+ latest_outbound_message_ts: None,+ latest_non_spam_message_ts: None,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ };++ let returned_thread_id = repo+ .insert_draft_message(+ &input,+ message_db_id,+ new_thread_id,+ &contacts,+ link_id,+ Some(new_thread),+ )+ .await?;++ assert_eq!(returned_thread_id, new_thread_id);++ // Verify the thread was created+ let thread_link: Uuid = sqlx::query_scalar("SELECT link_id FROM email_threads WHERE id = $1")+ .bind(new_thread_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(thread_link, link_id);++ // Verify the message references the new thread+ let msg_thread: Uuid = sqlx::query_scalar("SELECT thread_id FROM email_messages WHERE id = $1")+ .bind(message_db_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(msg_thread, new_thread_id);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_draft_message_with_scheduled_send(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread_db_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;+ let message_db_id = Uuid::parse_str("dd000003-0000-0000-0000-000000000003")?;+ let send_time =+ chrono::DateTime::parse_from_rfc3339("2025-06-01T12:00:00Z")?.with_timezone(&Utc);++ let input = CreateDraftInput {+ db_id: None,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id: Some(thread_db_id),+ subject: "Scheduled draft".to_string(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: None,+ body_html: None,+ body_macro: None,+ headers_json: None,+ send_time: Some(send_time),+ };++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };++ repo.insert_draft_message(+ &input,+ message_db_id,+ thread_db_id,+ &contacts,+ link_id,+ None,+ )+ .await?;++ // Verify the scheduled message was created+ let row =+ sqlx::query("SELECT send_time, sent FROM email_scheduled_messages WHERE message_id = $1")+ .bind(message_db_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(row.get::<chrono::DateTime<Utc>, _>("send_time"), send_time);+ assert!(!row.get::<bool, _>("sent"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread_db_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ // Re-use the existing draft message ID (msg2)+ let message_db_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;++ let input = CreateDraftInput {+ db_id: Some(message_db_id),+ provider_id: None,+ replying_to_id: Some(Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?),+ provider_thread_id: Some("provider-thread-1".to_string()),+ thread_db_id: Some(thread_db_id),+ subject: "Updated draft subject".to_string(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: Some("Updated body".to_string()),+ body_html: None,+ body_macro: None,+ headers_json: None,+ send_time: None,+ };++ let contacts = UpsertedContacts {+ from_contact_id: Some(Uuid::parse_str("c0000001-0000-0000-0000-000000000001")?),+ recipients: vec![],+ };++ repo.insert_draft_message(+ &input,+ message_db_id,+ thread_db_id,+ &contacts,+ link_id,+ None,+ )+ .await?;++ // Verify the message was updated (not duplicated)+ let row = sqlx::query("SELECT subject, body_text FROM email_messages WHERE id = $1")+ .bind(message_db_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(+ row.get::<Option<String>, _>("subject").as_deref(),+ Some("Updated draft subject")+ );+ assert_eq!(+ row.get::<Option<String>, _>("body_text").as_deref(),+ Some("Updated body")+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_draft_message_updates_thread_metadata(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool.clone());++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread_db_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;+ let message_db_id = Uuid::parse_str("dd000004-0000-0000-0000-000000000004")?;++ // Insert a macro draft (no provider_id, is_draft=true) into the thread+ let input = CreateDraftInput {+ db_id: None,+ provider_id: None,+ replying_to_id: None,+ provider_thread_id: None,+ thread_db_id: Some(thread_db_id),+ subject: "Metadata test draft".to_string(),+ to: vec![],+ cc: vec![],+ bcc: vec![],+ body_text: None,+ body_html: None,+ body_macro: None,+ headers_json: None,+ send_time: None,+ };++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };++ repo.insert_draft_message(+ &input,+ message_db_id,+ thread_db_id,+ &contacts,+ link_id,+ None,+ )+ .await?;++ // Thread should now be inbox_visible because it has a macro draft+ let row = sqlx::query("SELECT inbox_visible FROM email_threads WHERE id = $1")+ .bind(thread_db_id)+ .fetch_one(&pool)+ .await?;++ assert!(+ row.get::<bool, _>("inbox_visible"),+ "Thread with macro draft should be inbox_visible"+ );++ Ok(())+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/message.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/message.rsindex 40eb6bd8c3..22870da9f1 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/message.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/message.rs@@ -1,4 +1,7 @@use super::*;+use crate::domain::models::{RecipientType, UpsertedContacts, UpsertedRecipient};+use chrono::Timelike;+use sqlx::Row;// ── senders_by_message_ids ──────────────────────────────────────────@@ -449,3 +452,254 @@ async fn test_scheduled_send_times_by_message_ids_empty_input(Ok(())}++// ── process_scheduled_message ──────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_process_scheduled_message_insert(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ // Truncate to microseconds — Postgres TIMESTAMPTZ only stores microsecond precision+ let send_time = {+ let t = chrono::Utc::now() + chrono::Duration::hours(1);+ t.with_nanosecond(t.nanosecond() / 1000 * 1000).unwrap()+ };++ let mut tx = pool.begin().await?;+ super::super::message::process_scheduled_message(&mut *tx, link_id, msg_id, Some(send_time))+ .await?;+ tx.commit().await?;++ let row = sqlx::query(+ "SELECT send_time, sent FROM email_scheduled_messages WHERE link_id = $1 AND message_id = $2",+ )+ .bind(link_id)+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;++ let stored_time = row.get::<chrono::DateTime<chrono::Utc>, _>("send_time");+ let sent = row.get::<bool, _>("sent");+ assert_eq!(stored_time, send_time);+ assert!(!sent);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_process_scheduled_message_upsert(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ // Truncate to microseconds — Postgres TIMESTAMPTZ only stores microsecond precision+ let trunc =+ |t: chrono::DateTime<chrono::Utc>| t.with_nanosecond(t.nanosecond() / 1000 * 1000).unwrap();+ let send_time1 = trunc(chrono::Utc::now() + chrono::Duration::hours(1));+ let send_time2 = trunc(chrono::Utc::now() + chrono::Duration::hours(2));++ // Insert first+ let mut tx = pool.begin().await?;+ super::super::message::process_scheduled_message(&mut *tx, link_id, msg_id, Some(send_time1))+ .await?;+ tx.commit().await?;++ // Upsert with new time+ let mut tx = pool.begin().await?;+ super::super::message::process_scheduled_message(&mut *tx, link_id, msg_id, Some(send_time2))+ .await?;+ tx.commit().await?;++ let row = sqlx::query(+ "SELECT send_time FROM email_scheduled_messages WHERE link_id = $1 AND message_id = $2",+ )+ .bind(link_id)+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;++ let stored_time = row.get::<chrono::DateTime<chrono::Utc>, _>("send_time");+ assert_eq!(stored_time, send_time2, "Send time should be updated");++ // Still only one row+ let count: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM email_scheduled_messages WHERE link_id = $1 AND message_id = $2",+ )+ .bind(link_id)+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(count, 1);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_process_scheduled_message_delete(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let send_time = chrono::Utc::now() + chrono::Duration::hours(1);++ // Insert first+ let mut tx = pool.begin().await?;+ super::super::message::process_scheduled_message(&mut *tx, link_id, msg_id, Some(send_time))+ .await?;+ tx.commit().await?;++ // Delete by passing None+ let mut tx = pool.begin().await?;+ super::super::message::process_scheduled_message(&mut *tx, link_id, msg_id, None).await?;+ tx.commit().await?;++ let count: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM email_scheduled_messages WHERE link_id = $1 AND message_id = $2",+ )+ .bind(link_id)+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(count, 0, "Scheduled message should be deleted");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_process_scheduled_message_delete_nonexistent(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;++ // Delete when nothing exists — should not error+ let mut tx = pool.begin().await?;+ super::super::message::process_scheduled_message(&mut *tx, link_id, msg_id, None).await?;+ tx.commit().await?;++ Ok(())+}++// ── upsert_recipients ──────────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_recipients_insert(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // msg2 (draft) currently has no recipients in the fixture+ let msg_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;+ let bob_id = Uuid::parse_str("c0000002-0000-0000-0000-000000000002")?;+ let carol_id = Uuid::parse_str("c0000003-0000-0000-0000-000000000003")?;++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![+ UpsertedRecipient {+ contact_id: bob_id,+ name: Some("Bob Jones".to_string()),+ recipient_type: RecipientType::To,+ },+ UpsertedRecipient {+ contact_id: carol_id,+ name: None,+ recipient_type: RecipientType::Cc,+ },+ ],+ };++ let mut tx = pool.begin().await?;+ super::super::message::upsert_recipients(&mut *tx, msg_id, &contacts).await?;+ tx.commit().await?;++ let count: i64 =+ sqlx::query_scalar("SELECT COUNT(*) FROM email_message_recipients WHERE message_id = $1")+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(count, 2, "Should have 2 recipients");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_recipients_removes_stale(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // msg1 has bob=TO in the fixture. Replace with carol=CC.+ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;+ let carol_id = Uuid::parse_str("c0000003-0000-0000-0000-000000000003")?;++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![UpsertedRecipient {+ contact_id: carol_id,+ name: None,+ recipient_type: RecipientType::Cc,+ }],+ };++ let mut tx = pool.begin().await?;+ super::super::message::upsert_recipients(&mut *tx, msg_id, &contacts).await?;+ tx.commit().await?;++ let count: i64 =+ sqlx::query_scalar("SELECT COUNT(*) FROM email_message_recipients WHERE message_id = $1")+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(+ count, 1,+ "Stale recipient should be removed, only carol remains"+ );++ let row = sqlx::query(+ "SELECT contact_id, recipient_type::text FROM email_message_recipients WHERE message_id = $1",+ )+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(row.get::<Uuid, _>("contact_id"), carol_id);+ assert_eq!(row.get::<String, _>("recipient_type"), "CC");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_recipients_empty_deletes_all(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // msg1 has bob=TO. Calling upsert with empty recipients should delete all existing.+ let msg_id = Uuid::parse_str("ee000001-0000-0000-0000-000000000001")?;++ let contacts = UpsertedContacts {+ from_contact_id: None,+ recipients: vec![],+ };++ let mut tx = pool.begin().await?;+ super::super::message::upsert_recipients(&mut *tx, msg_id, &contacts).await?;+ tx.commit().await?;++ let count: i64 =+ sqlx::query_scalar("SELECT COUNT(*) FROM email_message_recipients WHERE message_id = $1")+ .bind(msg_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(+ count, 0,+ "Empty recipients should delete all existing recipients"+ );++ Ok(())+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rsindex 982da03ec0..fba3abc412 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/mod.rs@@ -1,3 +1,4 @@+mod draft;mod dynamic_query;mod labels;mod link;diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rsindex b802aa66ac..7aa6d1d62f 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/thread.rs@@ -195,3 +195,217 @@ async fn test_messages_by_thread_id_paginated_fields_populated(Ok(())}++// ── insert_thread ─────────────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_thread_new(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let new_id = Uuid::parse_str("55555555-5555-5555-5555-555555555555")?;+ let now = chrono::Utc::now();++ let thread = crate::domain::models::ThreadRow {+ db_id: new_id,+ provider_id: None,+ link_id,+ inbox_visible: false,+ is_read: true,+ latest_inbound_message_ts: None,+ latest_outbound_message_ts: None,+ latest_non_spam_message_ts: None,+ created_at: now,+ updated_at: now,+ };++ let mut tx = pool.begin().await?;+ let returned_id = super::super::thread::insert_thread(&mut *tx, &thread, link_id).await?;+ tx.commit().await?;++ assert_eq!(returned_id, new_id);++ // Verify it exists+ let repo = EmailPgRepo::new(pool);+ let fetched = repo+ .thread_by_id(new_id)+ .await?+ .expect("Thread should exist");+ assert_eq!(fetched.db_id, new_id);+ assert!(!fetched.inbox_visible);+ assert!(fetched.is_read);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_insert_thread_conflict_with_provider_id(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let now = chrono::Utc::now();++ // Thread with same provider_id + link_id as fixture thread 1 ("provider-thread-1")+ let thread = crate::domain::models::ThreadRow {+ db_id: Uuid::parse_str("66666666-6666-6666-6666-666666666666")?,+ provider_id: Some("provider-thread-1".to_string()),+ link_id,+ inbox_visible: true,+ is_read: false,+ latest_inbound_message_ts: Some(now),+ latest_outbound_message_ts: None,+ latest_non_spam_message_ts: None,+ created_at: now,+ updated_at: now,+ };++ let mut tx = pool.begin().await?;+ let returned_id = super::super::thread::insert_thread(&mut *tx, &thread, link_id).await?;+ tx.commit().await?;++ // Should return the existing thread's ID, not the new one+ assert_eq!(+ returned_id,+ Uuid::parse_str("11111111-1111-1111-1111-111111111111")?+ );++ Ok(())+}++// ── update_thread_metadata ────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_update_thread_metadata_with_inbound_message(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ use sqlx::Row;++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ // Thread 1 has msg1 (sent, INBOX+SENT labels) and msg2 (draft, no provider_id)+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ let mut tx = pool.begin().await?;+ super::super::thread::update_thread_metadata(&mut tx, thread_id, link_id).await?;+ tx.commit().await?;++ let row = sqlx::query("SELECT inbox_visible, is_read FROM email_threads WHERE id = $1")+ .bind(thread_id)+ .fetch_one(&pool)+ .await?;++ // msg2 is a macro draft (is_draft=true, no provider_id) → inbox_visible = true+ assert!(row.get::<bool, _>("inbox_visible"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_update_thread_metadata_read_status(pool: Pool<Postgres>) -> anyhow::Result<()> {+ use sqlx::Row;++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ // Thread 2 has msg3 (is_read=true)+ let thread_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;++ let mut tx = pool.begin().await?;+ super::super::thread::update_thread_metadata(&mut tx, thread_id, link_id).await?;+ tx.commit().await?;++ let row = sqlx::query("SELECT is_read FROM email_threads WHERE id = $1")+ .bind(thread_id)+ .fetch_one(&pool)+ .await?;++ // All messages in thread 2 are read → thread should be read+ assert!(row.get::<bool, _>("is_read"));++ Ok(())+}++// ── upsert_user_history ───────────────────────────────────────────++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_user_history_insert(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ let mut tx = pool.begin().await?;+ super::super::thread::upsert_user_history(&mut *tx, link_id, thread_id).await?;+ tx.commit().await?;++ let count: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM email_user_history WHERE link_id = $1 AND thread_id = $2",+ )+ .bind(link_id)+ .bind(thread_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(count, 1);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("email_draft"))+)]+async fn test_upsert_user_history_updates_timestamp(pool: Pool<Postgres>) -> anyhow::Result<()> {+ use sqlx::Row;++ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ // Insert first time+ let mut tx = pool.begin().await?;+ super::super::thread::upsert_user_history(&mut *tx, link_id, thread_id).await?;+ tx.commit().await?;++ let row1 = sqlx::query(+ "SELECT updated_at FROM email_user_history WHERE link_id = $1 AND thread_id = $2",+ )+ .bind(link_id)+ .bind(thread_id)+ .fetch_one(&pool)+ .await?;+ let ts1 = row1.get::<chrono::DateTime<chrono::Utc>, _>("updated_at");++ // Insert again (upsert)+ let mut tx = pool.begin().await?;+ super::super::thread::upsert_user_history(&mut *tx, link_id, thread_id).await?;+ tx.commit().await?;++ let row2 = sqlx::query(+ "SELECT updated_at FROM email_user_history WHERE link_id = $1 AND thread_id = $2",+ )+ .bind(link_id)+ .bind(thread_id)+ .fetch_one(&pool)+ .await?;+ let ts2 = row2.get::<chrono::DateTime<chrono::Utc>, _>("updated_at");++ assert!(ts2 >= ts1, "Second upsert should update the timestamp");++ // Still only one row+ let count: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM email_user_history WHERE link_id = $1 AND thread_id = $2",+ )+ .bind(link_id)+ .bind(thread_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(count, 1);++ Ok(())+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rsindex 7b7197e0d2..5dda3003bb 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/thread.rs@@ -1,5 +1,7 @@use crate::domain::models::{MessageRow, ThreadRow};+use chrono::Utc;use sqlx::PgPool;+use std::collections::HashMap;use uuid::Uuid;use super::db_types::{DbMessageRow, DbThreadRow};@@ -56,3 +58,323 @@ pub(super) async fn messages_by_thread_id_paginated(Ok(rows.into_iter().map(MessageRow::from).collect())}++/// Insert a new thread record within a transaction.+pub(super) async fn insert_thread(+ tx: &mut sqlx::PgConnection,+ thread: &ThreadRow,+ link_id: Uuid,+) -> Result<Uuid, sqlx::Error> {+ let result = sqlx::query!(+ r#"+ INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read,+ latest_inbound_message_ts, latest_outbound_message_ts,+ latest_non_spam_message_ts)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ ON CONFLICT (link_id, provider_id) WHERE provider_id IS NOT NULL DO UPDATE+ SET+ latest_inbound_message_ts = EXCLUDED.latest_inbound_message_ts,+ updated_at = NOW()+ RETURNING id+ "#,+ thread.db_id,+ thread.provider_id,+ link_id,+ thread.inbox_visible,+ thread.is_read,+ thread.latest_inbound_message_ts,+ thread.latest_outbound_message_ts,+ thread.latest_non_spam_message_ts,+ )+ .fetch_one(tx)+ .await?;++ Ok(result.id)+}++// --- Thread metadata update ---+// Ported from email_db_client::threads::update::update_thread_metadata.++mod system_labels {+ pub const INBOX: &str = "INBOX";+ pub const SENT: &str = "SENT";+ pub const SPAM: &str = "SPAM";+ pub const TRASH: &str = "TRASH";+}++/// Lightweight message metadata used only for computing thread metadata.+struct MessageMetadata {+ is_draft: bool,+ is_sent: bool,+ is_read: bool,+ provider_id: Option<String>,+ internal_date_ts: Option<chrono::DateTime<Utc>>,+ updated_at: chrono::DateTime<Utc>,+ labels: Vec<String>,+ /// Whether the sender (from_contact_id) is also a recipient of this message.+ sender_is_recipient: bool,+}++fn is_macro_draft(msg: &MessageMetadata) -> bool {+ msg.is_draft && msg.provider_id.is_none()+}++fn is_inbound(msg: &MessageMetadata) -> bool {+ if !msg.labels.iter().any(|l| l == system_labels::INBOX) {+ return false;+ }++ if !(msg.is_draft || msg.is_sent) {+ return true;+ }++ // edge case for messages a user sent to themselves+ msg.sender_is_recipient+}++fn is_outbound(msg: &MessageMetadata) -> bool {+ if msg.labels.iter().any(|l| l == system_labels::TRASH) {+ return false;+ }++ msg.is_sent+}++fn is_spam_or_trash(msg: &MessageMetadata) -> bool {+ msg.labels+ .iter()+ .any(|l| matches!(l.as_str(), system_labels::SPAM | system_labels::TRASH))+}++/// Fetch lightweight message metadata for all messages in a thread.+async fn fetch_messages_metadata(+ tx: &mut sqlx::PgConnection,+ thread_db_id: Uuid,+) -> Result<Vec<MessageMetadata>, sqlx::Error> {+ struct RawMsg {+ id: Uuid,+ is_draft: bool,+ is_sent: bool,+ is_read: bool,+ provider_id: Option<String>,+ internal_date_ts: Option<chrono::DateTime<Utc>>,+ updated_at: chrono::DateTime<Utc>,+ }++ let messages = sqlx::query_as!(+ RawMsg,+ r#"+ SELECT+ id, is_draft, is_sent, is_read, provider_id,+ internal_date_ts, updated_at+ FROM email_messages+ WHERE thread_id = $1+ ORDER BY internal_date_ts DESC NULLS LAST+ "#,+ thread_db_id,+ )+ .fetch_all(&mut *tx)+ .await?;++ if messages.is_empty() {+ return Ok(Vec::new());+ }++ let message_ids: Vec<Uuid> = messages.iter().map(|m| m.id).collect();++ // Fetch labels for all messages+ struct LabelRow {+ message_id: Uuid,+ provider_label_id: String,+ }++ let label_rows = sqlx::query_as!(+ LabelRow,+ r#"+ SELECT ml.message_id, el.provider_label_id+ FROM email_message_labels ml+ JOIN email_labels el ON el.id = ml.label_id+ WHERE ml.message_id = ANY($1)+ "#,+ &message_ids,+ )+ .fetch_all(&mut *tx)+ .await?;++ let mut labels_map: HashMap<Uuid, Vec<String>> = HashMap::new();+ for row in label_rows {+ labels_map+ .entry(row.message_id)+ .or_default()+ .push(row.provider_label_id);+ }++ // Check which messages have the sender as a recipient (for self-sent edge case)+ struct SelfSentRow {+ message_id: Uuid,+ }++ let self_sent_rows = sqlx::query_as!(+ SelfSentRow,+ r#"+ SELECT DISTINCT emr.message_id+ FROM email_message_recipients emr+ JOIN email_messages m ON m.id = emr.message_id+ WHERE emr.message_id = ANY($1)+ AND m.from_contact_id IS NOT NULL+ AND emr.contact_id = m.from_contact_id+ "#,+ &message_ids,+ )+ .fetch_all(&mut *tx)+ .await?;++ let self_sent_set: std::collections::HashSet<Uuid> =+ self_sent_rows.into_iter().map(|r| r.message_id).collect();++ Ok(messages+ .into_iter()+ .map(|m| MessageMetadata {+ labels: labels_map.remove(&m.id).unwrap_or_default(),+ sender_is_recipient: self_sent_set.contains(&m.id),+ is_draft: m.is_draft,+ is_sent: m.is_sent,+ is_read: m.is_read,+ provider_id: m.provider_id,+ internal_date_ts: m.internal_date_ts,+ updated_at: m.updated_at,+ })+ .collect())+}++/// Recalculate and update thread metadata from all messages in the thread.+/// This is the exact same logic as `email_db_client::threads::update::update_thread_metadata`.+pub(super) async fn update_thread_metadata(+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ thread_db_id: Uuid,+ link_id: Uuid,+) -> Result<(), sqlx::Error> {+ let messages = fetch_messages_metadata(tx, thread_db_id).await?;++ // if any non-sent message in the thread has the INBOX label, the thread is visible in the inbox+ let inbox_visible = messages.iter().any(|message| {+ let has_inbox = message.labels.iter().any(|l| l == system_labels::INBOX);+ let has_sent = message.labels.iter().any(|l| l == system_labels::SENT);++ (has_inbox && !has_sent) || is_macro_draft(message)+ });++ // if any message in the thread is unread, the thread is considered unread in the FE+ let is_read = !messages.iter().any(|message| !message.is_read);++ let latest_draft_ts = messages+ .iter()+ .filter(|msg| is_macro_draft(msg))+ .map(|msg| msg.updated_at)+ .max();++ let latest_inbound_timestamp_ts = messages+ .iter()+ .find(|msg| is_inbound(msg))+ .map(|msg| msg.internal_date_ts)+ .unwrap_or(None);++ let latest_inbound_or_draft_ts = [latest_inbound_timestamp_ts, latest_draft_ts]+ .into_iter()+ .flatten()+ .max();++ let latest_outbound_message_ts = messages+ .iter()+ .find(|msg| is_outbound(msg))+ .map(|msg| msg.internal_date_ts)+ .unwrap_or(None);++ // latest non-spam message timestamp is the latest macro draft or provider message+ let latest_provider_message_ts = messages+ .iter()+ .find(|msg| !is_spam_or_trash(msg))+ .map(|msg| msg.internal_date_ts)+ .unwrap_or(None);++ let latest_non_spam_message_ts = [latest_provider_message_ts, latest_draft_ts]+ .into_iter()+ .flatten()+ .max();++ update_db_thread_metadata(+ tx,+ thread_db_id,+ link_id,+ inbox_visible,+ is_read,+ latest_inbound_or_draft_ts,+ latest_outbound_message_ts,+ latest_non_spam_message_ts,+ )+ .await?;++ Ok(())+}++#[allow(clippy::too_many_arguments)]+async fn update_db_thread_metadata(+ tx: &mut sqlx::PgConnection,+ thread_id: Uuid,+ link_id: Uuid,+ inbox_visible: bool,+ is_read: bool,+ latest_inbound_message_ts: Option<chrono::DateTime<Utc>>,+ latest_outbound_message_ts: Option<chrono::DateTime<Utc>>,+ latest_non_spam_message_ts: Option<chrono::DateTime<Utc>>,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"+ UPDATE email_threads+ SET+ inbox_visible = $1,+ is_read = $2,+ latest_inbound_message_ts = $3,+ latest_outbound_message_ts = $4,+ latest_non_spam_message_ts = $5,+ updated_at = NOW()+ WHERE+ id = $6 AND+ link_id = $7+ "#,+ inbox_visible,+ is_read,+ latest_inbound_message_ts,+ latest_outbound_message_ts,+ latest_non_spam_message_ts,+ thread_id,+ link_id,+ )+ .execute(tx)+ .await?;++ Ok(())+}++/// Upsert user history for thread interaction tracking.+pub(super) async fn upsert_user_history(+ tx: &mut sqlx::PgConnection,+ link_id: Uuid,+ thread_id: Uuid,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"+ INSERT INTO email_user_history (link_id, thread_id, created_at, updated_at)+ VALUES ($1, $2, NOW(), NOW())+ ON CONFLICT (link_id, thread_id)+ DO UPDATE SET+ updated_at = NOW()+ "#,+ link_id,+ thread_id,+ )+ .execute(tx)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/contacts/normalize.rs b/rust/cloud-storage/email_db_client/src/contacts/normalize.rsindex b74940528b..41a00bb16f 100644--- a/rust/cloud-storage/email_db_client/src/contacts/normalize.rs+++ b/rust/cloud-storage/email_db_client/src/contacts/normalize.rs@@ -1,22 +1,8 @@-#[cfg(test)]-mod tests;-use models_email::db::contact::ContactPhotoless;-use once_cell::sync::Lazy;-use regex::Regex;pub fn normalize_contact(contact: ContactPhotoless) -> ContactPhotoless {- let normalized_name = if email_utils::is_generic_email(&contact.email_address) {- None- } else {- contact.name.as_ref().and_then(|name_str| {- if contains_email(name_str) {- None- } else {- Some(remove_name_suffix(name_str))- }- })- };+ let normalized_name =+ email_utils::normalize_contact_name(&contact.email_address, contact.name.as_deref());ContactPhotoless {id: contact.id,@@ -25,45 +11,3 @@ pub fn normalize_contact(contact: ContactPhotoless) -> ContactPhotoless {name: normalized_name,}}--/// Checks if a string contains an email address pattern-///-/// This function detects email patterns like "[email protected]" but not-/// patterns like "Gordon @ Calendly" (spaces around @ without domain).-fn contains_email(text: &str) -> bool {- static EMAIL_PATTERN: Lazy<Regex> = Lazy::new(|| Regex::new(r"\S+@\S+\.\S+").unwrap());- EMAIL_PATTERN.is_match(text)-}--/// Removes service suffixes from a contact name and normalizes spaces-///-/// This function detects and removes:-/// 1. Suffixes in the format " (via ServiceName)"-/// 2. Suffixes in the format " via ServiceName"-/// 3. Specific known suffixes like " (Figma)" and " (Google Calendar)"-///-/// # Arguments-/// * `name` - The name to process-///-/// # Returns-/// * The processed name with suffixes removed and non-breaking spaces replaced-fn remove_name_suffix(name: &str) -> String {- // Static regex patterns compiled only once- static VIA_PATTERN: Lazy<Regex> = Lazy::new(|| Regex::new(r" via [^()]+$").unwrap());- static VIA_PARENS_PATTERN: Lazy<Regex> = Lazy::new(|| Regex::new(r" \(via [^()]+\)$").unwrap());- static SPECIFIC_SUFFIX_PATTERN: Lazy<Regex> = Lazy::new(|| {- Regex::new(- r" \((Figma|Google Calendar|Shared via Google|Google Drive|Dropbox|Microsoft 365)\)$",- )- .unwrap()- });-- // First remove any non-breaking spaces (U+00A0) and replace with regular spaces- let name = name.replace('\u{00A0}', " ");-- // Apply the regex replacements in sequence- let name = VIA_PATTERN.replace(&name, "").to_string();- let name = VIA_PARENS_PATTERN.replace(&name, "").to_string();-- SPECIFIC_SUFFIX_PATTERN.replace(&name, "").to_string()-}diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rsindex 6741a1de0a..ec6262c0f3 100644--- a/rust/cloud-storage/email_service/src/api/context.rs+++ b/rust/cloud-storage/email_service/src/api/context.rs@@ -2,7 +2,7 @@ use axum::extract::FromRef;use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl,- inbound::{EmailPreviewState, EmailThreadRouterState},+ inbound::{EmailDraftRouterState, EmailPreviewState, EmailThreadRouterState},outbound::EmailPgRepo,};use email_service::config::Config;@@ -36,4 +36,5 @@ pub(crate) struct ApiContext {pub email_service: EmailPreviewState<EmailSvc>,pub entity_access_service: Arc<EmailEntityAccessService>,pub email_thread_state: EmailThreadRouterState<EmailSvc, EmailEntityAccessService>,+ pub email_draft_state: EmailDraftRouterState<EmailSvc>,}diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rsindex 29c053aae0..35c37ec538 100644--- a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs@@ -1,5 +1,6 @@pub(crate) mod add_attachment;pub(crate) mod add_forwarded_attachment;+#[allow(dead_code)]pub(crate) mod create;pub(crate) mod delete;pub(crate) mod remove_attachment;@@ -9,10 +10,11 @@ pub(crate) mod scheduled;use crate::api::ApiContext;use axum::Router;use axum::routing::{delete, post};+use email::inbound::draft_router;pub fn router(state: ApiContext) -> Router<ApiContext> {Router::new()- .route("/", post(create::handler))+ .merge(draft_router(state.email_draft_state)).nest("/scheduled", scheduled::router()).route("/:id", delete(delete::handler)).route("/:id/attachments", post(add_attachment::handler))diff --git a/rust/cloud-storage/email_service/src/api/middleware/link.rs b/rust/cloud-storage/email_service/src/api/middleware/link.rsindex a64456eaa7..66f754e091 100644--- a/rust/cloud-storage/email_service/src/api/middleware/link.rs+++ b/rust/cloud-storage/email_service/src/api/middleware/link.rs@@ -9,6 +9,10 @@ pub(in crate::api) async fn attach_link_context<U: EmailService>(next: Next,) -> Result<Response, Response> {req.extensions_mut()- .insert(models_email::email::service::link::Link::mirror(link));+ .insert(models_email::email::service::link::Link::mirror(+ link.clone(),+ ));+ // Also insert the hex Link for use by hex crate handlers.+ req.extensions_mut().insert(link);Ok(next.run(req).await)}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex da22a074c2..f245bb31f5 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -9,7 +9,6 @@ use crate::api::email::drafts::add_attachment::{use crate::api::email::drafts::add_forwarded_attachment::{AddForwardedAttachmentRequest, AddForwardedAttachmentResponse,};-use crate::api::email::drafts::create::{CreateDraftRequest, CreateDraftResponse};use crate::api::email::init::InitResponse;use crate::api::email::labels::create::CreateLabelRequest;use crate::api::email::labels::create::CreateLabelResponse;@@ -23,7 +22,9 @@ use crate::api::email::threads::labels::UpdateThreadLabelRequest;use crate::api::{email, health};use ::email::inbound;use ::email::inbound::{- ApiPaginatedThreadCursor, ApiSortMethod, ApiThread, GetPreviewsCursorParams, GetThreadResponse,+ ApiDraftContactInfo, ApiDraftInput, ApiDraftOutput, ApiPaginatedThreadCursor, ApiSortMethod,+ ApiThread, CreateDraftRequest as HexCreateDraftRequest,+ CreateDraftResponse as HexCreateDraftResponse, GetPreviewsCursorParams, GetThreadResponse,};use model::response::EmptyResponse;use models_email::api::settings::Settings;@@ -50,7 +51,7 @@ use utoipa::OpenApi;email::backfill::get::handler,email::backfill::get::active_handler,email::init::handler,- email::drafts::create::handler,+ inbound::create_draft_handler,email::drafts::delete::handler,email::drafts::scheduled::list::handler,email::drafts::scheduled::remove::handler,@@ -86,8 +87,11 @@ use utoipa::OpenApi;GetActiveBackfillJobResponse,BackfillJob,// Draft types- CreateDraftRequest,- CreateDraftResponse,+ HexCreateDraftRequest,+ HexCreateDraftResponse,+ ApiDraftInput,+ ApiDraftOutput,+ ApiDraftContactInfo,AddDraftAttachmentRequest,AddDraftAttachmentResponse,AddForwardedAttachmentRequest,diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex 89d6b2372e..4726f1c453 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -3,7 +3,7 @@ use anyhow::Context;use document_storage_service_client::DocumentStorageServiceClient;use email::{domain::service::EmailServiceImpl,- inbound::{EmailPreviewState, EmailThreadRouterState},+ inbound::{EmailDraftRouterState, EmailPreviewState, EmailThreadRouterState},outbound::EmailPgRepo,};use email_service::config::EmailServiceCloudfrontSignerPrivateKey;@@ -136,6 +136,9 @@ async fn main() -> anyhow::Result<()> {service: email_service.service(),access_service: entity_access_service.clone(),};+ let email_draft_state = EmailDraftRouterState {+ service: email_service.service(),+ };api::setup_and_serve(ApiContext {db,@@ -153,6 +156,7 @@ async fn main() -> anyhow::Result<()> {email_service,entity_access_service,email_thread_state,+ email_draft_state,}).await?;Ok(())diff --git a/rust/cloud-storage/email_utils/src/lib.rs b/rust/cloud-storage/email_utils/src/lib.rsindex ba92074d93..1d65f54d48 100644--- a/rust/cloud-storage/email_utils/src/lib.rs+++ b/rust/cloud-storage/email_utils/src/lib.rs@@ -1,4 +1,6 @@pub mod body_replyless;pub mod generic_email;+pub mod normalize_contact;pub use generic_email::{dedupe_emails, is_generic_email};+pub use normalize_contact::normalize_contact_name;diff --git a/rust/cloud-storage/email_utils/src/normalize_contact/mod.rs b/rust/cloud-storage/email_utils/src/normalize_contact/mod.rsnew file mode 100644index 0000000000..b499e21dcc--- /dev/null+++ b/rust/cloud-storage/email_utils/src/normalize_contact/mod.rs@@ -0,0 +1,70 @@+#[cfg(test)]+mod test;++use lazy_static::lazy_static;+use regex::Regex;++/// Normalizes a contact name for storage.+///+/// Returns `None` if:+/// - The email is a generic/no-reply address+/// - The name contains an email address pattern+/// - The input name is `None`+///+/// Otherwise returns the name with service suffixes stripped and non-breaking spaces normalized.+pub fn normalize_contact_name(email: &str, name: Option<&str>) -> Option<String> {+ if crate::is_generic_email(email) {+ return None;+ }++ name.and_then(|name_str| {+ if contains_email(name_str) {+ None+ } else {+ Some(remove_name_suffix(name_str))+ }+ })+}++/// Checks if a string contains an email address pattern+///+/// This function detects email patterns like "[email protected]" but not+/// patterns like "Gordon @ Calendly" (spaces around @ without domain).+fn contains_email(text: &str) -> bool {+ lazy_static! {+ static ref EMAIL_PATTERN: Regex = Regex::new(r"\S+@\S+\.\S+").unwrap();+ }+ EMAIL_PATTERN.is_match(text)+}++/// Removes service suffixes from a contact name and normalizes spaces+///+/// This function detects and removes:+/// 1. Suffixes in the format " (via ServiceName)"+/// 2. Suffixes in the format " via ServiceName"+/// 3. Specific known suffixes like " (Figma)" and " (Google Calendar)"+///+/// # Arguments+/// * `name` - The name to process+///+/// # Returns+/// * The processed name with suffixes removed and non-breaking spaces replaced+fn remove_name_suffix(name: &str) -> String {+ lazy_static! {+ static ref VIA_PATTERN: Regex = Regex::new(r" via [^()]+$").unwrap();+ static ref VIA_PARENS_PATTERN: Regex = Regex::new(r" \(via [^()]+\)$").unwrap();+ static ref SPECIFIC_SUFFIX_PATTERN: Regex = Regex::new(+ r" \((Figma|Google Calendar|Shared via Google|Google Drive|Dropbox|Microsoft 365)\)$",+ )+ .unwrap();+ }++ // First remove any non-breaking spaces (U+00A0) and replace with regular spaces+ let name = name.replace('\u{00A0}', " ");++ // Apply the regex replacements in sequence+ let name = VIA_PATTERN.replace(&name, "").to_string();+ let name = VIA_PARENS_PATTERN.replace(&name, "").to_string();++ SPECIFIC_SUFFIX_PATTERN.replace(&name, "").to_string()+}diff --git a/rust/cloud-storage/email_db_client/src/contacts/normalize/tests.rs b/rust/cloud-storage/email_utils/src/normalize_contact/test.rssimilarity index 81%rename from rust/cloud-storage/email_db_client/src/contacts/normalize/tests.rsrename to rust/cloud-storage/email_utils/src/normalize_contact/test.rsindex 5b9a32a731..64829d509b 100644--- a/rust/cloud-storage/email_db_client/src/contacts/normalize/tests.rs+++ b/rust/cloud-storage/email_utils/src/normalize_contact/test.rs@@ -1,4 +1,42 @@-use crate::contacts::normalize::{contains_email, remove_name_suffix};+use super::{contains_email, remove_name_suffix};+use crate::normalize_contact::normalize_contact_name;++#[test]+fn test_normalize_contact_name_generic_email() {+ assert_eq!(+ normalize_contact_name("[email protected]", Some("No Reply")),+ None+ );+}++#[test]+fn test_normalize_contact_name_with_email_in_name() {+ assert_eq!(+ normalize_contact_name("[email protected]", Some("[email protected]")),+ None+ );+}++#[test]+fn test_normalize_contact_name_with_suffix() {+ assert_eq!(+ normalize_contact_name("[email protected]", Some("John Doe via Gmail")),+ Some("John Doe".to_string())+ );+}++#[test]+fn test_normalize_contact_name_none() {+ assert_eq!(normalize_contact_name("[email protected]", None), None);+}++#[test]+fn test_normalize_contact_name_regular() {+ assert_eq!(+ normalize_contact_name("[email protected]", Some("John Doe")),+ Some("John Doe".to_string())+ );+}#[test]fn test_remove_name_suffix() {@@ -80,13 +118,10 @@ fn test_remove_name_suffix() {#[test]fn test_contains_email_with_valid_emails() {- // Standard email formatsassert!(contains_email("[email protected]"));assert!(contains_email("[email protected]"));assert!(contains_email("[email protected]"));assert!(contains_email("[email protected]"));-- // Emails within textassert!(contains_email("Contact [email protected] for info"));assert!(contains_email("John Doe ([email protected])"));assert!(contains_email("Email: [email protected]"));@@ -96,7 +131,6 @@ fn test_contains_email_with_valid_emails() {#[test]fn test_contains_email_with_spaces_around_at() {- // These should NOT match (spaces around @)assert!(!contains_email("Gordon @ Calendly"));assert!(!contains_email("Sales @ Company"));assert!(!contains_email("Support @ Microsoft"));@@ -106,7 +140,6 @@ fn test_contains_email_with_spaces_around_at() {#[test]fn test_contains_email_without_domain() {- // No dot after @ - should not matchassert!(!contains_email("user@localhost"));assert!(!contains_email("test@domain"));assert!(!contains_email("Contact @ HQ"));@@ -114,23 +147,14 @@ fn test_contains_email_without_domain() {#[test]fn test_contains_email_edge_cases() {- // Empty and whitespaceassert!(!contains_email(""));assert!(!contains_email(" "));-- // Just @ symbolassert!(!contains_email("@"));assert!(!contains_email(" @ "));-- // Multiple @ symbols- assert!(contains_email("test@@example.com")); // Matches because of pattern+ assert!(contains_email("test@@example.com"));assert!(contains_email("[email protected] and [email protected]"));-- // Special charactersassert!(contains_email("[email protected]"));assert!(contains_email("[email protected]"));-- // No @ at allassert!(!contains_email("John Doe"));assert!(!contains_email("Regular Name"));assert!(!contains_email("Company Name Inc."));@@ -138,15 +162,10 @@ fn test_contains_email_edge_cases() {#[test]fn test_contains_email_with_formatting() {- // Parenthesesassert!(contains_email("([email protected])"));assert!(contains_email("[[email protected]]"));-- // Quotesassert!(contains_email("\"[email protected]\""));assert!(contains_email("'[email protected]'"));-- // Mixed with other textassert!(contains_email("For questions, email [email protected] or call us"));diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex 1d71184a78..7a0ae217a5 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -55,6 +55,14 @@ impl EmailService for NoopEmailService {) -> Result<Option<email::domain::models::Thread>, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))}++ async fn create_draft(+ &self,+ _link: &email::domain::models::Link,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::CreatedDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))+ }}struct NoopCommsService;diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rsindex 93ae696ab0..fe04c14d80 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs@@ -99,6 +99,14 @@ impl EmailService for MockEmail {) -> Result<Option<email::domain::models::Thread>, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}++ async fn create_draft(+ &self,+ _link: &email::domain::models::Link,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::CreatedDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }}fn mock_router() -> Router {@@ -171,6 +179,14 @@ impl EmailService for MockEmailLinkResult {) -> Result<Option<email::domain::models::Thread>, EmailErr> {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}++ async fn create_draft(+ &self,+ _link: &email::domain::models::Link,+ _input: email::domain::models::CreateDraftInput,+ ) -> Result<email::domain::models::CreatedDraft, EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }}#[tokio::test]