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
feat(team): add email notification (#2246)
Sean Aye33050d33dc04
diff --git a/js/app/bun.lock b/js/app/bun.lockindex aa38ae1ceb..798c774f57 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -2329,7 +2329,7 @@"pathval": ["[email protected]", "", {}, "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA=="],- "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/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex 053670b9a5..e3ce379e2a 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -2236,74 +2236,6 @@ export const getTeamInvites = async (} as getTeamInvitesResponse;};-/**- * @summary Regenerates a team invite notifying the user again.- */-export type reinviteToTeamResponse200 = {- data: void;- status: 200;-};--export type reinviteToTeamResponse400 = {- data: ErrorResponse;- status: 400;-};--export type reinviteToTeamResponse401 = {- data: ErrorResponse;- status: 401;-};--export type reinviteToTeamResponse429 = {- data: ErrorResponse;- status: 429;-};--export type reinviteToTeamResponse500 = {- data: ErrorResponse;- status: 500;-};--export type reinviteToTeamResponseSuccess = reinviteToTeamResponse200 & {- headers: Headers;-};-export type reinviteToTeamResponseError = (- | reinviteToTeamResponse400- | reinviteToTeamResponse401- | reinviteToTeamResponse429- | reinviteToTeamResponse500-) & {- headers: Headers;-};--export type reinviteToTeamResponse =- | reinviteToTeamResponseSuccess- | reinviteToTeamResponseError;--export const getReinviteToTeamUrl = (teamId: string, teamInviteId: string) => {- return `/team/${teamId}/reinvite/${teamInviteId}`;-};--export const reinviteToTeam = async (- teamId: string,- teamInviteId: string,- options?: RequestInit-): Promise<reinviteToTeamResponse> => {- const res = await fetch(getReinviteToTeamUrl(teamId, teamInviteId), {- ...options,- method: 'POST',- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: reinviteToTeamResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as reinviteToTeamResponse;-};-/*** @summary Removes a user from a team.*/diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 09069f32b1..3f3feb137e 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -1934,78 +1934,6 @@}}},- "/team/{team_id}/reinvite/{team_invite_id}": {- "post": {- "tags": ["teams::inbound::axum_router::reinvite_to_team"],- "summary": "Regenerates a team invite notifying the user again.",- "operationId": "reinvite_to_team",- "parameters": [- {- "name": "team_id",- "in": "path",- "description": "The ID of the team to invite to",- "required": true,- "schema": {- "type": "string"- }- },- {- "name": "team_invite_id",- "in": "path",- "description": "The ID of the team invite to reinvite",- "required": true,- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "description": ""- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "429": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },"/team/{team_id}/remove/{remove_user_id}": {"delete": {"tags": ["teams::inbound::axum_router::remove_user_from_team"],diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.tsindex 118f6acd38..54d813ee35 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts@@ -51,6 +51,7 @@ export * from './getNotificationTypePreferencesResponse';export * from './getTypedNotificationsByEventItemIdParams';export * from './inviteToTeamMetadata';export * from './inviteToTeamMetadataRole';+export * from './inviteToTeamMetadataSenderProfilePictureUrl';export * from './itemSharedMetadata';export * from './itemSharedMetadataItemName';export * from './itemSharedMetadataPermissionLevel';diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.tsindex 3ba093ba63..8c88034bee 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/inviteToTeamMetadata.ts@@ -5,12 +5,18 @@* OpenAPI spec version: 0.1.0*/import type { InviteToTeamMetadataRole } from './inviteToTeamMetadataRole';+import type { InviteToTeamMetadataSenderProfilePictureUrl } from './inviteToTeamMetadataSenderProfilePictureUrl';+/**+ * Metadata for when a user is invited to a team.+ */export interface InviteToTeamMetadata {/** The user who sent the invitation */invitedBy: string;/** Role/permission level in the team */role?: InviteToTeamMetadataRole;+ /** The sender's profile picture URL, if available. */+ senderProfilePictureUrl?: InviteToTeamMetadataSenderProfilePictureUrl;/** The unique identifier of the team */teamId: string;/** The name of the team being invited to */diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/inviteToTeamMetadataSenderProfilePictureUrl.ts b/js/app/packages/service-clients/service-notification/generated/schemas/inviteToTeamMetadataSenderProfilePictureUrl.tsnew file mode 100644index 0000000000..43881b928a--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/inviteToTeamMetadataSenderProfilePictureUrl.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The sender's profile picture URL, if available.+ */+export type InviteToTeamMetadataSenderProfilePictureUrl = string | null;diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex 0195a34089..80f41a1427 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -1409,6 +1409,7 @@},"InviteToTeamMetadata": {"type": "object",+ "description": "Metadata for when a user is invited to a team.","required": ["teamName", "teamId", "invitedBy"],"properties": {"invitedBy": {@@ -1419,8 +1420,13 @@"type": ["string", "null"],"description": "Role/permission level in the team"},+ "senderProfilePictureUrl": {+ "type": ["string", "null"],+ "description": "The sender's profile picture URL, if available."+ },"teamId": {"type": "string",+ "format": "uuid","description": "The unique identifier of the team"},"teamName": {diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 0c42b51c0f..10b1b6c94e 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5248,6 +5248,21 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "invite_email"+version = "0.1.0"+dependencies = [+ "askama",+ "macro_env",+ "macro_user_id",+ "notification",+ "serde",+ "serde_json",+ "url",+ "utoipa",+ "uuid",+]+[[package]]name = "ip_extractor"version = "0.1.0"@@ -6318,6 +6333,7 @@ dependencies = ["anyhow","chrono","doppleganger",+ "invite_email","macro_user_id","mention_utils","model-entity",@@ -6325,7 +6341,6 @@ dependencies = ["models_pagination","notification","paste",- "referral_invitation","rootcause","serde","serde_json",@@ -8110,6 +8125,7 @@ dependencies = ["axum-extra","chrono","http-body-util",+ "invite_email","ip_extractor","macro_db_migrator","macro_user_id",@@ -8120,7 +8136,6 @@ dependencies = ["model_user","notification","rate_limit",- "referral_invitation","rootcause","serde","serde_json",@@ -8129,24 +8144,12 @@ dependencies = ["tokio","tower 0.5.2","tracing",+ "url","urlencoding","utoipa","uuid",]-[[package]]-name = "referral_invitation"-version = "0.1.0"-dependencies = [- "askama",- "macro_env",- "macro_user_id",- "notification",- "serde",- "serde_json",- "url",-]-[[package]]name = "regex"version = "1.12.2"@@ -10074,7 +10077,9 @@ dependencies = ["non_empty","notification","roles_and_permissions",+ "rootcause","serde",+ "serde_json","sqlx","thiserror 2.0.17","tokio",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 16f66c1c00..8b42b05288 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -99,7 +99,7 @@ members = ["properties_service","rate_limit","referral",- "referral_invitation",+ "invite_email","roles_and_permissions","rpc/axum_rpc","rpc/axum_rpc_emit",diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex e9a8cf6197..c8ff3c70d6 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -120,7 +120,6 @@ use model::user::{teams::inbound::axum_router::patch_team_user_tier::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::reject_invitation::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_user_invites::handler::<crate::api::context::TeamsServiceType>,- teams::inbound::axum_router::reinvite_to_team::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::get_user_teams::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::remove_user_from_team::handler::<crate::api::context::TeamsServiceType>,teams::inbound::axum_router::delete_team_invite::handler::<crate::api::context::TeamsServiceType>,diff --git a/rust/cloud-storage/referral_invitation/Cargo.toml b/rust/cloud-storage/invite_email/Cargo.tomlsimilarity index 71%rename from rust/cloud-storage/referral_invitation/Cargo.tomlrename to rust/cloud-storage/invite_email/Cargo.tomlindex 6157592959..c1407fead3 100644--- a/rust/cloud-storage/referral_invitation/Cargo.toml+++ b/rust/cloud-storage/invite_email/Cargo.toml@@ -1,6 +1,6 @@[package]edition = "2024"-name = "referral_invitation"+name = "invite_email"publish = falseversion = "0.1.0"@@ -11,7 +11,9 @@ macro_env = { path = "../macro_env" }macro_user_id = { path = "../macro_user_id" }notification = { path = "../notification" }serde = { workspace = true }-url = { workspace = true }+url = { workspace = true, features = ["serde"] }+utoipa = { workspace = true }+uuid = { workspace = true }[dev-dependencies]serde_json = { workspace = true }diff --git a/rust/cloud-storage/referral_invitation/preview_invite.py b/rust/cloud-storage/invite_email/preview_invite.pysimilarity index 100%rename from rust/cloud-storage/referral_invitation/preview_invite.pyrename to rust/cloud-storage/invite_email/preview_invite.pydiff --git a/rust/cloud-storage/referral_invitation/src/lib.rs b/rust/cloud-storage/invite_email/src/lib.rssimilarity index 53%rename from rust/cloud-storage/referral_invitation/src/lib.rsrename to rust/cloud-storage/invite_email/src/lib.rsindex 22eb273388..5a72752abb 100644--- a/rust/cloud-storage/referral_invitation/src/lib.rs+++ b/rust/cloud-storage/invite_email/src/lib.rs@@ -1,7 +1,8 @@#![deny(missing_docs)]-//! Domain models for referral invitation notifications.+//! Domain models for invitation email notifications.//!-//! Contains the [`InviteToMacro`] notification type and the [`ReferralCode`] newtype.+//! Contains the [`InviteToMacro`] referral notification, the [`InviteToTeamMetadata`] team+//! invitation notification, and the [`ReferralCode`] newtype.#[cfg(test)]mod test;@@ -9,12 +10,15 @@ mod test;use askama::Template;use macro_env::Environment;use macro_user_id::email::EmailStr;+use macro_user_id::user_id::MacroUserIdStr;use notification::domain::models::{Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, queue_message::EmailContent,};use serde::{Deserialize, Serialize};use std::time::Duration;use url::Url;+use utoipa::ToSchema;+use uuid::Uuid;/// Wrapper for the referral code to make it type safe#[derive(Debug, Clone, Serialize, Deserialize)]@@ -31,7 +35,7 @@ pub struct InviteToMacro {/// and reward them.pub referral_code: ReferralCode,/// The sender's profile picture URL, if available.- pub sender_profile_picture_url: Option<String>,+ pub sender_profile_picture_url: Option<Url>,/// The sender's display name, if they have set one.pub sender_name: Option<String>,/// The sender's email address.@@ -52,7 +56,7 @@ impl Notification for InviteToMacro {const MINUTES_PER_WEEK: u64 = 60 * 24 * 7;-fn get_url(env: Environment, code: &ReferralCode) -> Url {+fn signup_url(env: Environment) -> Url {let host = match env {Environment::Production => "https://macro.com",Environment::Develop => "https://dev.macro.com",@@ -60,6 +64,11 @@ fn get_url(env: Environment, code: &ReferralCode) -> Url {};let mut url = Url::parse(host).expect("all the inputs are static, valid values");url.set_path("/app/signup");+ url+}++fn get_url(env: Environment, code: &ReferralCode) -> Url {+ let mut url = signup_url(env);url.query_pairs_mut().clear().append_pair("referral_code", &code.0)@@ -96,3 +105,68 @@ impl NotificationExtEmail for InviteToMacro {.finish()}}++/// Metadata for when a user is invited to a team.+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, Template)]+#[serde(rename_all = "camelCase")]+#[template(path = "invite_to_team.html")]+pub struct InviteToTeamMetadata {+ /// The name of the team being invited to+ #[serde(alias = "team_name")]+ pub team_name: String,+ /// The unique identifier of the team+ #[serde(alias = "team_id")]+ pub team_id: Uuid,+ /// The user who sent the invitation+ #[serde(alias = "invited_by")]+ #[schema(value_type = String)]+ pub invited_by: MacroUserIdStr<'static>,+ /// Role/permission level in the team+ pub role: Option<String>,++ /// The sender's profile picture URL, if available.+ #[serde(default)]+ #[schema(value_type = Option<String>)]+ pub sender_profile_picture_url: Option<Url>,+}++impl InviteToTeamMetadata {+ /// Returns the signup URL for the current environment.+ pub fn signup_url(&self) -> Url {+ signup_url(Environment::new_or_prod())+ }+}++impl Notification for InviteToTeamMetadata {+ const TYPE_NAME: &'static str = "invite_to_team";+}++impl NotificationExtEmail for InviteToTeamMetadata {+ fn format_email(&self) -> EmailContent {+ EmailContent {+ subject: format!(+ "{} has invited you to the {} team on Macro",+ self.invited_by.as_ref(),+ self.team_name+ ),+ body: self+ .render()+ .expect("InviteToTeamMetadata template render failed in format_email"),+ }+ }++ fn rate_limit_config() -> RateLimitConfig {+ const HOURS_PER_WEEK: u64 = 24 * 7;+ RateLimitConfig {+ max_count: 1,+ window: Duration::from_hours(HOURS_PER_WEEK),+ }+ }++ fn rate_limit_key(&self) -> RateLimitKey {+ RateLimitKey::builder(&Self::TYPE_NAME)+ .append(&self.team_id)+ .append(&self.invited_by.as_ref())+ .finish()+ }+}diff --git a/rust/cloud-storage/referral_invitation/src/test.rs b/rust/cloud-storage/invite_email/src/test.rssimilarity index 100%rename from rust/cloud-storage/referral_invitation/src/test.rsrename to rust/cloud-storage/invite_email/src/test.rsdiff --git a/rust/cloud-storage/referral_invitation/templates/invite.html b/rust/cloud-storage/invite_email/templates/invite.htmlsimilarity index 100%rename from rust/cloud-storage/referral_invitation/templates/invite.htmlrename to rust/cloud-storage/invite_email/templates/invite.htmldiff --git a/rust/cloud-storage/invite_email/templates/invite_to_team.html b/rust/cloud-storage/invite_email/templates/invite_to_team.htmlnew file mode 100644index 0000000000..8ed5d0b1b3--- /dev/null+++ b/rust/cloud-storage/invite_email/templates/invite_to_team.html@@ -0,0 +1,229 @@+<!doctype html>+<html+ xmlns:o="urn:schemas-microsoft-com:office:office"+ xmlns:v="urn:schemas-microsoft-com:vml"+ xmlns="http://www.w3.org/1999/xhtml"+>+ <head>+ <title>You're Invited to Join {{ team_name }} on Macro</title>+ <!--[if !mso]><!-->+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <!--<![endif]-->+ <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />+ <meta content="width=device-width, initial-scale=1" name="viewport" />+ <!--[if mso]>+ <noscript>+ <xml>+ <o:OfficeDocumentSettings>+ <o:AllowPNG />+ <o:PixelsPerInch>96</o:PixelsPerInch>+ </o:OfficeDocumentSettings>+ </xml>+ </noscript>+ <![endif]-->+ <!--[if lte mso 11]>+ <style type="text/css">+ .mj-outlook-group-fix {+ width: 100% !important;+ }+ </style>+ <![endif]-->++ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,[email protected],500&display=swap" rel="stylesheet">++ <style type="text/css">+ @font-face {+ font-family: "Berkeley Mono";+ src: url("https://pub-4030931feb3e4212b2ac93166a411ea7.r2.dev/berkley.woff2")+ format("woff2");+ font-display: fallback;+ }++ #outlook a {+ padding: 0;+ }++ img {+ -ms-interpolation-mode: bicubic;+ text-decoration: none;+ line-height: 100%;+ outline: none;+ height: auto;+ border: 0;+ }+ </style>+ </head>+ <body+ style="+ -webkit-text-size-adjust: 100%;+ -ms-text-size-adjust: 100%;+ word-spacing: normal;+ padding: 0;+ margin: 0;+ "+ >+ <div style="box-sizing: border-box; padding: 60px 20px; width: 100%">+ <div+ style="+ font-family:+ "Berkeley Mono", "Courier New", Courier,+ monospace;+ background-color: #fcfcfc;+ border: 1px solid #e0e0e0;+ box-sizing: border-box;+ border-radius: 4px;+ max-width: 570px;+ font-size: 15px;+ margin: 0 auto;+ overflow: clip;+ color: #999;+ width: 100%;+ "+ >+ <table+ cellpadding="0"+ cellspacing="0"+ style="+ font-family: "Inter", sans-serif;+ background-color: #f5f5f5;+ color: #090909;+ box-sizing: border-box;+ font-size: 18px;+ padding: 10px 20px;+ width: 100%;+ border: none;+ "+ >+ <tbody>+ <tr>+ {% if let Some(url) = sender_profile_picture_url %}+ <td+ style="+ vertical-align: middle;+ width: 40px;+ min-width: 40px;+ padding-right: 8px;+ "+ >+ <div+ style="+ border: 1px solid #e0e0e0;+ box-sizing: border-box;+ border-radius: 20px;+ overflow: clip;+ height: 40px;+ width: 40px;+ "+ >+ <img+ src="{{ url }}"+ alt=""+ style="+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+ "+ />+ </div>+ </td>+ {% endif %}+ <td style="vertical-align: middle; line-height: 1.2">+ <span+ style="+ color: #626262;+ font-family:+ "Berkeley Mono", "Courier New",+ Courier, monospace;+ "+ >{{ invited_by }}</span+ > has invited you to the <strong>{{ team_name }}</strong> team+ </td>+ </tr>+ </tbody>+ </table>+ <hr style="border: none; border-top: 1px dashed #e0e0e0; margin: 0" />+ <div style="box-sizing: border-box; padding: 20px">+ <div+ style="+ color: #090909;+ font-size: 16px;+ font-family: "Inter", sans-serif;+ line-height: 1.4;+ "+ >+ You've been invited to join the <strong>{{ team_name }}</strong> team on Macro.{% if let Some(r) = role %}+ Your role will be <strong>{{ r }}</strong>.{% endif %}+ Collaborate on documents. Stay in sync with tasks. Search over+ everything. AI Assistance with anything.+ </div>++ <table+ style="+ mso-table-lspace: 0pt;+ mso-table-rspace: 0pt;+ border: none;+ width: 100%;+ "+ cellpadding="0"+ cellspacing="0"+ >+ <tbody>+ <tr>+ <td+ style="+ vertical-align: bottom;+ padding: 20px 0 0 0;+ width: 50%;+ "+ >+ <a+ style="+ font-family:+ "Berkeley Mono", "Courier New",+ Courier, monospace;+ background-color: #ff8f00;+ text-decoration: none;+ display: inline-block;+ white-space: nowrap;+ border-radius: 2px;+ width: min-content;+ padding: 4px 10px;+ color: #090909;+ "+ href="{{ signup_url() }}"+ target="_blank"+ >+ Join {{ team_name }}+ </a>+ </td>+ <td+ style="+ vertical-align: top;+ text-align: right;+ padding: 0;+ width: 50%;+ "+ >+ <img+ src="https://static-file-service.macro.com/file/b911aba9-94a6-435c-aa16-8404739f13b0"+ alt="Macro"+ style="+ -ms-interpolation-mode: bicubic;+ line-height: 100%;+ outline: none;+ width: 60px;+ border: 0;+ "+ />+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ </div>+ </body>+</html>diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.tomlindex e1e2673724..2ef7924d2e 100644--- a/rust/cloud-storage/model_notifications/Cargo.toml+++ b/rust/cloud-storage/model_notifications/Cargo.toml@@ -15,7 +15,7 @@ models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination" }notification = { path = "../notification" }paste = { workspace = true }-referral_invitation = { path = "../referral_invitation" }+invite_email = { path = "../invite_email" }rootcause = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/cloud-storage/model_notifications/src/digest_state.rs b/rust/cloud-storage/model_notifications/src/digest_state.rsindex 1f8971eba1..bc86d61aca 100644--- a/rust/cloud-storage/model_notifications/src/digest_state.rs+++ b/rust/cloud-storage/model_notifications/src/digest_state.rs@@ -1,8 +1,8 @@use crate::{InviteToTeamMetadata, NewEmailMetadata};+use invite_email::InviteToMacro;use notification::domain::models::email_notification_digest::{EmailBlockList, NotificationSetBuilder,};-use referral_invitation::InviteToMacro;/// define a blocklist of notification types which will never be templated into a digest emailpub fn digest_email_block_list() -> EmailBlockList {diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex 1212fe085b..ce1ec54cc0 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -1,5 +1,6 @@use chrono::DateTime;use macro_user_id::user_id::MacroUserIdStr;+use rootcause::report;use serde::{Deserialize, Serialize};use std::hash::{DefaultHasher, Hasher};use utoipa::ToSchema;@@ -224,9 +225,7 @@ impl NotificationTitle for NotifEvent {channel_reply_metadata.format_title(sender_id)}NotifEvent::NewEmail(new_email_metadata) => new_email_metadata.format_title(sender_id),- NotifEvent::InviteToTeam(invite_to_team_metadata) => {- invite_to_team_metadata.format_title(sender_id)- }+ NotifEvent::InviteToTeam(_) => Err(report!("not implemented")),NotifEvent::TaskAssigned(task_assigned_metadata) => {task_assigned_metadata.format_title(sender_id)}@@ -262,9 +261,7 @@ impl NotificationTitle for NotifEvent {channel_reply_metadata.format_body(sender_id)}NotifEvent::NewEmail(new_email_metadata) => new_email_metadata.format_body(sender_id),- NotifEvent::InviteToTeam(invite_to_team_metadata) => {- invite_to_team_metadata.format_body(sender_id)- }+ NotifEvent::InviteToTeam(_) => Err(report!("not implemented")),NotifEvent::TaskAssigned(task_assigned_metadata) => {task_assigned_metadata.format_body(sender_id)}diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex 8bf00f2674..5341159c5f 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -1,12 +1,12 @@use doppleganger::Doppleganger;+pub use invite_email::InviteToTeamMetadata;use macro_user_id::cowlike::CowLike;use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};use mention_utils::parse::{ParsedXmlText, XmlFormatter};use model_entity::Entity;use model_entity::EntityType;-use notification::domain::models::Notification;use notification::domain::models::{- NotifCollapseKey, NotificationExtIos,+ NotifCollapseKey, Notification, NotificationExtIos,apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},};use rootcause::Report;@@ -121,23 +121,6 @@ pub struct ItemSharedMetadata {pub permission_level: Option<String>,}-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct InviteToTeamMetadata {- /// The name of the team being invited to- #[serde(alias = "team_name")]- pub team_name: String,- /// The unique identifier of the team- #[serde(alias = "team_id")]- pub team_id: String,- /// The user who sent the invitation- #[serde(alias = "invited_by")]- #[schema(value_type = String)]- pub invited_by: MacroUserIdStr<'static>,- /// Role/permission level in the team- pub role: Option<String>,-}-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]pub struct ChannelMentionMetadata {@@ -263,10 +246,6 @@ impl notification::domain::models::Notification for DocumentMentionMetadata {const TYPE_NAME: &'static str = "document_mention";}-impl notification::domain::models::Notification for InviteToTeamMetadata {- const TYPE_NAME: &'static str = "invite_to_team";-}-pub trait NotificationTitle {/// format the notification into a user facing titlefn format_title(@@ -413,25 +392,6 @@ impl NotificationTitle for ChannelInviteMetadata {}}-impl NotificationTitle for InviteToTeamMetadata {- fn format_title(- &self,- _sender_id: Option<MacroUserIdStr<'_>>,- ) -> Result<String, rootcause::Report> {- let email = self.invited_by.email_part();- let sender = email.email_str();-- Ok(format!("{sender} invited you to join a team"))- }-- fn format_body(- &self,- _sender_id: Option<MacroUserIdStr<'_>>,- ) -> Result<String, rootcause::Report> {- Ok(self.team_name.clone())- }-}-/// Metadata for when a user is assigned to a task#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/test.rs b/rust/cloud-storage/notification_service/src/api/user_notification/test.rsindex b3e0fabca5..e0d0293d8e 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification/test.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification/test.rs@@ -132,7 +132,7 @@ fn to_typed_row_new_email() {fn to_typed_row_invite_to_team() {let metadata = serde_json::json!({"teamName": "Engineering",- "teamId": "team-1",+ "teamId": "00000000-0000-0000-0000-000000000001","invitedBy": "macro|[email protected]","role": null});diff --git a/rust/cloud-storage/referral/Cargo.toml b/rust/cloud-storage/referral/Cargo.tomlindex e03c96e8ca..e618ffefb1 100644--- a/rust/cloud-storage/referral/Cargo.toml+++ b/rust/cloud-storage/referral/Cargo.toml@@ -36,7 +36,7 @@ macro_uuid = { path = "../macro_uuid" }model-entity = { path = "../model-entity" }notification = { path = "../notification" }rate_limit = { path = "../rate_limit", features = ["axum"] }-referral_invitation = { path = "../referral_invitation" }+invite_email = { path = "../invite_email" }# Axum dependencies (for inbound)axum = { workspace = true, optional = true }@@ -54,6 +54,7 @@ async-stripe = { workspace = true, default-features = false, features = ["runtime-tokio-hyper",], optional = true } # Outbound dependenciessqlx = { workspace = true, optional = true }+url = { workspace = true }urlencoding = { workspace = true }[dev-dependencies]diff --git a/rust/cloud-storage/referral/src/domain/models.rs b/rust/cloud-storage/referral/src/domain/models.rsindex 49eb31d4fd..dead1315f7 100644--- a/rust/cloud-storage/referral/src/domain/models.rs+++ b/rust/cloud-storage/referral/src/domain/models.rs@@ -1,6 +1,6 @@//! Domain models for the referral crate.-pub use referral_invitation::{InviteToMacro, ReferralCode};+pub use invite_email::{InviteToMacro, ReferralCode};use macro_uuid::ShortUuidConverter;use rate_limit::RateLimitExceeded;diff --git a/rust/cloud-storage/referral/src/domain/service.rs b/rust/cloud-storage/referral/src/domain/service.rsindex effe3a5bbd..13ac6f9e39 100644--- a/rust/cloud-storage/referral/src/domain/service.rs+++ b/rust/cloud-storage/referral/src/domain/service.rs@@ -120,7 +120,8 @@ impl<let notification = InviteToMacro {recipient_email: recipient.clone(),referral_code,- sender_profile_picture_url,+ sender_profile_picture_url: sender_profile_picture_url+ .and_then(|s| url::Url::parse(&s).ok()),sender_name,sender_email,};diff --git a/rust/cloud-storage/referral/src/domain/service/test.rs b/rust/cloud-storage/referral/src/domain/service/test.rsindex 3e05ef0fb6..8b51fd7788 100644--- a/rust/cloud-storage/referral/src/domain/service/test.rs+++ b/rust/cloud-storage/referral/src/domain/service/test.rs@@ -45,9 +45,8 @@ impl Deref for MockNotificationIngress {fn mock_repo() -> MockReferralRepo {let mut repo = MockReferralRepo::new();- repo.expect_get_referral_code_for_user().returning(|_| {- Box::pin(async { Ok(referral_invitation::ReferralCode("TESTCODE".to_string())) })- });+ repo.expect_get_referral_code_for_user()+ .returning(|_| Box::pin(async { Ok(invite_email::ReferralCode("TESTCODE".to_string())) }));repo.expect_get_sender_info().returning(|_| Box::pin(async { Ok((None, None)) }));repodiff --git a/rust/cloud-storage/teams/.sqlx/query-06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44.json b/rust/cloud-storage/teams/.sqlx/query-06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44.jsondeleted file mode 100644index 4c5afc274a..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM notification_user_device_registration\n WHERE device_endpoint = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "06a72bfcfbcc5f5bbed6cd093436309607f9375d2ba7b151e9dc1a8493f88e44"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json b/rust/cloud-storage/teams/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.jsondeleted file mode 100644index 01cece9642..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json+++ /dev/null@@ -1,33 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM notification_user_device_registration\n WHERE device_token = $1 AND device_type = $2\n RETURNING device_endpoint\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "device_endpoint",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- {- "Custom": {- "name": "notification_device_type_option",- "kind": {- "Enum": [- "ios",- "android"- ]- }- }- }- ]- },- "nullable": [- false- ]- },- "hash": "270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f.json b/rust/cloud-storage/teams/.sqlx/query-3152bd385bf8a62ac1258308acc31e02e1d6a1a5aa81499903ec6ca86f678219.jsonsimilarity index 54%rename from rust/cloud-storage/teams/.sqlx/query-4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f.jsonrename to rust/cloud-storage/teams/.sqlx/query-3152bd385bf8a62ac1258308acc31e02e1d6a1a5aa81499903ec6ca86f678219.jsonindex ccb0629e96..e508902b50 100644--- a/rust/cloud-storage/teams/.sqlx/query-4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f.json+++ b/rust/cloud-storage/teams/.sqlx/query-3152bd385bf8a62ac1258308acc31e02e1d6a1a5aa81499903ec6ca86f678219.json@@ -1,14 +1,14 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE team_invite\n SET last_sent_at = NOW()\n WHERE id = $1\n ",+ "query": "\n UPDATE team_invite\n SET last_sent_at = NOW()\n WHERE id = ANY($1::uuid[])\n ","describe": {"columns": [],"parameters": {"Left": [- "Uuid"+ "UuidArray"]},"nullable": []},- "hash": "4c4866e44650e9d0ebc04dfe61010f88b42d23348339fad30418bc2666c7947f"+ "hash": "3152bd385bf8a62ac1258308acc31e02e1d6a1a5aa81499903ec6ca86f678219"}diff --git a/rust/cloud-storage/teams/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json b/rust/cloud-storage/teams/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.jsondeleted file mode 100644index e4a18ac5f0..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE user_notification\n SET done = $3\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "UuidArray",- "Bool"- ]- },- "nullable": []- },- "hash": "3293eab63193f1b3822a59e9a6a9621520f26e6ec8248abed103985281ef7ff1"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa.json b/rust/cloud-storage/teams/.sqlx/query-3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa.jsondeleted file mode 100644index 6696253445..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT EXISTS(\n SELECT 1 FROM notification_message_receipt\n WHERE user_id = $1\n AND notification_id = $2\n AND failed = false\n ) as \"exists!\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "exists!",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Text",- "Uuid"- ]- },- "nullable": [- null- ]- },- "hash": "3357165799ff1f7bf1de3891174668e0ab16c64bd9dfc905213681e6021474fa"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1.json b/rust/cloud-storage/teams/.sqlx/query-36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1.jsondeleted file mode 100644index c07ec0acbe..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO user_notification_type_preference (user_id, notification_event_type)\n VALUES ($1, $2)\n ON CONFLICT (user_id, notification_event_type) DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Varchar"- ]- },- "nullable": []- },- "hash": "36dfcf982834f117d97d1ba332be6784c946f05120c7c228ff258389ceba97a1"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-4e096eb7d3c507e3647685073fba7b3f36ef0e70c887db31f5cc5a8eb8ee1844.json b/rust/cloud-storage/teams/.sqlx/query-4e096eb7d3c507e3647685073fba7b3f36ef0e70c887db31f5cc5a8eb8ee1844.jsondeleted file mode 100644index 55fcda1121..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-4e096eb7d3c507e3647685073fba7b3f36ef0e70c887db31f5cc5a8eb8ee1844.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM user_notification\n WHERE user_id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "4e096eb7d3c507e3647685073fba7b3f36ef0e70c887db31f5cc5a8eb8ee1844"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-587ab2cbf540d6f98236ca8cc3c098a0efa439c0ccefa93c46971a0f2fe7efcf.json b/rust/cloud-storage/teams/.sqlx/query-587ab2cbf540d6f98236ca8cc3c098a0efa439c0ccefa93c46971a0f2fe7efcf.jsonnew file mode 100644index 0000000000..6fa7775825--- /dev/null+++ b/rust/cloud-storage/teams/.sqlx/query-587ab2cbf540d6f98236ca8cc3c098a0efa439c0ccefa93c46971a0f2fe7efcf.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, team_id, email\n FROM team_invite\n WHERE team_id = $1\n AND email = ANY($2::text[])\n AND last_sent_at < NOW() - INTERVAL '5 minutes'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "email",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "587ab2cbf540d6f98236ca8cc3c098a0efa439c0ccefa93c46971a0f2fe7efcf"+}diff --git a/rust/cloud-storage/teams/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.json b/rust/cloud-storage/teams/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.jsondeleted file mode 100644index d0a749ebd2..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id FROM user_mute_notification\n WHERE user_id = ANY($1)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "TextArray"- ]- },- "nullable": [- false- ]- },- "hash": "621186dcec072b603a5f3d7b9e987a1638589d539c60d9dc5c2ab0865ff062d6"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674.json b/rust/cloud-storage/teams/.sqlx/query-625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674.jsondeleted file mode 100644index d374c2f79f..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM user_notification_type_preference\n WHERE user_id = $1 AND notification_event_type = $2\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "625ee33d48768e369ee1fe3abe27811ad04313b1aa31f4b51abe5fd3bf569674"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b.json b/rust/cloud-storage/teams/.sqlx/query-67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b.jsondeleted file mode 100644index dcc26c7a76..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b.json+++ /dev/null@@ -1,69 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n email,\n team_id,\n team_role as \"team_role!: TeamRole\",\n invited_by,\n created_at as \"created_at!: chrono::DateTime<chrono::Utc>\",\n last_sent_at as \"last_sent_at!: chrono::DateTime<chrono::Utc>\"\n FROM team_invite\n WHERE id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "email",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 3,- "name": "team_role!: TeamRole",- "type_info": {- "Custom": {- "name": "team_role",- "kind": {- "Enum": [- "member",- "admin",- "owner"- ]- }- }- }- },- {- "ordinal": 4,- "name": "invited_by",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "created_at!: chrono::DateTime<chrono::Utc>",- "type_info": "Timestamp"- },- {- "ordinal": 6,- "name": "last_sent_at!: chrono::DateTime<chrono::Utc>",- "type_info": "Timestamp"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- false- ]- },- "hash": "67cab3f29fef008aed42a34ebc208cae3c299ce7ea4d4e3b19100546ce6d7a1b"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-73c67fbf678e1479d528adcc5bea7da3261d0a04e24cc16f96ec9f2dea3b2e98.json b/rust/cloud-storage/teams/.sqlx/query-73c67fbf678e1479d528adcc5bea7da3261d0a04e24cc16f96ec9f2dea3b2e98.jsondeleted file mode 100644index 65459bcefd..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-73c67fbf678e1479d528adcc5bea7da3261d0a04e24cc16f96ec9f2dea3b2e98.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT id\n FROM \"User\"\n WHERE email = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "73c67fbf678e1479d528adcc5bea7da3261d0a04e24cc16f96ec9f2dea3b2e98"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.json b/rust/cloud-storage/teams/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.jsondeleted file mode 100644index 34382e8725..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT id, apns_collapse_key as \"apns_collapse_key!: String\"\n FROM notification\n WHERE id = ANY($1) AND apns_collapse_key IS NOT NULL\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "apns_collapse_key!: String",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "UuidArray"- ]- },- "nullable": [- false,- true- ]- },- "hash": "74d33764e454fb9ab4f2775974462d6fdb092bffc720d929de5e7b50ecef5139"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json b/rust/cloud-storage/teams/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.jsondeleted file mode 100644index a8e7326c35..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id FROM user_notification_item_unsubscribe\n WHERE item_id = $1 AND user_id = ANY($2)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray"- ]- },- "nullable": [- false- ]- },- "hash": "765650cab2b1a1d1abe6ca406438bf48968cebebc7316b87b192d649e096cd67"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.json b/rust/cloud-storage/teams/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.jsondeleted file mode 100644index 9e6f7f8877..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT d.device_endpoint\n FROM notification_user_device_registration d\n WHERE d.device_token = $1\n LIMIT 1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "device_endpoint",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "78f1cf9da464937604c1a2d5115c014cab9de72bd88605ff47a316baa2c7acc2"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198.json b/rust/cloud-storage/teams/.sqlx/query-7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198.jsondeleted file mode 100644index 721b0038f2..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id, notification_event_type\n FROM user_notification_type_preference\n WHERE user_id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "notification_event_type",- "type_info": "Varchar"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false- ]- },- "hash": "7c0b9d645a85e30577377e4d8c8a8f976e86c6251e12517a2b1e14d525e09198"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.json b/rust/cloud-storage/teams/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.jsondeleted file mode 100644index a166680895..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc.json+++ /dev/null@@ -1,21 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id, apns_collapse_key)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (id) DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Varchar",- "Text",- "Text",- "Text",- "Jsonb",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "7ccdaab5873129437c98581ac37eb4148255b83e18fad15349d06c54040fd6cc"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.json b/rust/cloud-storage/teams/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.jsondeleted file mode 100644index 215280eac8..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53.json+++ /dev/null@@ -1,97 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($3::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($3, $4))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $2\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "owner_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "notification_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "event_item_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "event_item_type",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "sent",- "type_info": "Bool"- },- {- "ordinal": 5,- "name": "done",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "viewed_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "deleted_at",- "type_info": "Timestamptz"- },- {- "ordinal": 10,- "name": "notification_metadata: serde_json::Value",- "type_info": "Jsonb"- },- {- "ordinal": 11,- "name": "notification_event_type",- "type_info": "Varchar"- },- {- "ordinal": 12,- "name": "sender_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "Int8",- "Timestamptz",- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- null,- null,- null,- null,- false,- false,- true- ]- },- "hash": "7cd8368263b84e0dd25d0e7d1ae40b68d3cf69baaf036d2a17bf7d06176f8a53"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.json b/rust/cloud-storage/teams/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.jsondeleted file mode 100644index 4cb16ae2df..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO user_notification (notification_id, user_id)\n SELECT $1, user_id\n FROM UNNEST($2::text[]) as user_id\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "TextArray"- ]- },- "nullable": []- },- "hash": "81f96534cd4a7b52d4ec2948dce8052076a25eea0af92eae1908e0e068af2116"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.json b/rust/cloud-storage/teams/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.jsondeleted file mode 100644index eab49b91f7..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE user_notification\n SET sent = true\n WHERE notification_id = $1 AND user_id = ANY($2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "TextArray"- ]- },- "nullable": []- },- "hash": "86eee52e30e4168f4a7f319d1dcaa59144a5b3269120df892f161c74b5fe7436"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239.json b/rust/cloud-storage/teams/.sqlx/query-92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239.jsondeleted file mode 100644index a8520fdfd0..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO notification_message_receipt (message_id, user_id, notification_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (message_id) DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text",- "Uuid"- ]- },- "nullable": []- },- "hash": "92edc80110af7b96f7f908989461a4abb11652671a95454969369a0484ed9239"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1.json b/rust/cloud-storage/teams/.sqlx/query-94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1.jsondeleted file mode 100644index 4035617965..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE user_notification\n SET deleted_at = NOW()\n WHERE user_id = $1 AND notification_id = $2\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Uuid"- ]- },- "nullable": []- },- "hash": "94c019227741f6c4fe8411454cb7c0a3a97e5594c29f11fa893238656e161ff1"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json b/rust/cloud-storage/teams/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.jsondeleted file mode 100644index ad14cfedba..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json+++ /dev/null@@ -1,44 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id, device_endpoint, device_type as \"device_type: DbDeviceType\"\n FROM notification_user_device_registration\n WHERE user_id = ANY($1)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "device_endpoint",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "device_type: DbDeviceType",- "type_info": {- "Custom": {- "name": "notification_device_type_option",- "kind": {- "Enum": [- "ios",- "android"- ]- }- }- }- }- ],- "parameters": {- "Left": [- "TextArray"- ]- },- "nullable": [- false,- false,- false- ]- },- "hash": "a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json b/rust/cloud-storage/teams/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.jsondeleted file mode 100644index 7626c0a06b..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE user_notification\n SET seen_at = NOW()\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "UuidArray"- ]- },- "nullable": []- },- "hash": "a5d9f358b5382c0eaed918f903bc6aa328f527e6e47d649c37dfcf1c9f3a7139"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json b/rust/cloud-storage/teams/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.jsondeleted file mode 100644index e5d913399d..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO notification_user_device_registration (id, user_id, device_token, device_endpoint, device_type)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (device_endpoint) DO UPDATE SET user_id = $2, device_token = $3, device_type = $5, updated_at = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text",- "Text",- {- "Custom": {- "name": "notification_device_type_option",- "kind": {- "Enum": [- "ios",- "android"- ]- }- }- }- ]- },- "nullable": []- },- "hash": "b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9.json b/rust/cloud-storage/teams/.sqlx/query-b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9.jsondeleted file mode 100644index 1168d26a34..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE notification_message_receipt\n SET failed = true, failed_at = NOW()\n WHERE message_id = $1\n RETURNING user_id, notification_id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "notification_id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false- ]- },- "hash": "b6705d3675950d0bbbd4a0ba10f7716a24694cfd98741fc0508d607684b1c8a9"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2.json b/rust/cloud-storage/teams/.sqlx/query-b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2.jsondeleted file mode 100644index 0b09fbeec2..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2.json+++ /dev/null@@ -1,98 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND n.event_item_id = ANY($2)\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($4::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($4, $5))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $3\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "owner_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "notification_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "event_item_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "event_item_type",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "sent",- "type_info": "Bool"- },- {- "ordinal": 5,- "name": "done",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "viewed_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "deleted_at",- "type_info": "Timestamptz"- },- {- "ordinal": 10,- "name": "notification_metadata: serde_json::Value",- "type_info": "Jsonb"- },- {- "ordinal": 11,- "name": "notification_event_type",- "type_info": "Varchar"- },- {- "ordinal": 12,- "name": "sender_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Int8",- "Timestamptz",- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- null,- null,- null,- null,- false,- false,- true- ]- },- "hash": "b6cda5fd5ec775474b301aa8a7376ff2dfd8c5812db1b6d493cbb355685907f2"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73.json b/rust/cloud-storage/teams/.sqlx/query-db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73.jsondeleted file mode 100644index d197caf563..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id FROM user_notification_type_preference\n WHERE notification_event_type = $1 AND user_id = ANY($2)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray"- ]- },- "nullable": [- false- ]- },- "hash": "db297e24e3ed1e94c27121977d81813bbe4cde5e5b7bec42e424c72db0e27e73"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad.json b/rust/cloud-storage/teams/.sqlx/query-e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad.jsondeleted file mode 100644index b36882b3ae..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad.json+++ /dev/null@@ -1,95 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as \"notification_metadata: serde_json::Value\",\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.notification_id = $2\n AND un.deleted_at IS NULL\n LIMIT 1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "owner_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "notification_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "event_item_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "event_item_type",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "sent",- "type_info": "Bool"- },- {- "ordinal": 5,- "name": "done",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "viewed_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "deleted_at",- "type_info": "Timestamptz"- },- {- "ordinal": 10,- "name": "notification_metadata: serde_json::Value",- "type_info": "Jsonb"- },- {- "ordinal": 11,- "name": "notification_event_type",- "type_info": "Varchar"- },- {- "ordinal": 12,- "name": "sender_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "Uuid"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false,- null,- null,- null,- null,- false,- false,- true- ]- },- "hash": "e231e279615526b33206979b400328d23be40ef9da49697ef6b75cdfcd69caad"-}diff --git a/rust/cloud-storage/teams/.sqlx/query-f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b.json b/rust/cloud-storage/teams/.sqlx/query-f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b.jsondeleted file mode 100644index 39180b3b0f..0000000000--- a/rust/cloud-storage/teams/.sqlx/query-f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE user_notification\n SET deleted_at = NOW()\n WHERE user_id = $1 AND notification_id = ANY($2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "UuidArray"- ]- },- "nullable": []- },- "hash": "f3e53dd531be738b881df199783a2beded3bd378038cbd6f012080ac77c5291b"-}diff --git a/rust/cloud-storage/teams/Cargo.toml b/rust/cloud-storage/teams/Cargo.tomlindex a81908ac18..d21e85dcf1 100644--- a/rust/cloud-storage/teams/Cargo.toml+++ b/rust/cloud-storage/teams/Cargo.toml@@ -55,4 +55,6 @@ sqlx = { workspace = true, optional = true }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }+rootcause = { workspace = true }+serde_json = { workspace = true }tokio = { workspace = true }diff --git a/rust/cloud-storage/teams/src/domain/model.rs b/rust/cloud-storage/teams/src/domain/model.rsindex 54adb7689b..c6071212e9 100644--- a/rust/cloud-storage/teams/src/domain/model.rs+++ b/rust/cloud-storage/teams/src/domain/model.rs@@ -400,20 +400,6 @@ pub enum JoinTeamError {AddRolesToUserError(#[from] UserRolesAndPermissionsError),}-/// Errors for reinviting a user to a team-#[derive(Debug, thiserror::Error)]-pub enum ReinviteError {- /// The invite was sent too recently- #[error("Too many requests")]- TooManyRequests,- /// The invite does not exist- #[error("Invite not found")]- InviteNotFound,- /// Storage layer error- #[error("Storage layer error {0}")]- StorageLayerError(#[from] anyhow::Error),-}-/// Errors for revoking permissions for team members#[derive(Debug, thiserror::Error)]pub enum RevokePermissionsForTeamMembersError {diff --git a/rust/cloud-storage/teams/src/domain/team_repo.rs b/rust/cloud-storage/teams/src/domain/team_repo.rsindex 0fb82f045b..d5277b8c21 100644--- a/rust/cloud-storage/teams/src/domain/team_repo.rs+++ b/rust/cloud-storage/teams/src/domain/team_repo.rs@@ -6,7 +6,7 @@ use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStruse crate::domain::model::{CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,- PatchTeamUserTierRequest, ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,+ PatchTeamUserTierRequest, RemoveTeamInviteError, RemoveUserFromTeamError,RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team, TeamError,TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamUserTier, TeamWithMembers,};@@ -60,6 +60,12 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {emails: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send;+ /// Marks the given team invites as sent by updating their last_sent_at timestamp.+ fn mark_invites_sent(+ &self,+ invite_ids: &[uuid::Uuid],+ ) -> impl Future<Output = Result<(), TeamError>> + Send;+/// Removes user from a team.fn remove_user_from_team(&self,@@ -165,18 +171,6 @@ pub trait TeamRepository: Clone + Send + Sync + 'static {req: &PatchTeamRequest,) -> impl Future<Output = Result<(), TeamError>> + Send;- /// Gets detailed info about a team invite by id- fn get_team_invite_details_by_id(- &self,- invite_id: &uuid::Uuid,- ) -> impl Future<Output = Result<TeamInviteDetails, TeamError>> + Send;-- /// Updates the last_sent_at field of a team invite- fn update_team_invite_last_sent_at(- &self,- invite_id: &uuid::Uuid,- ) -> impl Future<Output = Result<(), TeamError>> + Send;-/// Gets the role of a user in a teamfn get_team_role(&self,@@ -298,13 +292,6 @@ pub trait TeamService: Clone + Send + Sync + 'static {req: &PatchTeamRequest,) -> impl Future<Output = Result<(), TeamError>> + Send;- /// Reinvites a user to a team (rate-limited to 5 min)- fn reinvite_to_team(- &self,- team_invite_id: &uuid::Uuid,- invited_by: &MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<TeamInviteDetails, ReinviteError>> + Send;-/// Gets the role of a user in a teamfn get_team_role(&self,diff --git a/rust/cloud-storage/teams/src/domain/team_service.rs b/rust/cloud-storage/teams/src/domain/team_service.rsindex a706c369e5..09ebb67af7 100644--- a/rust/cloud-storage/teams/src/domain/team_service.rs+++ b/rust/cloud-storage/teams/src/domain/team_service.rs@@ -1,5 +1,8 @@//! Contains the service logic for teams+#[cfg(test)]+mod test;+use std::{collections::HashSet, sync::Arc};use anyhow::Context;@@ -19,7 +22,7 @@ use crate::domain::{customer_repo::CustomerRepository,model::{CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, PatchTeamRequest,- PatchTeamUserTierRequest, ReinviteError, RemoveTeamInviteError, RemoveUserFromTeamError,+ PatchTeamUserTierRequest, RemoveTeamInviteError, RemoveUserFromTeamError,RestorePermissionsForTeamMembersError, RevokePermissionsForTeamMembersError, Team,TeamError, TeamInvite, TeamInviteDetails, TeamMember, TeamRole, TeamUserTier,TeamWithMembers,@@ -152,30 +155,18 @@ where#[tracing::instrument(skip(self), err)]async fn send_invite_notification(&self,- team_id: &uuid::Uuid,- team_invite_id: &uuid::Uuid,- email: &str,- team_name: &str,- invited_by: &MacroUserIdStr<'static>,+ recipient_id: MacroUserIdStr<'_>,+ team_invite_id: uuid::Uuid,+ notification: InviteToTeamMetadata,) -> anyhow::Result<()> {- let notification = InviteToTeamMetadata {- invited_by: invited_by.clone(),- team_name: team_name.to_string(),- team_id: team_id.to_string(),- role: None,- };-- let recipient = MacroUserIdStr::try_from_email(email)- .map_err(|e| anyhow::anyhow!("failed to parse email as macro user id: {}", e))?;-- let entity_id = team_invite_id.to_string();let request = SendNotificationRequestBuilder {- notification_entity: EntityType::Team.with_entity_str(&entity_id),+ notification_entity: EntityType::Team.with_entity_string(team_invite_id.to_string()),+ sender_id: Some(notification.invited_by.clone()),notification,- sender_id: Some(invited_by.clone()),- recipient_ids: HashSet::from([recipient]),+ recipient_ids: HashSet::from([recipient_id]),}.into_request()+ .with_email().with_conn_gateway();self.notification_ingress@@ -233,19 +224,38 @@ whereif let Some(team_name) = team_name {let invited_by_owned = invited_by.clone().into_owned();+ let mut sent_invite_ids = Vec::new();for invite in &invited {- self.send_invite_notification(- team_id,- &invite.team_invite_id,- invite.email.as_ref(),- &team_name,- &invited_by_owned,- )- .await- .inspect_err(- |e| tracing::error!(error=?e, "unable to send invite notification"),- )- .ok();+ if self+ .send_invite_notification(+ MacroUserIdStr::try_from_email(invite.email.as_ref())+ .expect("this cannot fail"),+ invite.team_invite_id,+ InviteToTeamMetadata {+ team_id: *team_id,+ invited_by: invited_by_owned.clone(),+ team_name: team_name.clone(),+ role: None,+ sender_profile_picture_url: None,+ },+ )+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "unable to send invite notification"),+ )+ .is_ok()+ {+ sent_invite_ids.push(invite.team_invite_id);+ }+ }+ if !sent_invite_ids.is_empty() {+ self.team_repository+ .mark_invites_sent(&sent_invite_ids)+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "unable to mark invites as sent"),+ )+ .ok();}}}@@ -490,54 +500,6 @@ whereself.team_repository.patch_team(team_id, req).await}- #[tracing::instrument(skip(self), err)]- async fn reinvite_to_team(- &self,- team_invite_id: &uuid::Uuid,- invited_by: &MacroUserIdStr<'_>,- ) -> Result<TeamInviteDetails, ReinviteError> {- let invite = self- .team_repository- .get_team_invite_details_by_id(team_invite_id)- .await- .map_err(|e| match e {- TeamError::TeamInviteDoesNotExist => ReinviteError::InviteNotFound,- other => ReinviteError::StorageLayerError(other.into()),- })?;-- // Rate limit: must wait 5 minutes between reinvites- let five_minutes_ago = chrono::Utc::now() - chrono::Duration::minutes(5);- if invite.last_sent_at > five_minutes_ago {- return Err(ReinviteError::TooManyRequests);- }-- self.team_repository- .update_team_invite_last_sent_at(team_invite_id)- .await- .map_err(|e| ReinviteError::StorageLayerError(e.into()))?;-- // Send notification- let team_name = self- .team_repository- .get_team_name(&invite.team_id)- .await- .map_err(|e| ReinviteError::StorageLayerError(e.into()))?;-- let invited_by = invited_by.clone().into_owned();- self.send_invite_notification(- &invite.team_id,- team_invite_id,- &invite.email,- &team_name,- &invited_by,- )- .await- .inspect_err(|e| tracing::error!(error=?e, "unable to send reinvite notification"))- .ok();-- Ok(invite)- }-#[tracing::instrument(skip(self), err)]async fn get_team_role(&self,diff --git a/rust/cloud-storage/teams/src/domain/team_service/test.rs b/rust/cloud-storage/teams/src/domain/team_service/test.rsnew file mode 100644index 0000000000..ea9ad3d2d0--- /dev/null+++ b/rust/cloud-storage/teams/src/domain/team_service/test.rs@@ -0,0 +1,584 @@+use std::{+ collections::HashSet,+ future::Future,+ sync::{+ Arc, Mutex,+ atomic::{AtomicUsize, Ordering},+ },+};++use macro_user_id::{email::Email, lowercased::Lowercase, user_id::MacroUserIdStr};+use notification::domain::{+ models::{Notification, NotificationResult, request::SendNotificationRequest},+ service::{NotificationIngress, SendNotificationError},+};+use roles_and_permissions::domain::{+ model::{PermissionId, RoleId, UserRolesAndPermissionsError},+ port::UserRolesAndPermissionsService,+};++use super::*;+use crate::domain::{+ customer_repo::CustomerRepository,+ model::{+ CreateSubscriptionArgs, CustomerError, PatchTeamRequest, RemoveTeamInviteError,+ RemoveUserFromTeamError, Team, TeamError, TeamInvite, TeamInviteDetails, TeamMember,+ TeamRole, TeamUserTier, TeamWithMembers,+ },+ team_repo::{TeamChannelsRepository, TeamRepository},+};++// -- Mock TeamRepository --++#[derive(Clone)]+struct MockTeamRepository {+ invites_to_return: Vec<TeamInvite<'static>>,+ team_name: String,+ mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>>,+}++impl MockTeamRepository {+ fn new(+ invites: Vec<TeamInvite<'static>>,+ team_name: &str,+ mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>>,+ ) -> Self {+ Self {+ invites_to_return: invites,+ team_name: team_name.to_string(),+ mark_sent_calls,+ }+ }+}++impl TeamRepository for MockTeamRepository {+ fn get_stripe_customer_id(+ &self,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<stripe::CustomerId>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_subscription_id(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<Option<stripe::SubscriptionId>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn create_team(+ &self,+ _: &MacroUserIdStr<'_>,+ _: &str,+ _: &TeamUserTier,+ ) -> impl Future<Output = Result<Team, CreateTeamError>> + Send {+ async { unimplemented!() }+ }++ fn invite_users_to_team(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ _: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,+ ) -> impl Future<Output = Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError>> + Send {+ let invites = self.invites_to_return.clone();+ async move { Ok(invites) }+ }++ fn mark_invites_sent(+ &self,+ invite_ids: &[uuid::Uuid],+ ) -> impl Future<Output = Result<(), TeamError>> + Send {+ self.mark_sent_calls+ .lock()+ .unwrap()+ .push(invite_ids.to_vec());+ async { Ok(()) }+ }++ fn remove_user_from_team(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<TeamUserTier, RemoveUserFromTeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_invite_by_id(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<TeamInvite<'_>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn delete_team_invite(+ &self,+ _: &uuid::Uuid,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<(), RemoveTeamInviteError>> + Send {+ async { unimplemented!() }+ }++ fn update_team_subscription(+ &self,+ _: &uuid::Uuid,+ _: &stripe::SubscriptionId,+ ) -> impl Future<Output = Result<(), TeamError>> + Send {+ async { unimplemented!() }+ }++ fn delete_team(&self, _: &uuid::Uuid) -> impl Future<Output = Result<(), TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_all_team_members(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<Vec<TeamMember<'_>>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn accept_team_invite(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<TeamMember<'static>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn is_user_member_of_team(+ &self,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<bool, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_members(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<Vec<TeamMember<'_>>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn bulk_is_member_of_other_team(+ &self,+ _: non_empty::NonEmpty<&[uuid::Uuid]>,+ _: non_empty::NonEmpty<&[MacroUserIdStr<'_>]>,+ ) -> impl Future<Output = Result<Vec<MacroUserIdStr<'_>>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_by_id(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<TeamWithMembers, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_user_teams(+ &self,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<Team>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_user_team_invites(+ &self,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<TeamInviteDetails>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_invites(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<Vec<TeamInviteDetails>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_name(+ &self,+ _: &uuid::Uuid,+ ) -> impl Future<Output = Result<String, TeamError>> + Send {+ let name = self.team_name.clone();+ async move { Ok(name) }+ }++ fn patch_team(+ &self,+ _: &uuid::Uuid,+ _: &PatchTeamRequest,+ ) -> impl Future<Output = Result<(), TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_role(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<TeamRole>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn get_team_member(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<TeamMember<'_>, TeamError>> + Send {+ async { unimplemented!() }+ }++ fn patch_team_tier(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ _: TeamUserTier,+ ) -> impl Future<Output = Result<(), TeamError>> + Send {+ async { unimplemented!() }+ }+}++// -- Mock CustomerRepository --++#[derive(Clone)]+struct MockCustomerRepository;++impl CustomerRepository for MockCustomerRepository {+ fn convert_subscription_to_team(+ &self,+ _: &stripe::SubscriptionId,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {+ async { unimplemented!() }+ }++ fn get_subscription_id_for_customer(+ &self,+ _: &stripe::CustomerId,+ ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {+ async { unimplemented!() }+ }++ fn create_subscription(+ &self,+ _: CreateSubscriptionArgs,+ ) -> impl Future<Output = Result<stripe::SubscriptionId, CustomerError>> + Send {+ async { unimplemented!() }+ }++ fn increase_subscription_quantity(+ &self,+ _: &stripe::SubscriptionId,+ _: TeamUserTier,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {+ async { unimplemented!() }+ }++ fn decrease_subscription_quantity(+ &self,+ _: &stripe::SubscriptionId,+ _: TeamUserTier,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {+ async { unimplemented!() }+ }++ fn update_subscription_tier(+ &self,+ _: &stripe::SubscriptionId,+ _: TeamUserTier,+ _: TeamUserTier,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {+ async { unimplemented!() }+ }++ fn cancel_subscription(+ &self,+ _: &stripe::SubscriptionId,+ ) -> impl Future<Output = Result<(), CustomerError>> + Send {+ async { unimplemented!() }+ }+}++// -- Mock TeamChannelsRepository --++#[derive(Clone)]+struct MockTeamChannelsRepository;++impl TeamChannelsRepository for MockTeamChannelsRepository {+ fn add_team_member_to_channels(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<(), TeamError>> + Send {+ async { unimplemented!() }+ }++ fn remove_team_member_from_channels(+ &self,+ _: &uuid::Uuid,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<(), TeamError>> + Send {+ async { unimplemented!() }+ }+}++// -- Mock UserRolesAndPermissionsService --++#[derive(Clone)]+struct MockUserRolesAndPermissionsService;++impl UserRolesAndPermissionsService for MockUserRolesAndPermissionsService {+ fn get_user_roles(+ &self,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<HashSet<RoleId>, UserRolesAndPermissionsError>> + Send {+ async { unimplemented!() }+ }++ fn get_user_permissions(+ &self,+ _: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<HashSet<PermissionId>, UserRolesAndPermissionsError>> + Send+ {+ async { unimplemented!() }+ }++ fn update_user_roles_and_permissions_for_subscription(+ &self,+ _: Email<Lowercase<'_>>,+ _: roles_and_permissions::domain::model::SubscriptionStatus,+ _: roles_and_permissions::domain::model::ProductTier,+ ) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {+ async { unimplemented!() }+ }++ fn dangerous_upsert_roles_for_user(+ &self,+ _: &MacroUserIdStr<'_>,+ _: non_empty::NonEmpty<&[RoleId]>,+ ) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {+ async { unimplemented!() }+ }++ fn dangerous_remove_roles_from_user(+ &self,+ _: &MacroUserIdStr<'_>,+ _: &non_empty::NonEmpty<&[RoleId]>,+ ) -> impl Future<Output = Result<(), UserRolesAndPermissionsError>> + Send {+ async { unimplemented!() }+ }+}++// -- Mock NotificationIngress --++/// A mock that fails on specific call indices (0-based).+/// For example, `fail_indices: {1}` means the second call will fail.+struct MockNotificationIngress {+ fail_indices: HashSet<usize>,+ call_count: AtomicUsize,+ /// Captured serialized snapshots of each request, in call order.+ recorded_requests: Mutex<Vec<serde_json::Value>>,+}++impl MockNotificationIngress {+ fn new(fail_indices: HashSet<usize>) -> Self {+ Self {+ fail_indices,+ call_count: AtomicUsize::new(0),+ recorded_requests: Mutex::new(Vec::new()),+ }+ }++ /// Returns cloned snapshots of all recorded requests.+ fn recorded_requests(&self) -> Vec<serde_json::Value> {+ self.recorded_requests.lock().unwrap().clone()+ }+}++impl NotificationIngress for MockNotificationIngress {+ fn send_notification<+ 'a,+ T: Notification + Clone + 'static,+ U: serde::Serialize + Send + Sync + 'static,+ >(+ &'a self,+ req: SendNotificationRequest<'a, T, U>,+ ) -> impl Future<+ Output = Result<Option<NotificationResult<'a>>, rootcause::Report<SendNotificationError>>,+ > + Send {+ let index = self.call_count.fetch_add(1, Ordering::SeqCst);+ let should_fail = self.fail_indices.contains(&index);+ let snapshot = serde_json::to_value(&req).unwrap();+ self.recorded_requests.lock().unwrap().push(snapshot);+ async move {+ if should_fail {+ Err(rootcause::Report::new(SendNotificationError::Other))+ } else {+ Ok(None)+ }+ }+ }+}++// -- Helpers --++fn make_invite(email: &str, invite_id: uuid::Uuid, team_id: uuid::Uuid) -> TeamInvite<'static> {+ TeamInvite {+ team_id,+ team_invite_id: invite_id,+ email: Email::parse_from_str(email)+ .unwrap()+ .into_owned()+ .lowercase(),+ }+}++fn build_service(+ invites: Vec<TeamInvite<'static>>,+ fail_indices: HashSet<usize>,+ mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>>,+) -> (impl TeamService, Arc<MockNotificationIngress>) {+ let team_repo = MockTeamRepository::new(invites, "Test Team", mark_sent_calls);+ let notification_ingress = Arc::new(MockNotificationIngress::new(fail_indices));+ let service = TeamServiceImpl::new(+ team_repo,+ MockCustomerRepository,+ MockTeamChannelsRepository,+ MockUserRolesAndPermissionsService,+ notification_ingress.clone(),+ );+ (service, notification_ingress)+}++// -- Tests --++/// When one notification fails, only the successful invite IDs are passed to+/// mark_invites_sent.+#[tokio::test]+async fn test_invite_marks_sent_only_for_successful_notifications() {+ let team_id = uuid::Uuid::from_u128(1);+ let invite_id_1 = uuid::Uuid::from_u128(101);+ let invite_id_2 = uuid::Uuid::from_u128(102);+ let invite_id_3 = uuid::Uuid::from_u128(103);++ let invites = vec![+ make_invite("[email protected]", invite_id_1, team_id),+ make_invite("[email protected]", invite_id_2, team_id),+ make_invite("[email protected]", invite_id_3, team_id),+ ];++ // The second notification (bob, index 1) will fail+ let fail_indices = HashSet::from([1]);+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));++ let (service, _notification_ingress) =+ build_service(invites, fail_indices, mark_sent_calls.clone());++ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let emails = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let emails = non_empty::NonEmpty::new(emails.as_slice()).unwrap();++ let result = service+ .invite_users_to_team(&team_id, &invited_by, emails)+ .await+ .unwrap();++ // All three invites should be returned regardless of notification success+ assert_eq!(result.len(), 3);++ // mark_invites_sent should be called once with only alice and carol's IDs+ let marks = mark_sent_calls.lock().unwrap();+ assert_eq!(marks.len(), 1);+ let marked_ids = &marks[0];+ assert_eq!(marked_ids.len(), 2);+ assert!(marked_ids.contains(&invite_id_1)); // alice succeeded+ assert!(!marked_ids.contains(&invite_id_2)); // bob failed+ assert!(marked_ids.contains(&invite_id_3)); // carol succeeded+}++/// When all notifications fail, mark_invites_sent is never called.+#[tokio::test]+async fn test_invite_does_not_call_mark_sent_when_all_notifications_fail() {+ let team_id = uuid::Uuid::from_u128(1);+ let invite_id = uuid::Uuid::from_u128(201);++ let invites = vec![make_invite("[email protected]", invite_id, team_id)];++ // The only notification (index 0) fails+ let fail_indices = HashSet::from([0]);+ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));++ let (service, _notification_ingress) =+ build_service(invites, fail_indices, mark_sent_calls.clone());++ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let emails = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let emails = non_empty::NonEmpty::new(emails.as_slice()).unwrap();++ service+ .invite_users_to_team(&team_id, &invited_by, emails)+ .await+ .unwrap();++ // mark_invites_sent should NOT be called since all notifications failed+ assert!(mark_sent_calls.lock().unwrap().is_empty());+}++/// When all notifications succeed, all invite IDs are passed to mark_invites_sent.+#[tokio::test]+async fn test_invite_marks_all_sent_when_all_notifications_succeed() {+ let team_id = uuid::Uuid::from_u128(1);+ let invite_id_1 = uuid::Uuid::from_u128(301);+ let invite_id_2 = uuid::Uuid::from_u128(302);++ let invites = vec![+ make_invite("[email protected]", invite_id_1, team_id),+ make_invite("[email protected]", invite_id_2, team_id),+ ];++ let mark_sent_calls: Arc<Mutex<Vec<Vec<uuid::Uuid>>>> = Arc::new(Mutex::new(Vec::new()));++ let (service, _notification_ingress) = build_service(+ invites,+ HashSet::new(), // all succeed+ mark_sent_calls.clone(),+ );++ let invited_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let emails = vec![+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ Email::parse_from_str("[email protected]")+ .unwrap()+ .lowercase(),+ ];+ let emails = non_empty::NonEmpty::new(emails.as_slice()).unwrap();++ service+ .invite_users_to_team(&team_id, &invited_by, emails)+ .await+ .unwrap();++ let marks = mark_sent_calls.lock().unwrap();+ assert_eq!(marks.len(), 1);+ let marked_ids = &marks[0];+ assert_eq!(marked_ids.len(), 2);+ assert!(marked_ids.contains(&invite_id_1));+ assert!(marked_ids.contains(&invite_id_2));+}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rsindex 8cb510fd6f..525a787f36 100644--- a/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs+++ b/rust/cloud-storage/teams/src/inbound/axum_router/mod.rs@@ -24,8 +24,6 @@ pub mod middleware;pub mod patch_team;/// Patch a team users tier.pub mod patch_team_user_tier;-/// Reinvite a user to a team.-pub mod reinvite_to_team;/// Reject a team invitation.pub mod reject_invitation;/// Remove a user from a team.@@ -46,7 +44,7 @@ use model_error_response::ErrorResponse;use crate::domain::{model::{- CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError, ReinviteError,+ CreateTeamError, DeleteTeamError, InviteUsersToTeamError, JoinTeamError,RemoveTeamInviteError, RemoveUserFromTeamError, TeamError,},team_repo::TeamService,@@ -91,10 +89,6 @@ where.route("/{team_id}", delete(delete_team::handler::<T>)).route("/{team_id}/invites", get(get_team_invites::handler::<T>)).route("/{team_id}/invite", post(invite_to_team::handler::<T>))- .route(- "/{team_id}/reinvite/{team_invite_id}",- post(reinvite_to_team::handler::<T>),- ).route("/join/{team_invite_id}",delete(reject_invitation::handler::<T>),@@ -286,29 +280,3 @@ impl IntoResponse for RemoveUserFromTeamError {.into_response()}}--impl IntoResponse for ReinviteError {- fn into_response(self) -> Response {- match self {- ReinviteError::TooManyRequests => (- StatusCode::TOO_MANY_REQUESTS,- Json(ErrorResponse {- message: "team invite has not been sent in the last 5 minutes".into(),- }),- ),- ReinviteError::InviteNotFound => (- StatusCode::NOT_FOUND,- Json(ErrorResponse {- message: "team invite does not exist".into(),- }),- ),- ReinviteError::StorageLayerError(_) => (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "internal server error".into(),- }),- ),- }- .into_response()- }-}diff --git a/rust/cloud-storage/teams/src/inbound/axum_router/reinvite_to_team.rs b/rust/cloud-storage/teams/src/inbound/axum_router/reinvite_to_team.rsdeleted file mode 100644index 71e11b538a..0000000000--- a/rust/cloud-storage/teams/src/inbound/axum_router/reinvite_to_team.rs+++ /dev/null@@ -1,50 +0,0 @@-use axum::extract::{Path, State};-use model_error_response::ErrorResponse;-use model_user::axum_extractor::MacroUserExtractor;--use crate::domain::{model::ReinviteError, team_repo::TeamService};--use super::{TeamRouterState, middleware::TeamAccessRoleExtractor};--/// Path parameters for reinvite endpoint.-#[derive(serde::Deserialize)]-pub struct Param {- /// The team ID.- pub team_id: uuid::Uuid,- /// The team invite ID.- pub team_invite_id: uuid::Uuid,-}--/// Regenerates a team invite notifying the user again.-#[utoipa::path(- post,- path = "/team/{team_id}/reinvite/{team_invite_id}",- operation_id = "reinvite_to_team",- params(- ("team_id" = String, Path, description = "The ID of the team to invite to"),- ("team_invite_id" = String, Path, description = "The ID of the team invite to reinvite")- ),- responses(- (status = 200),- (status = 400, body = ErrorResponse),- (status = 401, body = ErrorResponse),- (status = 429, body = ErrorResponse),- (status = 500, body = ErrorResponse),- ),-)]-#[tracing::instrument(skip_all, err)]-pub async fn handler<T: TeamService>(- _access: TeamAccessRoleExtractor<super::middleware::AdminRole, T>,- State(state): State<TeamRouterState<T>>,- user_context: MacroUserExtractor,- Path(Param {- team_id: _,- team_invite_id,- }): Path<Param>,-) -> Result<(), ReinviteError> {- state- .service- .reinvite_to_team(&team_invite_id, &user_context.macro_user_id)- .await?;- Ok(())-}diff --git a/rust/cloud-storage/teams/src/outbound/team_repo.rs b/rust/cloud-storage/teams/src/outbound/team_repo.rsindex 75e98d515d..f7c9f46295 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo.rs@@ -298,25 +298,58 @@ impl TeamRepository for TeamRepositoryImpl {.fetch_all(&mut *transaction).await?;- // Convert returned emails back to Email type- let created_emails: Vec<TeamInvite<'static>> = invites- .into_iter()- .filter_map(|(id, team_id, email)| {- let email = Email::parse_from_str(&email)- .ok()- .map(|e| e.into_owned().lowercase());+ // Also re-send existing invites whose rate limit window has passed+ let resent_invites: Vec<(uuid::Uuid, uuid::Uuid, String)> = sqlx::query!(+ r#"+ SELECT id, team_id, email+ FROM team_invite+ WHERE team_id = $1+ AND email = ANY($2::text[])+ AND last_sent_at < NOW() - INTERVAL '5 minutes'+ "#,+ team_id,+ &email_strings[..],+ )+ .map(|r| (r.id, r.team_id, r.email))+ .fetch_all(&mut *transaction)+ .await?;- email.map(|email| TeamInvite {+ let to_email = |id: uuid::Uuid, team_id: uuid::Uuid, email: String| {+ Email::parse_from_str(&email)+ .ok()+ .map(|e| e.into_owned().lowercase())+ .map(|email| TeamInvite {team_id,team_invite_id: id,email,})- })+ };++ // Combine new invites and resent invites+ let all_invites: Vec<TeamInvite<'static>> = invites+ .into_iter()+ .chain(resent_invites)+ .filter_map(|(id, team_id, email)| to_email(id, team_id, email)).collect();transaction.commit().await?;- Ok(created_emails)+ Ok(all_invites)+ }++ #[tracing::instrument(skip(self), err)]+ async fn mark_invites_sent(&self, invite_ids: &[uuid::Uuid]) -> Result<(), TeamError> {+ sqlx::query!(+ r#"+ UPDATE team_invite+ SET last_sent_at = NOW()+ WHERE id = ANY($1::uuid[])+ "#,+ invite_ids,+ )+ .execute(&self.pool)+ .await?;+ Ok(())}#[tracing::instrument(skip(self), err)]@@ -855,64 +888,6 @@ impl TeamRepository for TeamRepositoryImpl {Ok(())}- #[tracing::instrument(skip(self), err)]- async fn get_team_invite_details_by_id(- &self,- invite_id: &uuid::Uuid,- ) -> Result<TeamInviteDetails, TeamError> {- let invite = sqlx::query!(- r#"- SELECT- id,- email,- team_id,- team_role as "team_role!: TeamRole",- invited_by,- created_at as "created_at!: chrono::DateTime<chrono::Utc>",- last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>"- FROM team_invite- WHERE id = $1- "#,- invite_id,- )- .map(|row| TeamInviteDetails {- id: row.id,- email: row.email,- team_id: row.team_id,- team_role: row.team_role,- invited_by: row.invited_by,- created_at: row.created_at,- last_sent_at: row.last_sent_at,- })- .fetch_one(&self.pool)- .await- .map_err(|e| match e {- sqlx::Error::RowNotFound => TeamError::TeamInviteDoesNotExist,- _ => e.into(),- })?;-- Ok(invite)- }-- #[tracing::instrument(skip(self), err)]- async fn update_team_invite_last_sent_at(- &self,- invite_id: &uuid::Uuid,- ) -> Result<(), TeamError> {- sqlx::query!(- r#"- UPDATE team_invite- SET last_sent_at = NOW()- WHERE id = $1- "#,- invite_id,- )- .execute(&self.pool)- .await?;-- Ok(())- }-#[tracing::instrument(skip(self), err)]async fn get_team_role(&self,diff --git a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs b/rust/cloud-storage/teams/src/outbound/team_repo/test.rsindex cb4c0241ab..9dbd5be2a8 100644--- a/rust/cloud-storage/teams/src/outbound/team_repo/test.rs+++ b/rust/cloud-storage/teams/src/outbound/team_repo/test.rs@@ -132,6 +132,233 @@ async fn test_invite_users_to_team(pool: Pool<Postgres>) -> anyhow::Result<()> {Ok(())}+/// Re-inviting an already-invited user within the 5-minute window should not+/// return them (rate limited), so the result should be empty.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_invite_existing_user_within_rate_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool);+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ // [email protected] already has an invite with last_sent_at = NOW() in the fixture+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;++ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;++ // Rate limit blocks re-send, no new invite created either+ assert!(invited.is_empty());++ Ok(())+}++/// Re-inviting an already-invited user after the 5-minute window has passed+/// should return them (re-sent).+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_invite_existing_user_after_rate_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ // Push last_sent_at back 10 minutes so the rate limit window has passed+ sqlx::query!(+ r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '10 minutes' WHERE team_id = $1 AND email = '[email protected]'"#,+ &team_id,+ )+ .execute(&pool)+ .await?;++ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;++ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;++ assert_eq!(invited.len(), 1);+ assert_eq!(invited[0].email.as_ref(), "[email protected]");++ Ok(())+}++/// Inviting a mix of new users and existing users (past rate limit) should+/// return both.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_invite_mix_new_and_existing(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ // Push existing invite past the rate limit window+ sqlx::query!(+ r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '10 minutes' WHERE team_id = $1 AND email = '[email protected]'"#,+ &team_id,+ )+ .execute(&pool)+ .await?;++ let invites = vec![+ Email::parse_from_str("[email protected]")?.lowercase(),+ Email::parse_from_str("[email protected]")?.lowercase(),+ ];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;++ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;++ assert_eq!(invited.len(), 2);++ let emails: Vec<&str> = invited.iter().map(|i| i.email.as_ref()).collect();+ assert!(emails.contains(&"[email protected]"));+ assert!(emails.contains(&"[email protected]"));++ Ok(())+}++/// Re-inviting updates last_sent_at (via mark_invites_sent) so a second+/// immediate re-invite is rate limited.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_reinvite_updates_last_sent_at(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ // Push past rate limit+ sqlx::query!(+ r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '10 minutes' WHERE team_id = $1 AND email = '[email protected]'"#,+ &team_id,+ )+ .execute(&pool)+ .await?;++ // First re-invite should succeed+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;+ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;+ assert_eq!(invited.len(), 1);++ // Mark the invite as sent (simulating successful notification delivery)+ let sent_ids: Vec<uuid::Uuid> = invited.iter().map(|i| i.team_invite_id).collect();+ team_repo.mark_invites_sent(&sent_ids).await?;++ // Second immediate re-invite should be rate limited+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;+ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;+ assert!(invited.is_empty());++ Ok(())+}++/// invite_users_to_team does NOT update last_sent_at by itself; without a+/// subsequent mark_invites_sent call, the invite remains eligible for resend.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_resend_without_mark_sent_stays_eligible(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ // Push past rate limit+ sqlx::query!(+ r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '10 minutes' WHERE team_id = $1 AND email = '[email protected]'"#,+ &team_id,+ )+ .execute(&pool)+ .await?;++ // First re-invite returns the invite+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;+ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;+ assert_eq!(invited.len(), 1);++ // Do NOT call mark_invites_sent (simulating failed notification delivery)++ // Second re-invite should still return the invite because last_sent_at was not updated+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;+ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;+ assert_eq!(invited.len(), 1);++ Ok(())+}++/// mark_invites_sent updates last_sent_at for the specified invite IDs.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("teams"))+)]+async fn test_mark_invites_sent(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_repo = TeamRepositoryImpl::new(pool.clone());+ let team_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;+ let invite_id = macro_uuid::string_to_uuid("11111111-1111-1111-1111-111111111111")?;++ // Push last_sent_at back so it's past the rate limit+ sqlx::query!(+ r#"UPDATE team_invite SET last_sent_at = NOW() - INTERVAL '10 minutes' WHERE id = $1"#,+ &invite_id,+ )+ .execute(&pool)+ .await?;++ // Verify the invite is past rate limit by reading last_sent_at+ let before = sqlx::query!(+ r#"SELECT last_sent_at FROM team_invite WHERE id = $1"#,+ &invite_id,+ )+ .fetch_one(&pool)+ .await?;++ team_repo.mark_invites_sent(&[invite_id]).await?;++ let after = sqlx::query!(+ r#"SELECT last_sent_at FROM team_invite WHERE id = $1"#,+ &invite_id,+ )+ .fetch_one(&pool)+ .await?;++ // last_sent_at should have been updated to a more recent timestamp+ assert!(after.last_sent_at > before.last_sent_at);++ // The invite should now be rate limited+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let invites = vec![Email::parse_from_str("[email protected]")?.lowercase()];+ let invites = non_empty::NonEmpty::new(invites.as_slice())?;+ let invited = team_repo+ .invite_users_to_team(&team_id, &user_id, invites)+ .await?;+ assert!(invited.is_empty());++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("teams"))