Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(email-service): Add tests for sql queries (#598)
Evan Hutnik53941c705af5
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-5c235a72a986b83ee63c6fb7eea31d43d23d94a8a007c9e298aa4e3651e5589e.json b/rust/cloud-storage/email_db_client/.sqlx/query-5c235a72a986b83ee63c6fb7eea31d43d23d94a8a007c9e298aa4e3651e5589e.jsonnew file mode 100644index 0000000000..a0292ade5a--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-5c235a72a986b83ee63c6fb7eea31d43d23d94a8a007c9e298aa4e3651e5589e.json@@ -0,0 +1,71 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n t.id as thread_id,\n COALESCE(\n MIN(m.sent_at) FILTER (WHERE m.is_draft = false),\n MIN(m.updated_at)\n ) as \"first_message_ts!\",\n COALESCE(\n MAX(m.sent_at) FILTER (WHERE m.is_draft = false),\n MAX(m.updated_at)\n ) as \"last_message_ts!\",\n -- Last time user viewed this thread\n uh.updated_at as \"viewed_at?\",\n latest_msg.snippet,\n latest_msg.subject as \"subject?\",\n l.macro_id,\n latest_msg.sender as sender,\n latest_msg.pretty_sender as \"pretty_sender!\"\n FROM email_threads t\n INNER JOIN email_messages m ON m.thread_id = t.id AND m.link_id = $1\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1\n LEFT JOIN email_links l ON l.id = t.link_id\n -- LATERAL join to get snippet/subject/sender from the single latest message.\n -- This subquery runs once per thread and returns exactly one message's data.\n LEFT JOIN LATERAL (\n SELECT\n m2.snippet,\n m2.subject,\n c.email_address as sender,\n COALESCE(c.name, c.email_address) as pretty_sender\n FROM email_messages m2\n LEFT JOIN email_contacts c ON c.id = m2.from_contact_id\n WHERE m2.thread_id = t.id\n AND m2.link_id = $1\n ORDER BY\n -- Primary sort: most recent timestamp (use sent_at if available, otherwise updated_at)\n COALESCE(m2.sent_at, m2.updated_at) DESC NULLS LAST,\n -- Secondary sort: prefer non-drafts over drafts when timestamps are equal\n -- (0 for non-drafts comes before 1 for drafts in ASC order)\n (CASE WHEN m2.is_draft THEN 1 ELSE 0 END) ASC\n LIMIT 1\n ) latest_msg ON true\n WHERE t.id = ANY($2)\n AND t.link_id = $1\n GROUP BY\n t.id,\n uh.updated_at,\n latest_msg.snippet,\n latest_msg.subject,\n l.macro_id,\n latest_msg.sender,\n latest_msg.pretty_sender\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "first_message_ts!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "last_message_ts!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "viewed_at?",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "snippet",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "subject?",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "macro_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "sender",+ "type_info": "Varchar"+ },+ {+ "ordinal": 8,+ "name": "pretty_sender!",+ "type_info": "Varchar"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ false,+ true,+ true,+ false,+ false,+ null+ ]+ },+ "hash": "5c235a72a986b83ee63c6fb7eea31d43d23d94a8a007c9e298aa4e3651e5589e"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-f51181a381e07ff3703344b25b69e9874cad020c4970a3e892b9a747ed6a35e2.json b/rust/cloud-storage/email_db_client/.sqlx/query-f51181a381e07ff3703344b25b69e9874cad020c4970a3e892b9a747ed6a35e2.jsondeleted file mode 100644index 1bba03ea11..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-f51181a381e07ff3703344b25b69e9874cad020c4970a3e892b9a747ed6a35e2.json+++ /dev/null@@ -1,71 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n m.thread_id,\n COALESCE(\n MIN(m.sent_at) FILTER (WHERE m.is_draft = false),\n MIN(m.updated_at)\n ) as \"first_message_ts!\",\n COALESCE(\n MAX(m.sent_at) FILTER (WHERE m.is_draft = false),\n MAX(m.updated_at)\n ) as \"last_message_ts!\",\n uh.updated_at as \"viewed_at?\",\n m.snippet,\n m.subject as \"subject?\",\n l.macro_id,\n latest_msg.sender as sender,\n latest_msg.pretty_sender as \"pretty_sender!\"\n FROM email_messages m\n LEFT JOIN email_user_history uh ON uh.thread_id = m.thread_id AND uh.link_id = $1\n LEFT JOIN email_links l ON l.id = m.link_id\n LEFT JOIN LATERAL (\n SELECT\n c.email_address as sender,\n COALESCE(c.name, c.email_address) as pretty_sender\n FROM email_messages m2\n LEFT JOIN email_contacts c ON c.id = m2.from_contact_id\n WHERE m2.thread_id = m.thread_id\n AND m2.link_id = $1\n ORDER BY m2.internal_date_ts DESC NULLS LAST\n LIMIT 1\n ) latest_msg ON true\n WHERE m.thread_id = ANY($2)\n AND m.link_id = $1\n GROUP BY\n m.thread_id,\n uh.updated_at,\n m.snippet,\n m.subject,\n l.macro_id,\n latest_msg.sender,\n latest_msg.pretty_sender\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "thread_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "first_message_ts!",- "type_info": "Timestamptz"- },- {- "ordinal": 2,- "name": "last_message_ts!",- "type_info": "Timestamptz"- },- {- "ordinal": 3,- "name": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 4,- "name": "snippet",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "subject?",- "type_info": "Text"- },- {- "ordinal": 6,- "name": "macro_id",- "type_info": "Text"- },- {- "ordinal": 7,- "name": "sender",- "type_info": "Varchar"- },- {- "ordinal": 8,- "name": "pretty_sender!",- "type_info": "Varchar"- }- ],- "parameters": {- "Left": [- "Uuid",- "UuidArray"- ]- },- "nullable": [- false,- null,- null,- false,- true,- true,- false,- false,- null- ]- },- "hash": "f51181a381e07ff3703344b25b69e9874cad020c4970a3e892b9a747ed6a35e2"-}diff --git a/rust/cloud-storage/email_db_client/fixtures/fetch_db_attachments.sql b/rust/cloud-storage/email_db_client/fixtures/fetch_db_attachments.sqlnew file mode 100644index 0000000000..9fdf1edaf8--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/fetch_db_attachments.sql@@ -0,0 +1,101 @@++-- SQL fixture for fetch_db_attachments tests+-- Tests fetching attachments with and without SFS mappings, ordered by filename (NULLS LAST)++------------------------------------------------------------+-- User Link+------------------------------------------------------------++INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000001b', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001b',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++------------------------------------------------------------+-- Contact+------------------------------------------------------------++INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0010',+ '00000000-0000-0000-0000-00000000001b',+ '[email protected]',+ NOW(), NOW());++------------------------------------------------------------+-- Thread+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000201',+ '00000000-0000-0000-0000-00000000001b',+ true, false, NOW(), NOW());++------------------------------------------------------------+-- Message 1: Multiple attachments with and without SFS+------------------------------------------------------------++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ has_attachments, is_read, is_starred, is_draft, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0501',+ '00000000-0000-0000-0000-000000000201',+ '00000000-0000-0000-0000-00000000001b',+ 'provider-msg-501',+ FALSE,+ '00000000-0000-0000-0000-0000000c0010',+ '2025-01-05 10:00:00 +00:00',+ true, false, false, false, NOW(), NOW());++-- Attachment 1: With SFS mapping, filename starts with 'a'+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0501',+ '00000000-0000-0000-0000-0000000e0501',+ 'provider-att-501',+ 'alpha_document.pdf',+ 'application/pdf',+ 102400,+ NULL,+ NOW());++INSERT INTO email_attachments_sfs (id, attachment_id, sfs_id, created_at)+VALUES ('00000000-0000-0000-0000-000000005501',+ '00000000-0000-0000-0000-0000001a0501',+ '00000000-0000-0000-0000-000000f10001',+ NOW());++-- Attachment 2: Without SFS mapping, filename starts with 'z'+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0502',+ '00000000-0000-0000-0000-0000000e0501',+ 'provider-att-502',+ 'zulu_spreadsheet.xlsx',+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ 204800,+ 'content-id-502',+ NOW());++-- Attachment 3: With SFS mapping, filename starts with 'b'+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0503',+ '00000000-0000-0000-0000-0000000e0501',+ 'provider-att-503',+ 'bravo_image.jpg',+ 'image/jpeg',+ 512000,+ 'content-id-503',+ NOW());++INSERT INTO email_attachments_sfs (id, attachment_id, sfs_id, created_at)+VALUES ('00000000-0000-0000-0000-000000005503',+ '00000000-0000-0000-0000-0000001a0503',+ '00000000-0000-0000-0000-000000f10003',+ NOW());++-- Attachment 4: No filename (NULL), should be ordered last+INSERT INTO email_attachments (id, message_id, provider_attachment_id, filename, mime_type, size_bytes, content_id, created_at)+VALUES ('00000000-0000-0000-0000-0000001a0504',+ '00000000-0000-0000-0000-0000000e0501',+ 'provider-att-504',+ NULL,+ 'application/octet-stream',+ 1024,+ NULL,+ NOW());\ No newline at end of filediff --git a/rust/cloud-storage/email_db_client/fixtures/get_thread_summary_info.sql b/rust/cloud-storage/email_db_client/fixtures/get_thread_summary_info.sqlnew file mode 100644index 0000000000..a04058f0d5--- /dev/null+++ b/rust/cloud-storage/email_db_client/fixtures/get_thread_summary_info.sql@@ -0,0 +1,351 @@++-- SQL fixture for get_thread_summary_info tests+-- Tests the timestamp logic for first_message_ts and last_message_ts+-- COALESCE rules:+-- - first_message_ts: MIN(sent_at) for non-drafts, fallback to MIN(updated_at)+-- - last_message_ts: MAX(sent_at) for non-drafts, fallback to MAX(updated_at)++------------------------------------------------------------+-- User Link+------------------------------------------------------------++INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000001c', 'macro|[email protected]', '00000000-0000-0000-0000-00000000001c',+ '[email protected]', 'GMAIL', true, NOW(), NOW());++------------------------------------------------------------+-- Contacts+------------------------------------------------------------++INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000c0020',+ '00000000-0000-0000-0000-00000000001c',+ '[email protected]',+ 'Alice Smith',+ NOW(), NOW()),+ ('00000000-0000-0000-0000-0000000c0021',+ '00000000-0000-0000-0000-00000000001c',+ '[email protected]',+ 'Bob Jones',+ NOW(), NOW());++------------------------------------------------------------+-- Thread 1: All non-draft messages with sent_at+-- Should use MIN(sent_at) and MAX(sent_at)+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000301',+ '00000000-0000-0000-0000-00000000001c',+ true, false, NOW(), NOW());++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0601',+ '00000000-0000-0000-0000-000000000301',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-601',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-10 10:00:00 +00:00',+ '2025-01-10 10:00:00 +00:00',+ false,+ 'First message snippet',+ 'Test Subject 1',+ '2025-01-10 09:00:00 +00:00',+ '2025-01-10 09:30:00 +00:00'),+ ('00000000-0000-0000-0000-0000000e0602',+ '00000000-0000-0000-0000-000000000301',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-602',+ FALSE,+ '00000000-0000-0000-0000-0000000c0021',+ '2025-01-10 11:00:00 +00:00',+ '2025-01-10 11:00:00 +00:00',+ false,+ 'Second message snippet',+ 'Test Subject 1',+ '2025-01-10 10:00:00 +00:00',+ '2025-01-10 10:30:00 +00:00'),+ ('00000000-0000-0000-0000-0000000e0603',+ '00000000-0000-0000-0000-000000000301',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-603',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-10 12:00:00 +00:00',+ '2025-01-10 12:00:00 +00:00',+ false,+ 'Latest message snippet',+ 'Test Subject 1',+ '2025-01-10 11:00:00 +00:00',+ '2025-01-10 11:30:00 +00:00');++------------------------------------------------------------+-- Thread 2: All draft messages (no sent_at)+-- Should fallback to MIN(updated_at) and MAX(updated_at)+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000302',+ '00000000-0000-0000-0000-00000000001c',+ true, false, NOW(), NOW());++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0604',+ '00000000-0000-0000-0000-000000000302',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-604',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-11 10:00:00 +00:00',+ NULL,+ true,+ 'Draft 1',+ 'Draft Subject',+ '2025-01-11 09:00:00 +00:00',+ '2025-01-11 09:15:00 +00:00'),+ ('00000000-0000-0000-0000-0000000e0605',+ '00000000-0000-0000-0000-000000000302',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-605',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-11 11:00:00 +00:00',+ NULL,+ true,+ 'Draft 2',+ 'Draft Subject',+ '2025-01-11 10:00:00 +00:00',+ '2025-01-11 10:45:00 +00:00');++------------------------------------------------------------+-- Thread 3: Mix of drafts and non-drafts+-- Should use sent_at from non-drafts only+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000303',+ '00000000-0000-0000-0000-00000000001c',+ true, false, NOW(), NOW());++-- Draft with earliest updated_at (should be ignored for first_message_ts)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0606',+ '00000000-0000-0000-0000-000000000303',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-606',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-12 08:00:00 +00:00',+ NULL,+ true,+ 'Early draft',+ 'Mixed Subject',+ '2025-01-12 07:00:00 +00:00',+ '2025-01-12 07:30:00 +00:00');++-- Non-draft (should be used for first_message_ts)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0607',+ '00000000-0000-0000-0000-000000000303',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-607',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-12 10:00:00 +00:00',+ '2025-01-12 10:00:00 +00:00',+ false,+ 'First real message',+ 'Mixed Subject',+ '2025-01-12 09:00:00 +00:00',+ '2025-01-12 09:30:00 +00:00');++-- Draft with latest updated_at (should be ignored for last_message_ts)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0608',+ '00000000-0000-0000-0000-000000000303',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-608',+ FALSE,+ '00000000-0000-0000-0000-0000000c0021',+ '2025-01-12 15:00:00 +00:00',+ NULL,+ true,+ 'Latest draft',+ 'Mixed Subject',+ '2025-01-12 14:00:00 +00:00',+ '2025-01-12 14:30:00 +00:00');++-- Non-draft (should be used for last_message_ts)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0609',+ '00000000-0000-0000-0000-000000000303',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-609',+ FALSE,+ '00000000-0000-0000-0000-0000000c0021',+ '2025-01-12 12:00:00 +00:00',+ '2025-01-12 12:00:00 +00:00',+ false,+ 'Latest real message',+ 'Mixed Subject',+ '2025-01-12 11:00:00 +00:00',+ '2025-01-12 11:30:00 +00:00');++------------------------------------------------------------+-- Thread 4: Non-drafts with NULL sent_at+-- Should fallback to updated_at+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000304',+ '00000000-0000-0000-0000-00000000001c',+ true, false, NOW(), NOW());++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0610',+ '00000000-0000-0000-0000-000000000304',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-610',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-13 10:00:00 +00:00',+ NULL,+ false,+ 'Message without sent_at',+ 'No Sent Subject',+ '2025-01-13 09:00:00 +00:00',+ '2025-01-13 09:20:00 +00:00'),+ ('00000000-0000-0000-0000-0000000e0611',+ '00000000-0000-0000-0000-000000000304',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-611',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-13 11:00:00 +00:00',+ NULL,+ false,+ 'Another message without sent_at',+ 'No Sent Subject',+ '2025-01-13 10:00:00 +00:00',+ '2025-01-13 10:40:00 +00:00');++------------------------------------------------------------+-- Thread 5: Single message (edge case)+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000305',+ '00000000-0000-0000-0000-00000000001c',+ true, false, NOW(), NOW());++INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0612',+ '00000000-0000-0000-0000-000000000305',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-612',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-14 10:00:00 +00:00',+ '2025-01-14 10:00:00 +00:00',+ false,+ 'Single message',+ 'Single Subject',+ '2025-01-14 09:00:00 +00:00',+ '2025-01-14 09:30:00 +00:00');++------------------------------------------------------------+-- Thread 6: Mix with some messages having sent_at and some not+-- Non-drafts with sent_at should take precedence+------------------------------------------------------------++INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-000000000306',+ '00000000-0000-0000-0000-00000000001c',+ true, false, NOW(), NOW());++-- Non-draft without sent_at (earliest updated_at)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0613',+ '00000000-0000-0000-0000-000000000306',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-613',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-15 08:00:00 +00:00',+ NULL,+ false,+ 'No sent_at',+ 'Partial Sent Subject',+ '2025-01-15 07:00:00 +00:00',+ '2025-01-15 07:20:00 +00:00');++-- Non-draft with sent_at (should determine first_message_ts)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0614',+ '00000000-0000-0000-0000-000000000306',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-614',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-15 10:00:00 +00:00',+ '2025-01-15 10:00:00 +00:00',+ false,+ 'With sent_at',+ 'Partial Sent Subject',+ '2025-01-15 09:00:00 +00:00',+ '2025-01-15 09:30:00 +00:00');++-- Non-draft with sent_at (should determine last_message_ts)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0615',+ '00000000-0000-0000-0000-000000000306',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-615',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-15 12:00:00 +00:00',+ '2025-01-15 12:00:00 +00:00',+ false,+ 'Latest with sent_at',+ 'Partial Sent Subject',+ '2025-01-15 11:00:00 +00:00',+ '2025-01-15 11:30:00 +00:00');++-- Non-draft without sent_at (latest updated_at, but should be ignored)+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,+ sent_at, is_draft, snippet, subject, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-0000000e0616',+ '00000000-0000-0000-0000-000000000306',+ '00000000-0000-0000-0000-00000000001c',+ 'provider-msg-616',+ FALSE,+ '00000000-0000-0000-0000-0000000c0020',+ '2025-01-15 15:00:00 +00:00',+ NULL,+ false,+ 'Latest no sent_at',+ 'Partial Sent Subject',+ '2025-01-15 14:00:00 +00:00',+ '2025-01-15 14:30:00 +00:00');++------------------------------------------------------------+-- Add user history for some threads (for viewed_at testing)+------------------------------------------------------------++INSERT INTO email_user_history (link_id, thread_id, created_at, updated_at)+VALUES ('00000000-0000-0000-0000-00000000001c',+ '00000000-0000-0000-0000-000000000301',+ NOW(),+ '2025-01-10 13:00:00 +00:00');\ No newline at end of filediff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rsindex f874f659c8..d949c0acca 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs@@ -1,3 +1,5 @@+#[cfg(test)]+mod test;pub mod upload;pub mod upload_filters;diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/test.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/test.rsnew file mode 100644index 0000000000..a295f7d13c--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/test.rs@@ -0,0 +1,43 @@+use crate::attachments::provider::fetch_db_attachments;+use anyhow::Result;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::types::Uuid;+use sqlx::{Pool, Postgres};++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("fetch_db_attachments"))+)]+async fn fetch_db_attachments_includes_sfs_mappings(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let message_id = Uuid::parse_str("00000000-0000-0000-0000-0000000e0501")?;+ let res = fetch_db_attachments(&pool, message_id).await?;++ // Verify SFS mappings are included/excluded correctly+ assert_eq!(res.len(), 4);++ // alpha_document.pdf has SFS mapping+ assert_eq!(res[0].filename, Some("alpha_document.pdf".to_string()));+ assert_eq!(+ res[0].sfs_id,+ Some(Uuid::parse_str("00000000-0000-0000-0000-000000f10001")?)+ );++ // bravo_image.jpg has SFS mapping+ assert_eq!(res[1].filename, Some("bravo_image.jpg".to_string()));+ assert_eq!(+ res[1].sfs_id,+ Some(Uuid::parse_str("00000000-0000-0000-0000-000000f10003")?)+ );++ // zulu_spreadsheet.xlsx does NOT have SFS mapping+ assert_eq!(res[2].filename, Some("zulu_spreadsheet.xlsx".to_string()));+ assert_eq!(res[2].sfs_id, None);++ // NULL filename does NOT have SFS mapping+ assert_eq!(res[3].filename, None);+ assert_eq!(res[3].sfs_id, None);++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/user_history/mod.rs b/rust/cloud-storage/email_db_client/src/user_history/mod.rsindex 865fcb2e85..b2a25b1dd8 100644--- a/rust/cloud-storage/email_db_client/src/user_history/mod.rs+++ b/rust/cloud-storage/email_db_client/src/user_history/mod.rs@@ -1,3 +1,6 @@+#[cfg(test)]+mod test;+use anyhow::anyhow;use models_email::service::message::ThreadHistoryInfo;use sqlx::PgPool;@@ -29,8 +32,16 @@ pub async fn upsert_user_history(Ok(())}-/// get history info for threads. created_at is when the first message was created, updated_at is when-/// the latest message was created, viewed_at is the last time the thread was opened by the user+/// Get summary information for multiple email threads.+///+/// Returns a HashMap of thread history info including:+/// - `created_at`: timestamp of the first message in the thread (prefers sent_at from non-drafts, falls back to updated_at)+/// - `updated_at`: timestamp of the last message in the thread (prefers sent_at from non-drafts, falls back to updated_at)+/// - `viewed_at`: last time the user opened/viewed the thread (only included if >= updated_at)+/// - `snippet`, `subject`, `sender`, `pretty_sender`: from the latest message in the thread+///+/// The "latest message" is determined by:+/// 1. Message with the most recent sent_at (if available) or updated_at#[tracing::instrument(skip(pool), err)]pub async fn get_thread_summary_info(pool: &PgPool,@@ -43,47 +54,58 @@ pub async fn get_thread_summary_info(let rows = sqlx::query!(r#"- SELECT- m.thread_id,- COALESCE(- MIN(m.sent_at) FILTER (WHERE m.is_draft = false),- MIN(m.updated_at)- ) as "first_message_ts!",- COALESCE(- MAX(m.sent_at) FILTER (WHERE m.is_draft = false),- MAX(m.updated_at)- ) as "last_message_ts!",- uh.updated_at as "viewed_at?",- m.snippet,- m.subject as "subject?",- l.macro_id,- latest_msg.sender as sender,- latest_msg.pretty_sender as "pretty_sender!"- FROM email_messages m- LEFT JOIN email_user_history uh ON uh.thread_id = m.thread_id AND uh.link_id = $1- LEFT JOIN email_links l ON l.id = m.link_id- LEFT JOIN LATERAL (SELECT- c.email_address as sender,- COALESCE(c.name, c.email_address) as pretty_sender- FROM email_messages m2- LEFT JOIN email_contacts c ON c.id = m2.from_contact_id- WHERE m2.thread_id = m.thread_id- AND m2.link_id = $1- ORDER BY m2.internal_date_ts DESC NULLS LAST- LIMIT 1- ) latest_msg ON true- WHERE m.thread_id = ANY($2)- AND m.link_id = $1- GROUP BY- m.thread_id,- uh.updated_at,- m.snippet,- m.subject,- l.macro_id,- latest_msg.sender,- latest_msg.pretty_sender- "#,+ t.id as thread_id,+ COALESCE(+ MIN(m.sent_at) FILTER (WHERE m.is_draft = false),+ MIN(m.updated_at)+ ) as "first_message_ts!",+ COALESCE(+ MAX(m.sent_at) FILTER (WHERE m.is_draft = false),+ MAX(m.updated_at)+ ) as "last_message_ts!",+ -- Last time user viewed this thread+ uh.updated_at as "viewed_at?",+ latest_msg.snippet,+ latest_msg.subject as "subject?",+ l.macro_id,+ latest_msg.sender as sender,+ latest_msg.pretty_sender as "pretty_sender!"+ FROM email_threads t+ INNER JOIN email_messages m ON m.thread_id = t.id AND m.link_id = $1+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = $1+ LEFT JOIN email_links l ON l.id = t.link_id+ -- LATERAL join to get snippet/subject/sender from the single latest message.+ -- This subquery runs once per thread and returns exactly one message's data.+ LEFT JOIN LATERAL (+ SELECT+ m2.snippet,+ m2.subject,+ c.email_address as sender,+ COALESCE(c.name, c.email_address) as pretty_sender+ FROM email_messages m2+ LEFT JOIN email_contacts c ON c.id = m2.from_contact_id+ WHERE m2.thread_id = t.id+ AND m2.link_id = $1+ ORDER BY+ -- Primary sort: most recent timestamp (use sent_at if available, otherwise updated_at)+ COALESCE(m2.sent_at, m2.updated_at) DESC NULLS LAST,+ -- Secondary sort: prefer non-drafts over drafts when timestamps are equal+ -- (0 for non-drafts comes before 1 for drafts in ASC order)+ (CASE WHEN m2.is_draft THEN 1 ELSE 0 END) ASC+ LIMIT 1+ ) latest_msg ON true+ WHERE t.id = ANY($2)+ AND t.link_id = $1+ GROUP BY+ t.id,+ uh.updated_at,+ latest_msg.snippet,+ latest_msg.subject,+ l.macro_id,+ latest_msg.sender,+ latest_msg.pretty_sender+ "#,link_id,thread_ids)@@ -101,6 +123,8 @@ pub async fn get_thread_summary_info(snippet: row.snippet,created_at: row.first_message_ts,updated_at: row.last_message_ts,+ // if the last time the user viewed the thread was before the most recent message came in,+ // the user hasn't viewed the most recent message.viewed_at: row.viewed_at.and_then(|viewed| {if viewed >= row.last_message_ts {Some(viewed)diff --git a/rust/cloud-storage/email_db_client/src/user_history/test.rs b/rust/cloud-storage/email_db_client/src/user_history/test.rsnew file mode 100644index 0000000000..ec9d2be456--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/user_history/test.rs@@ -0,0 +1,227 @@+use super::*;+use anyhow::Result;+use chrono::{DateTime, Utc};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_all_non_drafts_with_sent_at(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000301")?;++ let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;++ assert_eq!(result.len(), 1);+ let info = result.get(&thread_id).unwrap();++ // Should use MIN(sent_at) and MAX(sent_at) from non-drafts+ let expected_first =+ DateTime::parse_from_rfc3339("2025-01-10T10:00:00+00:00")?.with_timezone(&Utc);+ let expected_last =+ DateTime::parse_from_rfc3339("2025-01-10T12:00:00+00:00")?.with_timezone(&Utc);++ assert_eq!(info.created_at, expected_first);+ assert_eq!(info.updated_at, expected_last);+ assert_eq!(info.subject, Some("Test Subject 1".to_string()));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_all_drafts_fallback_to_updated_at(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000302")?;++ let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;++ assert_eq!(result.len(), 1);+ let info = result.get(&thread_id).unwrap();++ // Should fallback to MIN(updated_at) and MAX(updated_at) since all are drafts+ let expected_first =+ DateTime::parse_from_rfc3339("2025-01-11T09:15:00+00:00")?.with_timezone(&Utc);+ let expected_last =+ DateTime::parse_from_rfc3339("2025-01-11T10:45:00+00:00")?.with_timezone(&Utc);++ assert_eq!(info.created_at, expected_first);+ assert_eq!(info.updated_at, expected_last);+ assert_eq!(info.subject, Some("Draft Subject".to_string()));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_mixed_drafts_ignores_draft_timestamps(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000303")?;++ let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;++ assert_eq!(result.len(), 1);+ let info = result.get(&thread_id).unwrap();++ // Should use sent_at from non-drafts only, ignoring drafts+ // Draft at 07:30 (earliest updated_at) should be ignored+ // Non-draft at 10:00 should be first_message_ts+ // Draft at 14:30 (latest updated_at) should be ignored+ // Non-draft at 12:00 should be last_message_ts+ let expected_first =+ DateTime::parse_from_rfc3339("2025-01-12T10:00:00+00:00")?.with_timezone(&Utc);+ let expected_last =+ DateTime::parse_from_rfc3339("2025-01-12T12:00:00+00:00")?.with_timezone(&Utc);++ assert_eq!(info.created_at, expected_first);+ assert_eq!(info.updated_at, expected_last);+ assert_eq!(info.subject, Some("Mixed Subject".to_string()));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_single_message_same_first_and_last(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000305")?;++ let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;++ assert_eq!(result.len(), 1);+ let info = result.get(&thread_id).unwrap();++ // Single message: first and last timestamps should be the same+ let expected_ts =+ DateTime::parse_from_rfc3339("2025-01-14T10:00:00+00:00")?.with_timezone(&Utc);++ assert_eq!(info.created_at, expected_ts);+ assert_eq!(info.updated_at, expected_ts);+ assert_eq!(info.subject, Some("Single Subject".to_string()));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_partial_sent_at_prefers_sent_at_over_updated_at(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000306")?;++ let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;++ assert_eq!(result.len(), 1);+ let info = result.get(&thread_id).unwrap();++ // When some non-drafts have sent_at and some don't:+ // - FILTER (WHERE is_draft = false) returns only non-drafts+ // - MIN/MAX of sent_at ignores NULLs, so only considers messages with sent_at+ // - First message with sent_at: 10:00+ // - Last message with sent_at: 12:00+ // Messages without sent_at (07:20 and 14:30) should be ignored+ let expected_first =+ DateTime::parse_from_rfc3339("2025-01-15T10:00:00+00:00")?.with_timezone(&Utc);+ let expected_last =+ DateTime::parse_from_rfc3339("2025-01-15T12:00:00+00:00")?.with_timezone(&Utc);++ assert_eq!(info.created_at, expected_first);+ assert_eq!(info.updated_at, expected_last);+ assert_eq!(info.subject, Some("Partial Sent Subject".to_string()));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_multiple_threads(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_ids = vec![+ Uuid::parse_str("00000000-0000-0000-0000-000000000301")?,+ Uuid::parse_str("00000000-0000-0000-0000-000000000302")?,+ Uuid::parse_str("00000000-0000-0000-0000-000000000305")?,+ ];++ let result = get_thread_summary_info(&pool, link_id, &thread_ids).await?;++ // Should return info for all 3 threads+ assert_eq!(result.len(), 3);+ assert!(result.contains_key(&thread_ids[0]));+ assert!(result.contains_key(&thread_ids[1]));+ assert!(result.contains_key(&thread_ids[2]));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_empty_thread_ids_returns_empty(+ pool: Pool<Postgres>,+) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_ids: Vec<Uuid> = vec![];++ let result = get_thread_summary_info(&pool, link_id, &thread_ids).await?;++ assert_eq!(result.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("get_thread_summary_info"))+)]+async fn get_thread_summary_info_viewed_at_logic(pool: Pool<Postgres>) -> Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;++ let link_id = Uuid::parse_str("00000000-0000-0000-0000-00000000001c")?;+ let thread_id = Uuid::parse_str("00000000-0000-0000-0000-000000000301")?;++ let result = get_thread_summary_info(&pool, link_id, &[thread_id]).await?;++ assert_eq!(result.len(), 1);+ let info = result.get(&thread_id).unwrap();++ // viewed_at (13:00) is after last_message_ts (12:00), so should be included+ let expected_viewed =+ DateTime::parse_from_rfc3339("2025-01-10T13:00:00+00:00")?.with_timezone(&Utc);+ assert_eq!(info.viewed_at, Some(expected_viewed));++ Ok(())+}