Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(email): Set email sender as Signal/Noise with email_filters (#2190)

Evan Hutnikc8a15410ee59
diff --git a/js/app/packages/app/component/next-soup/actions/index.ts b/js/app/packages/app/component/next-soup/actions/index.ts
index 70f0ebe803..9a78558329 100644
--- a/js/app/packages/app/component/next-soup/actions/index.ts
+++ b/js/app/packages/app/component/next-soup/actions/index.ts
@@ -1,4 +1,6 @@
export { makeBlockSenderAction } from './make-block-sender-action';
+export { makeMarkSenderSignalAction } from './make-mark-sender-important-action';
+export { makeMarkSenderNoiseAction } from './make-mark-sender-noise-action';
export { makeMarkDoneAction } from './make-mark-done-action';
export { makeDeleteAction } from './make-delete-action';
export { makeRenameAction } from './make-rename-action';
diff --git a/js/app/packages/app/component/next-soup/actions/make-mark-sender-important-action.ts b/js/app/packages/app/component/next-soup/actions/make-mark-sender-important-action.ts
new file mode 100644
index 0000000000..8ff5eea7bb
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-mark-sender-important-action.ts
@@ -0,0 +1,5 @@
+import { markSenderSignalWithToast } from '@queries/email/thread';
+import { makeSenderFilterAction } from './make-sender-filter-action';
+
+export const makeMarkSenderSignalAction = () =>
+ makeSenderFilterAction(markSenderSignalWithToast);
diff --git a/js/app/packages/app/component/next-soup/actions/make-mark-sender-noise-action.ts b/js/app/packages/app/component/next-soup/actions/make-mark-sender-noise-action.ts
new file mode 100644
index 0000000000..fa59c5442d
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-mark-sender-noise-action.ts
@@ -0,0 +1,5 @@
+import { markSenderNoiseWithToast } from '@queries/email/thread';
+import { makeSenderFilterAction } from './make-sender-filter-action';
+
+export const makeMarkSenderNoiseAction = () =>
+ makeSenderFilterAction(markSenderNoiseWithToast);
diff --git a/js/app/packages/app/component/next-soup/actions/make-sender-filter-action.ts b/js/app/packages/app/component/next-soup/actions/make-sender-filter-action.ts
new file mode 100644
index 0000000000..b659929055
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/actions/make-sender-filter-action.ts
@@ -0,0 +1,26 @@
+import type { EntityData } from '@entity';
+import type { SoupState } from '../create-soup-state';
+
+export const makeSenderFilterAction = (
+ action: (email: string) => Promise<void>
+) => {
+ const canExecute = (entity: EntityData): boolean =>
+ entity.type === 'email' && !!entity.senderEmail;
+
+ const execute = async (entities: EntityData[]) => {
+ const seen = new Set<string>();
+ for (const entity of entities) {
+ if (entity.type !== 'email' || !entity.senderEmail) continue;
+ const key = entity.senderEmail.trim().toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ await action(entity.senderEmail);
+ }
+ };
+
+ const executeWithSoup = async (entities: EntityData[], _soup: SoupState) => {
+ await execute(entities);
+ };
+
+ return { canExecute, execute, executeWithSoup };
+};
diff --git a/js/app/packages/app/component/next-soup/filters/inbox-filters.ts b/js/app/packages/app/component/next-soup/filters/inbox-filters.ts
index fbc683a996..36f64931f9 100644
--- a/js/app/packages/app/component/next-soup/filters/inbox-filters.ts
+++ b/js/app/packages/app/component/next-soup/filters/inbox-filters.ts
@@ -6,6 +6,7 @@ import {
type EntityData,
} from '@entity';
import { useUserId } from '@core/context/user';
+import { ENABLE_CLIENT_EMAIL_SIGNAL_FILTER } from '@core/constant/featureFlags';
const PRIORITY_LABELS = [
{
@@ -149,6 +150,7 @@ export function signalFilter(entity: EntityData): boolean {
return true;
}
case 'email':
+ if (!ENABLE_CLIENT_EMAIL_SIGNAL_FILTER) return true;
return isSignalEmail(entity) || entity.isDraft;
case 'project':
return true;
@@ -160,6 +162,8 @@ export function signalFilter(entity: EntityData): boolean {
* Returns the opposite of signal filter.
*/
export function noiseFilter(entity: EntityData): boolean {
+ if (entity.type === 'email' && !ENABLE_CLIENT_EMAIL_SIGNAL_FILTER)
+ return true;
return !signalFilter(entity);
}
@@ -173,6 +177,7 @@ export function noiseFilter(entity: EntityData): boolean {
*/
export function explicitNoiseFilter(entity: EntityData): boolean {
if (entity.type === 'email') {
+ if (!ENABLE_CLIENT_EMAIL_SIGNAL_FILTER) return false;
return isNoiseEmail(entity);
}
// Non-email items are never explicit noise
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
index a2c6e8ef7a..9af1293839 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
@@ -10,6 +10,8 @@ import {
makeCopyLinkAction,
makeDeleteAction,
makeMarkDoneAction,
+ makeMarkSenderNoiseAction,
+ makeMarkSenderSignalAction,
makeMoveToProjectAction,
makeRenameAction,
makeShareAction,
@@ -18,6 +20,14 @@ import type { SoupState } from '../create-soup-state';
import { useUserId } from '@core/context/user';
import { useAnalytics } from '@app/component/analytics-context';
import { Show } from 'solid-js';
+import { useSoupView } from './soup-view-context';
+
+const SIGNAL_TABS = new Set<string | undefined>([
+ undefined,
+ 'signal',
+ 'important',
+]);
+const NOISE_TABS = new Set(['noise']);
interface SoupEntityActionsMenuProps {
entities: EntityData[];
@@ -27,6 +37,7 @@ interface SoupEntityActionsMenuProps {
export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
const analytics = useAnalytics();
+ const { activeTab } = useSoupView();
const userId = useUserId();
const notificationSource = useGlobalNotificationSource();
@@ -56,6 +67,9 @@ export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
const blockSenderAction = makeBlockSenderAction();
+ const markSenderSignalAction = makeMarkSenderSignalAction();
+ const markSenderNoiseAction = makeMarkSenderNoiseAction();
+
const canExecuteAny = (canExecute: (e: EntityData) => boolean) =>
props.entities.some(canExecute);
@@ -113,8 +127,9 @@ export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
canExecuteAll(renameAction.canExecute) ||
canExecuteAny(moveToProjectAction.canExecute) ||
canExecuteAny(copyAction.canExecute) ||
- props.entities.length === 1 ||
- canExecuteAll(blockSenderAction.canExecute);
+ props.entities.length === 1;
+
+ const showSenderGroup = () => canExecuteAll(blockSenderAction.canExecute);
const showDeleteGroup = () => canExecuteAll(deleteAction.canExecute);
@@ -187,14 +202,44 @@ export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
/>
</Show>
- <Show when={canExecuteAll(blockSenderAction.canExecute)}>
+ <Show when={showSenderGroup() && (showTopGroup() || showMiddleGroup())}>
+ <Divider />
+ </Show>
+
+ <Show
+ when={
+ NOISE_TABS.has(activeTab() ?? '') &&
+ canExecuteAll(markSenderSignalAction.canExecute)
+ }
+ >
+ <MenuItem
+ text="Sender → Signal"
+ onClick={() => handleAction(markSenderSignalAction.executeWithSoup)}
+ />
+ </Show>
+
+ <Show
+ when={
+ SIGNAL_TABS.has(activeTab()) &&
+ canExecuteAll(markSenderNoiseAction.canExecute)
+ }
+ >
+ <MenuItem
+ text="Sender → Noise"
+ onClick={() => handleAction(markSenderNoiseAction.executeWithSoup)}
+ />
+ </Show>
+
+ <Show when={showSenderGroup()}>
<MenuItem
text="Block Sender"
onClick={() => handleAction(blockSenderAction.executeWithSoup)}
/>
</Show>
- <Show when={showDeleteGroup() && showMiddleGroup()}>
+ <Show
+ when={showDeleteGroup() && (showSenderGroup() || showMiddleGroup())}
+ >
<Divider />
</Show>
diff --git a/js/app/packages/block-email/component/Email.tsx b/js/app/packages/block-email/component/Email.tsx
index 4e198bebee..dfac437ce6 100644
--- a/js/app/packages/block-email/component/Email.tsx
+++ b/js/app/packages/block-email/component/Email.tsx
@@ -321,6 +321,8 @@ function EmailContent(props: EmailViewProps) {
registerEmailHotkeys(scopeId(), context.thread, {
archiveThread: context.archiveThread,
blockSender: context.blockSender,
+ markSenderSignal: context.markSenderSignal,
+ markSenderNoise: context.markSenderNoise,
navigateToPreviousMessage,
navigateToNextMessage,
});
diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsx
index ff319c3b23..8c60f0ae10 100644
--- a/js/app/packages/block-email/component/EmailContext.tsx
+++ b/js/app/packages/block-email/component/EmailContext.tsx
@@ -22,6 +22,8 @@ import { createEffectOnEntityTypeNotification } from '@notifications';
import {
useArchiveThreadMutation,
blockSenderWithToast,
+ markSenderSignalWithToast,
+ markSenderNoiseWithToast,
useThreadQuery,
} from '@queries/email/thread';
import { emailKeys } from '@queries/email/keys';
@@ -103,6 +105,8 @@ export type EmailContextValues = {
archiveThread: () => boolean;
blockSender: () => boolean;
+ markSenderSignal: () => boolean;
+ markSenderNoise: () => boolean;
initialLoadComplete: Accessor<boolean>;
onInitialDataLoad: (callback: () => boolean) => void;
};
@@ -373,6 +377,32 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
return true;
};
+ const getSenderEmail = (): string | undefined => {
+ const thread = threadQuery.data;
+ if (!thread?.messages?.length) return undefined;
+
+ const userEmail = currentUserEmail()?.toLowerCase();
+ return thread.messages.find(
+ (m) =>
+ m.from?.email &&
+ (!userEmail || m.from.email.toLowerCase() !== userEmail)
+ )?.from?.email;
+ };
+
+ const markSenderSignal = () => {
+ const senderEmail = getSenderEmail();
+ if (!senderEmail) return false;
+ markSenderSignalWithToast(senderEmail);
+ return true;
+ };
+
+ const markSenderNoise = () => {
+ const senderEmail = getSenderEmail();
+ if (!senderEmail) return false;
+ markSenderNoiseWithToast(senderEmail);
+ return true;
+ };
+
const [messagesListRef, setMessagesListRef] = createSignal<
HTMLDivElement | undefined
>(undefined);
@@ -492,6 +522,8 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {
onRecipientsChange,
archiveThread,
blockSender,
+ markSenderSignal,
+ markSenderNoise,
messagesContainerRef,
messagesListRef,
query: {
diff --git a/js/app/packages/block-email/util/emailHotkeys.ts b/js/app/packages/block-email/util/emailHotkeys.ts
index 5fa0835f95..78c4cb9838 100644
--- a/js/app/packages/block-email/util/emailHotkeys.ts
+++ b/js/app/packages/block-email/util/emailHotkeys.ts
@@ -6,6 +6,8 @@ import type { Accessor } from 'solid-js';
export interface EmailHotkeyHandlers {
archiveThread: () => boolean;
blockSender: () => boolean;
+ markSenderSignal: () => boolean;
+ markSenderNoise: () => boolean;
navigateToPreviousMessage: () => boolean;
navigateToNextMessage: () => boolean;
}
@@ -67,6 +69,20 @@ export function registerEmailHotkeys(
hotkeyToken: TOKENS.email.blockSender,
displayPriority: 5,
});
+ registerHotkey({
+ scopeId: scopeId,
+ description: 'Mark sender as Signal',
+ keyDownHandler: handlers.markSenderSignal,
+ hotkeyToken: TOKENS.email.markSenderSignal,
+ displayPriority: 5,
+ });
+ registerHotkey({
+ scopeId: scopeId,
+ description: 'Mark sender as Noise',
+ keyDownHandler: handlers.markSenderNoise,
+ hotkeyToken: TOKENS.email.markSenderNoise,
+ displayPriority: 5,
+ });
registerHotkey({
hotkey: 'arrowup',
scopeId,
diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.ts
index 1161a9fd0e..73548a7f83 100644
--- a/js/app/packages/core/constant/featureFlags.ts
+++ b/js/app/packages/core/constant/featureFlags.ts
@@ -296,3 +296,8 @@ export const ENABLE_PROXY_EMAIL_IMAGES = resolveFeatureFlag(
'ENABLE_PROXY_EMAIL_IMAGES',
true
);
+
+export const ENABLE_CLIENT_EMAIL_SIGNAL_FILTER = resolveFeatureFlag(
+ 'ENABLE_CLIENT_EMAIL_SIGNAL_FILTER',
+ false
+);
diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.ts
index a42469ff6b..23b65b904e 100644
--- a/js/app/packages/core/hotkey/tokens.ts
+++ b/js/app/packages/core/hotkey/tokens.ts
@@ -91,6 +91,8 @@ export const TOKENS = {
nextMessage: 'email.nextMessage',
cancelReply: 'email.cancelReply',
blockSender: 'email.blockSender',
+ markSenderSignal: 'email.markSenderSignal',
+ markSenderNoise: 'email.markSenderNoise',
compose: {
edit: {
recipients: 'email.compose.edit.recipients',
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index a0d8c12d3d..06705f7fc2 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -2,6 +2,7 @@ import { toast } from '@core/component/Toast/Toast';
import { DEFAULT_THREAD_MESSAGES_LIMIT } from '@core/constant/pagination';
import { catchToResult, isErr, ok, throwOnErr } from '@core/util/maybeResult';
import { optimisticUpdateSoupEntity } from '../soup/cache';
+import { invalidateAllSoup } from '../soup/normalized-cache';
import { emailClient } from '@service-email/client';
import type {
ApiDraftInput,
@@ -411,3 +412,48 @@ export async function blockSenderWithToast(senderEmail: string) {
}
);
}
+
+async function upsertSenderFilterWithToast(
+ senderEmail: string,
+ isImportant: boolean
+) {
+ const label = isImportant ? 'Signal' : 'Noise';
+
+ const result = await emailClient.upsertEmailFilter({
+ email_address: senderEmail,
+ is_important: isImportant,
+ });
+
+ if (isErr(result)) {
+ toast.failure(`Failed to mark sender as ${label}`, senderEmail);
+ return;
+ }
+
+ const filterId = result[1].filter.id;
+ invalidateAllSoup();
+
+ toast.success(
+ `Sender marked as ${label}`,
+ `Messages from ${senderEmail} will appear in ${label}`,
+ {
+ text: 'Undo',
+ onClick: async () => {
+ const undoResult = await emailClient.deleteEmailFilter({
+ id: filterId,
+ });
+ if (isErr(undoResult)) {
+ toast.failure('Failed to undo', senderEmail);
+ } else {
+ invalidateAllSoup();
+ toast.success('Sender filter removed');
+ }
+ },
+ }
+ );
+}
+
+export const markSenderSignalWithToast = (senderEmail: string) =>
+ upsertSenderFilterWithToast(senderEmail, true);
+
+export const markSenderNoiseWithToast = (senderEmail: string) =>
+ upsertSenderFilterWithToast(senderEmail, false);
diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.ts
index d1089ed590..4d9b7c3739 100644
--- a/js/app/packages/service-clients/service-email/client.ts
+++ b/js/app/packages/service-clients/service-email/client.ts
@@ -21,6 +21,7 @@ import type {
GetAttachmentResponse,
GetThreadResponse,
ListContactsResponse,
+ ListEmailFiltersResponse,
ListLabelsResponse,
ListLinksResponse,
SendMessageRequest,
@@ -29,6 +30,8 @@ import type {
UpdateLabelBatchResponse,
UpdateThreadLabelRequest,
UpdateThreadLabelsResponse,
+ UpsertEmailFilterRequest,
+ UpsertEmailFilterResponse,
UpsertScheduledRequest,
UpsertScheduledResponse,
} from './generated/schemas';
@@ -351,4 +354,26 @@ export const emailClient = {
body: JSON.stringify({ email_address: args.email_address }),
});
},
+ async listEmailFilters() {
+ return mapOk(
+ await emailFetch<ListEmailFiltersResponse>('/email/filters', {
+ method: 'GET',
+ }),
+ (result) => result
+ );
+ },
+ async upsertEmailFilter(args: UpsertEmailFilterRequest) {
+ return mapOk(
+ await emailFetch<UpsertEmailFilterResponse>('/email/filters', {
+ method: 'PUT',
+ body: JSON.stringify(args),
+ }),
+ (result) => result
+ );
+ },
+ async deleteEmailFilter(args: { id: string }) {
+ return emailFetch(`/email/filters/${args.id}`, {
+ method: 'DELETE',
+ });
+ },
};
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index 0f006fd109..c2a36a3443 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -32,6 +32,7 @@ import type {
InitResponse,
ListBlockedResponse,
ListContactsResponse,
+ ListEmailFiltersResponse,
ListLabelsResponse,
ListLinksParams,
ListLinksResponse,
@@ -48,6 +49,8 @@ import type {
UpdateThreadLabelsResponse,
UpdateThreadProjectRequest,
UpdateThreadProjectResponse,
+ UpsertEmailFilterRequest,
+ UpsertEmailFilterResponse,
UpsertScheduledRequest,
UpsertScheduledResponse,
} from './schemas';
@@ -1264,6 +1267,184 @@ export const removeForwardedAttachment = async (
} as removeForwardedAttachmentResponse;
};
+/**
+ * @summary List all email filters for the current user.
+ */
+export type listEmailFiltersResponse200 = {
+ data: ListEmailFiltersResponse;
+ status: 200;
+};
+
+export type listEmailFiltersResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type listEmailFiltersResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type listEmailFiltersResponseSuccess = listEmailFiltersResponse200 & {
+ headers: Headers;
+};
+export type listEmailFiltersResponseError = (
+ | listEmailFiltersResponse401
+ | listEmailFiltersResponse500
+) & {
+ headers: Headers;
+};
+
+export type listEmailFiltersResponse =
+ | listEmailFiltersResponseSuccess
+ | listEmailFiltersResponseError;
+
+export const getListEmailFiltersUrl = () => {
+ return `/email/filters`;
+};
+
+export const listEmailFilters = async (
+ options?: RequestInit
+): Promise<listEmailFiltersResponse> => {
+ const res = await fetch(getListEmailFiltersUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listEmailFiltersResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listEmailFiltersResponse;
+};
+
+/**
+ * @summary Create or update an email filter.
+ */
+export type upsertEmailFilterResponse200 = {
+ data: UpsertEmailFilterResponse;
+ status: 200;
+};
+
+export type upsertEmailFilterResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type upsertEmailFilterResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type upsertEmailFilterResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type upsertEmailFilterResponseSuccess = upsertEmailFilterResponse200 & {
+ headers: Headers;
+};
+export type upsertEmailFilterResponseError = (
+ | upsertEmailFilterResponse400
+ | upsertEmailFilterResponse401
+ | upsertEmailFilterResponse500
+) & {
+ headers: Headers;
+};
+
+export type upsertEmailFilterResponse =
+ | upsertEmailFilterResponseSuccess
+ | upsertEmailFilterResponseError;
+
+export const getUpsertEmailFilterUrl = () => {
+ return `/email/filters`;
+};
+
+export const upsertEmailFilter = async (
+ upsertEmailFilterRequest: UpsertEmailFilterRequest,
+ options?: RequestInit
+): Promise<upsertEmailFilterResponse> => {
+ const res = await fetch(getUpsertEmailFilterUrl(), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(upsertEmailFilterRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: upsertEmailFilterResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as upsertEmailFilterResponse;
+};
+
+/**
+ * @summary Delete an email filter by ID.
+ */
+export type deleteEmailFilterResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type deleteEmailFilterResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type deleteEmailFilterResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type deleteEmailFilterResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type deleteEmailFilterResponseSuccess = deleteEmailFilterResponse204 & {
+ headers: Headers;
+};
+export type deleteEmailFilterResponseError = (
+ | deleteEmailFilterResponse401
+ | deleteEmailFilterResponse404
+ | deleteEmailFilterResponse500
+) & {
+ headers: Headers;
+};
+
+export type deleteEmailFilterResponse =
+ | deleteEmailFilterResponseSuccess
+ | deleteEmailFilterResponseError;
+
+export const getDeleteEmailFilterUrl = (id: string) => {
+ return `/email/filters/${id}`;
+};
+
+export const deleteEmailFilter = async (
+ id: string,
+ options?: RequestInit
+): Promise<deleteEmailFilterResponse> => {
+ const res = await fetch(getDeleteEmailFilterUrl(id), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: deleteEmailFilterResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as deleteEmailFilterResponse;
+};
+
/**
* @summary Initialize email functionality for the user. Populates initial threads and enables inbox syncing.
*/
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilter.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilter.ts
new file mode 100644
index 0000000000..61f6a44875
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilter.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiEmailFilterEmailAddress } from './apiEmailFilterEmailAddress';
+import type { ApiEmailFilterEmailDomain } from './apiEmailFilterEmailDomain';
+
+/**
+ * A single email filter in API responses.
+ */
+export interface ApiEmailFilter {
+ created_at: string;
+ email_address?: ApiEmailFilterEmailAddress;
+ email_domain?: ApiEmailFilterEmailDomain;
+ id: string;
+ is_important: boolean;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilterEmailAddress.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilterEmailAddress.ts
new file mode 100644
index 0000000000..0e1745a5ba
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilterEmailAddress.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiEmailFilterEmailAddress = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilterEmailDomain.ts b/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilterEmailDomain.ts
new file mode 100644
index 0000000000..224e8a54a8
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/apiEmailFilterEmailDomain.ts
@@ -0,0 +1,8 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ApiEmailFilterEmailDomain = string | null;
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.ts
index de0ce47b83..24c4820116 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
@@ -62,6 +62,9 @@ export * from './apiDraftOutputReplyingToId';
export * from './apiDraftOutputSendTime';
export * from './apiDraftOutputThreadDbId';
export * from './apiDraftOutputTo';
+export * from './apiEmailFilter';
+export * from './apiEmailFilterEmailAddress';
+export * from './apiEmailFilterEmailDomain';
export * from './apiLabel';
export * from './apiLabelListVisibility';
export * from './apiLabelType';
@@ -186,6 +189,7 @@ export * from './linkSignature';
export * from './listBlockedResponse';
export * from './listContactsResponse';
export * from './listContactsResponseContacts';
+export * from './listEmailFiltersResponse';
export * from './listLabelsResponse';
export * from './listLinksParams';
export * from './listLinksResponse';
@@ -246,6 +250,10 @@ export * from './updateThreadProjectRequest';
export * from './updateThreadProjectRequestProjectId';
export * from './updateThreadProjectResponse';
export * from './updateThreadProjectResponseOldProjectId';
+export * from './upsertEmailFilterRequest';
+export * from './upsertEmailFilterRequestEmailAddress';
+export * from './upsertEmailFilterRequestEmailDomain';
+export * from './upsertEmailFilterResponse';
export * from './upsertScheduledRequest';
export * from './upsertScheduledResponse';
export * from './userProvider';
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/listEmailFiltersResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/listEmailFiltersResponse.ts
new file mode 100644
index 0000000000..fe7f083596
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/listEmailFiltersResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiEmailFilter } from './apiEmailFilter';
+
+/**
+ * Response body for listing email filters.
+ */
+export interface ListEmailFiltersResponse {
+ filters: ApiEmailFilter[];
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequest.ts b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequest.ts
new file mode 100644
index 0000000000..da299b8214
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequest.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 { UpsertEmailFilterRequestEmailAddress } from './upsertEmailFilterRequestEmailAddress';
+import type { UpsertEmailFilterRequestEmailDomain } from './upsertEmailFilterRequestEmailDomain';
+
+/**
+ * Request body for creating or updating an email filter.
+ */
+export interface UpsertEmailFilterRequest {
+ /** Exact email address to match. Mutually exclusive with `email_domain`. */
+ email_address?: UpsertEmailFilterRequestEmailAddress;
+ /** Email domain to match. Mutually exclusive with `email_address`. */
+ email_domain?: UpsertEmailFilterRequestEmailDomain;
+ /** Whether matching senders should be considered important. */
+ is_important: boolean;
+}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequestEmailAddress.ts b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequestEmailAddress.ts
new file mode 100644
index 0000000000..95788f1c5f
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequestEmailAddress.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Exact email address to match. Mutually exclusive with `email_domain`.
+ */
+export type UpsertEmailFilterRequestEmailAddress = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequestEmailDomain.ts b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequestEmailDomain.ts
new file mode 100644
index 0000000000..25df522619
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterRequestEmailDomain.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Email domain to match. Mutually exclusive with `email_address`.
+ */
+export type UpsertEmailFilterRequestEmailDomain = string | null;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterResponse.ts
new file mode 100644
index 0000000000..71024ebe3a
--- /dev/null
+++ b/js/app/packages/service-clients/service-email/generated/schemas/upsertEmailFilterResponse.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * email_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ApiEmailFilter } from './apiEmailFilter';
+
+/**
+ * Response body for upsert email filter.
+ */
+export interface UpsertEmailFilterResponse {
+ filter: ApiEmailFilter;
+}
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index b3715d5555..2499891a71 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -1185,6 +1185,156 @@
}
}
},
+ "/email/filters": {
+ "get": {
+ "tags": ["Email Filters"],
+ "summary": "List all email filters for the current user.",
+ "operationId": "list_email_filters",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListEmailFiltersResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["Email Filters"],
+ "summary": "Create or update an email filter.",
+ "operationId": "upsert_email_filter",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpsertEmailFilterRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpsertEmailFilterResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/email/filters/{id}": {
+ "delete": {
+ "tags": ["Email Filters"],
+ "summary": "Delete an email filter by ID.",
+ "operationId": "delete_email_filter",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "Filter ID.",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/email/init": {
"post": {
"tags": ["Init"],
@@ -2834,6 +2984,30 @@
}
}
},
+ "ApiEmailFilter": {
+ "type": "object",
+ "description": "A single email filter in API responses.",
+ "required": ["id", "is_important", "created_at"],
+ "properties": {
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "email_address": {
+ "type": ["string", "null"]
+ },
+ "email_domain": {
+ "type": ["string", "null"]
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "is_important": {
+ "type": "boolean"
+ }
+ }
+ },
"ApiLabel": {
"type": "object",
"required": [
@@ -3937,6 +4111,19 @@
}
}
},
+ "ListEmailFiltersResponse": {
+ "type": "object",
+ "description": "Response body for listing email filters.",
+ "required": ["filters"],
+ "properties": {
+ "filters": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApiEmailFilter"
+ }
+ }
+ }
+ },
"ListLabelsResponse": {
"type": "object",
"description": "Response body for listing labels.",
@@ -4568,6 +4755,35 @@
}
}
},
+ "UpsertEmailFilterRequest": {
+ "type": "object",
+ "description": "Request body for creating or updating an email filter.",
+ "required": ["is_important"],
+ "properties": {
+ "email_address": {
+ "type": ["string", "null"],
+ "description": "Exact email address to match. Mutually exclusive with `email_domain`."
+ },
+ "email_domain": {
+ "type": ["string", "null"],
+ "description": "Email domain to match. Mutually exclusive with `email_address`."
+ },
+ "is_important": {
+ "type": "boolean",
+ "description": "Whether matching senders should be considered important."
+ }
+ }
+ },
+ "UpsertEmailFilterResponse": {
+ "type": "object",
+ "description": "Response body for upsert email filter.",
+ "required": ["filter"],
+ "properties": {
+ "filter": {
+ "$ref": "#/components/schemas/ApiEmailFilter"
+ }
+ }
+ },
"UpsertScheduledRequest": {
"type": "object",
"required": ["send_time"],
diff --git a/rust/cloud-storage/email/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/email/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
deleted file mode 100644
index 44d3a67e72..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json b/rust/cloud-storage/email/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
deleted file mode 100644
index 60bfee0647..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-48df79c41ba4ec7fa2454ac962aee9ff97875c9e2335b46fe13b2bbdee721186.json b/rust/cloud-storage/email/.sqlx/query-48df79c41ba4ec7fa2454ac962aee9ff97875c9e2335b46fe13b2bbdee721186.json
new file mode 100644
index 0000000000..b38dcf84f8
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-48df79c41ba4ec7fa2454ac962aee9ff97875c9e2335b46fe13b2bbdee721186.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id, link_id, email_address, email_domain, is_important, created_at\n FROM email_filters\n WHERE link_id = $1\n ORDER BY created_at DESC",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_domain",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "is_important",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "48df79c41ba4ec7fa2454ac962aee9ff97875c9e2335b46fe13b2bbdee721186"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json b/rust/cloud-storage/email/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
deleted file mode 100644
index 58618b2697..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n -- CTE to recursively find all parent projects, starting from the given project.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project ID provided.\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n -- The hierarchy CTE includes the starting project, so this is all we need.\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n -- We only need to check ProjectPermission for the items in the hierarchy.\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json b/rust/cloud-storage/email/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
deleted file mode 100644
index 524cc25ec7..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The chat itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json b/rust/cloud-storage/email/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
deleted file mode 100644
index 03a8dbf6bb..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-679d0dd86957b91b759135cf9fc7314630cfd377b004a8c1dfedbf5764137ebd.json b/rust/cloud-storage/email/.sqlx/query-679d0dd86957b91b759135cf9fc7314630cfd377b004a8c1dfedbf5764137ebd.json
new file mode 100644
index 0000000000..1bc2f8db8f
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-679d0dd86957b91b759135cf9fc7314630cfd377b004a8c1dfedbf5764137ebd.json
@@ -0,0 +1,54 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_filters (link_id, email_address, is_important)\n VALUES ($1, $2, $3)\n ON CONFLICT (link_id, lower(email_address)) WHERE email_address IS NOT NULL\n DO UPDATE SET is_important = EXCLUDED.is_important\n RETURNING id, link_id, email_address, email_domain, is_important, created_at",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_domain",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "is_important",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Varchar",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "679d0dd86957b91b759135cf9fc7314630cfd377b004a8c1dfedbf5764137ebd"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json b/rust/cloud-storage/email/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
deleted file mode 100644
index 655495fb29..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT c.id\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "UuidArray"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json b/rust/cloud-storage/email/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
deleted file mode 100644
index 2bde15938f..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json b/rust/cloud-storage/email/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
deleted file mode 100644
index e42c9f2009..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json b/rust/cloud-storage/email/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
deleted file mode 100644
index 2b67c5606d..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n -- CTE to recursively find all parent projects for the given email thread.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project directly associated with the thread.\n SELECT\n p.id as project_id\n FROM\n \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE\n etp.\"threadId\" = $1\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT\n parent.id as project_id\n FROM\n project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The thread ID itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "b3aeddd507e0efee0e0cecef6eae7503820f0f3302e95a459790c5cb78e5dfb0"
-}
diff --git a/rust/cloud-storage/email/.sqlx/query-c4d2fed1a0fb95c20ef9b4049cc5cacfb7f0a441c630528d2cde076211ff63f9.json b/rust/cloud-storage/email/.sqlx/query-c4d2fed1a0fb95c20ef9b4049cc5cacfb7f0a441c630528d2cde076211ff63f9.json
new file mode 100644
index 0000000000..93c23384d7
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-c4d2fed1a0fb95c20ef9b4049cc5cacfb7f0a441c630528d2cde076211ff63f9.json
@@ -0,0 +1,54 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO email_filters (link_id, email_domain, is_important)\n VALUES ($1, $2, $3)\n ON CONFLICT (link_id, lower(email_domain)) WHERE email_domain IS NOT NULL\n DO UPDATE SET is_important = EXCLUDED.is_important\n RETURNING id, link_id, email_address, email_domain, is_important, created_at",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_domain",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "is_important",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Varchar",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "c4d2fed1a0fb95c20ef9b4049cc5cacfb7f0a441c630528d2cde076211ff63f9"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-e70d5acce88125ae894d9d57356559c6e59e236c9650211a52fdc90602318cc3.json b/rust/cloud-storage/email/.sqlx/query-e70d5acce88125ae894d9d57356559c6e59e236c9650211a52fdc90602318cc3.json
new file mode 100644
index 0000000000..3ace0da282
--- /dev/null
+++ b/rust/cloud-storage/email/.sqlx/query-e70d5acce88125ae894d9d57356559c6e59e236c9650211a52fdc90602318cc3.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM email_filters WHERE id = $1 AND link_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e70d5acce88125ae894d9d57356559c6e59e236c9650211a52fdc90602318cc3"
+}
diff --git a/rust/cloud-storage/email/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json b/rust/cloud-storage/email/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json
deleted file mode 100644
index 4c96ff0fd5..0000000000
--- a/rust/cloud-storage/email/.sqlx/query-e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"EmailThreadPermission\" etp\n JOIN \"Project\" p ON etp.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE etp.\"threadId\" = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "e7235d6ad2033a2ff7be0bf57ab042cd71e3b3d0e1f8a9750e55cdda92e70c6f"
-}
diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_email_filters.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_email_filters.sql
new file mode 100644
index 0000000000..efa35a2a75
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_email_filters.sql
@@ -0,0 +1,71 @@
+-- Additional fixture data for EmailLiteral::Importance tests that rely on email_filters.
+-- This script is intended to be layered on top of email_dynamic_query.sql.
+
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES
+ ('40000005-0000-0000-0000-000000000005', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Sam Alerts', NOW(), NOW()),
+ ('40000006-0000-0000-0000-000000000006', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Blocked Alerts', NOW(), NOW()),
+ ('40000007-0000-0000-0000-000000000007', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Guest Mail', NOW(), NOW()),
+ ('40000008-0000-0000-0000-000000000008', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'VIP Mail', NOW(), NOW());
+
+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,
+ created_at, updated_at
+)
+VALUES
+ ('20000012-0000-0000-0000-000000000012', 'thread12', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, false, NULL, NULL, '2024-01-04 00:00:00+00', NOW(), NOW()),
+ ('20000013-0000-0000-0000-000000000013', 'thread13', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, false, NULL, NULL, '2024-01-03 00:00:00+00', NOW(), NOW()),
+ ('20000014-0000-0000-0000-000000000014', 'thread14', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, false, NULL, NULL, '2024-01-02 00:00:00+00', NOW(), NOW()),
+ ('20000015-0000-0000-0000-000000000015', 'thread15', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, false, NULL, NULL, '2024-01-01 00:00:00+00', NOW(), NOW()),
+ ('20000016-0000-0000-0000-000000000016', 'thread16', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, false, NULL, NULL, '2023-12-31 00:00:00+00', NOW(), NOW());
+
+INSERT INTO email_messages (
+ id, thread_id, link_id, provider_id, from_contact_id,
+ subject, snippet, internal_date_ts,
+ is_draft, is_sent, is_starred, is_read,
+ created_at, updated_at
+)
+VALUES
+ ('30000012-0000-0000-0000-000000000012', '20000012-0000-0000-0000-000000000012',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg12', '40000005-0000-0000-0000-000000000005',
+ 'Alerts Promotion', 'Should become important via domain rule', '2024-01-04 00:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+ ('30000013-0000-0000-0000-000000000013', '20000013-0000-0000-0000-000000000013',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg13', '40000006-0000-0000-0000-000000000006',
+ 'Blocked Alerts Update', 'Should stay unimportant via address override', '2024-01-03 00:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+ ('30000014-0000-0000-0000-000000000014', '20000014-0000-0000-0000-000000000014',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg14', '40000007-0000-0000-0000-000000000007',
+ 'Guest Mail', 'Should become not-important via domain rule', '2024-01-02 00:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+ ('30000015-0000-0000-0000-000000000015', '20000015-0000-0000-0000-000000000015',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg15', '40000008-0000-0000-0000-000000000008',
+ 'VIP Mail', 'Should stay important via address override', '2024-01-01 00:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+ ('30000016-0000-0000-0000-000000000016', '20000016-0000-0000-0000-000000000016',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg16', '40000005-0000-0000-0000-000000000005',
+ 'Trashed Alerts Promotion', 'Should not become important because it is trashed', '2023-12-31 00:00:00+00',
+ false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ ('30000012-0000-0000-0000-000000000012', '10000010-0000-0000-0000-000000000010'),
+ ('30000013-0000-0000-0000-000000000013', '10000009-0000-0000-0000-000000000009'),
+ ('30000016-0000-0000-0000-000000000016', '10000010-0000-0000-0000-000000000010'),
+ ('30000016-0000-0000-0000-000000000016', '10000006-0000-0000-0000-000000000006');
+
+INSERT INTO email_filters (link_id, email_domain, is_important, created_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'alerts.test', true, NOW()),
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'mail.test', false, NOW());
+
+INSERT INTO email_filters (link_id, email_address, is_important, created_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', false, NOW()),
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', true, NOW());
diff --git a/rust/cloud-storage/email/src/domain/models/email_filter.rs b/rust/cloud-storage/email/src/domain/models/email_filter.rs
new file mode 100644
index 0000000000..1784b30e90
--- /dev/null
+++ b/rust/cloud-storage/email/src/domain/models/email_filter.rs
@@ -0,0 +1,33 @@
+use chrono::{DateTime, Utc};
+use uuid::Uuid;
+
+/// A sender-level importance override rule.
+///
+/// Each filter targets either an email address or a domain (never both),
+/// and marks matching senders as important or not-important.
+#[derive(Debug, Clone)]
+pub struct EmailFilter {
+ /// Database primary key.
+ pub id: Uuid,
+ /// The email link this filter belongs to.
+ pub link_id: Uuid,
+ /// Exact email address match (mutually exclusive with `email_domain`).
+ pub email_address: Option<String>,
+ /// Domain match (mutually exclusive with `email_address`).
+ pub email_domain: Option<String>,
+ /// Whether matching senders should be considered important.
+ pub is_important: bool,
+ /// When this filter was created.
+ pub created_at: DateTime<Utc>,
+}
+
+/// Input for creating or updating an email filter.
+#[derive(Debug, Clone)]
+pub struct UpsertEmailFilterInput {
+ /// Exact email address (mutually exclusive with `email_domain`).
+ pub email_address: Option<String>,
+ /// Domain (mutually exclusive with `email_address`).
+ pub email_domain: Option<String>,
+ /// Whether matching senders should be considered important.
+ pub is_important: bool,
+}
diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rs
index 98b476d07e..78b618c989 100644
--- a/rust/cloud-storage/email/src/domain/models/error.rs
+++ b/rust/cloud-storage/email/src/domain/models/error.rs
@@ -44,4 +44,7 @@ pub enum EmailErr {
/// The caller does not have permission to perform this action.
#[error("You do not have permission to perform this action")]
Unauthorized,
+ /// Invalid email filter input.
+ #[error("{0}")]
+ InvalidEmailFilter(String),
}
diff --git a/rust/cloud-storage/email/src/domain/models/mod.rs b/rust/cloud-storage/email/src/domain/models/mod.rs
index a534823041..504f16d851 100644
--- a/rust/cloud-storage/email/src/domain/models/mod.rs
+++ b/rust/cloud-storage/email/src/domain/models/mod.rs
@@ -1,6 +1,7 @@
pub mod attachment;
pub mod contact;
pub mod draft;
+pub mod email_filter;
pub mod error;
pub mod label;
pub mod link;
@@ -18,6 +19,7 @@ pub use draft::{
CreateDraftInput, CreatedDraft, ParsedAddresses, ResolvedDraftInput, SimpleMessageInfo,
UpsertedContacts, UpsertedRecipient,
};
+pub use email_filter::{EmailFilter, UpsertEmailFilterInput};
pub use error::EmailErr;
pub use label::{
Label, LabelListVisibility, LabelType, LinkLabel, MessageLabel, MessageListVisibility,
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index a0ba79b681..6419b20c41 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -1,9 +1,10 @@
use crate::domain::models::{
Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,
- CreatedDraft, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest,
- Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses,
- ParsedThread, PreviewCursorQuery, RecipientType, ResolvedDraftInput, SimpleMessage,
- SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult, UpsertedContacts, UserProvider,
+ CreatedDraft, EmailErr, EmailFilter, EmailThreadPreview, EnrichedEmailThreadPreview,
+ GetEmailsRequest, Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow,
+ ParsedAddresses, ParsedThread, PreviewCursorQuery, RecipientType, ResolvedDraftInput,
+ SimpleMessage, SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult,
+ UpsertEmailFilterInput, UpsertedContacts, UserProvider,
};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
@@ -227,6 +228,26 @@ pub trait EmailRepo: Send + Sync + 'static {
&self,
thread_id: Uuid,
) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+
+ /// Upsert an email filter (by address or domain) for a link.
+ fn upsert_email_filter(
+ &self,
+ link_id: Uuid,
+ input: UpsertEmailFilterInput,
+ ) -> impl Future<Output = Result<EmailFilter, Self::Err>> + Send;
+
+ /// Delete an email filter by its ID, scoped to a link.
+ fn delete_email_filter(
+ &self,
+ filter_id: Uuid,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// List all email filters for a link.
+ fn list_email_filters(
+ &self,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<EmailFilter>, Self::Err>> + Send;
}
pub trait EmailService: Send + Sync + 'static {
@@ -308,6 +329,26 @@ pub trait EmailService: Send + Sync + 'static {
thread_receipt: EntityAccessReceipt<EditAccessLevel>,
project_receipt: Option<EntityAccessReceipt<EditAccessLevel>>,
) -> impl Future<Output = Result<Option<String>, EmailErr>> + Send;
+
+ /// Upsert an email filter for the given link.
+ fn upsert_email_filter(
+ &self,
+ link: &Link,
+ input: UpsertEmailFilterInput,
+ ) -> impl Future<Output = Result<EmailFilter, EmailErr>> + Send;
+
+ /// Delete an email filter by its ID for the given link.
+ fn delete_email_filter(
+ &self,
+ link: &Link,
+ filter_id: Uuid,
+ ) -> impl Future<Output = Result<bool, EmailErr>> + Send;
+
+ /// List all email filters for the given link.
+ fn list_email_filters(
+ &self,
+ link: &Link,
+ ) -> impl Future<Output = Result<Vec<EmailFilter>, EmailErr>> + Send;
}
/// Port for modifying Gmail message labels via the provider API.
diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rs
index 9c9e2dbdcd..19b8985340 100644
--- a/rust/cloud-storage/email/src/domain/service/mod.rs
+++ b/rust/cloud-storage/email/src/domain/service/mod.rs
@@ -6,8 +6,9 @@ mod thread_labels;
use crate::domain::{
models::{
- CreateDraftInput, CreatedDraft, EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest,
- Link, LinkLabel, ParsedThread, Thread, UpdateThreadLabelsResult,
+ CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EnrichedEmailThreadPreview,
+ GetEmailsRequest, Link, LinkLabel, ParsedThread, Thread, UpdateThreadLabelsResult,
+ UpsertEmailFilterInput,
},
ports::{EmailMessageEnqueuer, EmailRepo, EmailService, GmailLabelModifier},
};
@@ -51,6 +52,66 @@ where
}
}
+impl<T, U, E, G> EmailServiceImpl<T, U, E, G> {
+ /// Validate and normalize email filter input.
+ fn validate_email_filter_input(
+ input: UpsertEmailFilterInput,
+ ) -> Result<UpsertEmailFilterInput, EmailErr> {
+ match (&input.email_address, &input.email_domain) {
+ (Some(addr), None) => {
+ let addr = addr.trim().to_lowercase();
+ if addr.is_empty() {
+ return Err(EmailErr::InvalidEmailFilter(
+ "Email address cannot be empty".to_string(),
+ ));
+ }
+ if !addr.contains('@') {
+ return Err(EmailErr::InvalidEmailFilter(
+ "Invalid email address format".to_string(),
+ ));
+ }
+ if addr.len() > 320 {
+ return Err(EmailErr::InvalidEmailFilter(
+ "Email address is too long".to_string(),
+ ));
+ }
+ Ok(UpsertEmailFilterInput {
+ email_address: Some(addr),
+ email_domain: None,
+ is_important: input.is_important,
+ })
+ }
+ (None, Some(domain)) => {
+ let domain = domain.trim().to_lowercase();
+ if domain.is_empty() {
+ return Err(EmailErr::InvalidEmailFilter(
+ "Email domain cannot be empty".to_string(),
+ ));
+ }
+ if domain.contains('@') {
+ return Err(EmailErr::InvalidEmailFilter(
+ "Domain must not contain '@'; use email_address for full addresses"
+ .to_string(),
+ ));
+ }
+ if domain.len() > 255 {
+ return Err(EmailErr::InvalidEmailFilter(
+ "Email domain is too long".to_string(),
+ ));
+ }
+ Ok(UpsertEmailFilterInput {
+ email_address: None,
+ email_domain: Some(domain),
+ is_important: input.is_important,
+ })
+ }
+ _ => Err(EmailErr::InvalidEmailFilter(
+ "Exactly one of email_address or email_domain must be provided".to_string(),
+ )),
+ }
+ }
+}
+
impl<T, U, E, G> EmailService for EmailServiceImpl<T, U, E, G>
where
T: EmailRepo,
@@ -182,4 +243,31 @@ where
Ok(old_project_id)
}
+
+ async fn upsert_email_filter(
+ &self,
+ link: &Link,
+ input: UpsertEmailFilterInput,
+ ) -> Result<EmailFilter, EmailErr> {
+ let validated = Self::validate_email_filter_input(input)?;
+
+ self.email_repo
+ .upsert_email_filter(link.id, validated)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
+
+ async fn delete_email_filter(&self, link: &Link, filter_id: Uuid) -> Result<bool, EmailErr> {
+ self.email_repo
+ .delete_email_filter(filter_id, link.id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
+
+ async fn list_email_filters(&self, link: &Link) -> Result<Vec<EmailFilter>, EmailErr> {
+ self.email_repo
+ .list_email_filters(link.id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(e.into()))
+ }
}
diff --git a/rust/cloud-storage/email/src/inbound/axum.rs b/rust/cloud-storage/email/src/inbound/axum.rs
index a300c41e7f..53d7d98d52 100644
--- a/rust/cloud-storage/email/src/inbound/axum.rs
+++ b/rust/cloud-storage/email/src/inbound/axum.rs
@@ -1,6 +1,7 @@
mod api_types;
mod axum_impls;
mod draft_router;
+mod email_filter_router;
mod get_thread_router;
mod list_labels_router;
mod previews_router;
@@ -11,6 +12,7 @@ mod thread_project_router;
pub use api_types::*;
pub use axum_impls::*;
pub use draft_router::*;
+pub use email_filter_router::*;
pub use get_thread_router::*;
pub use list_labels_router::*;
pub use previews_router::*;
diff --git a/rust/cloud-storage/email/src/inbound/axum/email_filter_router.rs b/rust/cloud-storage/email/src/inbound/axum/email_filter_router.rs
new file mode 100644
index 0000000000..da04b94aaa
--- /dev/null
+++ b/rust/cloud-storage/email/src/inbound/axum/email_filter_router.rs
@@ -0,0 +1,215 @@
+use axum::{
+ Json, Router,
+ extract::{Path, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::{delete, get, put},
+};
+use axum_extra::extract::Cached;
+use chrono::{DateTime, Utc};
+use model_error_response::ErrorResponse;
+use thiserror::Error;
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{EmailErr, EmailFilter, UpsertEmailFilterInput},
+ ports::EmailService,
+};
+
+use super::{EmailLinkExtractor, EmailRouterState};
+
+// ── API types ────────────────────────────────────────────────────────
+
+/// Request body for creating or updating an email filter.
+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
+pub struct UpsertEmailFilterRequest {
+ /// Exact email address to match. Mutually exclusive with `email_domain`.
+ pub email_address: Option<String>,
+ /// Email domain to match. Mutually exclusive with `email_address`.
+ pub email_domain: Option<String>,
+ /// Whether matching senders should be considered important.
+ pub is_important: bool,
+}
+
+/// A single email filter in API responses.
+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
+pub struct ApiEmailFilter {
+ pub id: Uuid,
+ pub email_address: Option<String>,
+ pub email_domain: Option<String>,
+ pub is_important: bool,
+ pub created_at: DateTime<Utc>,
+}
+
+impl From<EmailFilter> for ApiEmailFilter {
+ fn from(f: EmailFilter) -> Self {
+ ApiEmailFilter {
+ id: f.id,
+ email_address: f.email_address,
+ email_domain: f.email_domain,
+ is_important: f.is_important,
+ created_at: f.created_at,
+ }
+ }
+}
+
+/// Response body for upsert email filter.
+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
+pub struct UpsertEmailFilterResponse {
+ pub filter: ApiEmailFilter,
+}
+
+/// Response body for listing email filters.
+#[derive(serde::Serialize, serde::Deserialize, Debug, utoipa::ToSchema)]
+pub struct ListEmailFiltersResponse {
+ pub filters: Vec<ApiEmailFilter>,
+}
+
+// ── Errors ───────────────────────────────────────────────────────────
+
+/// Errors from the email filter handlers.
+#[derive(Debug, Error)]
+pub enum EmailFilterError {
+ /// Validation / bad request.
+ #[error("{0}")]
+ Validation(String),
+ /// Not found.
+ #[error("{0}")]
+ NotFound(String),
+ /// Internal error.
+ #[error("Internal error")]
+ Internal(EmailErr),
+}
+
+impl IntoResponse for EmailFilterError {
+ fn into_response(self) -> axum::response::Response {
+ if matches!(self, EmailFilterError::Internal(_)) {
+ tracing::error!(error=?self, "email filter error");
+ }
+
+ let status = match &self {
+ EmailFilterError::Validation(_) => StatusCode::BAD_REQUEST,
+ EmailFilterError::NotFound(_) => StatusCode::NOT_FOUND,
+ EmailFilterError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ let message = self.to_string();
+ (status, Json(ErrorResponse { message: &message })).into_response()
+ }
+}
+
+impl From<EmailErr> for EmailFilterError {
+ fn from(err: EmailErr) -> Self {
+ match &err {
+ EmailErr::InvalidEmailFilter(_) => EmailFilterError::Validation(err.to_string()),
+ _ => EmailFilterError::Internal(err),
+ }
+ }
+}
+
+// ── Router ───────────────────────────────────────────────────────────
+
+/// Create the email filter router with `PUT /`, `DELETE /{id}`, and `GET /` handlers.
+pub fn email_filter_router<S, T>() -> Router<S>
+where
+ S: Send + Sync + Clone + 'static,
+ T: EmailService,
+ EmailRouterState<T>: axum::extract::FromRef<S>,
+{
+ Router::new()
+ .route("/", put(upsert_email_filter_handler::<T>))
+ .route("/", get(list_email_filters_handler::<T>))
+ .route("/{id}", delete(delete_email_filter_handler::<T>))
+}
+
+// ── Handlers ─────────────────────────────────────────────────────────
+
+/// Create or update an email filter.
+#[utoipa::path(
+ put,
+ tag = "Email Filters",
+ path = "/email/filters",
+ operation_id = "upsert_email_filter",
+ request_body = UpsertEmailFilterRequest,
+ responses(
+ (status = 200, body = UpsertEmailFilterResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip(state, link, body))]
+pub async fn upsert_email_filter_handler<T: EmailService>(
+ State(state): State<EmailRouterState<T>>,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,
+ Json(body): Json<UpsertEmailFilterRequest>,
+) -> Result<Json<UpsertEmailFilterResponse>, EmailFilterError> {
+ let input = UpsertEmailFilterInput {
+ email_address: body.email_address,
+ email_domain: body.email_domain,
+ is_important: body.is_important,
+ };
+
+ let filter = state.inner.upsert_email_filter(&link, input).await?;
+
+ Ok(Json(UpsertEmailFilterResponse {
+ filter: filter.into(),
+ }))
+}
+
+/// Delete an email filter by ID.
+#[utoipa::path(
+ delete,
+ tag = "Email Filters",
+ path = "/email/filters/{id}",
+ operation_id = "delete_email_filter",
+ params(
+ ("id" = Uuid, Path, description = "Filter ID."),
+ ),
+ responses(
+ (status = 204),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip(state, link))]
+pub async fn delete_email_filter_handler<T: EmailService>(
+ State(state): State<EmailRouterState<T>>,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,
+ Path(filter_id): Path<Uuid>,
+) -> Result<impl IntoResponse, EmailFilterError> {
+ let deleted = state.inner.delete_email_filter(&link, filter_id).await?;
+
+ if !deleted {
+ return Err(EmailFilterError::NotFound(format!(
+ "Email filter with id {filter_id} not found"
+ )));
+ }
+
+ Ok(StatusCode::NO_CONTENT)
+}
+
+/// List all email filters for the current user.
+#[utoipa::path(
+ get,
+ tag = "Email Filters",
+ path = "/email/filters",
+ operation_id = "list_email_filters",
+ responses(
+ (status = 200, body = ListEmailFiltersResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn list_email_filters_handler<T: EmailService>(
+ State(state): State<EmailRouterState<T>>,
+ Cached(EmailLinkExtractor(link, _)): Cached<EmailLinkExtractor<T>>,
+) -> Result<Json<ListEmailFiltersResponse>, EmailFilterError> {
+ let filters = state.inner.list_email_filters(&link).await?;
+
+ Ok(Json(ListEmailFiltersResponse {
+ filters: filters.into_iter().map(Into::into).collect(),
+ }))
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
index 17de34c75a..491aa6588e 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs
@@ -53,6 +53,44 @@ fn build_email_match(preamble: &str, email: &Email) -> SqlFragment {
}
}
+fn build_sender_importance_override_filter(is_important: bool) -> SqlFragment {
+ let importance_literal = if is_important { "TRUE" } else { "FALSE" };
+ let opposite_importance_literal = if is_important { "FALSE" } else { "TRUE" };
+
+ SqlFragment::raw(format!(
+ r#"(
+ EXISTS (
+ SELECT 1
+ FROM email_contacts sender_c
+ JOIN email_filters ef
+ ON ef.link_id = m.link_id
+ AND ef.email_address IS NOT NULL
+ AND LOWER(ef.email_address) = LOWER(sender_c.email_address)
+ WHERE sender_c.id = m.from_contact_id
+ AND ef.is_important = {importance_literal}
+ )
+ OR EXISTS (
+ SELECT 1
+ FROM email_contacts sender_c
+ JOIN email_filters ef
+ ON ef.link_id = m.link_id
+ AND ef.email_domain IS NOT NULL
+ AND LOWER(ef.email_domain) = LOWER(split_part(sender_c.email_address, '@', 2))
+ WHERE sender_c.id = m.from_contact_id
+ AND ef.is_important = {importance_literal}
+ AND NOT EXISTS (
+ SELECT 1
+ FROM email_filters ef_addr
+ WHERE ef_addr.link_id = m.link_id
+ AND ef_addr.email_address IS NOT NULL
+ AND LOWER(ef_addr.email_address) = LOWER(sender_c.email_address)
+ AND ef_addr.is_important = {opposite_importance_literal}
+ )
+ )
+ )"#,
+ ))
+}
+
pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragment {
let fragment = ast.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => SqlFragment::and(a, b),
@@ -98,7 +136,7 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmen
),
filter_ast::ExprFrame::Literal(EmailLiteral::Importance(true)) => {
- SqlFragment::raw(
+ let mut f = SqlFragment::raw(
r#"(
NOT EXISTS (
SELECT 1 FROM email_message_labels ml
@@ -107,14 +145,59 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmen
AND l.name = 'TRASH'
)
AND (
- m.is_draft = TRUE
- OR EXISTS (
+ "#,
+ );
+ f.extend(build_sender_importance_override_filter(true));
+ f.push_raw(
+ r#"
+ OR (
+ NOT "#,
+ );
+ f.extend(build_sender_importance_override_filter(false));
+ f.push_raw(
+ r#"
+ AND (
+ m.is_draft = TRUE
+ OR EXISTS (
+ SELECT 1 FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id
+ AND l.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
+ )
+ OR NOT EXISTS (
+ SELECT 1 FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id
+ AND l.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
+ )
+ )
+ )
+ )
+ )"#,
+ );
+ f
+ }
+ filter_ast::ExprFrame::Literal(EmailLiteral::Importance(false)) => {
+ let mut f = SqlFragment::raw(
+ r#"(
+ "#,
+ );
+ f.extend(build_sender_importance_override_filter(false));
+ f.push_raw(
+ r#"
+ OR (
+ NOT "#,
+ );
+ f.extend(build_sender_importance_override_filter(true));
+ f.push_raw(
+ r#"
+ AND NOT EXISTS (
SELECT 1 FROM email_message_labels ml
JOIN email_labels l ON ml.label_id = l.id
WHERE ml.message_id = m.id
AND l.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
)
- OR NOT EXISTS (
+ AND EXISTS (
SELECT 1 FROM email_message_labels ml
JOIN email_labels l ON ml.label_id = l.id
WHERE ml.message_id = m.id
@@ -122,25 +205,8 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmen
)
)
)"#,
- )
- }
- filter_ast::ExprFrame::Literal(EmailLiteral::Importance(false)) => {
- SqlFragment::raw(
- r#"(
- NOT EXISTS (
- SELECT 1 FROM email_message_labels ml
- JOIN email_labels l ON ml.label_id = l.id
- WHERE ml.message_id = m.id
- AND l.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT')
- )
- AND EXISTS (
- SELECT 1 FROM email_message_labels ml
- JOIN email_labels l ON ml.label_id = l.id
- WHERE ml.message_id = m.id
- AND l.name IN ('CATEGORY_UPDATES', 'CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS')
- )
- )"#,
- )
+ );
+ f
}
filter_ast::ExprFrame::Literal(EmailLiteral::NotificationDone(_)) => {
SqlFragment::raw("TRUE")
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
index 7426552a2c..fabc7aefca 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
@@ -55,6 +55,33 @@ fn test_build_message_email_filter_importance_true_excludes_trash() {
assert!(debug.contains("NOT EXISTS"));
}
+#[test]
+fn test_build_message_email_filter_importance_true_includes_email_filters() {
+ let expr = Expr::Literal(EmailLiteral::Importance(true));
+ let result = build_message_email_filter(&expr);
+ let debug = result.to_debug_sql();
+
+ assert!(debug.contains("FROM email_filters ef"));
+ assert!(
+ debug
+ .contains("LOWER(ef.email_domain) = LOWER(split_part(sender_c.email_address, '@', 2))")
+ );
+ assert!(debug.contains("ef.is_important = TRUE"));
+ assert!(debug.contains("ef_addr.is_important = FALSE"));
+}
+
+#[test]
+fn test_build_message_email_filter_importance_false_includes_email_filters() {
+ let expr = Expr::Literal(EmailLiteral::Importance(false));
+ let result = build_message_email_filter(&expr);
+ let debug = result.to_debug_sql();
+
+ assert!(debug.contains("FROM email_filters ef"));
+ assert!(debug.contains("LOWER(ef.email_address) = LOWER(sender_c.email_address)"));
+ assert!(debug.contains("ef.is_important = FALSE"));
+ assert!(debug.contains("ef_addr.is_important = TRUE"));
+}
+
#[test]
fn test_build_message_email_filter_recipient() {
let email = Email::Complete(
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/email_filter.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/email_filter.rs
new file mode 100644
index 0000000000..403f48a2b0
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/email_filter.rs
@@ -0,0 +1,118 @@
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use crate::domain::models::EmailFilter;
+
+#[derive(sqlx::FromRow)]
+struct EmailFilterRow {
+ id: Uuid,
+ link_id: Uuid,
+ email_address: Option<String>,
+ email_domain: Option<String>,
+ is_important: bool,
+ created_at: DateTime<Utc>,
+}
+
+impl From<EmailFilterRow> for EmailFilter {
+ fn from(row: EmailFilterRow) -> Self {
+ EmailFilter {
+ id: row.id,
+ link_id: row.link_id,
+ email_address: row.email_address,
+ email_domain: row.email_domain,
+ is_important: row.is_important,
+ created_at: row.created_at,
+ }
+ }
+}
+
+/// Upsert an email filter by address. If a filter for this link+address already
+/// exists, update its `is_important` value.
+#[tracing::instrument(skip(pool), err)]
+pub async fn upsert_email_filter_by_address(
+ pool: &PgPool,
+ link_id: Uuid,
+ email_address: &str,
+ is_important: bool,
+) -> Result<EmailFilter, sqlx::Error> {
+ let row = sqlx::query_as!(
+ EmailFilterRow,
+ r#"INSERT INTO email_filters (link_id, email_address, is_important)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (link_id, lower(email_address)) WHERE email_address IS NOT NULL
+ DO UPDATE SET is_important = EXCLUDED.is_important
+ RETURNING id, link_id, email_address, email_domain, is_important, created_at"#,
+ link_id,
+ email_address,
+ is_important,
+ )
+ .fetch_one(pool)
+ .await?;
+
+ Ok(row.into())
+}
+
+/// Upsert an email filter by domain. If a filter for this link+domain already
+/// exists, update its `is_important` value.
+#[tracing::instrument(skip(pool), err)]
+pub async fn upsert_email_filter_by_domain(
+ pool: &PgPool,
+ link_id: Uuid,
+ email_domain: &str,
+ is_important: bool,
+) -> Result<EmailFilter, sqlx::Error> {
+ let row = sqlx::query_as!(
+ EmailFilterRow,
+ r#"INSERT INTO email_filters (link_id, email_domain, is_important)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (link_id, lower(email_domain)) WHERE email_domain IS NOT NULL
+ DO UPDATE SET is_important = EXCLUDED.is_important
+ RETURNING id, link_id, email_address, email_domain, is_important, created_at"#,
+ link_id,
+ email_domain,
+ is_important,
+ )
+ .fetch_one(pool)
+ .await?;
+
+ Ok(row.into())
+}
+
+/// Delete an email filter by its ID, scoped to a link.
+#[tracing::instrument(skip(pool), err)]
+pub async fn delete_email_filter(
+ pool: &PgPool,
+ filter_id: Uuid,
+ link_id: Uuid,
+) -> Result<bool, sqlx::Error> {
+ let result = sqlx::query!(
+ r#"DELETE FROM email_filters WHERE id = $1 AND link_id = $2"#,
+ filter_id,
+ link_id,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(result.rows_affected() > 0)
+}
+
+/// List all email filters for a link.
+#[tracing::instrument(skip(pool), err)]
+pub async fn list_email_filters(
+ pool: &PgPool,
+ link_id: Uuid,
+) -> Result<Vec<EmailFilter>, sqlx::Error> {
+ let rows = sqlx::query_as!(
+ EmailFilterRow,
+ r#"SELECT id, link_id, email_address, email_domain, is_important, created_at
+ FROM email_filters
+ WHERE link_id = $1
+ ORDER BY created_at DESC"#,
+ link_id,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows.into_iter().map(Into::into).collect())
+}
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.rs
index 3bf985c437..e9884aa163 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,9 +1,9 @@
use crate::domain::{
models::{
- Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailThreadPreview,
- Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses,
- PreviewCursorQuery, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo, ThreadRow,
- UpsertedContacts, UserProvider,
+ Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailFilter,
+ EmailThreadPreview, Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow,
+ ParsedAddresses, PreviewCursorQuery, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo,
+ ThreadRow, UpsertEmailFilterInput, UpsertedContacts, UserProvider,
},
ports::{EmailRepo, RecipientsByMessageId},
};
@@ -17,6 +17,7 @@ mod contact;
mod db_types;
mod draft;
mod dynamic;
+mod email_filter;
mod label;
mod link;
mod message;
@@ -256,4 +257,40 @@ impl EmailRepo for EmailPgRepo {
async fn get_thread_project_id(&self, thread_id: Uuid) -> Result<Option<String>, Self::Err> {
thread::get_thread_project_id(&self.pool, thread_id).await
}
+
+ async fn upsert_email_filter(
+ &self,
+ link_id: Uuid,
+ input: UpsertEmailFilterInput,
+ ) -> Result<EmailFilter, Self::Err> {
+ if let Some(address) = &input.email_address {
+ email_filter::upsert_email_filter_by_address(
+ &self.pool,
+ link_id,
+ address,
+ input.is_important,
+ )
+ .await
+ } else if let Some(domain) = &input.email_domain {
+ email_filter::upsert_email_filter_by_domain(
+ &self.pool,
+ link_id,
+ domain,
+ input.is_important,
+ )
+ .await
+ } else {
+ unreachable!(
+ "UpsertEmailFilterInput must have either email_address or email_domain; validated by service layer"
+ )
+ }
+ }
+
+ async fn delete_email_filter(&self, filter_id: Uuid, link_id: Uuid) -> Result<bool, Self::Err> {
+ email_filter::delete_email_filter(&self.pool, filter_id, link_id).await
+ }
+
+ async fn list_email_filters(&self, link_id: Uuid) -> Result<Vec<EmailFilter>, Self::Err> {
+ email_filter::list_email_filters(&self.pool, link_id).await
+ }
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
index 3c2ab58c98..f40df99040 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs
@@ -634,6 +634,107 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyh
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_dynamic_query_email_filters")
+ )
+)]
+async fn test_dynamic_query_importance_true_email_filters_domain_with_address_override(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Importance(true)));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
+
+ let result_ids: std::collections::HashSet<String> =
+ results.iter().map(|r| r.id.to_string()).collect();
+
+ assert!(
+ result_ids.contains("20000012-0000-0000-0000-000000000012"),
+ "Should include thread 12 via sender domain important rule"
+ );
+ assert!(
+ !result_ids.contains("20000013-0000-0000-0000-000000000013"),
+ "Should exclude thread 13 because sender address override beats important domain rule"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_dynamic_query_email_filters")
+ )
+)]
+async fn test_dynamic_query_importance_true_email_filters_excludes_trashed_messages(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Importance(true)));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
+
+ let result_ids: std::collections::HashSet<String> =
+ results.iter().map(|r| r.id.to_string()).collect();
+
+ assert!(
+ !result_ids.contains("20000016-0000-0000-0000-000000000016"),
+ "Should exclude thread 16 because the sender is important but the only matching message is trashed"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../fixtures",
+ scripts("email_dynamic_query", "email_dynamic_query_email_filters")
+ )
+)]
+async fn test_dynamic_query_importance_false_email_filters_domain_with_address_override(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Importance(false)));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;
+
+ let result_ids: std::collections::HashSet<String> =
+ results.iter().map(|r| r.id.to_string()).collect();
+
+ assert!(
+ result_ids.contains("20000014-0000-0000-0000-000000000014"),
+ "Should include thread 14 via sender domain not-important rule"
+ );
+ assert!(
+ !result_ids.contains("20000015-0000-0000-0000-000000000015"),
+ "Should exclude thread 15 because sender address important override beats not-important domain rule"
+ );
+
+ Ok(())
+}
+
// ── Project ID filter tests ──────────────────────────────────────────
#[sqlx::test(
diff --git a/rust/cloud-storage/email_service/src/api/email/filters/mod.rs b/rust/cloud-storage/email_service/src/api/email/filters/mod.rs
new file mode 100644
index 0000000000..a75dda87b4
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/filters/mod.rs
@@ -0,0 +1,7 @@
+use axum::Router;
+
+use crate::api::ApiContext;
+
+pub fn router() -> Router<ApiContext> {
+ email::inbound::email_filter_router::<ApiContext, crate::api::context::EmailSvc>()
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/mod.rs b/rust/cloud-storage/email_service/src/api/email/mod.rs
index 233b1436b5..33c182cdcb 100644
--- a/rust/cloud-storage/email_service/src/api/email/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/mod.rs
@@ -7,6 +7,7 @@ pub(crate) mod attachments;
pub(crate) mod backfill;
pub(crate) mod contacts;
pub(crate) mod drafts;
+pub(crate) mod filters;
pub(crate) mod init;
pub(crate) mod labels;
pub(crate) mod links;
@@ -24,6 +25,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.nest("/messages", messages::router(state.clone()))
.nest("/links", links::router())
.nest("/contacts", contacts::router(state.clone()))
+ .nest("/filters", filters::router())
.nest("/backfill", backfill::router(state.clone()))
.nest("/settings", settings::router(state.clone()))
.nest("/sync", sync::router(state.clone()))
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index d91e8f4bd3..016c8633cf 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -29,8 +29,9 @@ use ::email::inbound::{
SendMessageRequest as HexSendMessageRequest, SendMessageResponse as HexSendMessageResponse,
};
use ::email::inbound::{
- UpdateThreadLabelRequest, UpdateThreadLabelsResponse, UpdateThreadProjectRequest,
- UpdateThreadProjectResponse,
+ ApiEmailFilter, ListEmailFiltersResponse, UpdateThreadLabelRequest, UpdateThreadLabelsResponse,
+ UpdateThreadProjectRequest, UpdateThreadProjectResponse, UpsertEmailFilterRequest,
+ UpsertEmailFilterResponse,
};
use model::response::EmptyResponse;
use models_email::api::settings::Settings;
@@ -81,6 +82,9 @@ use utoipa::OpenApi;
email::labels::create::handler,
email::labels::delete::handler,
inbound::list_labels_handler,
+ inbound::upsert_email_filter_handler,
+ inbound::delete_email_filter_handler,
+ inbound::list_email_filters_handler,
email::contacts::list::list_contacts_handler,
email::contacts::block_sender::handler,
email::contacts::unblock_sender::handler,
@@ -147,6 +151,11 @@ use utoipa::OpenApi;
BlockSenderResponse,
UnblockSenderRequest,
ListBlockedResponse,
+ // Email filter types
+ UpsertEmailFilterRequest,
+ UpsertEmailFilterResponse,
+ ListEmailFiltersResponse,
+ ApiEmailFilter,
// Sort/filter types
ApiSortMethod,
// Legacy service types (keeping for backward compatibility)
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260325102949_email_filters.sql b/rust/cloud-storage/macro_db_client/migrations/20260325102949_email_filters.sql
new file mode 100644
index 0000000000..a1c32d3ffe
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260325102949_email_filters.sql
@@ -0,0 +1,29 @@
+CREATE TABLE IF NOT EXISTS email_filters
+(
+ id UUID DEFAULT gen_random_uuid() NOT NULL,
+ link_id UUID NOT NULL REFERENCES email_links (id) ON DELETE CASCADE,
+ email_address VARCHAR(320),
+ email_domain VARCHAR(255),
+ is_important BOOLEAN NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ CONSTRAINT email_filters_pkey PRIMARY KEY (id),
+ CONSTRAINT email_filters_address_xor_domain_chk
+ CHECK (
+ (email_address IS NOT NULL AND trim(email_address) <> '')
+ <>
+ (email_domain IS NOT NULL AND trim(email_domain) <> '')
+ ),
+ CONSTRAINT email_filters_email_domain_format_chk
+ CHECK (email_domain IS NULL OR (trim(email_domain) <> '' AND position('@' IN email_domain) = 0))
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS email_filters_link_id_email_address_uq
+ ON email_filters (link_id, lower(email_address))
+ WHERE email_address IS NOT NULL;
+
+CREATE UNIQUE INDEX IF NOT EXISTS email_filters_link_id_email_domain_uq
+ ON email_filters (link_id, lower(email_domain))
+ WHERE email_domain IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_email_filters_link_id
+ ON email_filters (link_id);
\ No newline at end of file
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index 01f7135b3e..3c037f2232 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -115,6 +115,29 @@ impl EmailService for NoopEmailService {
) -> Result<Option<String>, EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
}
+
+ async fn upsert_email_filter(
+ &self,
+ _link: &email::domain::models::Link,
+ _input: email::domain::models::UpsertEmailFilterInput,
+ ) -> Result<email::domain::models::EmailFilter, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
+ }
+
+ async fn delete_email_filter(
+ &self,
+ _link: &email::domain::models::Link,
+ _filter_id: Uuid,
+ ) -> Result<bool, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("not implemented")))
+ }
+
+ async fn list_email_filters(
+ &self,
+ _link: &email::domain::models::Link,
+ ) -> Result<Vec<email::domain::models::EmailFilter>, 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.rs
index b7d8d657d9..8b82e5c152 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -159,6 +159,29 @@ impl EmailService for MockEmail {
) -> Result<Option<String>, EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
}
+
+ async fn upsert_email_filter(
+ &self,
+ _link: &email::domain::models::Link,
+ _input: email::domain::models::UpsertEmailFilterInput,
+ ) -> Result<email::domain::models::EmailFilter, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
+ async fn delete_email_filter(
+ &self,
+ _link: &email::domain::models::Link,
+ _filter_id: Uuid,
+ ) -> Result<bool, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
+ async fn list_email_filters(
+ &self,
+ _link: &email::domain::models::Link,
+ ) -> Result<Vec<email::domain::models::EmailFilter>, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
}
fn mock_router() -> Router {
@@ -291,6 +314,29 @@ impl EmailService for MockEmailLinkResult {
) -> Result<Option<String>, EmailErr> {
Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
}
+
+ async fn upsert_email_filter(
+ &self,
+ _link: &email::domain::models::Link,
+ _input: email::domain::models::UpsertEmailFilterInput,
+ ) -> Result<email::domain::models::EmailFilter, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
+ async fn delete_email_filter(
+ &self,
+ _link: &email::domain::models::Link,
+ _filter_id: Uuid,
+ ) -> Result<bool, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
+
+ async fn list_email_filters(
+ &self,
+ _link: &email::domain::models::Link,
+ ) -> Result<Vec<email::domain::models::EmailFilter>, EmailErr> {
+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))
+ }
}
#[tokio::test]