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.

add GraphQL email labels and links (#5289)

Sean Aye4cddb8199d16
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index da5f74eea2..b8c11e1a33 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -50,7 +50,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/embedding",
@@ -143,7 +142,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -219,7 +217,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/embedding",
@@ -659,7 +656,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/embedding",
@@ -910,7 +906,6 @@
"crates/documents",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -1146,7 +1141,6 @@
"crates/database_env_vars",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1310,7 +1304,6 @@
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1394,7 +1387,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/embedding",
@@ -1709,7 +1701,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -1744,7 +1735,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -1792,7 +1782,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -1827,7 +1816,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -1867,7 +1855,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1946,7 +1933,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -1975,7 +1961,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -2039,7 +2024,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2102,7 +2086,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2248,7 +2231,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/entity_access",
@@ -2305,7 +2287,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2593,7 +2574,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -2630,7 +2610,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -2755,7 +2734,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -2785,7 +2763,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -2822,7 +2799,6 @@
"crates/documents",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -2833,6 +2809,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/graphql_common",
+ "crates/graphql_email",
"crates/graphql_entity_mutation",
"crates/graphql_permission",
"crates/graphql_soup",
@@ -3056,7 +3033,6 @@
"crates/documents",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -3067,6 +3043,7 @@
"crates/foreign_entity",
"crates/frecency",
"crates/graphql_common",
+ "crates/graphql_email",
"crates/graphql_permission",
"crates/graphql_soup",
"crates/invite_email",
@@ -3302,7 +3279,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -3333,7 +3309,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -3374,7 +3349,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -3406,7 +3380,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -3731,7 +3704,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/embedding",
@@ -3840,7 +3812,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/embedding",
@@ -4071,7 +4042,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4101,7 +4071,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -4150,7 +4119,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4180,7 +4148,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -4478,7 +4445,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4541,7 +4507,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4605,7 +4570,6 @@
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -4830,7 +4794,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_service_client",
"crates/email_utils",
"crates/embedding",
@@ -5109,7 +5072,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5139,7 +5101,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -5176,7 +5137,6 @@
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5369,7 +5329,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5400,7 +5359,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_grouping",
"crates/models_pagination",
@@ -5443,7 +5401,6 @@
"crates/documents",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -5524,7 +5481,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5713,7 +5669,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -5746,7 +5701,6 @@
"crates/model_notifications",
"crates/model_user",
"crates/models_bulk_upload",
- "crates/models_email",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -5788,7 +5742,6 @@
"crates/crm",
"crates/document_sub_type",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5872,7 +5825,6 @@
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -5935,7 +5887,6 @@
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -6047,7 +5998,6 @@
"crates/document_sub_type",
"crates/documents",
"crates/email",
- "crates/email_db_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
diff --git a/.sqlx/query-7504e91534d35f88b7c5068bdb8803acc5818ad927a467ab6e4c68fcf1bebd35.json b/.sqlx/query-7504e91534d35f88b7c5068bdb8803acc5818ad927a467ab6e4c68fcf1bebd35.json
new file mode 100644
index 0000000000..aa23e2ab2c
--- /dev/null
+++ b/.sqlx/query-7504e91534d35f88b7c5068bdb8803acc5818ad927a467ab6e4c68fcf1bebd35.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT signature_on_replies_forwards, signature\n FROM email_settings\n WHERE link_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "signature_on_replies_forwards",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "signature",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "7504e91534d35f88b7c5068bdb8803acc5818ad927a467ab6e4c68fcf1bebd35"
+}
diff --git a/.sqlx/query-f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337.json b/.sqlx/query-f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337.json
new file mode 100644
index 0000000000..45a91184cb
--- /dev/null
+++ b/.sqlx/query-f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337.json
@@ -0,0 +1,116 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT l.id as \"id!\", l.macro_id as \"macro_id!\",\n l.email_address as \"email_address!\",\n l.provider as \"provider!: _\",\n l.is_sync_active as \"is_sync_active!\",\n l.needs_reauth as \"needs_reauth!\",\n l.is_primary as \"is_primary!\",\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n s.signature_on_replies_forwards as \"signature_on_replies_forwards?\",\n s.signature,\n bj.status as \"latest_backfill_status?: _\",\n c.sfs_photo_url as \"photo_url?\"\n FROM (\n SELECT el.id, el.macro_id, el.email_address, el.provider,\n el.is_sync_active, el.needs_reauth, el.is_primary,\n el.created_at, el.updated_at\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.email_address, el.provider,\n el.is_sync_active, el.needs_reauth, el.is_primary,\n el.created_at, el.updated_at\n FROM email_links el\n JOIN macro_user_links mul ON el.id = mul.link_id\n WHERE mul.primary_macro_id = $1\n ) l\n LEFT JOIN email_settings s ON s.link_id = l.id\n LEFT JOIN LATERAL (\n SELECT status FROM email_backfill_jobs\n WHERE link_id = l.id\n ORDER BY created_at DESC\n LIMIT 1\n ) bj ON true\n LEFT JOIN email_contacts c\n ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)\n ORDER BY l.created_at DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "email_address!",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 3,
+ "name": "provider!: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_user_provider_enum",
+ "kind": {
+ "Enum": [
+ "GMAIL"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 4,
+ "name": "is_sync_active!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "needs_reauth!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "is_primary!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "signature_on_replies_forwards?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 10,
+ "name": "signature",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 11,
+ "name": "latest_backfill_status?: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_backfill_job_status",
+ "kind": {
+ "Enum": [
+ "Init",
+ "InProgress",
+ "Complete",
+ "Cancelled",
+ "Failed"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 12,
+ "name": "photo_url?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ false,
+ true,
+ false,
+ true
+ ]
+ },
+ "hash": "f2f9657c67f343270a00e21cc7f073c3bdcc5f0ba844efe92f021de000315337"
+}
diff --git a/Cargo.lock b/Cargo.lock
index f5d94018ca..02686eeb9a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4908,7 +4908,6 @@ dependencies = [
"crm",
"doppleganger",
"either",
- "email_db_client",
"email_utils",
"entity_access",
"entity_access_management",
@@ -6350,6 +6349,7 @@ dependencies = [
"filter_ast",
"futures",
"graphql_common",
+ "graphql_email",
"graphql_permission",
"item_filters",
"macro_authorization",
diff --git a/bun.lock b/bun.lock
index e00f612e5b..743ef93388 100644
--- a/bun.lock
+++ b/bun.lock
@@ -901,7 +901,7 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],
+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],
"@inquirer/ansi": ["@inquirer/[email protected]", "", {}, "sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q=="],
@@ -2675,7 +2675,7 @@
"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],
+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],
"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index 325e1e516c..f99fdfa74d 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -21,7 +21,9 @@ pub use graphql_channel::{
pub use graphql_common::GraphqlRequestParts;
pub use graphql_email::{
EmailContentKey, EmailContentLoad, EmailContentLoader, EmailServiceEmailContentReader,
- NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader, email_content_loader,
+ GraphqlEmailLabel, GraphqlEmailLink, GraphqlEmailLinkSettings, GraphqlEmailProvider,
+ GraphqlEmailQuery, GraphqlEmailSyncStatus, NoOpSoupEmailContentEdgeReader,
+ SoupEmailContentEdgeReader, email_content_loader,
};
pub use graphql_entity_mutation::{
ChannelSharePolicyInput, DuplicateEntityInput, EntityMutationPayload, EntityMutationRoot,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 4f86194d71..b67a2525a6 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -6,7 +6,7 @@ use std::{marker::PhantomData, sync::Arc};
use async_graphql::{Context, ID, MergedObject, Object, Schema, Subscription};
use axum::extract::FromRef;
use email::{
- domain::ports::{EmailService, NoOpEmailService},
+ domain::ports::{EmailService, EmailUserService, NoOpEmailService},
inbound::axum::previews_router::EmailRouterState,
};
use entity_access::domain::ports::{EntityAccessService, NoOpEntityAccessService};
@@ -16,7 +16,9 @@ use graphql_channel::{
NoOpChannelActivityMutationService,
};
use graphql_common::{parse_id, require_authorized_user};
-use graphql_email::{NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader};
+use graphql_email::{
+ GraphqlEmailQuery, NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader,
+};
use graphql_entity_mutation::EntityMutationRoot;
use graphql_favorite::{EntityFavoriteEdgeReader, NoOpEntityFavoriteEdgeReader};
use graphql_notification::{
@@ -243,7 +245,7 @@ pub fn build_schema_with_service<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR
>
where
S: SoupService + Clone,
- E: EmailService,
+ E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
St: Clone + Send + Sync + 'static,
@@ -272,7 +274,7 @@ pub fn build_schema_with_services<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER
where
S: SoupService + Clone,
R: SoupRealtimeSubscriptionService + Clone,
- E: EmailService,
+ E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
St: Clone + Send + Sync + 'static,
@@ -320,7 +322,7 @@ pub fn build_schema_from_arc<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR
>
where
S: SoupService,
- E: EmailService,
+ E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
St: Clone + Send + Sync + 'static,
@@ -349,7 +351,7 @@ pub fn build_schema_from_arcs<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR
where
S: SoupService,
R: SoupRealtimeSubscriptionService,
- E: EmailService,
+ E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
St: Clone + Send + Sync + 'static,
@@ -374,7 +376,7 @@ where
impl<S, E, EAS, Auth, St, NR, PR, ER, FR, AR> SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR>
where
S: SoupService + Clone,
- E: EmailService,
+ E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
St: Clone + Send + Sync + 'static,
@@ -434,7 +436,7 @@ where
impl<S, E, EAS, Auth, St, NR, PR, ER, FR, AR> GraphqlUser<S, E, EAS, Auth, St, NR, PR, ER, FR, AR>
where
S: SoupService,
- E: EmailService,
+ E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
St: Clone + Send + Sync + 'static,
@@ -452,6 +454,14 @@ where
async_graphql::ID(self.user_id.to_string())
}
+ /// Authenticated user email catalog fields supplied by `graphql_email`.
+ #[graphql(flatten)]
+ async fn email(&self, ctx: &Context<'_>) -> async_graphql::Result<GraphqlEmailQuery<E>> {
+ let state = ctx.data::<St>()?;
+ let service = EmailRouterState::<E>::from_ref(state).service();
+ Ok(GraphqlEmailQuery::new(service, self.user_id.clone()))
+ }
+
/// Fetch one accessible email thread by its canonical identifier.
async fn email_thread(
&self,
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 9c550e68c5..bf7786ff5c 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -4,9 +4,10 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use axum::http::{Request as HttpRequest, header};
use email::domain::models::{
- CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EnrichedEmailThreadPreview,
- GetEmailsRequest, Link, LinkLabel, ParsedMessage, ParsedThread, Thread,
- UpdateThreadLabelsResult, UpsertEmailFilterInput,
+ CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EmailSyncStatus,
+ EnrichedEmailThreadPreview, GetEmailsRequest, LabelListVisibility, LabelType, Link, LinkLabel,
+ MessageListVisibility, ParsedMessage, ParsedThread, Thread, UpdateThreadLabelsResult,
+ UpsertEmailFilterInput, UserEmailLink, UserEmailLinkSettings, UserProvider,
};
use entity_access::domain::models::{
AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel,
@@ -19,6 +20,7 @@ use macro_authorization::{
MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,
};
use macro_user_id::{
+ email::EmailStr,
lowercased::Lowercase,
user_id::{MacroUserId, MacroUserIdStr},
};
@@ -219,12 +221,66 @@ impl SoupService for CountingSoupService {
#[derive(Clone, Default)]
struct CountingEmailService {
inbox_calls: Arc<AtomicUsize>,
+ user_label_calls: Arc<AtomicUsize>,
+ user_link_calls: Arc<AtomicUsize>,
+ user_catalog_identities: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
}
fn test_email_err() -> EmailErr {
EmailErr::RepoErr(anyhow::anyhow!("counting email service"))
}
+impl EmailUserService for CountingEmailService {
+ async fn get_user_email_labels(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<LinkLabel>, EmailErr> {
+ self.user_label_calls.fetch_add(1, Ordering::SeqCst);
+ self.user_catalog_identities
+ .lock()
+ .expect("user catalog identities lock")
+ .push(macro_id);
+ Ok(vec![LinkLabel {
+ id: Uuid::from_u128(501),
+ link_id: Uuid::from_u128(502),
+ provider_label_id: "Label_501".to_owned(),
+ name: "Customers".to_owned(),
+ created_at: Default::default(),
+ message_list_visibility: MessageListVisibility::Show,
+ label_list_visibility: LabelListVisibility::LabelShow,
+ type_: LabelType::User,
+ }])
+ }
+
+ async fn get_user_email_links(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<UserEmailLink>, EmailErr> {
+ self.user_link_calls.fetch_add(1, Ordering::SeqCst);
+ self.user_catalog_identities
+ .lock()
+ .expect("user catalog identities lock")
+ .push(macro_id);
+ Ok(vec![UserEmailLink {
+ id: Uuid::from_u128(502),
+ macro_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ email_address: EmailStr::try_from("[email protected]".to_owned()).unwrap(),
+ photo_url: Some("https://example.com/inbox.png".to_owned()),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ sync_status: EmailSyncStatus::UpToDate,
+ needs_reauth: false,
+ settings: UserEmailLinkSettings {
+ signature_on_replies_forwards: true,
+ signature: Some("<p>Regards</p>".to_owned()),
+ },
+ is_primary: true,
+ created_at: Default::default(),
+ updated_at: Default::default(),
+ }])
+ }
+}
+
impl EmailService for CountingEmailService {
async fn get_email_thread_previews(
&self,
@@ -593,6 +649,9 @@ struct TestHarness {
email_content_reader: RecordingEmailContentReader,
authorization_calls: Arc<AtomicUsize>,
inbox_calls: Arc<AtomicUsize>,
+ user_label_calls: Arc<AtomicUsize>,
+ user_link_calls: Arc<AtomicUsize>,
+ user_catalog_identities: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
team_calls: Arc<AtomicUsize>,
raw_soup_calls: Arc<AtomicUsize>,
raw_soup_team_receipts: Arc<AtomicUsize>,
@@ -609,6 +668,9 @@ fn harness() -> TestHarness {
let email_content_reader = RecordingEmailContentReader::default();
let authorization_calls = Arc::clone(&authorization.authorization_calls);
let inbox_calls = Arc::clone(&email.inbox_calls);
+ let user_label_calls = Arc::clone(&email.user_label_calls);
+ let user_link_calls = Arc::clone(&email.user_link_calls);
+ let user_catalog_identities = Arc::clone(&email.user_catalog_identities);
let team_calls = Arc::clone(&entity_access.team_calls);
let raw_soup_calls = Arc::clone(&soup.raw_calls);
let raw_soup_team_receipts = Arc::clone(&soup.raw_team_receipts);
@@ -627,6 +689,9 @@ fn harness() -> TestHarness {
email_content_reader,
authorization_calls,
inbox_calls,
+ user_label_calls,
+ user_link_calls,
+ user_catalog_identities,
team_calls,
raw_soup_calls,
raw_soup_team_receipts,
@@ -779,12 +844,64 @@ async fn user_id_resolves_without_touching_services() {
);
assert_eq!(harness.authorization_calls.load(Ordering::SeqCst), 1);
assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(harness.user_label_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(harness.user_link_calls.load(Ordering::SeqCst), 0);
+ assert!(
+ harness
+ .user_catalog_identities
+ .lock()
+ .expect("user catalog identities lock")
+ .is_empty()
+ );
assert_eq!(harness.team_calls.load(Ordering::SeqCst), 0);
assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 0);
assert_eq!(harness.frecency_soup_calls.load(Ordering::SeqCst), 0);
assert_eq!(harness.grouped_soup_calls.load(Ordering::SeqCst), 0);
}
+#[tokio::test]
+async fn email_catalog_fields_use_the_authenticated_user_and_remain_direct_user_fields() {
+ let harness = harness();
+
+ let response = harness
+ .execute(
+ r#"{
+ user {
+ emailLabels { __typename id linkId providerLabelId name }
+ emailLinks {
+ id macroId emailAddress photoUrl provider isSyncActive syncStatus
+ needsReauth settings { signatureOnRepliesForwards signature }
+ isPrimary createdAt updatedAt
+ }
+ }
+ }"#,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let label = &data["user"]["emailLabels"][0];
+ assert_eq!(label["__typename"], "GraphqlSoupEmailLabel");
+ assert_eq!(label["linkId"], Uuid::from_u128(502).to_string());
+ let link = &data["user"]["emailLinks"][0];
+ assert_eq!(link["emailAddress"], "[email protected]");
+ assert_eq!(link["syncStatus"], "UP_TO_DATE");
+ assert_eq!(link["settings"]["signature"], "<p>Regards</p>");
+ assert_eq!(harness.user_label_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(harness.user_link_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(
+ *harness
+ .user_catalog_identities
+ .lock()
+ .expect("user catalog identities lock"),
+ vec![
+ MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),
+ MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),
+ ]
+ );
+}
+
#[tokio::test]
async fn internal_authorization_uses_the_acting_user_claim() {
let harness = harness();
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 5c89b4ea52..79f178b406 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -13,6 +13,8 @@ fn soup_response_schema_exposes_frontend_fields() {
"latestNonThreadMessage: GraphqlSoupChannelMessagePreview",
"input EmailThreadInput {",
"threadId: ID!",
+ "emailLabels: [GraphqlSoupEmailLabel!]!",
+ "emailLinks: [GraphqlEmailLink!]!",
"emailThread(input: EmailThreadInput!): GraphqlSoupEmailThread",
"type GraphqlSoupEmailThread implements GraphqlSoupEntity {",
"providerId: String",
@@ -22,6 +24,19 @@ fn soup_response_schema_exposes_frontend_fields() {
"participants: [GraphqlSoupEmailParticipant!]!",
"attachments: [GraphqlSoupEmailAttachment!]!",
"labels: [GraphqlSoupEmailLabel!]!",
+ "type GraphqlEmailLink {",
+ "macroId: String!",
+ "emailAddress: String!",
+ "photoUrl: String",
+ "provider: GraphqlEmailProvider!",
+ "isSyncActive: Boolean!",
+ "syncStatus: GraphqlEmailSyncStatus!",
+ "needsReauth: Boolean!",
+ "settings: GraphqlEmailLinkSettings!",
+ "isPrimary: Boolean!",
+ "type GraphqlEmailLinkSettings {",
+ "signatureOnRepliesForwards: Boolean!",
+ "signature: String",
"properties: [GraphqlProperty!]!",
"messages(offset: Int, limit: Int): [GraphqlSoupEmailMessage!]!",
"latestContentMessage: GraphqlSoupEmailMessage",
@@ -65,6 +80,15 @@ fn soup_response_schema_exposes_frontend_fields() {
.any(|line| line.trim() == "type GraphqlEntityRef {"),
"Soup metadata must reuse the canonical GraphqlEntity object"
);
+ assert_eq!(
+ sdl.matches("type GraphqlSoupEmailLabel {").count(),
+ 1,
+ "thread labels and the user catalog must share one normalized typename"
+ );
+ assert!(
+ !sdl.to_ascii_lowercase().contains("fusionauth"),
+ "internal FusionAuth identifiers must not enter the GraphQL contract"
+ );
}
#[test]
diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.toml
index c9dda2b805..17a8d41d53 100644
--- a/crates/email/Cargo.toml
+++ b/crates/email/Cargo.toml
@@ -36,7 +36,7 @@ axum = [
gmail_token = ["dep:authentication_service_client", "dep:redis", "ports"]
http_client = ["dep:reqwest", "ports"]
inbound = ["ports"]
-outbound = ["dep:sqlx", "dep:email_db_client", "ports"]
+outbound = ["dep:sqlx", "ports"]
ports = ["crm/ports", "dep:tokio", "frecency/ports"]
[dependencies]
@@ -62,7 +62,6 @@ frecency = { path = "../frecency" }
item_filters = { path = "../item_filters" }
lol_html = { workspace = true }
scraper = { workspace = true }
-email_db_client = { path = "../email_db_client", optional = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"], optional = true }
macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_event_topics = { path = "../macro_event_topics" }
diff --git a/crates/email/src/domain/models/link.rs b/crates/email/src/domain/models/link.rs
index 85d997fb67..1784f2488b 100644
--- a/crates/email/src/domain/models/link.rs
+++ b/crates/email/src/domain/models/link.rs
@@ -2,6 +2,9 @@ use chrono::{DateTime, Utc};
use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use uuid::Uuid;
+#[cfg(test)]
+mod test;
+
/// The provider of this email
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UserProvider {
@@ -16,6 +19,155 @@ impl UserProvider {
}
}
+/// Status of the latest initial mailbox backfill, when one exists.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum EmailBackfillStatus {
+ /// The backfill is queued but has not started.
+ Init,
+ /// The backfill is currently running.
+ InProgress,
+ /// The backfill completed successfully.
+ Complete,
+ /// The backfill was cancelled.
+ Cancelled,
+ /// The backfill failed.
+ Failed,
+}
+
+/// Coarse user-facing synchronization state for an accessible inbox.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum EmailSyncStatus {
+ /// Initial mailbox synchronization is queued or running.
+ Syncing,
+ /// The inbox is active and its latest backfill is complete.
+ UpToDate,
+ /// The latest initial mailbox synchronization failed.
+ Error,
+ /// The provider grant must be reauthorized before synchronization can resume.
+ NeedsReauth,
+ /// Synchronization is disabled for the inbox.
+ Inactive,
+}
+
+impl EmailSyncStatus {
+ /// Derive the user-facing state from persisted synchronization facts.
+ pub fn derive(
+ is_sync_active: bool,
+ needs_reauth: bool,
+ latest_backfill_status: Option<EmailBackfillStatus>,
+ ) -> Self {
+ if !is_sync_active {
+ return Self::Inactive;
+ }
+
+ if needs_reauth {
+ return Self::NeedsReauth;
+ }
+
+ match latest_backfill_status {
+ Some(EmailBackfillStatus::Init | EmailBackfillStatus::InProgress) => Self::Syncing,
+ Some(EmailBackfillStatus::Failed | EmailBackfillStatus::Cancelled) => Self::Error,
+ Some(EmailBackfillStatus::Complete) | None => Self::UpToDate,
+ }
+ }
+}
+
+/// Signature settings associated with an accessible inbox.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct UserEmailLinkSettings {
+ /// Whether signatures are included on replies and forwards.
+ pub signature_on_replies_forwards: bool,
+ /// Saved, sanitized signature HTML, when configured.
+ pub signature: Option<String>,
+}
+
+/// Persisted facts required to build an enriched user-scoped email link.
+///
+/// This is returned by the repository port. The domain service derives
+/// [`EmailSyncStatus`] from these facts before returning a [`UserEmailLink`].
+#[derive(Debug, Clone)]
+pub struct EmailInboxDetails {
+ /// Stable email link identifier.
+ pub id: Uuid,
+ /// Macro user that owns the inbox.
+ pub macro_id: MacroUserIdStr<'static>,
+ /// Provider email address for the inbox.
+ pub email_address: EmailStr<'static>,
+ /// SFS URL of the inbox's self-contact photo, when available.
+ pub photo_url: Option<String>,
+ /// Email provider.
+ pub provider: UserProvider,
+ /// Whether ongoing provider synchronization is enabled.
+ pub is_sync_active: bool,
+ /// Whether the provider grant must be reauthorized.
+ pub needs_reauth: bool,
+ /// Inbox signature settings.
+ pub settings: UserEmailLinkSettings,
+ /// Whether this is the owner's primary inbox.
+ pub is_primary: bool,
+ /// Latest initial backfill status, when one exists.
+ pub latest_backfill_status: Option<EmailBackfillStatus>,
+ /// Link creation timestamp.
+ pub created_at: DateTime<Utc>,
+ /// Link last-updated timestamp.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// Enriched email link visible to an authenticated user.
+///
+/// The model intentionally omits the provider's authentication-system user ID,
+/// which is an internal credential-linking detail rather than user-facing data.
+#[derive(Debug, Clone)]
+pub struct UserEmailLink {
+ /// Stable email link identifier.
+ pub id: Uuid,
+ /// Macro user that owns the inbox.
+ pub macro_id: MacroUserIdStr<'static>,
+ /// Provider email address for the inbox.
+ pub email_address: EmailStr<'static>,
+ /// SFS URL of the inbox's self-contact photo, when available.
+ pub photo_url: Option<String>,
+ /// Email provider.
+ pub provider: UserProvider,
+ /// Whether ongoing provider synchronization is enabled.
+ pub is_sync_active: bool,
+ /// Coarse synchronization state derived by the email domain.
+ pub sync_status: EmailSyncStatus,
+ /// Whether the provider grant must be reauthorized.
+ pub needs_reauth: bool,
+ /// Inbox signature settings.
+ pub settings: UserEmailLinkSettings,
+ /// Whether this is the owner's primary inbox.
+ pub is_primary: bool,
+ /// Link creation timestamp.
+ pub created_at: DateTime<Utc>,
+ /// Link last-updated timestamp.
+ pub updated_at: DateTime<Utc>,
+}
+
+impl From<EmailInboxDetails> for UserEmailLink {
+ fn from(details: EmailInboxDetails) -> Self {
+ Self {
+ id: details.id,
+ macro_id: details.macro_id,
+ email_address: details.email_address,
+ photo_url: details.photo_url,
+ provider: details.provider,
+ is_sync_active: details.is_sync_active,
+ sync_status: EmailSyncStatus::derive(
+ details.is_sync_active,
+ details.needs_reauth,
+ details.latest_backfill_status,
+ ),
+ needs_reauth: details.needs_reauth,
+ settings: details.settings,
+ is_primary: details.is_primary,
+ created_at: details.created_at,
+ updated_at: details.updated_at,
+ }
+ }
+}
+
#[derive(Clone)]
pub struct Link {
pub id: Uuid,
diff --git a/crates/email/src/domain/models/link/test.rs b/crates/email/src/domain/models/link/test.rs
new file mode 100644
index 0000000000..135a792eb0
--- /dev/null
+++ b/crates/email/src/domain/models/link/test.rs
@@ -0,0 +1,43 @@
+use super::{EmailBackfillStatus, EmailSyncStatus};
+
+#[test]
+fn inactive_sync_takes_precedence_over_other_facts() {
+ assert_eq!(
+ EmailSyncStatus::derive(false, true, Some(EmailBackfillStatus::InProgress)),
+ EmailSyncStatus::Inactive
+ );
+}
+
+#[test]
+fn reauthorization_takes_precedence_over_active_backfill_state() {
+ assert_eq!(
+ EmailSyncStatus::derive(true, true, Some(EmailBackfillStatus::InProgress)),
+ EmailSyncStatus::NeedsReauth
+ );
+}
+
+#[test]
+fn backfill_status_maps_to_the_user_facing_sync_state() {
+ for status in [EmailBackfillStatus::Init, EmailBackfillStatus::InProgress] {
+ assert_eq!(
+ EmailSyncStatus::derive(true, false, Some(status)),
+ EmailSyncStatus::Syncing
+ );
+ }
+
+ for status in [EmailBackfillStatus::Failed, EmailBackfillStatus::Cancelled] {
+ assert_eq!(
+ EmailSyncStatus::derive(true, false, Some(status)),
+ EmailSyncStatus::Error
+ );
+ }
+
+ assert_eq!(
+ EmailSyncStatus::derive(true, false, Some(EmailBackfillStatus::Complete)),
+ EmailSyncStatus::UpToDate
+ );
+ assert_eq!(
+ EmailSyncStatus::derive(true, false, None),
+ EmailSyncStatus::UpToDate
+ );
+}
diff --git a/crates/email/src/domain/models/mod.rs b/crates/email/src/domain/models/mod.rs
index 504f16d851..e550b39591 100644
--- a/crates/email/src/domain/models/mod.rs
+++ b/crates/email/src/domain/models/mod.rs
@@ -25,7 +25,10 @@ pub use label::{
Label, LabelListVisibility, LabelType, LinkLabel, MessageLabel, MessageListVisibility,
UpdateThreadLabelsResult,
};
-pub use link::{Link, UserProvider};
+pub use link::{
+ EmailBackfillStatus, EmailInboxDetails, EmailSyncStatus, Link, UserEmailLink,
+ UserEmailLinkSettings, UserProvider,
+};
pub use message::{Message, MessageRow, SimpleMessage};
pub use parsed_message::{ParsedLabel, ParsedMessage, ParsedThread};
pub use preview::{
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index 9eaa2dc878..bf4b6c6b0e 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -1,10 +1,11 @@
use crate::domain::models::{
Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,
- CreatedDraft, EmailErr, EmailFilter, EmailThreadPreview, EnrichedEmailThreadPreview,
- GetEmailsRequest, Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow,
- ParsedAddresses, ParsedMessage, ParsedThread, PreviewCursorQuery, RecipientType,
- ResolvedDraftInput, SimpleMessage, SimpleMessageInfo, Thread, ThreadRow,
- UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts, UserProvider,
+ CreatedDraft, EmailErr, EmailFilter, EmailInboxDetails, EmailThreadPreview,
+ EnrichedEmailThreadPreview, GetEmailsRequest, Label, Link, LinkLabel, MessageAttachment,
+ MessageLabel, MessageRow, ParsedAddresses, ParsedMessage, ParsedThread, PreviewCursorQuery,
+ RecipientType, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo, Thread, ThreadRow,
+ UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts, UserEmailLink,
+ UserProvider,
};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
@@ -49,6 +50,30 @@ pub struct LinkEmailSettings {
pub signature_on_replies_forwards: bool,
}
+/// Outbound repository capabilities for authenticated user email catalogs.
+///
+/// The port returns persisted facts only. Accessible-inbox aggregation and
+/// synchronization-status policy remain in the email domain service.
+pub trait EmailUserRepo: Send + Sync + 'static {
+ /// Resolve every owned or delegated inbox accessible to `macro_id`.
+ fn user_accessible_inboxes(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;
+
+ /// Fetch all labels belonging to one already-authorized inbox.
+ fn user_labels_for_link(
+ &self,
+ link_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<LinkLabel>, EmailErr>> + Send;
+
+ /// Fetch enriched persisted facts for every owned or delegated inbox.
+ fn user_inbox_details(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<EmailInboxDetails>, EmailErr>> + Send;
+}
+
pub trait EmailRepo: Send + Sync + 'static {
type Err: Send;
fn previews_for_view_cursor(
@@ -383,6 +408,21 @@ impl<T: EmailService> EmailPreviewServiceReadOnly for ReadonlyEmailPreviewAdapte
}
}
+/// User-scoped read operations consumed by email inbound adapters.
+pub trait EmailUserService: Send + Sync + 'static {
+ /// List labels across every owned or delegated inbox accessible to the user.
+ fn get_user_email_labels(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<LinkLabel>, EmailErr>> + Send;
+
+ /// List enriched owned or delegated email links accessible to the user.
+ fn get_user_email_links(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<UserEmailLink>, EmailErr>> + Send;
+}
+
pub trait EmailService: Send + Sync + 'static {
fn get_email_thread_previews(
&self,
@@ -580,6 +620,22 @@ fn no_op_email_err() -> EmailErr {
EmailErr::RepoErr(anyhow::anyhow!("no-op email service"))
}
+impl EmailUserService for NoOpEmailService {
+ async fn get_user_email_labels(
+ &self,
+ _macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<LinkLabel>, EmailErr> {
+ Err(no_op_email_err())
+ }
+
+ async fn get_user_email_links(
+ &self,
+ _macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<UserEmailLink>, EmailErr> {
+ Err(no_op_email_err())
+ }
+}
+
impl EmailService for NoOpEmailService {
async fn get_email_thread_previews(
&self,
diff --git a/crates/email/src/domain/service/mod.rs b/crates/email/src/domain/service/mod.rs
index 9a85fa2758..562240b8a9 100644
--- a/crates/email/src/domain/service/mod.rs
+++ b/crates/email/src/domain/service/mod.rs
@@ -4,6 +4,7 @@ mod send;
mod signature;
mod thread;
mod thread_labels;
+mod user;
#[cfg(test)]
mod test;
diff --git a/crates/email/src/domain/service/user.rs b/crates/email/src/domain/service/user.rs
new file mode 100644
index 0000000000..293a83ea4f
--- /dev/null
+++ b/crates/email/src/domain/service/user.rs
@@ -0,0 +1,50 @@
+use crate::domain::{
+ models::{EmailErr, LinkLabel, UserEmailLink},
+ ports::{EmailUserRepo, EmailUserService},
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::EmailServiceImpl;
+
+#[cfg(test)]
+mod test;
+
+impl<T, U, E, CS, Eam, B> EmailUserService for EmailServiceImpl<T, U, E, CS, Eam, B>
+where
+ T: EmailUserRepo,
+ U: Send + Sync + 'static,
+ E: Send + Sync + 'static,
+ CS: Send + Sync + 'static,
+ Eam: Send + Sync + 'static,
+ B: Send + Sync + 'static,
+{
+ async fn get_user_email_labels(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<LinkLabel>, EmailErr> {
+ let inboxes = self.email_repo.user_accessible_inboxes(macro_id).await?;
+ let mut labels = Vec::new();
+
+ // Preserve the REST analog's stable inbox order and each inbox's
+ // repository-defined label order while aggregating owned and delegated
+ // inboxes in the domain service.
+ for inbox in inboxes {
+ labels.extend(self.email_repo.user_labels_for_link(inbox.id).await?);
+ }
+
+ Ok(labels)
+ }
+
+ async fn get_user_email_links(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<UserEmailLink>, EmailErr> {
+ Ok(self
+ .email_repo
+ .user_inbox_details(macro_id)
+ .await?
+ .into_iter()
+ .map(UserEmailLink::from)
+ .collect())
+ }
+}
diff --git a/crates/email/src/domain/service/user/test.rs b/crates/email/src/domain/service/user/test.rs
new file mode 100644
index 0000000000..be2bbf6919
--- /dev/null
+++ b/crates/email/src/domain/service/user/test.rs
@@ -0,0 +1,170 @@
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
+
+use chrono::Utc;
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
+use uuid::Uuid;
+
+use crate::domain::{
+ models::{
+ EmailBackfillStatus, EmailInboxDetails, EmailSyncStatus, Link, LinkLabel,
+ UserEmailLinkSettings, UserProvider,
+ },
+ ports::{EmailUserRepo, EmailUserService},
+};
+
+use super::super::EmailServiceImpl;
+
+#[derive(Clone, Default)]
+struct FakeUserRepo {
+ inboxes: Vec<Link>,
+ labels: HashMap<Uuid, Vec<LinkLabel>>,
+ details: Vec<EmailInboxDetails>,
+ requested_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
+ requested_label_links: Arc<Mutex<Vec<Uuid>>>,
+}
+
+impl EmailUserRepo for FakeUserRepo {
+ async fn user_accessible_inboxes(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<Link>, crate::domain::models::EmailErr> {
+ self.requested_users.lock().unwrap().push(macro_id);
+ Ok(self.inboxes.clone())
+ }
+
+ async fn user_labels_for_link(
+ &self,
+ link_id: Uuid,
+ ) -> Result<Vec<LinkLabel>, crate::domain::models::EmailErr> {
+ self.requested_label_links.lock().unwrap().push(link_id);
+ Ok(self.labels.get(&link_id).cloned().unwrap_or_default())
+ }
+
+ async fn user_inbox_details(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<EmailInboxDetails>, crate::domain::models::EmailErr> {
+ self.requested_users.lock().unwrap().push(macro_id);
+ Ok(self.details.clone())
+ }
+}
+
+fn service(repo: FakeUserRepo) -> EmailServiceImpl<FakeUserRepo, (), (), (), (), ()> {
+ EmailServiceImpl {
+ email_repo: repo,
+ frecency_service: (),
+ enqueuer: (),
+ crm_service: (),
+ entity_access_management_service: (),
+ macro_event_broker: (),
+ sent_undo_delay_secs: 0,
+ }
+}
+
+fn user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+fn link(id: Uuid, owner: &str) -> Link {
+ Link {
+ id,
+ macro_id: MacroUserIdStr::try_from_email(owner).unwrap(),
+ fusionauth_user_id: "internal-auth-id".to_owned(),
+ email_address: EmailStr::try_from(owner.to_owned()).unwrap(),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ is_primary: true,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+}
+
+fn label(id: Uuid, link_id: Uuid, name: &str) -> LinkLabel {
+ LinkLabel {
+ id,
+ link_id,
+ provider_label_id: name.to_uppercase(),
+ name: name.to_owned(),
+ created_at: Utc::now(),
+ message_list_visibility: crate::domain::models::MessageListVisibility::Show,
+ label_list_visibility: crate::domain::models::LabelListVisibility::LabelShow,
+ type_: crate::domain::models::LabelType::User,
+ }
+}
+
+#[tokio::test]
+async fn labels_are_aggregated_across_owned_and_delegated_inboxes_in_order() {
+ let owned = Uuid::from_u128(1);
+ let delegated = Uuid::from_u128(2);
+ let owned_label = label(Uuid::from_u128(10), owned, "Owned");
+ let delegated_label = label(Uuid::from_u128(20), delegated, "Delegated");
+ let repo = FakeUserRepo {
+ inboxes: vec![
+ link(owned, "[email protected]"),
+ link(delegated, "[email protected]"),
+ ],
+ labels: HashMap::from([
+ (owned, vec![owned_label.clone()]),
+ (delegated, vec![delegated_label.clone()]),
+ ]),
+ ..Default::default()
+ };
+ let requested_users = Arc::clone(&repo.requested_users);
+ let requested_label_links = Arc::clone(&repo.requested_label_links);
+
+ let labels = service(repo)
+ .get_user_email_labels(user_id())
+ .await
+ .unwrap();
+
+ assert_eq!(
+ labels.iter().map(|label| label.id).collect::<Vec<_>>(),
+ vec![owned_label.id, delegated_label.id]
+ );
+ assert_eq!(*requested_users.lock().unwrap(), vec![user_id()]);
+ assert_eq!(
+ *requested_label_links.lock().unwrap(),
+ vec![owned, delegated]
+ );
+}
+
+#[tokio::test]
+async fn links_are_scoped_to_the_user_and_enriched_by_domain_policy() {
+ let link_id = Uuid::from_u128(30);
+ let now = Utc::now();
+ let repo = FakeUserRepo {
+ details: vec![EmailInboxDetails {
+ id: link_id,
+ macro_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ email_address: EmailStr::try_from("[email protected]".to_owned()).unwrap(),
+ photo_url: Some("https://example.com/photo.png".to_owned()),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ needs_reauth: false,
+ settings: UserEmailLinkSettings {
+ signature_on_replies_forwards: true,
+ signature: Some("<p>Regards</p>".to_owned()),
+ },
+ is_primary: true,
+ latest_backfill_status: Some(EmailBackfillStatus::InProgress),
+ created_at: now,
+ updated_at: now,
+ }],
+ ..Default::default()
+ };
+ let requested_users = Arc::clone(&repo.requested_users);
+
+ let links = service(repo).get_user_email_links(user_id()).await.unwrap();
+
+ assert_eq!(*requested_users.lock().unwrap(), vec![user_id()]);
+ assert_eq!(links.len(), 1);
+ assert_eq!(links[0].id, link_id);
+ assert_eq!(links[0].sync_status, EmailSyncStatus::Syncing);
+ assert_eq!(
+ links[0].settings.signature.as_deref(),
+ Some("<p>Regards</p>")
+ );
+}
diff --git a/crates/email/src/outbound/email_pg_repo/link.rs b/crates/email/src/outbound/email_pg_repo/link.rs
index 78a9f3a493..6974960bee 100644
--- a/crates/email/src/outbound/email_pg_repo/link.rs
+++ b/crates/email/src/outbound/email_pg_repo/link.rs
@@ -1,5 +1,8 @@
-use crate::domain::models::{Link, UserProvider};
-use macro_user_id::user_id::MacroUserIdStr;
+use crate::domain::models::{
+ EmailBackfillStatus, EmailInboxDetails, Link, UserEmailLinkSettings, UserProvider,
+};
+use chrono::{DateTime, Utc};
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use sqlx::PgPool;
use uuid::Uuid;
@@ -173,3 +176,140 @@ pub(super) async fn inboxes_for_macro_id(
})
.collect()
}
+
+/// Database representation of an initial mailbox backfill status.
+#[derive(Debug, Clone, Copy, sqlx::Type)]
+#[sqlx(type_name = "email_backfill_job_status", rename_all = "PascalCase")]
+enum DbEmailBackfillStatus {
+ /// The backfill is queued but has not started.
+ Init,
+ /// The backfill is running.
+ InProgress,
+ /// The backfill completed.
+ Complete,
+ /// The backfill was cancelled.
+ Cancelled,
+ /// The backfill failed.
+ Failed,
+}
+
+/// Database row for the enriched accessible-inbox projection.
+struct DbInboxDetailsRow {
+ /// Stable email link identifier.
+ id: Uuid,
+ /// Macro user that owns the link.
+ macro_id: String,
+ /// Provider email address.
+ email_address: String,
+ /// Email provider.
+ provider: DbUserProvider,
+ /// Whether synchronization is active.
+ is_sync_active: bool,
+ /// Whether the provider grant needs reauthorization.
+ needs_reauth: bool,
+ /// Whether this is the owner's primary inbox.
+ is_primary: bool,
+ /// Link creation timestamp.
+ created_at: DateTime<Utc>,
+ /// Link last-updated timestamp.
+ updated_at: DateTime<Utc>,
+ /// Whether signatures are included on replies and forwards.
+ signature_on_replies_forwards: Option<bool>,
+ /// Saved signature HTML.
+ signature: Option<String>,
+ /// Latest initial backfill status.
+ latest_backfill_status: Option<DbEmailBackfillStatus>,
+ /// SFS URL of the inbox's self-contact photo.
+ photo_url: Option<String>,
+}
+
+impl DbInboxDetailsRow {
+ /// Convert the database projection into domain-owned persisted facts.
+ fn try_into_model(self) -> Result<EmailInboxDetails, macro_user_id::error::ParseErr> {
+ Ok(EmailInboxDetails {
+ id: self.id,
+ macro_id: MacroUserIdStr::try_from(self.macro_id)?,
+ email_address: EmailStr::try_from(self.email_address)?,
+ photo_url: self.photo_url,
+ provider: match self.provider {
+ DbUserProvider::Gmail => UserProvider::Gmail,
+ },
+ is_sync_active: self.is_sync_active,
+ needs_reauth: self.needs_reauth,
+ settings: UserEmailLinkSettings {
+ signature_on_replies_forwards: self.signature_on_replies_forwards.unwrap_or(false),
+ signature: self.signature,
+ },
+ is_primary: self.is_primary,
+ latest_backfill_status: self.latest_backfill_status.map(|status| match status {
+ DbEmailBackfillStatus::Init => EmailBackfillStatus::Init,
+ DbEmailBackfillStatus::InProgress => EmailBackfillStatus::InProgress,
+ DbEmailBackfillStatus::Complete => EmailBackfillStatus::Complete,
+ DbEmailBackfillStatus::Cancelled => EmailBackfillStatus::Cancelled,
+ DbEmailBackfillStatus::Failed => EmailBackfillStatus::Failed,
+ }),
+ created_at: self.created_at,
+ updated_at: self.updated_at,
+ })
+ }
+}
+
+/// Fetch and map the enriched, user-scoped inbox details used by inbound
+/// email catalog adapters.
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn inbox_details_for_macro_id(
+ pool: &PgPool,
+ macro_id: &MacroUserIdStr<'_>,
+) -> Result<Vec<EmailInboxDetails>, sqlx::Error> {
+ let rows = sqlx::query_as!(
+ DbInboxDetailsRow,
+ r#"
+ SELECT l.id as "id!", l.macro_id as "macro_id!",
+ l.email_address as "email_address!",
+ l.provider as "provider!: _",
+ l.is_sync_active as "is_sync_active!",
+ l.needs_reauth as "needs_reauth!",
+ l.is_primary as "is_primary!",
+ l.created_at as "created_at!",
+ l.updated_at as "updated_at!",
+ s.signature_on_replies_forwards as "signature_on_replies_forwards?",
+ s.signature,
+ bj.status as "latest_backfill_status?: _",
+ c.sfs_photo_url as "photo_url?"
+ FROM (
+ SELECT el.id, el.macro_id, el.email_address, el.provider,
+ el.is_sync_active, el.needs_reauth, el.is_primary,
+ el.created_at, el.updated_at
+ FROM email_links el
+ WHERE el.macro_id = $1
+ UNION
+ SELECT el.id, el.macro_id, el.email_address, el.provider,
+ el.is_sync_active, el.needs_reauth, el.is_primary,
+ el.created_at, el.updated_at
+ FROM email_links el
+ JOIN macro_user_links mul ON el.id = mul.link_id
+ WHERE mul.primary_macro_id = $1
+ ) l
+ LEFT JOIN email_settings s ON s.link_id = l.id
+ LEFT JOIN LATERAL (
+ SELECT status FROM email_backfill_jobs
+ WHERE link_id = l.id
+ ORDER BY created_at DESC
+ LIMIT 1
+ ) bj ON true
+ LEFT JOIN email_contacts c
+ ON c.link_id = l.id AND LOWER(c.email_address) = LOWER(l.email_address)
+ ORDER BY l.created_at DESC
+ "#,
+ macro_id.as_ref()
+ )
+ .fetch_all(pool)
+ .await?;
+
+ rows.into_iter()
+ .map(|row| {
+ row.try_into_model()
+ .map_err(|error| sqlx::Error::Decode(Box::new(error)))
+ })
+ .collect()
+}
diff --git a/crates/email/src/outbound/email_pg_repo/mod.rs b/crates/email/src/outbound/email_pg_repo/mod.rs
index 6a0e35fc95..f7793d8068 100644
--- a/crates/email/src/outbound/email_pg_repo/mod.rs
+++ b/crates/email/src/outbound/email_pg_repo/mod.rs
@@ -1,11 +1,12 @@
use crate::domain::{
models::{
Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, EmailErr,
- EmailFilter, EmailThreadPreview, Label, Link, LinkLabel, MessageAttachment, MessageLabel,
- MessageRow, ParsedAddresses, PreviewCursorQuery, ResolvedDraftInput, SimpleMessage,
- SimpleMessageInfo, ThreadRow, UpsertEmailFilterInput, UpsertedContacts, UserProvider,
+ EmailFilter, EmailInboxDetails, EmailThreadPreview, Label, Link, LinkLabel,
+ MessageAttachment, MessageLabel, MessageRow, ParsedAddresses, PreviewCursorQuery,
+ ResolvedDraftInput, SimpleMessage, SimpleMessageInfo, ThreadRow, UpsertEmailFilterInput,
+ UpsertedContacts, UserProvider,
},
- ports::{EmailRepo, LinkEmailSettings, RecipientsByMessageId},
+ ports::{EmailRepo, EmailUserRepo, LinkEmailSettings, RecipientsByMessageId},
};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
@@ -24,6 +25,7 @@ mod message;
mod preview;
mod preview_views;
mod project;
+mod settings;
mod thread;
#[cfg(test)]
@@ -55,17 +57,39 @@ impl EmailPgRepo {
}
}
+impl EmailUserRepo for EmailPgRepo {
+ async fn user_accessible_inboxes(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<Link>, EmailErr> {
+ link::inboxes_for_macro_id(&self.pool, macro_id)
+ .await
+ .map_err(|error| EmailErr::RepoErr(error.into()))
+ }
+
+ async fn user_labels_for_link(&self, link_id: Uuid) -> Result<Vec<LinkLabel>, EmailErr> {
+ label::list_labels_by_link_id(&self.pool, link_id)
+ .await
+ .map_err(|error| EmailErr::RepoErr(error.into()))
+ }
+
+ async fn user_inbox_details(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<EmailInboxDetails>, EmailErr> {
+ link::inbox_details_for_macro_id(&self.pool, &macro_id)
+ .await
+ .map_err(|error| EmailErr::RepoErr(error.into()))
+ }
+}
+
impl EmailRepo for EmailPgRepo {
type Err = sqlx::Error;
async fn fetch_email_settings(&self, link_id: Uuid) -> Result<LinkEmailSettings, EmailErr> {
- let settings = email_db_client::settings::fetch_settings(&self.pool, link_id)
+ settings::fetch_email_settings(&self.pool, link_id)
.await
- .map_err(EmailErr::RepoErr)?;
- Ok(LinkEmailSettings {
- signature: settings.signature,
- signature_on_replies_forwards: settings.signature_on_replies_forwards,
- })
+ .map_err(|error| EmailErr::RepoErr(error.into()))
}
async fn previews_for_view_cursor(
diff --git a/crates/email/src/outbound/email_pg_repo/settings.rs b/crates/email/src/outbound/email_pg_repo/settings.rs
new file mode 100644
index 0000000000..277eaf70cd
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/settings.rs
@@ -0,0 +1,27 @@
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use crate::domain::ports::LinkEmailSettings;
+
+/// Fetch one inbox's signature settings.
+#[tracing::instrument(skip(pool), err)]
+pub(super) async fn fetch_email_settings(
+ pool: &PgPool,
+ link_id: Uuid,
+) -> Result<LinkEmailSettings, sqlx::Error> {
+ let row = sqlx::query!(
+ r#"
+ SELECT signature_on_replies_forwards, signature
+ FROM email_settings
+ WHERE link_id = $1
+ "#,
+ link_id
+ )
+ .fetch_one(pool)
+ .await?;
+
+ Ok(LinkEmailSettings {
+ signature: row.signature,
+ signature_on_replies_forwards: row.signature_on_replies_forwards,
+ })
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test/link.rs b/crates/email/src/outbound/email_pg_repo/test/link.rs
index 815964697f..d5835e2791 100644
--- a/crates/email/src/outbound/email_pg_repo/test/link.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/link.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::domain::{models::EmailBackfillStatus, ports::EmailUserRepo};
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
@@ -118,7 +119,7 @@ async fn test_inboxes_for_macro_id_includes_own_and_delegated(
let repo = EmailPgRepo::new(pool);
let macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
- let links = repo.inboxes_for_macro_id(macro_id).await?;
+ let links = repo.inboxes_for_macro_id(macro_id.clone()).await?;
let emails: std::collections::HashSet<&str> =
links.iter().map(|l| l.email_address.0.as_ref()).collect();
@@ -143,6 +144,89 @@ async fn test_inboxes_for_macro_id_includes_own_and_delegated(
"unrelated inbox must be excluded"
);
+ let detailed_emails = repo
+ .user_inbox_details(macro_id)
+ .await?
+ .into_iter()
+ .map(|inbox| inbox.email_address.0.as_ref().to_owned())
+ .collect::<std::collections::HashSet<_>>();
+ assert_eq!(
+ detailed_emails,
+ emails.into_iter().map(str::to_owned).collect(),
+ "enriched inbox details must preserve owned and delegated scoping"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn user_inbox_details_maps_enriched_owned_inbox(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ sqlx::query!(
+ r#"
+ UPDATE email_links
+ SET needs_reauth = TRUE
+ WHERE id = $1
+ "#,
+ link_id
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature)
+ VALUES ($1, TRUE, '<p>Regards</p>')
+ "#,
+ link_id
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO email_backfill_jobs (id, link_id, fusionauth_user_id, status)
+ VALUES ($1, $2, 'fa-user-1', 'InProgress')
+ "#,
+ Uuid::from_u128(901),
+ link_id
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO email_contacts (id, link_id, email_address, sfs_photo_url)
+ VALUES ($1, $2, '[email protected]', 'https://example.com/inbox.png')
+ "#,
+ Uuid::from_u128(902),
+ link_id
+ )
+ .execute(&pool)
+ .await?;
+
+ let details = EmailPgRepo::new(pool)
+ .user_inbox_details(MacroUserIdStr::parse_from_str("macro|[email protected]")?)
+ .await?;
+
+ assert_eq!(details.len(), 1);
+ let inbox = &details[0];
+ assert_eq!(inbox.id, link_id);
+ assert_eq!(inbox.email_address.0.as_ref(), "[email protected]");
+ assert_eq!(inbox.provider, UserProvider::Gmail);
+ assert!(inbox.is_sync_active);
+ assert!(inbox.needs_reauth);
+ assert!(inbox.is_primary);
+ assert_eq!(
+ inbox.latest_backfill_status,
+ Some(EmailBackfillStatus::InProgress)
+ );
+ assert!(inbox.settings.signature_on_replies_forwards);
+ assert_eq!(inbox.settings.signature.as_deref(), Some("<p>Regards</p>"));
+ assert_eq!(
+ inbox.photo_url.as_deref(),
+ Some("https://example.com/inbox.png")
+ );
Ok(())
}
diff --git a/crates/email/src/outbound/email_pg_repo/test/mod.rs b/crates/email/src/outbound/email_pg_repo/test/mod.rs
index 494e981480..9a9fd3d1b3 100644
--- a/crates/email/src/outbound/email_pg_repo/test/mod.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/mod.rs
@@ -8,6 +8,7 @@ mod message;
mod preview;
mod project;
mod project_scope_dynamic_query;
+mod settings;
mod signal_flag;
mod thread;
mod thread_labels;
diff --git a/crates/email/src/outbound/email_pg_repo/test/settings.rs b/crates/email/src/outbound/email_pg_repo/test/settings.rs
new file mode 100644
index 0000000000..0117cf9d72
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/test/settings.rs
@@ -0,0 +1,24 @@
+use super::*;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_message"))
+)]
+async fn fetch_email_settings_maps_signature_fields(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ sqlx::query!(
+ r#"
+ INSERT INTO email_settings (link_id, signature_on_replies_forwards, signature)
+ VALUES ($1, TRUE, '<p>Regards</p>')
+ "#,
+ link_id
+ )
+ .execute(&pool)
+ .await?;
+
+ let settings = EmailPgRepo::new(pool).fetch_email_settings(link_id).await?;
+
+ assert!(settings.signature_on_replies_forwards);
+ assert_eq!(settings.signature.as_deref(), Some("<p>Regards</p>"));
+ Ok(())
+}
diff --git a/crates/graphql_email/src/lib.rs b/crates/graphql_email/src/lib.rs
index de88b8be61..625376ce94 100644
--- a/crates/graphql_email/src/lib.rs
+++ b/crates/graphql_email/src/lib.rs
@@ -4,9 +4,16 @@
mod loaders;
mod objects;
+mod user_objects;
+mod user_query;
pub use loaders::{
EmailContentKey, EmailContentLoad, EmailContentLoader, EmailServiceEmailContentReader,
NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader, email_content_loader,
};
pub use objects::{GraphqlSoupEmailMessage, load_email_messages, load_latest_email_message};
+pub use user_objects::{
+ GraphqlEmailLabel, GraphqlEmailLink, GraphqlEmailLinkSettings, GraphqlEmailProvider,
+ GraphqlEmailSyncStatus,
+};
+pub use user_query::GraphqlEmailQuery;
diff --git a/crates/graphql_email/src/user_objects.rs b/crates/graphql_email/src/user_objects.rs
new file mode 100644
index 0000000000..f09b20bc78
--- /dev/null
+++ b/crates/graphql_email/src/user_objects.rs
@@ -0,0 +1,189 @@
+use async_graphql::{Enum, ID, SimpleObject};
+use email::domain::models::{
+ EmailSyncStatus, LabelListVisibility, LabelType, LinkLabel, MessageListVisibility,
+ UserEmailLink, UserEmailLinkSettings, UserProvider,
+};
+use uuid::Uuid;
+
+/// Canonical normalized GraphQL email label used by both email threads and
+/// the authenticated user's label catalog.
+#[derive(SimpleObject)]
+#[graphql(name = "GraphqlSoupEmailLabel")]
+pub struct GraphqlEmailLabel {
+ /// Stable database identifier for the label.
+ id: ID,
+ /// Identifier of the email link that owns the label.
+ link_id: ID,
+ /// Provider-specific label identifier.
+ provider_label_id: String,
+ /// User-visible label name.
+ name: String,
+ /// Label creation timestamp in RFC 3339 format.
+ created_at: String,
+ /// Provider message-list visibility value.
+ message_list_visibility: &'static str,
+ /// Provider label-list visibility value.
+ label_list_visibility: &'static str,
+ /// Whether the label is provider-created or user-created.
+ #[graphql(name = "type")]
+ type_: &'static str,
+}
+
+impl GraphqlEmailLabel {
+ /// Construct the canonical label object from domain label fields.
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ id: Uuid,
+ link_id: Uuid,
+ provider_label_id: String,
+ name: String,
+ created_at: chrono::DateTime<chrono::Utc>,
+ message_list_visibility: MessageListVisibility,
+ label_list_visibility: LabelListVisibility,
+ type_: LabelType,
+ ) -> Self {
+ Self {
+ id: ID(id.to_string()),
+ link_id: ID(link_id.to_string()),
+ provider_label_id,
+ name,
+ created_at: created_at.to_rfc3339(),
+ message_list_visibility: match message_list_visibility {
+ MessageListVisibility::Show => "show",
+ MessageListVisibility::Hide => "hide",
+ },
+ label_list_visibility: match label_list_visibility {
+ LabelListVisibility::LabelShow => "label_show",
+ LabelListVisibility::LabelShowIfUnread => "label_show_if_unread",
+ LabelListVisibility::LabelHide => "label_hide",
+ },
+ type_: match type_ {
+ LabelType::System => "system",
+ LabelType::User => "user",
+ },
+ }
+ }
+}
+
+impl From<LinkLabel> for GraphqlEmailLabel {
+ fn from(label: LinkLabel) -> Self {
+ Self::new(
+ label.id,
+ label.link_id,
+ label.provider_label_id,
+ label.name,
+ label.created_at,
+ label.message_list_visibility,
+ label.label_list_visibility,
+ label.type_,
+ )
+ }
+}
+
+/// Email provider for an authenticated user's linked inbox.
+#[derive(Enum, Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GraphqlEmailProvider {
+ /// Google Gmail.
+ Gmail,
+}
+
+impl From<UserProvider> for GraphqlEmailProvider {
+ fn from(provider: UserProvider) -> Self {
+ match provider {
+ UserProvider::Gmail => Self::Gmail,
+ }
+ }
+}
+
+/// Coarse synchronization state for an authenticated user's linked inbox.
+#[derive(Enum, Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GraphqlEmailSyncStatus {
+ /// Initial synchronization is queued or running.
+ Syncing,
+ /// The inbox is active and synchronized.
+ UpToDate,
+ /// Initial synchronization failed or was cancelled.
+ Error,
+ /// The provider grant must be reauthorized.
+ NeedsReauth,
+ /// Synchronization is disabled.
+ Inactive,
+}
+
+impl From<EmailSyncStatus> for GraphqlEmailSyncStatus {
+ fn from(status: EmailSyncStatus) -> Self {
+ match status {
+ EmailSyncStatus::Syncing => Self::Syncing,
+ EmailSyncStatus::UpToDate => Self::UpToDate,
+ EmailSyncStatus::Error => Self::Error,
+ EmailSyncStatus::NeedsReauth => Self::NeedsReauth,
+ EmailSyncStatus::Inactive => Self::Inactive,
+ }
+ }
+}
+
+/// Signature settings embedded in an authenticated user's email link.
+#[derive(SimpleObject)]
+pub struct GraphqlEmailLinkSettings {
+ /// Whether signatures are included on replies and forwards.
+ signature_on_replies_forwards: bool,
+ /// Saved, sanitized signature HTML, when configured.
+ signature: Option<String>,
+}
+
+impl From<UserEmailLinkSettings> for GraphqlEmailLinkSettings {
+ fn from(settings: UserEmailLinkSettings) -> Self {
+ Self {
+ signature_on_replies_forwards: settings.signature_on_replies_forwards,
+ signature: settings.signature,
+ }
+ }
+}
+
+/// Enriched email link accessible to the authenticated user.
+#[derive(SimpleObject)]
+pub struct GraphqlEmailLink {
+ /// Stable email link identifier.
+ id: ID,
+ /// Macro user that owns the inbox.
+ macro_id: String,
+ /// Provider email address for the inbox.
+ email_address: String,
+ /// SFS URL of the inbox's self-contact photo, when available.
+ photo_url: Option<String>,
+ /// Email provider.
+ provider: GraphqlEmailProvider,
+ /// Whether ongoing provider synchronization is enabled.
+ is_sync_active: bool,
+ /// Coarse synchronization state derived by the email domain.
+ sync_status: GraphqlEmailSyncStatus,
+ /// Whether the provider grant must be reauthorized.
+ needs_reauth: bool,
+ /// Inbox signature settings.
+ settings: GraphqlEmailLinkSettings,
+ /// Whether this is the owner's primary inbox.
+ is_primary: bool,
+ /// Link creation timestamp in RFC 3339 format.
+ created_at: String,
+ /// Link last-updated timestamp in RFC 3339 format.
+ updated_at: String,
+}
+
+impl From<UserEmailLink> for GraphqlEmailLink {
+ fn from(link: UserEmailLink) -> Self {
+ Self {
+ id: ID(link.id.to_string()),
+ macro_id: link.macro_id.to_string(),
+ email_address: link.email_address.0.as_ref().to_owned(),
+ photo_url: link.photo_url,
+ provider: link.provider.into(),
+ is_sync_active: link.is_sync_active,
+ sync_status: link.sync_status.into(),
+ needs_reauth: link.needs_reauth,
+ settings: link.settings.into(),
+ is_primary: link.is_primary,
+ created_at: link.created_at.to_rfc3339(),
+ updated_at: link.updated_at.to_rfc3339(),
+ }
+ }
+}
diff --git a/crates/graphql_email/src/user_query.rs b/crates/graphql_email/src/user_query.rs
new file mode 100644
index 0000000000..b7c09a54b1
--- /dev/null
+++ b/crates/graphql_email/src/user_query.rs
@@ -0,0 +1,76 @@
+use std::sync::Arc;
+
+use async_graphql::Object;
+use email::domain::ports::EmailUserService;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::user_objects::{GraphqlEmailLabel, GraphqlEmailLink};
+
+#[cfg(test)]
+mod test;
+
+/// Flattenable GraphQL fields for authenticated user email catalogs.
+pub struct GraphqlEmailQuery<S> {
+ /// Email domain service supplied by the composition root.
+ service: Arc<S>,
+ /// Authenticated user whose catalogs may be loaded.
+ user_id: MacroUserIdStr<'static>,
+}
+
+impl<S> Clone for GraphqlEmailQuery<S> {
+ fn clone(&self) -> Self {
+ Self {
+ service: Arc::clone(&self.service),
+ user_id: self.user_id.clone(),
+ }
+ }
+}
+
+impl<S> GraphqlEmailQuery<S> {
+ /// Create user-scoped email query fields from the authenticated identity and
+ /// the application's email domain service.
+ pub fn new(service: Arc<S>, user_id: MacroUserIdStr<'static>) -> Self {
+ Self { service, user_id }
+ }
+}
+
+/// Authenticated user email catalog fields.
+#[Object]
+impl<S> GraphqlEmailQuery<S>
+where
+ S: EmailUserService,
+{
+ /// Labels across every owned or delegated inbox accessible to the authenticated user.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn email_labels(&self) -> async_graphql::Result<Vec<GraphqlEmailLabel>> {
+ self.service
+ .get_user_email_labels(self.user_id.clone())
+ .await
+ .map(|labels| labels.into_iter().map(Into::into).collect())
+ .map_err(|error| {
+ tracing::error!(
+ error = ?error,
+ user_id = %self.user_id,
+ "failed to load authenticated user's email labels"
+ );
+ async_graphql::Error::new("email labels are unavailable")
+ })
+ }
+
+ /// Enriched owned or delegated email links accessible to the authenticated user.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn email_links(&self) -> async_graphql::Result<Vec<GraphqlEmailLink>> {
+ self.service
+ .get_user_email_links(self.user_id.clone())
+ .await
+ .map(|links| links.into_iter().map(Into::into).collect())
+ .map_err(|error| {
+ tracing::error!(
+ error = ?error,
+ user_id = %self.user_id,
+ "failed to load authenticated user's email links"
+ );
+ async_graphql::Error::new("email links are unavailable")
+ })
+ }
+}
diff --git a/crates/graphql_email/src/user_query/test.rs b/crates/graphql_email/src/user_query/test.rs
new file mode 100644
index 0000000000..a214625004
--- /dev/null
+++ b/crates/graphql_email/src/user_query/test.rs
@@ -0,0 +1,172 @@
+use std::sync::{Arc, Mutex};
+
+use async_graphql::{EmptyMutation, EmptySubscription, Schema};
+use chrono::{TimeZone, Utc};
+use email::domain::{
+ models::{
+ EmailErr, EmailSyncStatus, LabelListVisibility, LabelType, LinkLabel,
+ MessageListVisibility, UserEmailLink, UserEmailLinkSettings, UserProvider,
+ },
+ ports::EmailUserService,
+};
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
+use uuid::Uuid;
+
+use super::GraphqlEmailQuery;
+
+#[derive(Default)]
+struct FakeEmailUserService {
+ requested_users: Mutex<Vec<MacroUserIdStr<'static>>>,
+ fail: bool,
+}
+
+impl EmailUserService for FakeEmailUserService {
+ async fn get_user_email_labels(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<LinkLabel>, EmailErr> {
+ self.requested_users.lock().unwrap().push(macro_id);
+ if self.fail {
+ return Err(EmailErr::InvalidEmailFilter(
+ "sensitive label database detail".to_owned(),
+ ));
+ }
+ Ok(vec![label()])
+ }
+
+ async fn get_user_email_links(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<UserEmailLink>, EmailErr> {
+ self.requested_users.lock().unwrap().push(macro_id);
+ if self.fail {
+ return Err(EmailErr::InvalidEmailFilter(
+ "sensitive link database detail".to_owned(),
+ ));
+ }
+ Ok(vec![link()])
+ }
+}
+
+fn user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+fn label() -> LinkLabel {
+ LinkLabel {
+ id: Uuid::from_u128(1),
+ link_id: Uuid::from_u128(2),
+ provider_label_id: "Label_42".to_owned(),
+ name: "Customers".to_owned(),
+ created_at: Utc.with_ymd_and_hms(2025, 1, 2, 3, 4, 5).unwrap(),
+ message_list_visibility: MessageListVisibility::Show,
+ label_list_visibility: LabelListVisibility::LabelShowIfUnread,
+ type_: LabelType::User,
+ }
+}
+
+fn link() -> UserEmailLink {
+ UserEmailLink {
+ id: Uuid::from_u128(2),
+ macro_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ email_address: EmailStr::try_from("[email protected]".to_owned()).unwrap(),
+ photo_url: Some("https://example.com/photo.png".to_owned()),
+ provider: UserProvider::Gmail,
+ is_sync_active: true,
+ sync_status: EmailSyncStatus::NeedsReauth,
+ needs_reauth: true,
+ settings: UserEmailLinkSettings {
+ signature_on_replies_forwards: true,
+ signature: Some("<p>Regards</p>".to_owned()),
+ },
+ is_primary: false,
+ created_at: Utc.with_ymd_and_hms(2025, 1, 2, 3, 4, 5).unwrap(),
+ updated_at: Utc.with_ymd_and_hms(2025, 2, 3, 4, 5, 6).unwrap(),
+ }
+}
+
+#[tokio::test]
+async fn resolves_labels_and_links_for_the_bound_authenticated_user() {
+ let service = Arc::new(FakeEmailUserService::default());
+ let schema = Schema::build(
+ GraphqlEmailQuery::new(Arc::clone(&service), user_id()),
+ EmptyMutation,
+ EmptySubscription,
+ )
+ .finish();
+
+ let response = schema
+ .execute(
+ r#"{
+ emailLabels {
+ __typename id linkId providerLabelId name createdAt
+ messageListVisibility labelListVisibility type
+ }
+ emailLinks {
+ id macroId emailAddress photoUrl provider isSyncActive syncStatus
+ needsReauth settings { signatureOnRepliesForwards signature }
+ isPrimary createdAt updatedAt
+ }
+ }"#,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let label = &data["emailLabels"][0];
+ assert_eq!(label["__typename"], "GraphqlSoupEmailLabel");
+ assert_eq!(label["id"], Uuid::from_u128(1).to_string());
+ assert_eq!(label["linkId"], Uuid::from_u128(2).to_string());
+ assert_eq!(label["messageListVisibility"], "show");
+ assert_eq!(label["labelListVisibility"], "label_show_if_unread");
+ assert_eq!(label["type"], "user");
+
+ let link = &data["emailLinks"][0];
+ assert_eq!(link["macroId"], "macro|[email protected]");
+ assert_eq!(link["emailAddress"], "[email protected]");
+ assert_eq!(link["provider"], "GMAIL");
+ assert_eq!(link["syncStatus"], "NEEDS_REAUTH");
+ assert_eq!(link["needsReauth"], true);
+ assert_eq!(link["settings"]["signatureOnRepliesForwards"], true);
+ assert_eq!(link["settings"]["signature"], "<p>Regards</p>");
+ assert_eq!(
+ *service.requested_users.lock().unwrap(),
+ vec![user_id(), user_id()]
+ );
+
+ let sdl = schema.sdl();
+ assert!(!sdl.to_ascii_lowercase().contains("fusionauth"));
+}
+
+#[tokio::test]
+async fn returns_safe_graphql_errors_for_domain_failures() {
+ let service = Arc::new(FakeEmailUserService {
+ fail: true,
+ ..Default::default()
+ });
+ let schema = Schema::build(
+ GraphqlEmailQuery::new(service, user_id()),
+ EmptyMutation,
+ EmptySubscription,
+ )
+ .finish();
+
+ let response = schema
+ .execute("{ emailLabels { id } emailLinks { id } }")
+ .await;
+
+ assert_eq!(response.errors.len(), 2);
+ let messages = response
+ .errors
+ .iter()
+ .map(|error| error.message.as_str())
+ .collect::<Vec<_>>();
+ assert!(messages.contains(&"email labels are unavailable"));
+ assert!(messages.contains(&"email links are unavailable"));
+ assert!(
+ response
+ .errors
+ .iter()
+ .all(|error| !error.message.contains("sensitive"))
+ );
+}
diff --git a/crates/graphql_soup/Cargo.toml b/crates/graphql_soup/Cargo.toml
index 8bc0f58ad0..6abfe2a422 100644
--- a/crates/graphql_soup/Cargo.toml
+++ b/crates/graphql_soup/Cargo.toml
@@ -22,6 +22,7 @@ entity_access = { path = "../entity_access", default-features = false, features
] }
filter_ast = { path = "../filter_ast" }
graphql_common = { path = "../graphql_common" }
+graphql_email = { path = "../graphql_email" }
graphql_permission = { path = "../graphql_permission" }
item_filters = { path = "../item_filters" }
macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"] }
diff --git a/crates/graphql_soup/src/objects.rs b/crates/graphql_soup/src/objects.rs
index f4bb44837a..9d5be4eb90 100644
--- a/crates/graphql_soup/src/objects.rs
+++ b/crates/graphql_soup/src/objects.rs
@@ -4,6 +4,7 @@ use async_graphql::{
Context, ID, Interface, Json, Object, ObjectType, OutputType, SimpleObject, Union,
};
use graphql_common::{GraphqlCacheDeletion, GraphqlEntity, GraphqlSoupEntityType};
+use graphql_email::GraphqlEmailLabel;
use graphql_permission::GraphqlEntityPermission;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
@@ -15,8 +16,8 @@ use models_soup::{
crm_company::SoupCrmCompany,
document::{SoupDocument, SoupDocumentSubType},
email_thread::{
- SoupAttachment, SoupContact, SoupEnrichedEmailThreadPreview, SoupLabel,
- SoupLabelListVisibility, SoupLabelType, SoupMessageListVisibility,
+ SoupAttachment, SoupContact, SoupEnrichedEmailThreadPreview, SoupLabelListVisibility,
+ SoupLabelType, SoupMessageListVisibility,
},
foreign_entity::SoupForeignEntity,
item::SoupItem,
@@ -707,54 +708,6 @@ impl GraphqlSoupEmailParticipant {
}
}
-/// GraphQL representation of the soup email label.
-#[derive(SimpleObject)]
-pub struct GraphqlSoupEmailLabel {
- /// The unique identifier.
- id: ID,
- /// The identifier of the link.
- link_id: ID,
- /// The identifier of the provider label.
- provider_label_id: String,
- /// The name.
- name: String,
- /// The created timestamp in RFC 3339 format.
- created_at: String,
- /// The message list visibility.
- message_list_visibility: &'static str,
- /// The label list visibility.
- label_list_visibility: &'static str,
- /// The type.
- #[graphql(name = "type")]
- type_: &'static str,
-}
-
-impl GraphqlSoupEmailLabel {
- /// Construct a GraphQL email label from the Soup model.
- pub fn new(value: &SoupLabel) -> Self {
- Self {
- id: ID(value.id.to_string()),
- link_id: ID(value.link_id.to_string()),
- provider_label_id: value.provider_label_id.clone(),
- name: value.name.clone(),
- created_at: value.created_at.to_rfc3339(),
- message_list_visibility: match value.message_list_visibility {
- SoupMessageListVisibility::Show => "show",
- SoupMessageListVisibility::Hide => "hide",
- },
- label_list_visibility: match value.label_list_visibility {
- SoupLabelListVisibility::LabelShow => "label_show",
- SoupLabelListVisibility::LabelShowIfUnread => "label_show_if_unread",
- SoupLabelListVisibility::LabelHide => "label_hide",
- },
- type_: match value.type_ {
- SoupLabelType::System => "system",
- SoupLabelType::User => "user",
- },
- }
- }
-}
-
/// GraphQL representation of the soup email attachment.
#[derive(SimpleObject)]
pub struct GraphqlSoupEmailAttachment {
@@ -956,11 +909,42 @@ where
}
/// The labels.
- async fn labels(&self) -> Vec<GraphqlSoupEmailLabel> {
+ async fn labels(&self) -> Vec<GraphqlEmailLabel> {
self.0
.labels
.iter()
- .map(GraphqlSoupEmailLabel::new)
+ .map(|label| {
+ GraphqlEmailLabel::new(
+ label.id,
+ label.link_id,
+ label.provider_label_id.clone(),
+ label.name.clone(),
+ label.created_at,
+ match label.message_list_visibility {
+ SoupMessageListVisibility::Show => {
+ email::domain::models::MessageListVisibility::Show
+ }
+ SoupMessageListVisibility::Hide => {
+ email::domain::models::MessageListVisibility::Hide
+ }
+ },
+ match label.label_list_visibility {
+ SoupLabelListVisibility::LabelShow => {
+ email::domain::models::LabelListVisibility::LabelShow
+ }
+ SoupLabelListVisibility::LabelShowIfUnread => {
+ email::domain::models::LabelListVisibility::LabelShowIfUnread
+ }
+ SoupLabelListVisibility::LabelHide => {
+ email::domain::models::LabelListVisibility::LabelHide
+ }
+ },
+ match label.type_ {
+ SoupLabelType::System => email::domain::models::LabelType::System,
+ SoupLabelType::User => email::domain::models::LabelType::User,
+ },
+ )
+ })
.collect()
}
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 1f817d2e20..dd457be73e 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -858,6 +858,74 @@ input GraphqlEmailFilterAst {
crmScope: GraphqlCrmScope
}
+"""
+Enriched email link accessible to the authenticated user.
+"""
+type GraphqlEmailLink {
+ """
+ Stable email link identifier.
+ """
+ id: ID!
+ """
+ Macro user that owns the inbox.
+ """
+ macroId: String!
+ """
+ Provider email address for the inbox.
+ """
+ emailAddress: String!
+ """
+ SFS URL of the inbox's self-contact photo, when available.
+ """
+ photoUrl: String
+ """
+ Email provider.
+ """
+ provider: GraphqlEmailProvider!
+ """
+ Whether ongoing provider synchronization is enabled.
+ """
+ isSyncActive: Boolean!
+ """
+ Coarse synchronization state derived by the email domain.
+ """
+ syncStatus: GraphqlEmailSyncStatus!
+ """
+ Whether the provider grant must be reauthorized.
+ """
+ needsReauth: Boolean!
+ """
+ Inbox signature settings.
+ """
+ settings: GraphqlEmailLinkSettings!
+ """
+ Whether this is the owner's primary inbox.
+ """
+ isPrimary: Boolean!
+ """
+ Link creation timestamp in RFC 3339 format.
+ """
+ createdAt: String!
+ """
+ Link last-updated timestamp in RFC 3339 format.
+ """
+ updatedAt: String!
+}
+
+"""
+Signature settings embedded in an authenticated user's email link.
+"""
+type GraphqlEmailLinkSettings {
+ """
+ Whether signatures are included on replies and forwards.
+ """
+ signatureOnRepliesForwards: Boolean!
+ """
+ Saved, sanitized signature HTML, when configured.
+ """
+ signature: String
+}
+
"""
GraphQL input representing the email literal.
"""
@@ -920,6 +988,42 @@ input GraphqlEmailLiteral @oneOf {
updatedAt: GraphqlDateLiteral
}
+"""
+Email provider for an authenticated user's linked inbox.
+"""
+enum GraphqlEmailProvider {
+ """
+ Google Gmail.
+ """
+ GMAIL
+}
+
+"""
+Coarse synchronization state for an authenticated user's linked inbox.
+"""
+enum GraphqlEmailSyncStatus {
+ """
+ Initial synchronization is queued or running.
+ """
+ SYNCING
+ """
+ The inbox is active and synchronized.
+ """
+ UP_TO_DATE
+ """
+ Initial synchronization failed or was cancelled.
+ """
+ ERROR
+ """
+ The provider grant must be reauthorized.
+ """
+ NEEDS_REAUTH
+ """
+ Synchronization is disabled.
+ """
+ INACTIVE
+}
+
"""
GraphQL input representing the email value.
"""
@@ -2490,39 +2594,40 @@ type GraphqlSoupEmailContact {
}
"""
-GraphQL representation of the soup email label.
+Canonical normalized GraphQL email label used by both email threads and
+the authenticated user's label catalog.
"""
type GraphqlSoupEmailLabel {
"""
- The unique identifier.
+ Stable database identifier for the label.
"""
id: ID!
"""
- The identifier of the link.
+ Identifier of the email link that owns the label.
"""
linkId: ID!
"""
- The identifier of the provider label.
+ Provider-specific label identifier.
"""
providerLabelId: String!
"""
- The name.
+ User-visible label name.
"""
name: String!
"""
- The created timestamp in RFC 3339 format.
+ Label creation timestamp in RFC 3339 format.
"""
createdAt: String!
"""
- The message list visibility.
+ Provider message-list visibility value.
"""
messageListVisibility: String!
"""
- The label list visibility.
+ Provider label-list visibility value.
"""
labelListVisibility: String!
"""
- The type.
+ Whether the label is provider-created or user-created.
"""
type: String!
}
@@ -3142,6 +3247,14 @@ type GraphqlUser {
"""
id: ID!
"""
+ Labels across every owned or delegated inbox accessible to the authenticated user.
+ """
+ emailLabels: [GraphqlSoupEmailLabel!]!
+ """
+ Enriched owned or delegated email links accessible to the authenticated user.
+ """
+ emailLinks: [GraphqlEmailLink!]!
+ """
Fetch one accessible email thread by its canonical identifier.
"""
emailThread(input: EmailThreadInput!): GraphqlSoupEmailThread