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
add [tasks] - push notifications when assigned a task (#769)
Daniel Kweonc400f2a11d57
diff --git a/infra/stacks/properties-service/index.ts b/infra/stacks/properties-service/index.tsindex 6f968f7892..ca8ea0fd9f 100644--- a/infra/stacks/properties-service/index.ts+++ b/infra/stacks/properties-service/index.ts@@ -1,6 +1,11 @@import * as aws from '@pulumi/aws';import * as pulumi from '@pulumi/pulumi';-import { config, getMacroApiToken, stack } from '../../packages/shared';+import {+ config,+ getMacroApiToken,+ getMacroNotify,+ stack,+} from '../../packages/shared';import { get_coparse_api_vpc } from '../../packages/vpc';import { PropertiesService } from './properties-service';@@ -53,6 +58,8 @@ const internalAuthKeyArn: pulumi.Output<string> = aws.secretsmanagerconst MACRO_API_TOKENS = getMacroApiToken();+const { notificationQueueName, notificationQueueArn } = getMacroNotify();+const DOCUMENT_STORAGE_SERVICE_URL = `https://cloud-storage${stack === 'prod' ? '' : `-${stack}`}.macro.com`;const COMMS_SERVICE_URL = `https://comms-service${stack === 'prod' ? '' : `-${stack}`}.macro.com`;@@ -86,6 +93,7 @@ const propertiesService = new PropertiesService(`properties-service-${stack}`, {},serviceContainerPort: 8080,healthCheckPath: '/health',+ notificationQueueArn,containerEnvVars: [{name: 'DATABASE_URL',@@ -135,6 +143,10 @@ const propertiesService = new PropertiesService(`properties-service-${stack}`, {name: 'DOCUMENT_STORAGE_SERVICE_AUTH_KEY',value: pulumi.interpolate`${INTERNAL_AUTH_KEY}`,},+ {+ name: 'NOTIFICATION_QUEUE',+ value: pulumi.interpolate`${notificationQueueName}`,+ },],isPrivate: false,tags,diff --git a/infra/stacks/properties-service/properties-service.ts b/infra/stacks/properties-service/properties-service.tsindex 44149649d3..0b597c6627 100644--- a/infra/stacks/properties-service/properties-service.ts+++ b/infra/stacks/properties-service/properties-service.ts@@ -36,6 +36,7 @@ type CreatePropertiesServiceArgs = {healthCheckPath: string;tags: { [key: string]: string };secretKeyArns: (pulumi.Output<string> | string)[];+ notificationQueueArn: pulumi.Output<string> | string;};export class PropertiesService extends pulumi.ComponentResource {@@ -64,6 +65,7 @@ export class PropertiesService extends pulumi.ComponentResource {cloudStorageClusterName,tags,secretKeyArns,+ notificationQueueArn,}: CreatePropertiesServiceArgs,opts?: pulumi.ComponentResourceOptions) {@@ -136,6 +138,25 @@ export class PropertiesService extends pulumi.ComponentResource {{ parent: this });+ const queuePolicy = new aws.iam.Policy(+ `${BASE_NAME}-queue-policy`,+ {+ name: `${BASE_NAME}-queue-policy-${stack}`,+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: ['sqs:SendMessage'],+ Resource: [pulumi.interpolate`${notificationQueueArn}`],+ Effect: 'Allow',+ },+ ],+ },+ tags: this.tags,+ },+ { parent: this }+ );+this.role = new aws.iam.Role(`${BASE_NAME}-role`,{@@ -153,7 +174,7 @@ export class PropertiesService extends pulumi.ComponentResource {},],},- managedPolicyArns: [secretsManagerPolicy.arn],+ managedPolicyArns: [secretsManagerPolicy.arn, queuePolicy.arn],tags: this.tags,},{ parent: this }diff --git a/js/app/packages/notifications/notification-metadata.ts b/js/app/packages/notifications/notification-metadata.tsindex a715a7b3d0..5d3069c6a9 100644--- a/js/app/packages/notifications/notification-metadata.ts+++ b/js/app/packages/notifications/notification-metadata.ts@@ -10,6 +10,7 @@ import type {ItemSharedOrganizationMetadata,NewEmailMetadata,NotificationEventType,+ TaskAssignedMetadata,} from '@service-notification/generated/schemas';export interface NotificationMetadataByType {@@ -24,6 +25,7 @@ export interface NotificationMetadataByType {[NotificationEventType.new_email]: NewEmailMetadata;[NotificationEventType.invite_to_team]: InviteToTeamMetadata;[NotificationEventType.reject_team_invite]: null;+ [NotificationEventType.task_assigned]: TaskAssignedMetadata;}export type UnifiedNotificationMetadata =diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex 9d27dfab10..d553f85bda 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -138,6 +138,12 @@ function getSupportedHandler(},() => null)+ .with(+ { notificationEventType: 'task_assigned' },+ (n) => async (lm: SplitManager) => {+ openSplitIfNotOpen(lm, 'task', n.notificationMetadata.taskId);+ }+ ).exhaustive();}diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.tsindex 33608fd8a8..30df4c121e 100644--- a/js/app/packages/notifications/notification-preview.ts+++ b/js/app/packages/notifications/notification-preview.ts@@ -40,6 +40,7 @@ export const NOTIFICATION_LABEL_BY_TYPE: Record<NotificationType, string> = {[NotificationType.new_email]: 'EMAIL',[NotificationType.invite_to_team]: 'INVITE',[NotificationType.reject_team_invite]: 'REJECTED',+ [NotificationType.task_assigned]: 'ASSIGNED',} as const;const extractors: {@@ -219,6 +220,25 @@ const extractors: {content: undefined,};},+ task_assigned: (n) => {+ const m = n.notificationMetadata;+ if (!m) return null;+ return {+ type: n.notificationEventType,+ actor: m.assignedBy ? { id: m.assignedBy } : undefined,+ action: 'assigned you a task',+ target: {+ type: 'document' as EntityType, // Tasks are stored as documents+ id: m.taskId,+ name: m.taskName ?? undefined,+ show: true, // Show task name in platform notification title+ },+ content: m.taskName ?? undefined,+ meta: {+ itemId: m.taskId,+ },+ };+ },};type NotificationDataError = 'no_extractor' | 'no_extracted_data';diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOf.tsindex 5c2980e4d6..46db2dcfea 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOf.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelInviteMetadataAllOf.ts@@ -4,8 +4,7 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { String } from './string';export type ChannelInviteMetadataAllOf = {- invitedBy: String;+ invitedBy: string;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.tsindex b91f5932a5..d7468c2fa0 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.ts@@ -4,7 +4,6 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { String } from './string';export type ChannelMessageSendMetadataAllOf = {/** The content of the message */@@ -12,5 +11,5 @@ export type ChannelMessageSendMetadataAllOf = {/** The message id */messageId: string;/** The user who sent the message */- sender: String;+ sender: string;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOf.tsindex dfe043c01b..4189e356da 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOf.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOf.ts@@ -5,7 +5,6 @@* OpenAPI spec version: 0.1.0*/import type { DocumentMentionMetadataAllOfFileType } from './documentMentionMetadataAllOfFileType';-import type { String } from './string';export type DocumentMentionMetadataAllOf = {/** The name of the document */@@ -13,5 +12,5 @@ export type DocumentMentionMetadataAllOf = {/** The file type of the document */fileType?: DocumentMentionMetadataAllOfFileType;/** The owner of the document */- owner: String;+ owner: string;};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 d9be9b1ce3..7106d719c4 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@@ -71,6 +71,8 @@ export * from './notificationEventOneOfThree';export * from './notificationEventOneOfThreeNotificationEventType';export * from './notificationEventOneOfTwoone';export * from './notificationEventOneOfTwooneNotificationEventType';+export * from './notificationEventOneOfTwothree';+export * from './notificationEventOneOfTwothreeNotificationEventType';export * from './notificationEventType';export * from './notificationServiceApiVersion';export * from './notificationTemporalData';@@ -80,7 +82,8 @@ export * from './notificationTemporalDataViewedAt';export * from './pushNotificationData';export * from './pushNotificationDataAllOf';export * from './pushNotificationDataAllOfSenderId';-export * from './string';+export * from './taskAssignedMetadata';+export * from './taskAssignedMetadataTaskName';export * from './unsubscribeItemPathParams';export * from './userNotification';export * from './userNotificationAllOf';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 a413bfb0d4..3ba093ba63 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@@ -4,12 +4,11 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { String } from './string';import type { InviteToTeamMetadataRole } from './inviteToTeamMetadataRole';export interface InviteToTeamMetadata {/** The user who sent the invitation */- invitedBy: String;+ invitedBy: string;/** Role/permission level in the team */role?: InviteToTeamMetadataRole;/** The unique identifier of the team */diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedMetadata.tsindex 8386173b36..25d724e191 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedMetadata.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedMetadata.ts@@ -7,7 +7,6 @@import type { ItemSharedMetadataItemName } from './itemSharedMetadataItemName';import type { EntityType } from './entityType';import type { ItemSharedMetadataPermissionLevel } from './itemSharedMetadataPermissionLevel';-import type { String } from './string';/*** Metadata for when a item is shared with a user@@ -21,7 +20,7 @@ export interface ItemSharedMetadata {itemType: EntityType;/** Permission level granted (read, write, admin, etc.) */permissionLevel?: ItemSharedMetadataPermissionLevel;- sharedBy: String;+ sharedBy: string;/** List of user IDs that the item is shared with */userIds: string[];}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadata.tsindex 15b1a46c7b..336d8a4e72 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadata.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadata.ts@@ -7,7 +7,6 @@import type { ItemSharedOrganizationMetadataItemName } from './itemSharedOrganizationMetadataItemName';import type { EntityType } from './entityType';import type { ItemSharedOrganizationMetadataPermissionLevel } from './itemSharedOrganizationMetadataPermissionLevel';-import type { String } from './string';/*** Metadata for when a item is shared with an organization@@ -24,5 +23,5 @@ export interface ItemSharedOrganizationMetadata {/** Permission level granted (read, write, admin, etc.) */permissionLevel?: ItemSharedOrganizationMetadataPermissionLevel;/** The user who shared the item */- sharedBy: String;+ sharedBy: string;}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEvent.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEvent.tsindex 63b334b52a..c629d218ef 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEvent.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEvent.ts@@ -15,5 +15,6 @@ import type { NotificationEventOneOfOnefive } from './notificationEventOneOfOnefimport type { NotificationEventOneOfOneseven } from './notificationEventOneOfOneseven';import type { NotificationEventOneOfOnenine } from './notificationEventOneOfOnenine';import type { NotificationEventOneOfTwoone } from './notificationEventOneOfTwoone';+import type { NotificationEventOneOfTwothree } from './notificationEventOneOfTwothree';-export type NotificationEvent = NotificationEventOneOf | NotificationEventOneOfThree | NotificationEventOneOfFive | NotificationEventOneOfSeven | NotificationEventOneOfNine | NotificationEventOneOfOneone | NotificationEventOneOfOnethree | NotificationEventOneOfOnefive | NotificationEventOneOfOneseven | NotificationEventOneOfOnenine | NotificationEventOneOfTwoone;+export type NotificationEvent = NotificationEventOneOf | NotificationEventOneOfThree | NotificationEventOneOfFive | NotificationEventOneOfSeven | NotificationEventOneOfNine | NotificationEventOneOfOneone | NotificationEventOneOfOnethree | NotificationEventOneOfOnefive | NotificationEventOneOfOneseven | NotificationEventOneOfOnenine | NotificationEventOneOfTwoone | NotificationEventOneOfTwothree;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothree.tsnew file mode 100644index 0000000000..957b77f583--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothree.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { NotificationEventOneOfTwothreeNotificationEventType } from './notificationEventOneOfTwothreeNotificationEventType';+import type { TaskAssignedMetadata } from './taskAssignedMetadata';++/**+ * A user was assigned to a task+ */+export type NotificationEventOneOfTwothree = {+ notificationEventType: NotificationEventOneOfTwothreeNotificationEventType;+ /** A user was assigned to a task */+ notificationMetadata: TaskAssignedMetadata;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothreeNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothreeNotificationEventType.tsnew file mode 100644index 0000000000..71f67197a5--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothreeNotificationEventType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++export type NotificationEventOneOfTwothreeNotificationEventType = typeof NotificationEventOneOfTwothreeNotificationEventType[keyof typeof NotificationEventOneOfTwothreeNotificationEventType];+++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotificationEventOneOfTwothreeNotificationEventType = {+ task_assigned: 'task_assigned',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventType.tsindex 72e7bb6808..0641937dbb 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventType.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventType.ts@@ -24,4 +24,5 @@ export const NotificationEventType = {new_email: 'new_email',invite_to_team: 'invite_to_team',reject_team_invite: 'reject_team_invite',+ task_assigned: 'task_assigned',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/taskAssignedMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/taskAssignedMetadata.tsnew file mode 100644index 0000000000..790bd4f870--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/taskAssignedMetadata.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { TaskAssignedMetadataTaskName } from './taskAssignedMetadataTaskName';++/**+ * Metadata for when a user is assigned to a task+ */+export interface TaskAssignedMetadata {+ /** The user who assigned the task */+ assignedBy: string;+ /** The unique identifier of the task */+ taskId: string;+ /** The name of the task (optional) */+ taskName?: TaskAssignedMetadataTaskName;+}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/string.ts b/js/app/packages/service-clients/service-notification/generated/schemas/taskAssignedMetadataTaskName.tssimilarity index 55%rename from js/app/packages/service-clients/service-notification/generated/schemas/string.tsrename to js/app/packages/service-clients/service-notification/generated/schemas/taskAssignedMetadataTaskName.tsindex 6c6d63e422..527ab35af9 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/string.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/taskAssignedMetadataTaskName.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 0.1.0*/-export type String = string;+/**+ * The name of the task (optional)+ */+export type TaskAssignedMetadataTaskName = string | null;diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex 82ab46ade5..9849cdffaf 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -747,9 +747,7 @@{"type": "object","required": ["invitedBy"],- "properties": {- "invitedBy": { "$ref": "#/components/schemas/String" }- }+ "properties": { "invitedBy": { "type": "string" } }}],"description": "Metadata for when a user is invited to a channel"@@ -796,7 +794,7 @@"description": "The message id"},"sender": {- "$ref": "#/components/schemas/String",+ "type": "string","description": "The user who sent the message"}}@@ -893,7 +891,7 @@"description": "The file type of the document"},"owner": {- "$ref": "#/components/schemas/String",+ "type": "string","description": "The owner of the document"}}@@ -960,7 +958,7 @@"required": ["teamName", "teamId", "invitedBy"],"properties": {"invitedBy": {- "$ref": "#/components/schemas/String",+ "type": "string","description": "The user who sent the invitation"},"role": {@@ -998,7 +996,7 @@"type": ["string", "null"],"description": "Permission level granted (read, write, admin, etc.)"},- "sharedBy": { "$ref": "#/components/schemas/String" },+ "sharedBy": { "type": "string" },"userIds": {"type": "array","items": { "type": "string" },@@ -1033,7 +1031,7 @@"description": "Permission level granted (read, write, admin, etc.)"},"sharedBy": {- "$ref": "#/components/schemas/String",+ "type": "string","description": "The user who shared the item"}}@@ -1238,6 +1236,21 @@"enum": ["reject_team_invite"]}}+ },+ {+ "type": "object",+ "description": "A user was assigned to a task",+ "required": ["notificationMetadata", "notificationEventType"],+ "properties": {+ "notificationEventType": {+ "type": "string",+ "enum": ["task_assigned"]+ },+ "notificationMetadata": {+ "$ref": "#/components/schemas/TaskAssignedMetadata",+ "description": "A user was assigned to a task"+ }+ }}]},@@ -1255,7 +1268,8 @@"channel_message_document","new_email","invite_to_team",- "reject_team_invite"+ "reject_team_invite",+ "task_assigned"]},"NotificationServiceApiVersion": { "type": "string", "enum": ["v1"] },@@ -1288,7 +1302,25 @@}]},- "String": { "type": "string" },+ "TaskAssignedMetadata": {+ "type": "object",+ "description": "Metadata for when a user is assigned to a task",+ "required": ["taskId", "assignedBy"],+ "properties": {+ "assignedBy": {+ "type": "string",+ "description": "The user who assigned the task"+ },+ "taskId": {+ "type": "string",+ "description": "The unique identifier of the task"+ },+ "taskName": {+ "type": ["string", "null"],+ "description": "The name of the task (optional)"+ }+ }+ },"UnsubscribeItemPathParams": {"type": "object","required": ["item_type", "item_id"],diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 7ac584a5f2..62196bdfaa 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -6594,11 +6594,16 @@ dependencies = ["anyhow","comms_service_client","email_db_client",+ "futures","macro_db_client","macro_db_migrator","macro_middleware",+ "macro_notify",+ "macro_user_id","macro_uuid","mockall",+ "model-entity",+ "model_notifications","models_permissions","models_properties","serde_json",@@ -6648,6 +6653,7 @@ dependencies = ["macro_entrypoint","macro_env","macro_middleware",+ "macro_notify","macro_uuid","model","models_permissions",diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 88e241f200..8086942469 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -8,7 +8,9 @@ use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::Fuse macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;use macro_redis_cluster_client::Redis;-use properties::{PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl};+use properties::{+ NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,+};use soup::{domain::service::SoupImpl, inbound::axum_router::SoupRouterState,outbound::pg_soup_repo::PgSoupRepo,@@ -33,7 +35,8 @@ type DssSoupState = SoupRouterState<>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;-type PropertiesService = PropertiesServiceImpl<PropertiesPgRepo, PermissionServiceImpl>;+type PropertiesService =+ PropertiesServiceImpl<PropertiesPgRepo, PermissionServiceImpl, NotificationServiceImpl>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex c36d0eff40..e63f674cad 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -16,7 +16,9 @@ use macro_entrypoint::MacroEntrypoint;use macro_env_var::env_var;use macro_middleware::auth::internal_access::InternalApiSecretKey;use macro_redis_cluster_client::Redis;-use properties::{PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl};+use properties::{+ NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,+};use secretsmanager_client::SecretManager;use soup::{domain::service::SoupImpl, inbound::axum_router::SoupRouterState,@@ -195,8 +197,12 @@ async fn main() -> anyhow::Result<()> {config.vars.comms_service_url.as_ref().to_string(),),);- let properties_service =- PropertiesServiceImpl::new(PropertiesPgRepo::new(db.clone()), Some(permission_checker));+ let notification_service = NotificationServiceImpl::new(Arc::new(macro_notify_client.clone()));+ let properties_service = PropertiesServiceImpl::new(+ PropertiesPgRepo::new(db.clone()),+ Some(permission_checker),+ Some(notification_service),+ );let api_context = ApiContext {soup_router_state: SoupRouterState::new(SoupImpl::new(diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex ee754fbf84..c7eaafddc2 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -49,6 +49,8 @@ pub enum NotificationEvent {InviteToTeam(InviteToTeamMetadata),/// A team invite was rejectedRejectTeamInvite,+ /// A user was assigned to a task+ TaskAssigned(TaskAssignedMetadata),}#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]@@ -73,6 +75,7 @@ impl NotificationEvent {NotificationEvent::NewEmail(meta) => serde_json::to_value(meta).ok(),NotificationEvent::InviteToTeam(meta) => serde_json::to_value(meta).ok(),NotificationEvent::RejectTeamInvite => None,+ NotificationEvent::TaskAssigned(meta) => serde_json::to_value(meta).ok(),}}@@ -116,6 +119,7 @@ impl NotificationEvent {None => Ok(Self::RejectTeamInvite),Some(_) => Err(anyhow::anyhow!("RejectTeamInvite should not have metadata")),},+ TaskAssigned => deserialize_meta!(TaskAssigned),}}}diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex db35d1eb7f..dee3543f7c 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -186,6 +186,22 @@ pub struct NewEmailMetadata {pub snippet: String,}+/// Metadata for when a user is assigned to a task+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct TaskAssignedMetadata {+ /// The unique identifier of the task+ #[serde(alias = "task_id")]+ pub task_id: String,+ /// The name of the task (optional)+ #[serde(alias = "task_name")]+ pub task_name: Option<String>,+ /// The user who assigned the task+ #[serde(alias = "assigned_by")]+ #[schema(value_type = String)]+ pub assigned_by: MacroUserIdStr<'static>,+}+pub trait NotificationMetadata: Serialize + DeserializeOwned + Clone + Sized {fn event_type() -> NotificationEventType;@@ -232,3 +248,4 @@ impl_notification_metadata!(NotificationEventType::ChannelMessageReply);impl_notification_metadata!(NewEmailMetadata, NotificationEventType::NewEmail);+impl_notification_metadata!(TaskAssignedMetadata, NotificationEventType::TaskAssigned);diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rsindex bc6e46ee9f..2103831efd 100644--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs@@ -6,7 +6,7 @@ use model::document::{FileType, FileTypeExt};use model_notifications::NotificationWithRecipient;use model_notifications::{ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,- ChannelReplyMetadata, DocumentMentionMetadata,+ ChannelReplyMetadata, DocumentMentionMetadata, TaskAssignedMetadata,};use models_comms::ChannelType;use sns_client::{APNSPushNotification, Aps};@@ -179,6 +179,13 @@ pub fn generate_apns_notification<T: XmlFormatter>(model_notifications::NotificationEvent::NewEmail(_new_email_metadata) => None,model_notifications::NotificationEvent::InviteToTeam(_invite_to_team_metadata) => None,model_notifications::NotificationEvent::RejectTeamInvite => None,+ model_notifications::NotificationEvent::TaskAssigned(task_assigned_metadata) => Some(+ task_assigned_metadata+ .build_apns_notification::<T>(parse_user()?)?+ .map(|()| {+ create_push_data(Route(format!("/task/{}", task_assigned_metadata.task_id)))+ }),+ ),})}@@ -314,3 +321,33 @@ impl BuildNotification for ChannelInviteMetadata {})}}++impl BuildNotification for TaskAssignedMetadata {+ type Ctx<'a> = MacroUserIdStr<'a>;++ fn build_apns_notification<T: XmlFormatter>(+ &self,+ ctx: Self::Ctx<'_>,+ ) -> Result<APNSPushNotification<()>, NotificationErr> {+ let assigner_email = ctx.email_part().email_str().to_string();+ let title = assigner_email;++ let body = if let Some(ref task_name) = self.task_name {+ format!("assigned you to {}", task_name)+ } else {+ "assigned you a task".to_string()+ };++ Ok(APNSPushNotification {+ aps: Aps {+ alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {+ title: Some(title),+ body: Some(body.to_string()),+ ..Default::default()+ })),+ ..Default::default()+ },+ push_notification_data: (),+ })+ }+}diff --git a/rust/cloud-storage/properties/Cargo.toml b/rust/cloud-storage/properties/Cargo.tomlindex aaa7656810..a2ef3a6b9a 100644--- a/rust/cloud-storage/properties/Cargo.toml+++ b/rust/cloud-storage/properties/Cargo.toml@@ -7,10 +7,15 @@ version = "0.1.0"[dependencies]anyhow = { workspace = true }comms_service_client = { path = "../comms_service_client" }+futures = { workspace = true }email_db_client = { path = "../email_db_client" }macro_db_client = { path = "../macro_db_client" }macro_middleware = { path = "../macro_middleware", default-features = false, features = ["cloud_storage", "user_permissions"] }+macro_notify = { path = "../macro_notify" }+macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }+model_notifications = { path = "../model_notifications" }+model-entity = { path = "../model-entity" }models_permissions = { path = "../models_permissions" }models_properties = { path = "../models_properties" }serde_json = { workspace = true }diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsindex 04c459dd46..9de91333bb 100644--- a/rust/cloud-storage/properties/src/domain/ports.rs+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -86,6 +86,14 @@ pub trait PropertiesRepo: Send + Sync + 'static {entity_type: EntityType,property_definition_id: Uuid,) -> impl Future<Output = Result<Option<PropertyValue>, Self::Err>> + Send;++ /// Get the name of a document.+ /// Returns `None` if the document doesn't exist or has no name.+ /// Tasks are stored as documents, so this works for both documents and tasks.+ fn get_document_name(+ &self,+ id: &str,+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;}/// Permission service trait for entity access control.@@ -113,3 +121,19 @@ pub trait PermissionService: Send + Sync + 'static {task_id: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;}++/// Notification service trait for sending notifications.+///+/// This trait abstracts notification operations, allowing for different implementations+/// (e.g., macro_notify-backed, mock for testing).+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+pub trait NotificationService: Send + Sync + 'static {+ type Err;++ /// Send a notification message.+ /// Returns the notification ID if successful.+ fn send_notification(+ &self,+ message: model_notifications::NotificationQueueMessage,+ ) -> impl Future<Output = Result<uuid::Uuid, Self::Err>> + Send;+}diff --git a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rsindex 0ec2bba487..9237f72638 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs@@ -11,32 +11,40 @@ use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;use super::error::PropertiesErr;-use super::ports::{PermissionService, PropertiesRepo};+use super::ports::{NotificationService, PermissionService, PropertiesRepo};use super::service::PropertiesService;use helpers::{extract_option_ids_from_property_value, is_property_applicable_to};/// Implementation of PropertiesService using a repository and optional permission service.#[derive(Debug)]-pub struct PropertiesServiceImpl<R, P>+pub struct PropertiesServiceImpl<R, P, N>whereR: PropertiesRepo,P: PermissionService,+ N: NotificationService,{repository: R,permission_service: Option<P>,+ notification_service: Option<N>,}-impl<R, P> PropertiesServiceImpl<R, P>+impl<R, P, N> PropertiesServiceImpl<R, P, N>whereR: PropertiesRepo,P: PermissionService,+ N: NotificationService,{- /// Create a new PropertiesService with an optional permission service.- pub fn new(repository: R, permission_service: Option<P>) -> Self {+ /// Create a new PropertiesService with optional permission service and notification service.+ pub fn new(+ repository: R,+ permission_service: Option<P>,+ notification_service: Option<N>,+ ) -> Self {Self {repository,permission_service,+ notification_service,}}@@ -79,11 +87,12 @@ where}}-impl<R, P> PropertiesService for PropertiesServiceImpl<R, P>+impl<R, P, N> PropertiesService for PropertiesServiceImpl<R, P, N>whereR: PropertiesRepo,P: PermissionService,- anyhow::Error: From<R::Err> + From<P::Err>,+ N: NotificationService,+ anyhow::Error: From<R::Err> + From<P::Err> + From<N::Err>,{#[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type))]async fn set_system_property_status_complete(@@ -248,7 +257,7 @@ where.await;}SystemPropertyKey::ASSIGNEES_UUID if entity_type == EntityType::Task => {- self.handle_task_assignees_property(entity_id, value)+ self.handle_task_assignees_property(entity_id, value, user_id).await?;}_ => {diff --git a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rsindex 921f4ec55c..032777cf21 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs@@ -1,23 +1,26 @@//! Task-specific property handlers.+use futures::future::join_all;+use macro_user_id::cowlike::CowLike;use models_properties::EntityType;use models_properties::api::requests::SetPropertyValue;+use models_properties::service::property_value::PropertyValue;use system_properties::SystemPropertyKey;use uuid::Uuid;use crate::domain::error::PropertiesErr;-use crate::domain::ports::{PermissionService, PropertiesRepo};+use crate::domain::ports::{NotificationService, PermissionService, PropertiesRepo};use crate::domain::service::PropertiesService;use crate::domain::service_impl::PropertiesServiceImpl;-impl<R, P> PropertiesServiceImpl<R, P>+impl<R, P, N> PropertiesServiceImpl<R, P, N>whereR: PropertiesRepo,P: PermissionService,- anyhow::Error: From<R::Err> + From<P::Err>,+ N: NotificationService,+ anyhow::Error: From<R::Err> + From<P::Err> + From<N::Err>,{/// Handle task relationship properties (Parent Task / Subtasks) with bidirectional linking.- /// Entity type is guaranteed to be Task (enforced by match guard).pub async fn handle_task_relationship_property(&self,entity_id: &str,@@ -29,7 +32,6 @@ wherematch property_definition_id {SystemPropertyKey::PARENT_TASK_UUID => {- // Extract parent task ID (None to clear)let parent_task_id = match &value {None => None,Some(SetPropertyValue::EntityReference { reference }) => {@@ -52,7 +54,6 @@ wherePropertiesService::link_parent_task(self, task_id, parent_task_id).await?;}SystemPropertyKey::SUBTASKS_UUID => {- // Extract subtask IDs (empty to clear)let subtask_ids = match &value {None => vec![],Some(SetPropertyValue::MultiEntityReference { references }) => {@@ -79,7 +80,6 @@ wherePropertiesService::link_subtasks(self, task_id, subtask_ids).await?;}_ => {- // This should never happen due to the match guard, but handle it for completenessreturn Err(PropertiesErr::Validation("Invalid property for task relationship handling".to_string(),));@@ -90,18 +90,14 @@ where}/// Handle task assignees property with permissions.- /// Assignees is a multi-select entity property, so only accepts MultiEntityReference.- /// If value is None (clearing assignees), there's nothing to do for permissions.pub async fn handle_task_assignees_property(&self,entity_id: &str,value: Option<SetPropertyValue>,+ assigned_by_user_id: &str,) -> Result<(), PropertiesErr> {- // Clearing assignees - nothing to do for permissionslet Some(SetPropertyValue::MultiEntityReference { references }) = &value else {if value.is_some() {- // Assignees is multi-select, so only MultiEntityReference is valid- // This should be caught by validate_compatibility, but handle it here for safetyreturn Err(PropertiesErr::Validation("Assignees requires multiple entity references".to_string(),));@@ -119,11 +115,120 @@ whereself.handle_task_assignee_permissions(task_id, &assignee_ids).await?;+ self.handle_task_assignee_notifications(task_id, &assignee_ids, assigned_by_user_id)+ .await?;+ Ok(())+ }++ /// Handle notifications when task assignees are updated.+ pub async fn handle_task_assignee_notifications(+ &self,+ task_id: Uuid,+ assignee_ids: &[String],+ assigned_by_user_id: &str,+ ) -> Result<(), PropertiesErr> {+ if assignee_ids.is_empty() {+ return Ok(());+ }++ let notification_service = match &self.notification_service {+ Some(service) => service,+ None => {+ tracing::debug!("notification service not available, skipping notifications");+ return Ok(());+ }+ };++ let current_value = self+ .repository+ .get_entity_property_value(+ &task_id.to_string(),+ EntityType::Task,+ SystemPropertyKey::ASSIGNEES_UUID,+ )+ .await+ .map_err(anyhow::Error::from)+ .map_err(PropertiesErr::Repo)?;++ let current_assignee_ids: Vec<String> = match current_value {+ Some(PropertyValue::EntityRef(refs)) => {+ refs.iter().map(|r| r.entity_id.clone()).collect()+ }+ _ => vec![],+ };++ let recipient_ids: Vec<String> = assignee_ids+ .iter()+ .filter(|id| !current_assignee_ids.contains(id) && id.as_str() != assigned_by_user_id)+ .cloned()+ .collect();++ if recipient_ids.is_empty() {+ tracing::debug!("no new assignees to notify");+ return Ok(());+ }++ let task_name = self+ .repository+ .get_document_name(&task_id.to_string())+ .await+ .map_err(anyhow::Error::from)+ .map_err(PropertiesErr::Repo)?;++ let assigned_by =+ macro_user_id::user_id::MacroUserIdStr::parse_from_str(assigned_by_user_id)+ .map_err(|e| PropertiesErr::Validation(format!("Invalid user ID format: {}", e)))?+ .into_owned();++ let metadata = model_notifications::TaskAssignedMetadata {+ task_id: task_id.to_string(),+ task_name: task_name.clone(),+ assigned_by: assigned_by.clone(),+ };++ let notification_event = model_notifications::NotificationEvent::TaskAssigned(metadata);++ let notification_entity =+ model_entity::EntityType::Document.with_entity_string(task_id.to_string());++ let notification_futures: Vec<_> = recipient_ids+ .iter()+ .map(|recipient_id| {+ let message = model_notifications::NotificationQueueMessage {+ notification_entity: notification_entity.clone(),+ notification_event: notification_event.clone(),+ sender_id: Some(assigned_by.clone()),+ recipient_ids: Some(vec![recipient_id.clone()]),+ };++ let recipient_id_for_log = recipient_id.clone();+ async move {+ let send_result = notification_service.send_notification(message).await;+ match send_result {+ Ok(notification_id) => {+ tracing::debug!(+ recipient_id = %recipient_id_for_log,+ notification_id = %notification_id,+ "sent task assignment notification"+ );+ }+ Err(_e) => {+ tracing::error!(+ recipient_id = %recipient_id_for_log,+ "failed to send task assignment notification"+ );+ }+ }+ }+ })+ .collect();++ join_all(notification_futures).await;+Ok(())}/// Handle permissions when task assignees are updated.- /// Grants edit permissions to all assignees so they can edit the task.pub async fn handle_task_assignee_permissions(&self,task_id: Uuid,diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rsindex 387717c557..0fd1b01c61 100644--- a/rust/cloud-storage/properties/src/domain/test.rs+++ b/rust/cloud-storage/properties/src/domain/test.rs@@ -2,13 +2,11 @@use super::service_impl::PropertiesServiceImpl;use crate::domain::{- ports::{MockPermissionService, MockPropertiesRepo},+ ports::{MockNotificationService, MockPermissionService, MockPropertiesRepo},service::PropertiesService,};use anyhow::anyhow;-use models_properties::{- EntityType, service::property_value::PropertyValue, shared::EntityReference,-};+use models_properties::{EntityType, service::property_value::PropertyValue};use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;@@ -45,7 +43,11 @@ async fn test_set_system_property_status_complete_happy_path() {}).returning(|_, _, _, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let entity_id = "e1";let entity_type = EntityType::Document;@@ -64,7 +66,11 @@ async fn test_set_system_property_status_complete_error_path() {repo.expect_update_entity_property_value_if_exists().returning(|_, _, _, _| Box::pin(async { Err(anyhow!("boom")) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let err = service.set_system_property_status_complete("e1", EntityType::Document)@@ -89,7 +95,11 @@ async fn test_link_parent_task_delegates_to_repo() {.withf(move |t, p| *t == task_id && *p == Some(parent_id)).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );service.link_parent_task(task_id, Some(parent_id))@@ -107,7 +117,11 @@ async fn test_link_parent_task_clear_parent() {.withf(move |t, p| *t == task_id && p.is_none()).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );service.link_parent_task(task_id, None).await.unwrap();}@@ -119,7 +133,11 @@ async fn test_link_parent_task_error_propagates() {repo.expect_link_parent_task().returning(|_, _| Box::pin(async { Err(anyhow!("link failed")) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let err = service.link_parent_task(Uuid::nil(), Some(Uuid::nil()))@@ -147,7 +165,11 @@ async fn test_link_subtasks_delegates_to_repo() {}).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );service.link_subtasks(task_id, vec![subtask_1, subtask_2])@@ -165,7 +187,11 @@ async fn test_link_subtasks_clear_all() {.withf(move |t, s| *t == task_id && s.is_empty()).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );service.link_subtasks(task_id, vec![]).await.unwrap();}@@ -176,7 +202,11 @@ async fn test_link_subtasks_error_propagates() {repo.expect_link_subtasks().returning(|_, _| Box::pin(async { Err(anyhow!("subtask link failed")) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let err = service.link_subtasks(Uuid::nil(), vec![Uuid::nil()])@@ -202,7 +232,11 @@ async fn test_get_property_value_returns_value_when_exists() {}).returning(|_, _, _| Box::pin(async { Ok(Some(PropertyValue::Str("hello".to_string()))) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let result = service.get_property_value("e1", EntityType::Document, prop_id)@@ -219,7 +253,11 @@ async fn test_get_property_value_returns_none_when_not_attached() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Ok(None) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let result = service.get_property_value("e1", EntityType::Document, Uuid::nil())@@ -236,7 +274,11 @@ async fn test_get_property_value_error_path() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Err(anyhow!("db error")) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let err = service.get_property_value("e1", EntityType::Document, Uuid::nil())@@ -268,7 +310,11 @@ async fn test_get_system_property_value_returns_value_when_exists() {})});- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let result = service.get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)@@ -290,7 +336,11 @@ async fn test_get_system_property_value_returns_none_when_not_attached() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Ok(None) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let result = service.get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)@@ -307,7 +357,11 @@ async fn test_get_system_property_value_error_path() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Err(anyhow!("db error")) }));- let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));+ let service = PropertiesServiceImpl::new(+ repo,+ Some(create_mock_permission_service()),+ None::<MockNotificationService>,+ );let err = service.get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)@@ -339,7 +393,8 @@ async fn test_handle_task_assignee_permissions_grants_permissions() {}).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo, Some(perm_service));+ let service =+ PropertiesServiceImpl::new(repo, Some(perm_service), None::<MockNotificationService>);service.handle_task_assignee_permissions(task_id, &assignee_ids)@@ -354,7 +409,8 @@ async fn test_handle_task_assignee_permissions_empty_assignees() {let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);- let service = PropertiesServiceImpl::new(repo, Some(perm_service));+ let service =+ PropertiesServiceImpl::new(repo, Some(perm_service), None::<MockNotificationService>);// Should return Ok without calling permission serviceservice@@ -369,7 +425,11 @@ async fn test_handle_task_assignee_permissions_no_service() {let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);let assignee_ids = vec!["user1".to_string()];- let service = PropertiesServiceImpl::new(repo, None::<MockPermissionService>);+ let service = PropertiesServiceImpl::new(+ repo,+ None::<MockPermissionService>,+ None::<MockNotificationService>,+ );let err = service.handle_task_assignee_permissions(task_id, &assignee_ids)@@ -394,7 +454,8 @@ async fn test_handle_task_assignee_permissions_error_propagates() {.expect_grant_permissions_to_task().returning(|_, _| Box::pin(async { Err(anyhow!("permission error")) }));- let service = PropertiesServiceImpl::new(repo, Some(perm_service));+ let service =+ PropertiesServiceImpl::new(repo, Some(perm_service), None::<MockNotificationService>);let err = service.handle_task_assignee_permissions(task_id, &assignee_ids)@@ -404,18 +465,227 @@ async fn test_handle_task_assignee_permissions_error_propagates() {assert_eq!(err.to_string(), "permission error");}+// ============================================================================+// handle_task_assignee_notifications unit tests+// ============================================================================++struct NotificationTestCase {+ task_id: Uuid,+ assigned_by: String,+ assignees: Vec<String>,+ existing_assignees: Vec<String>,+ task_name: Option<String>,+ expected_notification_count: usize,+ expected_recipient_ids: Option<Vec<String>>,+ notification_service_available: bool,+}++async fn check_notifications(test_case: NotificationTestCase) {+ let mut repo = MockPropertiesRepo::new();+ let mut notif_service = MockNotificationService::new();++ let task_id = test_case.task_id;+ let assigned_by = test_case.assigned_by.clone();+ let assignees = test_case.assignees.clone();+ let existing_assignees = test_case.existing_assignees.clone();+ let task_name = test_case.task_name.clone();++ // Mock: get current assignees+ repo.expect_get_entity_property_value()+ .withf(move |entity_id, entity_type, prop_id| {+ entity_id == &task_id.to_string()+ && *entity_type == EntityType::Task+ && *prop_id == SystemPropertyKey::ASSIGNEES_UUID+ })+ .returning({+ let existing = existing_assignees.clone();+ move |_, _, _| {+ if existing.is_empty() {+ Box::pin(async { Ok(None) })+ } else {+ let refs: Vec<models_properties::shared::EntityReference> = existing+ .iter()+ .map(|id| models_properties::shared::EntityReference {+ entity_type: EntityType::User,+ entity_id: id.clone(),+ specific_message_id: None,+ })+ .collect();+ Box::pin(async { Ok(Some(PropertyValue::EntityRef(refs))) })+ }+ }+ });++ // Mock: get task name (only if we expect notifications)+ if test_case.expected_notification_count > 0 {+ let task_id_clone = task_id;+ let task_name_result = task_name.clone();+ repo.expect_get_document_name()+ .withf(move |id| id == &task_id_clone.to_string())+ .returning(move |_| {+ let name = task_name_result.clone();+ Box::pin(async move { Ok(name) })+ });+ }++ // Mock: send notifications+ if test_case.notification_service_available && test_case.expected_notification_count > 0 {+ let expected_count = test_case.expected_notification_count;+ let expected_recipients = test_case.expected_recipient_ids.clone();+ notif_service+ .expect_send_notification()+ .times(expected_count)+ .withf(move |message| {+ let event_type_correct = message.notification_event.event_type()+ == model_notifications::NotificationEventType::TaskAssigned;+ let recipient_correct = if let Some(expected) = &expected_recipients {+ message+ .recipient_ids+ .as_ref()+ .map(|ids| ids.len() == 1 && expected.contains(&ids[0]))+ .unwrap_or(false)+ } else {+ message+ .recipient_ids+ .as_ref()+ .map(|ids| ids.len() == 1)+ .unwrap_or(false)+ };+ event_type_correct && recipient_correct+ })+ .returning(|_| Box::pin(async { Ok(Uuid::new_v4()) }));+ }++ let service = if test_case.notification_service_available {+ PropertiesServiceImpl::new(repo, None::<MockPermissionService>, Some(notif_service))+ } else {+ PropertiesServiceImpl::new(+ repo,+ None::<MockPermissionService>,+ None::<MockNotificationService>,+ )+ };++ service+ .handle_task_assignee_notifications(task_id, &assignees, &assigned_by)+ .await+ .unwrap();+}++#[tokio::test]+async fn test_handle_task_assignee_notifications_sends_to_new_assignees_only() {+ check_notifications(NotificationTestCase {+ task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),+ assigned_by: "macro|[email protected]".to_string(),+ assignees: vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(), // existing, should not get notification+ ],+ existing_assignees: vec!["macro|[email protected]".to_string()],+ task_name: Some("Test Task".to_string()),+ expected_notification_count: 2, // user1 and user2, but not user3 (existing) or assigner+ expected_recipient_ids: None,+ notification_service_available: true,+ })+ .await;+}++#[tokio::test]+async fn test_handle_task_assignee_notifications_filters_out_assigner() {+ check_notifications(NotificationTestCase {+ task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),+ assigned_by: "macro|[email protected]".to_string(),+ assignees: vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ],+ existing_assignees: vec![],+ task_name: Some("Test Task".to_string()),+ expected_notification_count: 1, // only user1, not assigner+ expected_recipient_ids: Some(vec!["macro|[email protected]".to_string()]),+ notification_service_available: true,+ })+ .await;+}++#[tokio::test]+async fn test_handle_task_assignee_notifications_no_new_assignees() {+ check_notifications(NotificationTestCase {+ task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),+ assigned_by: "macro|[email protected]".to_string(),+ assignees: vec!["macro|[email protected]".to_string()],+ existing_assignees: vec!["macro|[email protected]".to_string()],+ task_name: None, // Should not call get_entity_name+ expected_notification_count: 0, // no new assignees+ expected_recipient_ids: None,+ notification_service_available: true,+ })+ .await;+}++#[tokio::test]+async fn test_handle_task_assignee_notifications_no_service() {+ check_notifications(NotificationTestCase {+ task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),+ assigned_by: "assigner".to_string(),+ assignees: vec!["user1".to_string()],+ existing_assignees: vec![],+ task_name: None, // Should not call get_entity_name when no service+ expected_notification_count: 0,+ expected_recipient_ids: None,+ notification_service_available: false,+ })+ .await;+}++#[tokio::test]+async fn test_handle_task_assignee_notifications_empty_assignees() {+ check_notifications(NotificationTestCase {+ task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),+ assigned_by: "assigner".to_string(),+ assignees: vec![],+ existing_assignees: vec![],+ task_name: None, // Should not call get_entity_name+ expected_notification_count: 0,+ expected_recipient_ids: None,+ notification_service_available: true,+ })+ .await;+}++#[tokio::test]+async fn test_handle_task_assignee_notifications_task_name_none() {+ check_notifications(NotificationTestCase {+ task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),+ assigned_by: "macro|[email protected]".to_string(),+ assignees: vec!["macro|[email protected]".to_string()],+ existing_assignees: vec![],+ task_name: None, // task doesn't exist yet+ expected_notification_count: 1,+ expected_recipient_ids: None,+ notification_service_available: true,+ })+ .await;+}+// ============================================================================// handle_task_assignees_property integration tests// ============================================================================#[tokio::test]-async fn test_handle_task_assignees_property_calls_permission_handler() {+async fn test_handle_task_assignees_property_calls_both_handlers() {let mut repo = MockPropertiesRepo::new();let mut perm_service = MockPermissionService::new();+ let mut notif_service = MockNotificationService::new();let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);let entity_id = task_id.to_string();- let assignees = vec!["user1".to_string(), "user2".to_string()];+ let assigned_by = "macro|[email protected]".to_string();+ let assignees = vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ];let value = Some(models_properties::api::requests::SetPropertyValue::MultiEntityReference {@@ -430,6 +700,14 @@ async fn test_handle_task_assignees_property_calls_permission_handler() {},);+ // Mock: no existing assignees+ repo.expect_get_entity_property_value()+ .returning(|_, _, _| Box::pin(async { Ok(None) }));++ // Mock: get task name+ repo.expect_get_document_name()+ .returning(|_| Box::pin(async { Ok(Some("Test Task".to_string())) }));+// Mock: permissions should be granted to all assigneeslet entity_id_clone = entity_id.clone();perm_service@@ -438,10 +716,16 @@ async fn test_handle_task_assignees_property_calls_permission_handler() {.withf(move |user_ids, tid| user_ids.len() == 2 && tid == &entity_id_clone).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo, Some(perm_service));+ // Mock: notifications should be sent+ notif_service+ .expect_send_notification()+ .times(2) // user1 and user2+ .returning(|_| Box::pin(async { Ok(Uuid::new_v4()) }));++ let service = PropertiesServiceImpl::new(repo, Some(perm_service), Some(notif_service));service- .handle_task_assignees_property(&entity_id, value)+ .handle_task_assignees_property(&entity_id, value, &assigned_by).await.unwrap();}@@ -450,15 +734,16 @@ async fn test_handle_task_assignees_property_calls_permission_handler() {async fn test_handle_task_assignees_property_clearing_assignees() {let repo = MockPropertiesRepo::new();let perm_service = MockPermissionService::new();+ let notif_service = MockNotificationService::new();let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);let entity_id = task_id.to_string();- let service = PropertiesServiceImpl::new(repo, Some(perm_service));+ let service = PropertiesServiceImpl::new(repo, Some(perm_service), Some(notif_service));// Should return Ok without calling any handlersservice- .handle_task_assignees_property(&entity_id, None)+ .handle_task_assignees_property(&entity_id, None, "assigner").await.unwrap();}diff --git a/rust/cloud-storage/properties/src/lib.rs b/rust/cloud-storage/properties/src/lib.rsindex 2bec390dba..96b61e7ddd 100644--- a/rust/cloud-storage/properties/src/lib.rs+++ b/rust/cloud-storage/properties/src/lib.rs@@ -14,8 +14,9 @@ pub mod domain;pub mod outbound;pub use domain::error::PropertiesErr;-pub use domain::ports::{PermissionService, PropertiesRepo};+pub use domain::ports::{NotificationService, PermissionService, PropertiesRepo};pub use domain::service::PropertiesService;pub use domain::service_impl::PropertiesServiceImpl;+pub use outbound::notification_service::NotificationServiceImpl;pub use outbound::permission_service::PermissionServiceImpl;pub use outbound::properties_pg_repo::PropertiesPgRepo;diff --git a/rust/cloud-storage/properties/src/outbound.rs b/rust/cloud-storage/properties/src/outbound.rsindex 171a153252..24006b3c45 100644--- a/rust/cloud-storage/properties/src/outbound.rs+++ b/rust/cloud-storage/properties/src/outbound.rs@@ -1,4 +1,5 @@pub mod entity_property_queries;+pub mod notification_service;pub mod permission_service;pub mod properties_pg_repo;pub mod property_definition_queries;diff --git a/rust/cloud-storage/properties/src/outbound/notification_service.rs b/rust/cloud-storage/properties/src/outbound/notification_service.rsnew file mode 100644index 0000000000..ae794b999b--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/notification_service.rs@@ -0,0 +1,30 @@+//! Notification service implementation for properties.++use uuid::Uuid;++use crate::domain::ports::NotificationService;++/// Notification service implementation using macro_notify client.+pub struct NotificationServiceImpl {+ notification_client: std::sync::Arc<macro_notify::MacroNotifyClient>,+}++impl NotificationServiceImpl {+ pub fn new(notification_client: std::sync::Arc<macro_notify::MacroNotifyClient>) -> Self {+ Self {+ notification_client,+ }+ }+}++impl NotificationService for NotificationServiceImpl {+ type Err = anyhow::Error;++ #[tracing::instrument(skip(self), err)]+ async fn send_notification(+ &self,+ message: model_notifications::NotificationQueueMessage,+ ) -> Result<Uuid, Self::Err> {+ self.notification_client.send_notification(message).await+ }+}diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rsindex d1892721c1..580442e662 100644--- a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs@@ -132,4 +132,21 @@ impl PropertiesRepo for PropertiesPgRepo {},}}++ #[tracing::instrument(skip(self))]+ async fn get_document_name(&self, id: &str) -> Result<Option<String>, Self::Err> {+ // Tasks are stored as documents, so this works for both documents and tasks+ match macro_db_client::document::get_document_name(&self.pool, id).await {+ Ok(name) => Ok(Some(name)),+ Err(e) => {+ // If document doesn't exist, return None instead of error+ if let Some(db_err) = e.downcast_ref::<sqlx::Error>()+ && matches!(db_err, sqlx::Error::RowNotFound)+ {+ return Ok(None);+ }+ Err(e)+ }+ }+ }}diff --git a/rust/cloud-storage/properties_service/Cargo.toml b/rust/cloud-storage/properties_service/Cargo.tomlindex b04f86149c..e490e041d5 100644--- a/rust/cloud-storage/properties_service/Cargo.toml+++ b/rust/cloud-storage/properties_service/Cargo.toml@@ -33,6 +33,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"auth","cloud_storage",] }+macro_notify = { path = "../macro_notify" }macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }models_permissions = { path = "../models_permissions" }diff --git a/rust/cloud-storage/properties_service/src/api/context.rs b/rust/cloud-storage/properties_service/src/api/context.rsindex dba9b7f065..04b1d6e987 100644--- a/rust/cloud-storage/properties_service/src/api/context.rs+++ b/rust/cloud-storage/properties_service/src/api/context.rs@@ -17,6 +17,11 @@ pub struct ApiContext {pub config: Arc<Config>,pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,pub comms_service_client: Arc<CommsServiceClient>,- pub properties_service:- Arc<PropertiesServiceImpl<properties::PropertiesPgRepo, properties::PermissionServiceImpl>>,+ pub properties_service: Arc<+ PropertiesServiceImpl<+ properties::PropertiesPgRepo,+ properties::PermissionServiceImpl,+ properties::NotificationServiceImpl,+ >,+ >,}diff --git a/rust/cloud-storage/properties_service/src/main.rs b/rust/cloud-storage/properties_service/src/main.rsindex 00d7e1053c..de2034d5e5 100644--- a/rust/cloud-storage/properties_service/src/main.rs+++ b/rust/cloud-storage/properties_service/src/main.rs@@ -70,9 +70,19 @@ async fn main() -> anyhow::Result<()> {let properties_repository = properties::PropertiesPgRepo::new(db.clone());let permission_service =properties::PermissionServiceImpl::new(db.clone(), comms_service_client.clone());++ // Initialize notification service+ let notification_queue = std::env::var("NOTIFICATION_QUEUE")+ .unwrap_or_else(|_| "local-notification-queue".to_string());+ let macro_notify_client =+ macro_notify::MacroNotify::new(notification_queue, "properties_service".to_string()).await;+ let notification_service =+ properties::NotificationServiceImpl::new(Arc::new(macro_notify_client));+let properties_service = Arc::new(properties::PropertiesServiceImpl::new(properties_repository,Some(permission_service),+ Some(notification_service),));tracing::info!("initialized properties service");