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
remove dead code (#1388)
Sean Aye7d7ba3956515
diff --git a/js/app/packages/app/component/dock/Dock.tsx b/js/app/packages/app/component/dock/Dock.tsxindex 3f8e65d84b..21d5c0e3eb 100644--- a/js/app/packages/app/component/dock/Dock.tsx+++ b/js/app/packages/app/component/dock/Dock.tsx@@ -18,7 +18,6 @@ import { Hotkey } from '@core/component/Hotkey';import { setCreateMenuOpen } from '../Launcher';import { useHasPaidAccess } from '@core/auth';import { TOKENS } from '@core/hotkey/tokens';-import { QuickAccess } from './QuickAccess';import { Button } from '@ui/components/Button';import { LabelAndHotKey } from '@core/component/Tooltip';import { isMobile } from '@core/mobile/isMobile';@@ -174,7 +173,6 @@ export function Dock() {<div class="w-full"/><Show when={ENABLE_DOCK_NOTITIFCATIONS}>- <QuickAccess /><GlobalNotificationBell notificationSource={notificationSource} /></Show></div>diff --git a/js/app/packages/app/component/dock/QuickAccess.tsx b/js/app/packages/app/component/dock/QuickAccess.tsxdeleted file mode 100644index 8a1e4f134c..0000000000--- a/js/app/packages/app/component/dock/QuickAccess.tsx+++ /dev/null@@ -1,262 +0,0 @@-import {- useGlobalBlockOrchestrator,- useGlobalNotificationSource,-} from '@app/component/GlobalAppState';-import { useSplitLayout } from '@app/component/split-layout/layout';-import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';-import { useChannelsContext } from '@core/context/channels';-import { Tooltip } from '@core/component/Tooltip';-import { UserIcon } from '@core/component/UserIcon';-import {- getMetadata,- isChannelMention,- isChannelMessageReply,- notificationIsRead,- tryToTypedNotification,- type UnifiedNotification,-} from '@notifications';-import type { ApiChannelWithLatest as ChannelWithLatest } from '@service-comms/generated/models';-import { ChannelTypeEnum } from '@service-comms/client';-import { useUserId } from '@core/context/user';-import { NotificationEventType } from '@service-notification/generated/schemas';-import { createMemo, createSignal, For, Show } from 'solid-js';--// Helper functions for notification processing-function getNotificationDescription(notification: UnifiedNotification): string {- switch (notification.notificationEventType) {- case NotificationEventType.channel_mention:- return 'mentioned in';- case NotificationEventType.channel_message_reply:- return 'replied in thread';- case NotificationEventType.channel_message_send:- return 'new messages in';- default:- return 'new activity in';- }-}--function isHighPriorityNotification(- notification: UnifiedNotification-): boolean {- return (- notification.entity_type === 'channel' &&- !notificationIsRead(notification) &&- (notification.notificationEventType ===- NotificationEventType.channel_mention ||- notification.notificationEventType ===- NotificationEventType.channel_message_reply ||- notification.notificationEventType ===- NotificationEventType.channel_message_send)- );-}--type QuickAccessItemProps = {- channel: ChannelWithLatest;- notifications: UnifiedNotification[];- notificationSource: ReturnType<typeof useGlobalNotificationSource>;-};--function QuickAccessItem(props: QuickAccessItemProps) {- const userId = useUserId();- const blockOrchestrator = useGlobalBlockOrchestrator();- const { replaceOrInsertSplit } = useSplitLayout();-- const messageLocation = async (- channelId: string,- messageId: string,- threadId?: string- ) => {- const blockHandle = await blockOrchestrator.getBlockHandle(channelId);- await blockHandle?.goToLocationFromParams({- [CHANNEL_URL_PARAMS.message]: messageId,- [CHANNEL_URL_PARAMS.thread]: threadId,- });- };-- const navigateToMessage = (- channelId: string,- messageId: string,- threadId?: string- ) => {- replaceOrInsertSplit(- {- type: 'channel',- id: channelId,- },- 'quick-access'- );- messageLocation(channelId, messageId, threadId);- };-- const [currentNotificationIndex, setCurrentNotificationIndex] =- createSignal(0);-- const unreadNotifications = createMemo(() =>- props.notifications.filter((n) => !notificationIsRead(n))- );-- const goToNextNotification = async () => {- const notifications = unreadNotifications();- const index = currentNotificationIndex();- const notification = notifications[index] || notifications[0];- const channelId = notification.entity_id;-- if (isChannelMention(notification) || isChannelMessageReply(notification)) {- const typed = tryToTypedNotification(notification);- if (typed) {- const metadata = getMetadata(typed);- if (metadata && 'messageId' in metadata && metadata.messageId) {- navigateToMessage(- channelId,- metadata.messageId,- ('threadId' in metadata && metadata.threadId) || undefined- );- } else {- replaceOrInsertSplit(- { type: 'channel', id: channelId },- 'quick-access'- );- }- } else {- replaceOrInsertSplit(- { type: 'channel', id: channelId },- 'quick-access'- );- }- } else {- // Default to channel for other notifications- replaceOrInsertSplit({ type: 'channel', id: channelId }, 'quick-access');- }-- const nextIndex = (currentNotificationIndex() + 1) % notifications.length;- setCurrentNotificationIndex(nextIndex);- };-- const getRecipientId = () => {- if (props.channel.channel_type === ChannelTypeEnum.DirectMessage) {- let userIdValue = userId();- let recipient = props.channel.participants.find(- (p) => p.user_id !== userIdValue- );- return recipient?.user_id;- }- return undefined;- };-- return (- <Tooltip- tooltip={- <div>- <p>- {(() => {- const notifications = unreadNotifications();- const index = currentNotificationIndex();- const notification = notifications[index] || notifications[0];- if (!notification) return 'Click to open channel';- return getNotificationDescription(notification);- })()} <span class="font-bold">{props.channel.name}</span>- </p>- <div></div>- <Show when={unreadNotifications().length > 1}>- <div class="text-ink-muted text-xs">- {currentNotificationIndex() + 1} of {unreadNotifications().length}- </div>- </Show>- </div>- }- placement="top"- floatingOptions={{- offset: 18,- }}- >- <div- onMouseDown={goToNextNotification}- class="relative flex justify-center items-center bg-panel hover:bg-panel-highlight border border-edge rounded-full size-8 transition-colors cursor-pointer select-none shrink-0"- >- <Show when={unreadNotifications().length > 0}>- <div class="-top-1 -right-1 z-10 absolute bg-accent px-px rounded-full min-w-[1lh] font-mono font-bold text-xxs text-panel text-center">- {unreadNotifications().length}- </div>- </Show>- <div class="flex flex-col items-center">- <Show- when={getRecipientId()}- fallback={- <div class="font-bold text-ink-muted text-xs">- {props.channel.name?.[0]?.toUpperCase() ?? 'C'}- </div>- }- keyed- >- {(id) => <UserIcon id={id} isDeleted={false} size="md" />}- </Show>- </div>- </div>- </Tooltip>- );-}--export function QuickAccess() {- const channelsContext = useChannelsContext();- const notificationSource = useGlobalNotificationSource();- const allNotifications = notificationSource.notifications;- const channelsWithNotifications = createMemo(() => {- const channels_ = channelsContext.channels();- const notifications = allNotifications();-- return channels_- .map((channel) => {- const channelNotifications = notifications- .filter((notification) => {- if (notification.entity_id !== channel.id) return false;- if (!isHighPriorityNotification(notification)) return false;-- // For DM channels, include all message notifications- if (channel.channel_type === ChannelTypeEnum.DirectMessage)- return true;-- // For other channels, only include mentions and replies- return (- notification.notificationEventType ===- NotificationEventType.channel_mention ||- notification.notificationEventType ===- NotificationEventType.channel_message_reply- );- })- .sort((a, b) => {- const getPriority = (n: UnifiedNotification) => {- if (- n.notificationEventType ===- NotificationEventType.channel_mention- )- return 3;- if (- n.notificationEventType ===- NotificationEventType.channel_message_reply- )- return 2;- return 1; // channel_message_send for DMs- };- return getPriority(b) - getPriority(a);- });-- return { channel, notifications: channelNotifications };- })- .filter((item) => item.notifications.length > 0) // Only show channels with notifications- .sort((a, b) => b.notifications.length - a.notifications.length);- });-- return (- <div class="flex items-center gap-1.5 p-1">- <For each={channelsWithNotifications()}>- {(item) => (- <QuickAccessItem- channel={item.channel}- notifications={item.notifications}- notificationSource={notificationSource}- />- )}- </For>- </div>- );-}diff --git a/js/app/packages/block-email/component/EmailContext.tsx b/js/app/packages/block-email/component/EmailContext.tsxindex 52f2ed78a1..3f22cfb07b 100644--- a/js/app/packages/block-email/component/EmailContext.tsx+++ b/js/app/packages/block-email/component/EmailContext.tsx@@ -18,11 +18,7 @@ import {type WithCustomUserInput,} from '@core/user';import { whenSettled } from '@core/util/whenSettled';-import {- createEffectOnEntityTypeNotification,- getMetadata,- isNewEmail,-} from '@notifications';+import { createEffectOnEntityTypeNotification } from '@notifications';import {useArchiveThreadMutation,useThreadQuery,@@ -173,10 +169,9 @@ export function EmailProvider(props: FlowProps<{ threadID: string }>) {notificationSource,'email',(notification) => {- if (!isNewEmail(notification)) return;- const metadata = getMetadata(notification);- const notificationThreadId = metadata.threadId;- if (notificationThreadId === threadQuery.data?.db_id) {+ const meta = notification.notificationMetadata;+ if (meta.tag !== 'new_email') return;+ if (meta.content.threadId === threadQuery.data?.db_id) {threadQuery.refetch();}}diff --git a/js/app/packages/core/component/GlobalNotificationBell.tsx b/js/app/packages/core/component/GlobalNotificationBell.tsxindex dbad698c8e..6d312e4da1 100644--- a/js/app/packages/core/component/GlobalNotificationBell.tsx+++ b/js/app/packages/core/component/GlobalNotificationBell.tsx@@ -5,7 +5,6 @@ import Bell from '@icon/regular/bell.svg';import {type NotificationSource,openNotification,- tryToTypedNotification,useUnreadNotifications,} from '@notifications';import { Show } from 'solid-js';@@ -36,11 +35,10 @@ export function GlobalNotificationBell(props: GlobalNotificationBellProps) {if (!notification) return;- const nm = tryToTypedNotification(notification);const layoutManager = globalSplitManager();- if (!nm || !layoutManager) return;+ if (!layoutManager) return;- openNotification(nm, layoutManager);+ openNotification(notification, layoutManager);notificationSource.markAsRead(notification);diff --git a/js/app/packages/core/component/NotificationRenderer.tsx b/js/app/packages/core/component/NotificationRenderer.tsxindex 083dc792c4..618090c7e5 100644--- a/js/app/packages/core/component/NotificationRenderer.tsx+++ b/js/app/packages/core/component/NotificationRenderer.tsx@@ -3,8 +3,10 @@ import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/Simport { macroIdToEmail, tryMacroId, useDisplayName } from '@core/user';import { formatDate } from '@core/util/date';import {- extractNotificationData,- tryToTypedNotification,+ getNotificationAction,+ getNotificationContent,+ getNotificationTargetName,+ shouldShowNotificationTarget,type UnifiedNotification,} from '@notifications';import { Show } from 'solid-js';@@ -15,42 +17,44 @@ type NotificationRendererProps = {};export function NotificationRenderer(props: NotificationRendererProps) {- const typed = () => tryToTypedNotification(props.notification);- const data = () => {- const t = typed();- if (!t) return null;- const result = extractNotificationData(t);- if (result === 'no_extractor' || result === 'no_extracted_data') {- return null;- }- return result;+ const time = () => formatDate(props.notification.createdAt);+ const actorId = () => props.notification.senderId ?? '';+ const macroId = () => tryMacroId(actorId());+ const [actorName] = useDisplayName(macroId());+ const emailFallback = () => {+ const mid = macroId();+ return mid ? macroIdToEmail(mid) : actorId() || undefined;};+ const displayName = () => actorName() || emailFallback() || 'Someone';- const time = () => formatDate(props.notification.createdAt);+ const action = () => getNotificationAction(props.notification);+ const targetName = () => getNotificationTargetName(props.notification);+ const content = () => getNotificationContent(props.notification);+ const showTarget = () => shouldShowNotificationTarget(props.notification);+ const isChannel = () => props.notification.entity_type === 'channel';+ const entityId = () => props.notification.entity_id;- return (- <Show when={data()}>- {(d) => {- const actorId = d().actor?.id ?? '';- const macroId = tryMacroId(actorId);- const [actorName] = useDisplayName(macroId);- const emailFallback = macroId- ? macroIdToEmail(macroId)- : actorId || undefined;- const displayName = () => actorName() || emailFallback || 'Someone';+ const emailMeta = () => {+ const meta = props.notification.notificationMetadata;+ if (meta.tag !== 'new_email') return null;+ return { subject: meta.content.subject, snippet: meta.content.snippet };+ };+ return (+ <Show when={props.notification.notificationMetadata}>+ {(_metadata) => {if (props.mode === 'preview') {return (<div class="truncate flex items-baseline gap-[0.2em] text-xs text-ink-muted font-medium font-sans"><span class="font-medium text-ink">{displayName()}</span>- <span class="font-normal">{d().action}</span>- <Show when={d().target?.type === 'channel' && d().target?.id}>+ <span class="font-normal">{action()}</span>+ <Show when={showTarget() && isChannel() && entityId()}><div class="self-center max-h-[1lh]">- <InlineItemPreview id={d().target!.id!} type="channel" />+ <InlineItemPreview id={entityId()} type="channel" /></div></Show>- <Show when={d().target?.name && d().target?.type !== 'channel'}>- <span class="font-medium text-ink">{d().target!.name}</span>+ <Show when={showTarget() && targetName() && !isChannel()}>+ <span class="font-medium text-ink">{targetName()}</span></Show><span class="text-ink-extra-muted ml-2 font-mono uppercase font-normal">{time()}@@ -62,31 +66,27 @@ export function NotificationRenderer(props: NotificationRendererProps) {return (<><div class="text-sm text-ink inline-flex items-center gap-1">- <span class="font-medium">{displayName()}</span> {d().action}{' '}- <Show when={d().target?.type === 'channel' && d().target?.id}>- <InlineItemPreview id={d().target!.id!} type="channel" />+ <span class="font-medium">{displayName()}</span> {action()}{' '}+ <Show when={showTarget() && isChannel() && entityId()}>+ <InlineItemPreview id={entityId()} type="channel" /></Show>- <Show when={d().target?.name && d().target?.type !== 'channel'}>- <span class="font-medium">{d().target!.name}</span>+ <Show when={showTarget() && targetName() && !isChannel()}>+ <span class="font-medium">{targetName()}</span></Show></div>- <Show when={d().content}>- <div class="text-xs text-ink-muted">- <StaticMarkdown markdown={d().content || ''} />- </div>- </Show>-- <Show when={d().meta?.permissionLevel}>+ <Show when={content()}><div class="text-xs text-ink-muted">- You now have {d().meta!.permissionLevel} access+ <StaticMarkdown markdown={content() || ''} /></div></Show>- <Show when={d().meta?.snippet}>- <div class="text-xs text-ink-muted">- {d().meta!.subject} - {d().meta!.snippet}- </div>+ <Show when={emailMeta()}>+ {(meta) => (+ <div class="text-xs text-ink-muted">+ {meta().subject} - {meta().snippet}+ </div>+ )}</Show></>);diff --git a/js/app/packages/core/component/Notifications.tsx b/js/app/packages/core/component/Notifications.tsxindex b17cc17cd2..5d5cfcda9a 100644--- a/js/app/packages/core/component/Notifications.tsx+++ b/js/app/packages/core/component/Notifications.tsx@@ -6,10 +6,8 @@ import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler'import {NOTIFICATION_LABEL_BY_TYPE,type NotificationSource,- tryToTypedNotification,type UnifiedNotification,} from '@notifications';-import type { NotificationEventType } from '@service-notification/generated/schemas';import { openNotification } from '@notifications/notification-navigation';import { createMemo, For, Show } from 'solid-js';@@ -31,10 +29,9 @@ export function Notifications(props: NotificationsProps) {const handleNotificationClick = async (notification: UnifiedNotification) => {const splitManager = globalSplitManager();- const typed = tryToTypedNotification(notification);- if (!typed || !splitManager) return;+ if (!splitManager) return;- openNotification(typed, splitManager);+ openNotification(notification, splitManager);await props.notificationSource.markAsRead(notification);};@@ -71,7 +68,7 @@ export function Notifications(props: NotificationsProps) {<div>{NOTIFICATION_LABEL_BY_TYPE[- notification.notificationEventType as NotificationEventType+ notification.notificationMetadata.tag]}</div>diff --git a/js/app/packages/core/types/index.ts b/js/app/packages/core/types/index.tsindex f1aa93a43e..1e3b0ca4a2 100644--- a/js/app/packages/core/types/index.ts+++ b/js/app/packages/core/types/index.ts@@ -15,7 +15,8 @@ export type Entity = {};export type { ApiPaginatedThreadCursor as ThreadPreview } from '@service-email/generated/schemas/apiPaginatedThreadCursor';-export { NotificationEventType as NotificationType } from '@service-notification/generated/schemas/notificationEventType';+import type { NotifEvent } from '@service-notification/generated/schemas';+export type NotificationType = NotifEvent['tag'];export type Nullable<T> = T | null;export type Maybe<T> = T | undefined;diff --git a/js/app/packages/entity/mocks/mockEntityData.ts b/js/app/packages/entity/mocks/mockEntityData.tsindex 086e3e2111..bab7dcbe68 100644--- a/js/app/packages/entity/mocks/mockEntityData.ts+++ b/js/app/packages/entity/mocks/mockEntityData.ts@@ -137,7 +137,10 @@ export const createMockNotification = (updatedAt: MOCK_TIMESTAMPS.today,deletedAt: null,viewedAt: null,- notificationMetadata: { tag: 'document_mention', content: {} },+ notificationMetadata: {+ tag: 'document_mention',+ content: { documentName: 'Test Document', owner: 'user_123' },+ },...overrides,});@@ -156,7 +159,7 @@ export const MOCK_NOTIFICATIONS: Notification[] = [}),createMockNotification({id: 'notif_channel_1',- notificationEventType: 'channel_message_document',+ notificationEventType: 'channel_message_send',senderId: MOCK_USER_IDS.sharedUser,createdAt: MOCK_TIMESTAMPS.lastWeek,entity_type: 'channel',diff --git a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.tsindex 9d2cfb7535..327de19ee6 100644--- a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts+++ b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts@@ -1,5 +1,6 @@import { match } from 'ts-pattern';import type { Notification } from '../types/notification';+import type { NotificationType } from '@core/types';/*** Gets unique sender IDs from a notification stack@@ -19,35 +20,36 @@ export function getUniqueSenderIds(notifications: Notification[]): string[] {* Gets the action verb for a notification type* @internal*/-export function getActionVerb(- type: Notification['notificationEventType']-): string {+export function getActionVerb(type: NotificationType): string {return match(type).with('channel_mention', () => 'mentioned you').with('document_mention', () => 'mentioned you')+ .with('mentioned_in_document_comment', () => 'mentioned you').with('channel_message_reply', () => 'replied').with('channel_message_send', () => 'sent a message')- .with('item_shared_user', () => 'shared')- .with('item_shared_organization', () => 'shared').with('new_email', () => 'sent an email')- .otherwise(() => 'notified you');+ .with('channel_invite', () => 'invited you')+ .with('invite_to_team', () => 'invited you')+ .with('task_assigned', () => 'assigned you')+ .exhaustive();}/*** Gets a noun for the notification type (for multi-notification descriptions)* @internal*/-export function getTypeNoun(- type: Notification['notificationEventType'],- count: number-): string {+export function getTypeNoun(type: NotificationType, count: number): string {return match(type).with('channel_message_reply', () => (count === 1 ? 'reply' : 'replies')).with('channel_message_send', () => (count === 1 ? 'message' : 'messages')).with('channel_mention', () => (count === 1 ? 'mention' : 'mentions')).with('document_mention', () => (count === 1 ? 'mention' : 'mentions'))- .with('item_shared_user', () => (count === 1 ? 'share' : 'shares'))- .with('item_shared_organization', () => (count === 1 ? 'share' : 'shares'))+ .with('mentioned_in_document_comment', () =>+ count === 1 ? 'mention' : 'mentions'+ ).with('new_email', () => (count === 1 ? 'email' : 'emails'))- .otherwise(() => (count === 1 ? 'notification' : 'notifications'));+ .with('channel_invite', () => (count === 1 ? 'invite' : 'invites'))+ .with('invite_to_team', () => (count === 1 ? 'invite' : 'invites'))+ .with('task_assigned', () => (count === 1 ? 'task' : 'tasks'))+ .exhaustive();}diff --git a/js/app/packages/entity/src/extractors-notification/notification-description.tsx b/js/app/packages/entity/src/extractors-notification/notification-description.tsxindex e4a0a8ce2c..40fe355231 100644--- a/js/app/packages/entity/src/extractors-notification/notification-description.tsx+++ b/js/app/packages/entity/src/extractors-notification/notification-description.tsx@@ -1,5 +1,6 @@import type { Notification } from '../types/notification';import type { NotificationStack } from '@notifications';+import type { NotificationType } from '@core/types';import { tryMacroId, useDisplayNameParts } from '@core/user';import {getUniqueSenderIds,@@ -31,8 +32,8 @@ export function NotificationDescription(props: NotificationDescriptionProps) {);};- const notificationType = () => {- if (props.notification) return props.notification.notificationEventType;+ const notificationType = (): NotificationType | undefined => {+ if (props.notification) return props.notification.notificationMetadata.tag;if (props.stack) return props.stack.type;return undefined;};diff --git a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx b/js/app/packages/entity/src/extractors-notification/notification-icon.tsxindex d8a4a31b08..65387673c0 100644--- a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx+++ b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx@@ -3,11 +3,13 @@ import type { JSX } from 'solid-js';import { match } from 'ts-pattern';import type { Notification } from '../types/notification';import type { NotificationStack } from '@notifications';+import type { NotificationType } from '@core/types';import ChatIcon from '@icon/regular/chat.svg';import ArrowBendUpLeftIcon from '@icon/regular/arrow-bend-up-left.svg';import AtIcon from '@icon/regular/at.svg';-import ShareIcon from '@icon/regular/share.svg';import EnvelopeIcon from '@icon/regular/envelope.svg';+import UserPlusIcon from '@icon/regular/user-plus.svg';+import CheckIcon from '@icon/regular/check.svg';import { cn } from '@ui/utils/classname';interface NotificationIconProps {@@ -20,26 +22,28 @@ interface NotificationIconProps {* Gets the appropriate icon for a notification type*/function getNotificationIcon(- type: Notification['notificationEventType']+ type: NotificationType): (props: { class?: string }) => JSX.Element {return match(type).with('channel_mention', () => AtIcon).with('document_mention', () => AtIcon)+ .with('mentioned_in_document_comment', () => AtIcon).with('channel_message_reply', () => ArrowBendUpLeftIcon).with('channel_message_send', () => ChatIcon)- .with('item_shared_user', () => ShareIcon)- .with('item_shared_organization', () => ShareIcon).with('new_email', () => EnvelopeIcon)- .otherwise(() => ChatIcon);+ .with('channel_invite', () => UserPlusIcon)+ .with('invite_to_team', () => UserPlusIcon)+ .with('task_assigned', () => CheckIcon)+ .exhaustive();}/*** Displays the appropriate icon for a notification or stack*/export function NotificationIcon(props: NotificationIconProps) {- const notificationType = () => {+ const notificationType = (): NotificationType | undefined => {if (props.stack) return props.stack.type;- if (props.notification) return props.notification.notificationEventType;+ if (props.notification) return props.notification.notificationMetadata.tag;return undefined;};diff --git a/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsxindex 610537788a..715078e224 100644--- a/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx+++ b/js/app/packages/entity/src/extractors-notification/notification-stacks.tsx@@ -5,7 +5,6 @@ import {type NotificationStack,getMostRecentNotification,openNotification,- tryToTypedNotification,} from '@notifications';import type { WithNotification } from '../types/notification';import type { EntityData } from '../types/entity';@@ -49,12 +48,11 @@ function NotificationStackRow(props: {const handleClick = async (e: PointerEvent | MouseEvent) => {const mostRecent = getMostRecentNotification(props.stack);- const typed = tryToTypedNotification(mostRecent);const splitManager = globalSplitManager();- if (!typed || !splitManager) return;+ if (!splitManager) return;e.stopPropagation();- await openNotification(typed, splitManager);+ await openNotification(mostRecent, splitManager);await notificationSource.markAsRead(mostRecent);props.onClick?.(e);};diff --git a/js/app/packages/entity/src/utils/notification.ts b/js/app/packages/entity/src/utils/notification.tsindex 9634f328ce..2bda54d340 100644--- a/js/app/packages/entity/src/utils/notification.ts+++ b/js/app/packages/entity/src/utils/notification.ts@@ -1,22 +1,10 @@-import {- isChannelMention,- isChannelMessageReply,- isChannelMessageSend,- isDocumentMention,- isItemSharedOrganization,- isItemSharedUser,- isNewEmail,- getMetadata,- type UnifiedNotificationWithMetadata,- type TypedNotification,-} from '@notifications/notification-metadata';import type { NotificationStack } from '@notifications/notification-stacking';import type { Notification } from '../types/notification';+import type { UnifiedNotification } from '@notifications';import { match } from 'ts-pattern';/*** Filters out invalid notification types that shouldn't be displayed- * Currently filters out 'channel_message_document' notifications.*/export function filterValidNotifications(notifications: Notification[] | undefined@@ -24,10 +12,7 @@ export function filterValidNotifications(if (!notifications) return [];return notifications.filter((n) => {- return (- n.notificationEventType !== 'channel_message_document' &&- n.notificationEventType !== undefined- );+ return n.notificationEventType !== undefined;});}@@ -39,7 +24,7 @@ export function filterNotDoneNotifications(}export function extractNotificationSenderIds(- notifications: TypedNotification[],+ notifications: UnifiedNotification[],maxCount: number = 3,reverse = false): string[] {@@ -48,14 +33,8 @@ export function extractNotificationSenderIds(for (const notification of notifications) {if (senderIds.size >= maxCount) break;- const metadata = notification.notificationMetadata;- if (- metadata &&- 'senderId' in metadata &&- typeof metadata.senderId === 'string' &&- metadata.senderId- ) {- senderIds.add(metadata.senderId);+ if (notification.senderId) {+ senderIds.add(notification.senderId);}}@@ -68,64 +47,43 @@ export function extractNotificationSenderIds(* Gets a human-readable action text for a notification based on its type* Returns a short verb phrase like "mentioned", "replied", "shared", etc.*/-export function getNotificationActionText(notification: Notification): string {- const type = notification.notificationEventType;+export function getNotificationActionText(n: Notification): string {+ const tag = n.notificationMetadata.tag;- return match(type)+ return match(tag).with('channel_mention', () => 'mentioned').with('channel_message_send', () => 'sent').with('channel_message_reply', () => 'replied').with('document_mention', () => 'mentioned')- .with('item_shared_user', () => 'shared')- .with('item_shared_organization', () => 'shared')+ .with('mentioned_in_document_comment', () => 'mentioned').with('channel_invite', () => 'invited').with('new_email', () => 'emailed').with('invite_to_team', () => 'invited')- .with('reject_team_invite', () => 'declined').with('task_assigned', () => 'assigned')- .with('channel_message_document', () => 'notified')- .otherwise(() => 'notified');+ .exhaustive();}export function extractMessageContent(notification: Notification): string {- const typed = notification as UnifiedNotificationWithMetadata;-- if (isChannelMention(typed)) {- const metadata = getMetadata(typed);- return metadata.messageContent || '';- }-- if (isChannelMessageSend(typed)) {- const metadata = getMetadata(typed);- return metadata.messageContent || '';- }-- if (isChannelMessageReply(typed)) {- const metadata = getMetadata(typed);- return metadata.messageContent || '';- }-- if (isDocumentMention(typed)) {- const metadata = getMetadata(typed);- return metadata.documentName || '';- }-- if (isItemSharedUser(typed)) {- const metadata = getMetadata(typed);- return metadata.itemName || '';- }-- if (isItemSharedOrganization(typed)) {- const metadata = getMetadata(typed);- return metadata.itemName || '';- }-- if (isNewEmail(typed)) {- const metadata = getMetadata(typed);- return metadata.subject || '';- }-- return '';+ const n = notification as UnifiedNotification;+ const meta = n.notificationMetadata;++ return match(meta)+ .with({ tag: 'channel_mention' }, (m) => m.content.messageContent || '')+ .with(+ { tag: 'channel_message_send' },+ (m) => m.content.messageContent || ''+ )+ .with(+ { tag: 'channel_message_reply' },+ (m) => m.content.messageContent || ''+ )+ .with({ tag: 'document_mention' }, (m) => m.content.documentName || '')+ .with({ tag: 'mentioned_in_document_comment' }, (m) => m.content.text || '')+ .with({ tag: 'new_email' }, (m) => m.content.subject || '')+ .with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? '')+ .with({ tag: 'channel_invite' }, () => '')+ .with({ tag: 'invite_to_team' }, () => '')+ .exhaustive();}/**diff --git a/js/app/packages/entity/tests/notification-description.test.ts b/js/app/packages/entity/tests/notification-description.test.tsindex f69755f20c..f8d132fc1d 100644--- a/js/app/packages/entity/tests/notification-description.test.ts+++ b/js/app/packages/entity/tests/notification-description.test.ts@@ -89,21 +89,26 @@ describe('notification-description helpers', () => {expect(getActionVerb('channel_message_send')).toBe('sent a message');});- it('returns correct verb for item_shared_user', () => {- expect(getActionVerb('item_shared_user')).toBe('shared');- });-- it('returns correct verb for item_shared_organization', () => {- expect(getActionVerb('item_shared_organization')).toBe('shared');+ it('returns correct verb for mentioned_in_document_comment', () => {+ expect(getActionVerb('mentioned_in_document_comment')).toBe(+ 'mentioned you'+ );});it('returns correct verb for new_email', () => {expect(getActionVerb('new_email')).toBe('sent an email');});- it('returns default verb for unknown types', () => {- expect(getActionVerb('channel_invite' as any)).toBe('notified you');- expect(getActionVerb('task_assigned' as any)).toBe('notified you');+ it('returns correct verb for channel_invite', () => {+ expect(getActionVerb('channel_invite')).toBe('invited you');+ });++ it('returns correct verb for invite_to_team', () => {+ expect(getActionVerb('invite_to_team')).toBe('invited you');+ });++ it('returns correct verb for task_assigned', () => {+ expect(getActionVerb('task_assigned')).toBe('assigned you');});});@@ -150,45 +155,55 @@ describe('notification-description helpers', () => {});});- describe('item_shared_user', () => {+ describe('mentioned_in_document_comment', () => {it('returns singular for count of 1', () => {- expect(getTypeNoun('item_shared_user', 1)).toBe('share');+ expect(getTypeNoun('mentioned_in_document_comment', 1)).toBe('mention');});it('returns plural for count greater than 1', () => {- expect(getTypeNoun('item_shared_user', 2)).toBe('shares');+ expect(getTypeNoun('mentioned_in_document_comment', 2)).toBe(+ 'mentions'+ );});});- describe('item_shared_organization', () => {+ describe('channel_invite', () => {it('returns singular for count of 1', () => {- expect(getTypeNoun('item_shared_organization', 1)).toBe('share');+ expect(getTypeNoun('channel_invite', 1)).toBe('invite');});it('returns plural for count greater than 1', () => {- expect(getTypeNoun('item_shared_organization', 3)).toBe('shares');+ expect(getTypeNoun('channel_invite', 3)).toBe('invites');});});- describe('new_email', () => {+ describe('invite_to_team', () => {it('returns singular for count of 1', () => {- expect(getTypeNoun('new_email', 1)).toBe('email');+ expect(getTypeNoun('invite_to_team', 1)).toBe('invite');});it('returns plural for count greater than 1', () => {- expect(getTypeNoun('new_email', 2)).toBe('emails');+ expect(getTypeNoun('invite_to_team', 2)).toBe('invites');});});- describe('unknown types', () => {- it('returns generic singular for count of 1', () => {- expect(getTypeNoun('channel_invite' as any, 1)).toBe('notification');- expect(getTypeNoun('task_assigned' as any, 1)).toBe('notification');+ describe('task_assigned', () => {+ it('returns singular for count of 1', () => {+ expect(getTypeNoun('task_assigned', 1)).toBe('task');});- it('returns generic plural for count greater than 1', () => {- expect(getTypeNoun('channel_invite' as any, 2)).toBe('notifications');- expect(getTypeNoun('task_assigned' as any, 5)).toBe('notifications');+ it('returns plural for count greater than 1', () => {+ expect(getTypeNoun('task_assigned', 5)).toBe('tasks');+ });+ });++ describe('new_email', () => {+ it('returns singular for count of 1', () => {+ expect(getTypeNoun('new_email', 1)).toBe('email');+ });++ it('returns plural for count greater than 1', () => {+ expect(getTypeNoun('new_email', 2)).toBe('emails');});});diff --git a/js/app/packages/entity/tests/notification.test.ts b/js/app/packages/entity/tests/notification.test.tsindex bb615a3065..6a796a6bc5 100644--- a/js/app/packages/entity/tests/notification.test.ts+++ b/js/app/packages/entity/tests/notification.test.ts@@ -15,7 +15,7 @@ describe('notification utils', () => {expect(filterValidNotifications(undefined)).toEqual([]);});- it('filters out channel_message_document notifications', () => {+ it('keeps all notifications with defined notificationEventType', () => {const notifications: Notification[] = [{id: '1',@@ -23,17 +23,17 @@ describe('notification utils', () => {} as Notification,{id: '2',- notificationEventType: 'channel_message_document',+ notificationEventType: 'channel_message_send',} as Notification,{id: '3',- notificationEventType: 'channel_message_send',+ notificationEventType: 'new_email',} as Notification,];const result = filterValidNotifications(notifications);- expect(result).toHaveLength(2);- expect(result.map((n) => n.id)).toEqual(['1', '3']);+ expect(result).toHaveLength(3);+ expect(result.map((n) => n.id)).toEqual(['1', '2', '3']);});it('filters out notifications with undefined type', () => {@@ -101,17 +101,11 @@ describe('notification utils', () => {});describe('extractNotificationSenderIds', () => {- it('extracts sender IDs from notification metadata', () => {+ it('extracts sender IDs from notifications', () => {const notifications = [- {- notificationMetadata: { senderId: 'user1' },- },- {- notificationMetadata: { senderId: 'user2' },- },- {- notificationMetadata: { senderId: 'user3' },- },+ { senderId: 'user1' },+ { senderId: 'user2' },+ { senderId: 'user3' },] as any[];const result = extractNotificationSenderIds(notifications);@@ -120,10 +114,10 @@ describe('notification utils', () => {it('limits results to maxCount', () => {const notifications = [- { notificationMetadata: { senderId: 'user1' } },- { notificationMetadata: { senderId: 'user2' } },- { notificationMetadata: { senderId: 'user3' } },- { notificationMetadata: { senderId: 'user4' } },+ { senderId: 'user1' },+ { senderId: 'user2' },+ { senderId: 'user3' },+ { senderId: 'user4' },] as any[];const result = extractNotificationSenderIds(notifications, 2);@@ -133,10 +127,10 @@ describe('notification utils', () => {it('defaults to maxCount of 3', () => {const notifications = [- { notificationMetadata: { senderId: 'user1' } },- { notificationMetadata: { senderId: 'user2' } },- { notificationMetadata: { senderId: 'user3' } },- { notificationMetadata: { senderId: 'user4' } },+ { senderId: 'user1' },+ { senderId: 'user2' },+ { senderId: 'user3' },+ { senderId: 'user4' },] as any[];const result = extractNotificationSenderIds(notifications);@@ -145,9 +139,9 @@ describe('notification utils', () => {it('deduplicates sender IDs', () => {const notifications = [- { notificationMetadata: { senderId: 'user1' } },- { notificationMetadata: { senderId: 'user2' } },- { notificationMetadata: { senderId: 'user1' } },+ { senderId: 'user1' },+ { senderId: 'user2' },+ { senderId: 'user1' },] as any[];const result = extractNotificationSenderIds(notifications);@@ -156,9 +150,9 @@ describe('notification utils', () => {it('skips notifications without senderId', () => {const notifications = [- { notificationMetadata: { senderId: 'user1' } },- { notificationMetadata: {} },- { notificationMetadata: { senderId: 'user2' } },+ { senderId: 'user1' },+ {},+ { senderId: 'user2' },] as any[];const result = extractNotificationSenderIds(notifications);@@ -167,9 +161,9 @@ describe('notification utils', () => {it('skips notifications with empty senderId', () => {const notifications = [- { notificationMetadata: { senderId: 'user1' } },- { notificationMetadata: { senderId: '' } },- { notificationMetadata: { senderId: 'user2' } },+ { senderId: 'user1' },+ { senderId: '' },+ { senderId: 'user2' },] as any[];const result = extractNotificationSenderIds(notifications);@@ -178,9 +172,9 @@ describe('notification utils', () => {it('reverses result when reverse is true', () => {const notifications = [- { notificationMetadata: { senderId: 'user1' } },- { notificationMetadata: { senderId: 'user2' } },- { notificationMetadata: { senderId: 'user3' } },+ { senderId: 'user1' },+ { senderId: 'user2' },+ { senderId: 'user3' },] as any[];const result = extractNotificationSenderIds(notifications, 3, true);@@ -191,95 +185,74 @@ describe('notification utils', () => {describe('getNotificationActionText', () => {it('returns correct action text for channel_mention', () => {const notification = {- notificationEventType: 'channel_mention',+ notificationMetadata: { tag: 'channel_mention' },} as Notification;expect(getNotificationActionText(notification)).toBe('mentioned');});it('returns correct action text for channel_message_send', () => {const notification = {- notificationEventType: 'channel_message_send',+ notificationMetadata: { tag: 'channel_message_send' },} as Notification;expect(getNotificationActionText(notification)).toBe('sent');});it('returns correct action text for channel_message_reply', () => {const notification = {- notificationEventType: 'channel_message_reply',+ notificationMetadata: { tag: 'channel_message_reply' },} as Notification;expect(getNotificationActionText(notification)).toBe('replied');});it('returns correct action text for document_mention', () => {const notification = {- notificationEventType: 'document_mention',+ notificationMetadata: { tag: 'document_mention' },} as Notification;expect(getNotificationActionText(notification)).toBe('mentioned');});- it('returns correct action text for item_shared_user', () => {- const notification = {- notificationEventType: 'item_shared_user',- } as Notification;- expect(getNotificationActionText(notification)).toBe('shared');- });-- it('returns correct action text for item_shared_organization', () => {+ it('returns correct action text for mentioned_in_document_comment', () => {const notification = {- notificationEventType: 'item_shared_organization',+ notificationMetadata: { tag: 'mentioned_in_document_comment' },} as Notification;- expect(getNotificationActionText(notification)).toBe('shared');+ expect(getNotificationActionText(notification)).toBe('mentioned');});it('returns correct action text for channel_invite', () => {const notification = {- notificationEventType: 'channel_invite',+ notificationMetadata: { tag: 'channel_invite' },} as Notification;expect(getNotificationActionText(notification)).toBe('invited');});it('returns correct action text for new_email', () => {const notification = {- notificationEventType: 'new_email',+ notificationMetadata: { tag: 'new_email' },} as Notification;expect(getNotificationActionText(notification)).toBe('emailed');});it('returns correct action text for invite_to_team', () => {const notification = {- notificationEventType: 'invite_to_team',+ notificationMetadata: { tag: 'invite_to_team' },} as Notification;expect(getNotificationActionText(notification)).toBe('invited');});- it('returns correct action text for reject_team_invite', () => {- const notification = {- notificationEventType: 'reject_team_invite',- } as Notification;- expect(getNotificationActionText(notification)).toBe('declined');- });-it('returns correct action text for task_assigned', () => {const notification = {- notificationEventType: 'task_assigned',+ notificationMetadata: { tag: 'task_assigned' },} as Notification;expect(getNotificationActionText(notification)).toBe('assigned');});-- it('returns correct action text for channel_message_document', () => {- const notification = {- notificationEventType: 'channel_message_document',- } as Notification;- expect(getNotificationActionText(notification)).toBe('notified');- });});describe('extractMessageContent', () => {it('extracts messageContent for channel_mention', () => {const notification = {- notificationEventType: 'channel_mention',notificationMetadata: {- messageContent: 'Hey @user, check this out',+ tag: 'channel_mention',+ content: { messageContent: 'Hey @user, check this out' },},} as any;@@ -290,9 +263,9 @@ describe('notification utils', () => {it('extracts messageContent for channel_message_send', () => {const notification = {- notificationEventType: 'channel_message_send',notificationMetadata: {- messageContent: 'Hello everyone',+ tag: 'channel_message_send',+ content: { messageContent: 'Hello everyone' },},} as any;@@ -301,9 +274,9 @@ describe('notification utils', () => {it('extracts messageContent for channel_message_reply', () => {const notification = {- notificationEventType: 'channel_message_reply',notificationMetadata: {- messageContent: 'Great point!',+ tag: 'channel_message_reply',+ content: { messageContent: 'Great point!' },},} as any;@@ -312,52 +285,65 @@ describe('notification utils', () => {it('extracts documentName for document_mention', () => {const notification = {- notificationEventType: 'document_mention',notificationMetadata: {- documentName: 'Project Plan.doc',+ tag: 'document_mention',+ content: { documentName: 'Project Plan.doc' },},} as any;expect(extractMessageContent(notification)).toBe('Project Plan.doc');});- it('extracts itemName for item_shared_user', () => {+ it('extracts text for mentioned_in_document_comment', () => {const notification = {- notificationEventType: 'item_shared_user',notificationMetadata: {- itemName: 'Shared Folder',+ tag: 'mentioned_in_document_comment',+ content: { text: 'Check this comment' },},} as any;- expect(extractMessageContent(notification)).toBe('Shared Folder');+ expect(extractMessageContent(notification)).toBe('Check this comment');});- it('extracts itemName for item_shared_organization', () => {+ it('extracts subject for new_email', () => {const notification = {- notificationEventType: 'item_shared_organization',notificationMetadata: {- itemName: 'Company Docs',+ tag: 'new_email',+ content: { subject: 'Important Update' },},} as any;- expect(extractMessageContent(notification)).toBe('Company Docs');+ expect(extractMessageContent(notification)).toBe('Important Update');});- it('extracts subject for new_email', () => {+ it('extracts taskName for task_assigned', () => {const notification = {- notificationEventType: 'new_email',notificationMetadata: {- subject: 'Important Update',+ tag: 'task_assigned',+ content: { taskName: 'Review PR' },},} as any;- expect(extractMessageContent(notification)).toBe('Important Update');+ expect(extractMessageContent(notification)).toBe('Review PR');+ });++ it('returns empty string for channel_invite', () => {+ const notification = {+ notificationMetadata: {+ tag: 'channel_invite',+ content: {},+ },+ } as any;++ expect(extractMessageContent(notification)).toBe('');});- it('returns empty string for unsupported notification type', () => {+ it('returns empty string for invite_to_team', () => {const notification = {- notificationEventType: 'channel_invite',- notificationMetadata: {},+ notificationMetadata: {+ tag: 'invite_to_team',+ content: {},+ },} as any;expect(extractMessageContent(notification)).toBe('');@@ -365,8 +351,10 @@ describe('notification utils', () => {it('returns empty string when content is missing', () => {const notification = {- notificationEventType: 'channel_mention',- notificationMetadata: {},+ notificationMetadata: {+ tag: 'channel_mention',+ content: {},+ },} as any;expect(extractMessageContent(notification)).toBe('');diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsxindex 5a3f820a9c..c27c8054f1 100644--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx@@ -13,13 +13,10 @@ import ChatIcon from '@icon/regular/chat.svg';import CheckIcon from '@icon/regular/check.svg';import {getAllNotificationsFromGroup,- getMetadata,getMostRecentNotification,- isChannelMessageReply,type NotificationStack,stackNotifications,- type TypedNotification,- tryToTypedNotification,+ type UnifiedNotification,} from '@notifications';import { formatDocumentName } from '@service-storage/util/filename';import { syncServiceClient } from '@service-sync/client';@@ -323,10 +320,14 @@ function NotificationRow(props: {return 'mentioned you';}- const metadata = tryToTypedNotification(- props.notification- )?.notificationMetadata;- if (!metadata || !('messageContent' in metadata)) return '';+ const tag = (props.notification as UnifiedNotification).notificationMetadata+ .tag;+ if (+ tag !== 'channel_mention' &&+ tag !== 'channel_message_send' &&+ tag !== 'channel_message_reply'+ )+ return '';return 'message';};@@ -339,17 +340,17 @@ function NotificationRow(props: {return '';}- const typed = tryToTypedNotification(props.notification);- if (!typed) return '';- const metadata = getMetadata(typed);+ const n = props.notification as UnifiedNotification;+ const tag = n.notificationMetadata.tag;if (- !metadata ||- !('messageContent' in metadata) ||- metadata.messageContent === undefined- )+ tag !== 'channel_mention' &&+ tag !== 'channel_message_send' &&+ tag !== 'channel_message_reply'+ ) {return '';+ }- const content = metadata.messageContent;+ const content = n.notificationMetadata.content.messageContent;return (<Showwhen={content?.trim()}@@ -412,7 +413,7 @@ function NotificationRow(props: {* Shared row component for stacked notifications (new messages and replies)*/function StackedNotificationRow(props: {- notifications: TypedNotification[];+ notifications: UnifiedNotification[];title: JSX.Element;icon: (props: { class?: string }) => JSX.Element;onClick?: (e: EntityClickEvent) => void;@@ -440,14 +441,16 @@ function StackedNotificationRow(props: {const messageContent = createMemo(() => {const notification = mostRecent();if (!notification) return '';- const typed = tryToTypedNotification(notification);- if (!typed) return '';- const metadata = getMetadata(typed);- if (metadata && 'messageContent' in metadata) {- const content = metadata.messageContent as string | null | undefined;- return content?.trim() ?? '';+ const tag = notification.notificationMetadata.tag;+ if (+ tag !== 'channel_mention' &&+ tag !== 'channel_message_send' &&+ tag !== 'channel_message_reply'+ ) {+ return '';}- return '';+ const content = notification.notificationMetadata.content.messageContent;+ return content?.trim() ?? '';});return (@@ -540,12 +543,9 @@ function StackedRepliesRow(props: {const threadParentSenderId = () => {const notification = props.group.notifications[0];if (!notification) return '';- const typed = tryToTypedNotification(notification);- if (!typed || !isChannelMessageReply(typed)) return '';- const metadata = getMetadata(- typed as TypedNotification<'channel_message_reply'>- );- return metadata?.threadParentSenderId ?? '';+ const meta = notification.notificationMetadata;+ if (meta.tag !== 'channel_message_reply') return '';+ return meta.content.threadParentSenderId ?? '';};const { firstName } = useDisplayNameParts(tryMacroId(threadParentSenderId()));diff --git a/js/app/packages/notifications/components/Playground.tsx b/js/app/packages/notifications/components/Playground.tsxindex 72f572dc4c..d865d07a42 100644--- a/js/app/packages/notifications/components/Playground.tsx+++ b/js/app/packages/notifications/components/Playground.tsx@@ -11,17 +11,12 @@ import {For,Show,} from 'solid-js';-import { tryToTypedNotification } from '../notification-metadata';import {maybeHandlePlatformNotification,type PlatformNotificationData,toPlatformNotificationData,} from '../notification-platform';-import {- extractNotificationData,- NOTIFICATION_LABEL_BY_TYPE,- type NotificationData,-} from '../notification-preview';+import { NOTIFICATION_LABEL_BY_TYPE } from '../notification-preview';import {DefaultDocumentNameResolver,DefaultUserNameResolver,@@ -51,14 +46,8 @@ function groupNotificationsByType(return groups;}-function extractTypedNotificationData(- notification: UnifiedNotification-): NotificationData | null {- const typed = tryToTypedNotification(notification);- if (!typed) return null;- const data = extractNotificationData(typed);- if (data === 'no_extractor' || data === 'no_extracted_data') return null;- return data;+function hasNotificationMetadata(notification: UnifiedNotification): boolean {+ return notification.notificationMetadata != null;}function TypeButton(props: {@@ -113,7 +102,7 @@ function NotificationItem(props: {isSelected: boolean;onSelect: () => void;}) {- const data = () => extractTypedNotificationData(props.notification);+ const hasData = () => hasNotificationMetadata(props.notification);const isUnread = () => !props.notification.viewedAt;return (@@ -132,7 +121,7 @@ function NotificationItem(props: {}`}/><div class="flex-1 min-w-0">- <Show when={data()}>+ <Show when={hasData()}><NotificationRenderernotification={props.notification}mode="preview"@@ -148,16 +137,13 @@ function NotificationItem(props: {}function BrowserFormat(props: { notification: UnifiedNotification }) {- const data = createMemo(() =>- extractTypedNotificationData(props.notification)- );+ const hasData = () => hasNotificationMetadata(props.notification);const [browserNotif, setBrowserNotif] = createSignal<any>(null);createEffect(() => {- const notifData = data();- if (notifData) {+ if (hasData()) {toPlatformNotificationData(- notifData,+ props.notification,DefaultUserNameResolver,DefaultDocumentNameResolver).then(setBrowserNotif);@@ -168,7 +154,7 @@ function BrowserFormat(props: { notification: UnifiedNotification }) {return (<Show- when={data()}+ when={hasData()}fallback={<div class="text-ink-muted text-sm italic">No extractable data</div>}diff --git a/js/app/packages/notifications/index.ts b/js/app/packages/notifications/index.tsindex 08747a5e4e..10978945b1 100644--- a/js/app/packages/notifications/index.ts+++ b/js/app/packages/notifications/index.ts@@ -33,40 +33,20 @@ export {useUnreadEntityTypeNotifications,useUnreadNotifications,} from './notification-helpers';-export type {- NotificationMetadataByType,- TypedNotification,- UnifiedNotificationMetadata,- UnifiedNotificationWithMetadata,-} from './notification-metadata';export {- extractMetadata,- getMetadata,- isChannelInvite,- isChannelMention,- isChannelMessageDocument,- isChannelMessageReply,- isChannelMessageSend,- isDocumentMention,- isInviteToTeam,- isItemSharedOrganization,- isItemSharedUser,- isNewEmail,- isNotificationWithMetadata,- isRejectTeamInvite,- tryToTypedNotification,+ getNotificationAction,+ getNotificationContent,+ getNotificationTargetName,+ shouldShowNotificationTarget,} from './notification-metadata';+export { openNotificationFromId } from './notification-navigation';export { openNotification } from './notification-navigation';export type {PlatformNotificationData,PlatformNotificationHandle,toPlatformNotificationData,} from './notification-platform';-export type { NotificationData } from './notification-preview';-export {- extractNotificationData,- NOTIFICATION_LABEL_BY_TYPE,-} from './notification-preview';+export { NOTIFICATION_LABEL_BY_TYPE } from './notification-preview';export type {DocumentNameResolver,NotificationBlockNameResolver,diff --git a/js/app/packages/notifications/notification-metadata.ts b/js/app/packages/notifications/notification-metadata.tsindex 630d30c4ca..13eaf37f76 100644--- a/js/app/packages/notifications/notification-metadata.ts+++ b/js/app/packages/notifications/notification-metadata.ts@@ -1,180 +1,79 @@import type { UnifiedNotification } from '@service-notification/client';-import type {- ChannelInviteMetadata,- ChannelMentionMetadata,- ChannelMessageSendMetadata,- ChannelReplyMetadata,- DocumentMentionMetadata,- InviteToTeamMetadata,- ItemSharedMetadata,- ItemSharedOrganizationMetadata,- NewEmailMetadata,- NotificationEventType,- TaskAssignedMetadata,-} from '@service-notification/generated/schemas';+import { match } from 'ts-pattern';-export interface NotificationMetadataByType {- [NotificationEventType.item_shared_user]: ItemSharedMetadata;- [NotificationEventType.item_shared_organization]: ItemSharedOrganizationMetadata;- [NotificationEventType.channel_mention]: ChannelMentionMetadata;- [NotificationEventType.document_mention]: DocumentMentionMetadata;- [NotificationEventType.channel_invite]: ChannelInviteMetadata;- [NotificationEventType.channel_message_send]: ChannelMessageSendMetadata;- [NotificationEventType.channel_message_reply]: ChannelReplyMetadata;- [NotificationEventType.channel_message_document]: DocumentMentionMetadata;- [NotificationEventType.new_email]: NewEmailMetadata;- [NotificationEventType.invite_to_team]: InviteToTeamMetadata;- [NotificationEventType.reject_team_invite]: null;- [NotificationEventType.task_assigned]: TaskAssignedMetadata;-}--export type UnifiedNotificationMetadata =- NotificationMetadataByType[keyof NotificationMetadataByType];--/**- * A notification with a specific event type.- * Use `getMetadata(notification)` to access the typed metadata content.- */-export type TypedNotification<- T extends NotificationEventType = NotificationEventType,-> = UnifiedNotification & {- notificationEventType: T;-};--/**- * Extract the typed metadata content from a notification.- * The API returns notificationMetadata in { tag, content } format.- * The connection gateway returns notificationMetadata as a flat object.- * This function handles both formats.- */-export function getMetadata<T extends NotificationEventType>(- n: TypedNotification<T>-): T extends keyof NotificationMetadataByType- ? NotificationMetadataByType[T]- : never {- const metadata = n.notificationMetadata as- | { tag: string; content: unknown }- | Record<string, unknown>;-- // Check if metadata is in { tag, content } format (from API)- // or flat format (from connection gateway)- const content =- 'content' in metadata && 'tag' in metadata ? metadata.content : metadata;-- return content as T extends keyof NotificationMetadataByType- ? NotificationMetadataByType[T]- : never;-}--function isNotificationType<T extends NotificationEventType>(- n: UnifiedNotification,- type: T-): n is TypedNotification<T> {- return n.notificationEventType === type;-}--export function isItemSharedUser(- n: UnifiedNotification-): n is TypedNotification<'item_shared_user'> {- return isNotificationType(n, 'item_shared_user');-}+// Helper functions for derived notification data-export function isItemSharedOrganization(- n: UnifiedNotification-): n is TypedNotification<'item_shared_organization'> {- return isNotificationType(n, 'item_shared_organization');+export function getNotificationAction(n: UnifiedNotification): string {+ return match(n.notificationMetadata.tag)+ .with('channel_mention', () => 'mentioned you in')+ .with('document_mention', () => 'sent a document')+ .with('mentioned_in_document_comment', () => 'mentioned you in')+ .with('channel_message_send', () => 'sent a message in')+ .with('channel_message_reply', () => 'replied in')+ .with('channel_invite', () => 'invited you to')+ .with('new_email', () => 'sent a new email')+ .with('invite_to_team', () => 'invited you to')+ .with('task_assigned', () => 'assigned you a task')+ .exhaustive();}-export function isChannelMention(+export function getNotificationTargetName(n: UnifiedNotification-): n is TypedNotification<'channel_mention'> {- return isNotificationType(n, 'channel_mention');-}--export function isDocumentMention(+): string | undefined {+ const m = n.notificationMetadata;+ return match(m)+ .with({ tag: 'channel_invite' }, (m) => m.content.channelName)+ .with({ tag: 'document_mention' }, (m) => m.content.documentName)+ .with(+ { tag: 'mentioned_in_document_comment' },+ (m) => m.content.documentName+ )+ .with({ tag: 'invite_to_team' }, (m) => m.content.teamName)+ .with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)+ .with({ tag: 'channel_mention' }, () => undefined)+ .with({ tag: 'channel_message_send' }, () => undefined)+ .with({ tag: 'channel_message_reply' }, () => undefined)+ .with({ tag: 'new_email' }, () => undefined)+ .exhaustive();+}++export function getNotificationContent(n: UnifiedNotification-): n is TypedNotification<'document_mention'> {- return isNotificationType(n, 'document_mention');-}--export function isChannelInvite(- n: UnifiedNotification-): n is TypedNotification<'channel_invite'> {- return isNotificationType(n, 'channel_invite');-}--export function isChannelMessageSend(- n: UnifiedNotification-): n is TypedNotification<'channel_message_send'> {- return isNotificationType(n, 'channel_message_send');-}--export function isChannelMessageReply(- n: UnifiedNotification-): n is TypedNotification<'channel_message_reply'> {- return isNotificationType(n, 'channel_message_reply');-}--export function isChannelMessageDocument(- n: UnifiedNotification-): n is TypedNotification<'channel_message_document'> {- return isNotificationType(n, 'channel_message_document');-}--export function isNewEmail(- n: UnifiedNotification-): n is TypedNotification<'new_email'> {- return isNotificationType(n, 'new_email');-}--export function isInviteToTeam(- n: UnifiedNotification-): n is TypedNotification<'invite_to_team'> {- return isNotificationType(n, 'invite_to_team');-}--export function isRejectTeamInvite(- n: UnifiedNotification-): n is TypedNotification<'reject_team_invite'> {- return isNotificationType(n, 'reject_team_invite');-}--export function extractMetadata<T extends NotificationEventType>(- notification: UnifiedNotification,- type: T-): T extends keyof NotificationMetadataByType- ? NotificationMetadataByType[T]- : null {- if (- !('notificationEventType' in notification) ||- notification.notificationEventType !== type ||- !('notificationMetadata' in notification)- ) {- return null as any;- }- return notification.notificationMetadata as any;-}--export function isNotificationWithMetadata(- notification: UnifiedNotification-): notification is UnifiedNotification & {- notificationEventType: keyof NotificationMetadataByType;- notificationMetadata: UnifiedNotificationMetadata;-} {- return (- 'notificationMetadata' in notification &&- notification.notificationMetadata != null &&- 'notificationEventType' in notification- );-}--export type UnifiedNotificationWithMetadata<- T extends keyof NotificationMetadataByType = keyof NotificationMetadataByType,-> = TypedNotification<T>;--export function tryToTypedNotification(- notification: UnifiedNotification-): TypedNotification<NotificationEventType> | null {- if (!isNotificationWithMetadata(notification)) return null;- return notification as TypedNotification<NotificationEventType>;+): string | undefined {+ const m = n.notificationMetadata;+ return match(m)+ .with({ tag: 'channel_mention' }, (m) => m.content.messageContent)+ .with({ tag: 'channel_message_send' }, (m) => m.content.messageContent)+ .with({ tag: 'channel_message_reply' }, (m) => m.content.messageContent)+ .with({ tag: 'document_mention' }, (m) => m.content.documentName)+ .with({ tag: 'mentioned_in_document_comment' }, (m) => m.content.text)+ .with({ tag: 'new_email' }, (m) => m.content.subject)+ .with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)+ .with({ tag: 'channel_invite' }, () => undefined)+ .with({ tag: 'invite_to_team' }, () => undefined)+ .exhaustive();+}++export function shouldShowNotificationTarget(n: UnifiedNotification): boolean {+ const m = n.notificationMetadata;+ return match(m)+ .with(+ { tag: 'channel_mention' },+ (m) => m.content.channelType !== 'directMessage'+ )+ .with(+ { tag: 'channel_message_send' },+ (m) => m.content.channelType !== 'directMessage'+ )+ .with(+ { tag: 'channel_message_reply' },+ (m) => m.content.channelType !== 'directMessage'+ )+ .with({ tag: 'new_email' }, () => false)+ .with({ tag: 'task_assigned' }, () => true)+ .with({ tag: 'document_mention' }, () => true)+ .with({ tag: 'mentioned_in_document_comment' }, () => true)+ .with({ tag: 'channel_invite' }, () => true)+ .with({ tag: 'invite_to_team' }, () => true)+ .exhaustive();}diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.tsindex 6f43c463ed..06c68373f0 100644--- a/js/app/packages/notifications/notification-navigation.ts+++ b/js/app/packages/notifications/notification-navigation.ts@@ -2,42 +2,21 @@ import type { SplitManager } from '@app/component/split-layout/layoutManager';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import type { BlockAlias, BlockName } from '@core/block';import { fileTypeToBlockName } from '@core/constant/allBlocks';-import { NotificationType } from '@core/types';+import type { NotificationType } from '@core/types';+import type { UnifiedNotification } from '@service-notification/client';import { getNotificationById } from '@queries/notification/user-notifications';import { errAsync, ResultAsync } from 'neverthrow';import { match, P } from 'ts-pattern';-import {- getMetadata,- tryToTypedNotification,- type TypedNotification,-} from './notification-metadata';import type { NotificationSource } from './notification-source';-/**- * Notification event types that are all handled by opening a channel- * with a specific message and optionally a thread id- */-const ChannelNotificationType = {- channel_mention: NotificationType.channel_mention,- channel_message_send: NotificationType.channel_message_send,- channel_message_reply: NotificationType.channel_message_reply,-} as const satisfies Partial<Record<string, NotificationType>>;--type ChannelNotificationType =- (typeof ChannelNotificationType)[keyof typeof ChannelNotificationType];--const CHANNEL_EVENT_TYPES = Object.values(ChannelNotificationType) as [- ChannelNotificationType,- ...ChannelNotificationType[],-];+const CHANNEL_EVENT_TYPES = [+ 'channel_mention',+ 'channel_message_send',+ 'channel_message_reply',+] as const;/*** Opens a split if it is not already open.- *- * @param layoutManager The layout manager to use.- * @param type The type of the block to open.- * @param id The id of the block to open.- * @returns A result async that resolves to void if the split was opened successfully, or an error if the split could not be opened.*/function openSplitIfNotOpen(layoutManager: SplitManager,@@ -58,23 +37,29 @@ function openSplitIfNotOpen(/*** Opens a channel notification.- *- * @param notification The notification to open.- * @param layoutManager The layout manager to use.- * @returns A result async that resolves to void if the notification was opened successfully, or an error if the notification could not be opened.*/async function openChannelNotification(- notification: TypedNotification<ChannelNotificationType>,+ notification: UnifiedNotification,layoutManager: SplitManager) {const channelId = notification.entity_id;- const metadata = getMetadata(notification);- const messageId = metadata.messageId;- const threadId = 'threadId' in metadata ? metadata.threadId : undefined;+ let messageId: string | undefined;+ let threadId: string | undefined;++ const tag = notification.notificationMetadata.tag;+ if (tag === 'channel_mention') {+ messageId = notification.notificationMetadata.content.messageId;+ threadId = notification.notificationMetadata.content.threadId ?? undefined;+ } else if (tag === 'channel_message_send') {+ messageId = notification.notificationMetadata.content.messageId;+ } else if (tag === 'channel_message_reply') {+ messageId = notification.notificationMetadata.content.messageId;+ threadId = notification.notificationMetadata.content.threadId;+ }+openSplitIfNotOpen(layoutManager, 'channel', channelId);const orchestrator = layoutManager.getOrchestrator();-const handle = await orchestrator.getBlockHandle(channelId, 'channel');handle?.goToLocationFromParams({@@ -97,95 +82,74 @@ type NotFoundError = {notificationId: string;};-type NotTypedError = {- tag: 'NotTypedError';- notificationId: string;-};--export type OpenNotificationFromIdError =- | NotSupportedError- | NotFoundError- | NotTypedError;+export type OpenNotificationFromIdError = NotSupportedError | NotFoundError;function getSupportedHandler(- notification: TypedNotification<NotificationType>+ notification: UnifiedNotification): ((layoutManager: SplitManager) => Promise<void>) | null {- return match(notification)- .with(- { notificationEventType: P.union(...CHANNEL_EVENT_TYPES) },- (n) => (lm: SplitManager) => openChannelNotification(n, lm)- )+ const tag = notification.notificationMetadata.tag;++ return match(tag).with(- { notificationEventType: 'new_email' },- (n) => async (lm: SplitManager) => {- openSplitIfNotOpen(lm, 'email', getMetadata(n).threadId);- }+ P.union(...CHANNEL_EVENT_TYPES),+ () => (lm: SplitManager) => openChannelNotification(notification, lm))+ .with('new_email', () => {+ const meta = notification.notificationMetadata;+ if (meta.tag !== 'new_email') return null;+ return async (lm: SplitManager) => {+ openSplitIfNotOpen(lm, 'email', meta.content.threadId);+ };+ }).with(- { notificationEventType: 'channel_invite' },- (n) => async (lm: SplitManager) =>- openSplitIfNotOpen(lm, 'channel', n.entity_id)+ 'channel_invite',+ () => async (lm: SplitManager) =>+ openSplitIfNotOpen(lm, 'channel', notification.entity_id))- .with(- {- notificationEventType: P.union(- 'item_shared_user',- 'item_shared_organization'- ),- },- (n) => async (lm: SplitManager) =>+ .with('document_mention', () => {+ const meta = notification.notificationMetadata;+ if (meta.tag !== 'document_mention') return null;+ return async (lm: SplitManager) =>openSplitIfNotOpen(lm,- safeFileTypeToBlockName(getMetadata(n).itemType),- n.entity_id- )- )- .with(- {- notificationEventType: P.union(- 'document_mention',- 'channel_message_document'- ),- },- (n) => async (lm: SplitManager) =>+ safeFileTypeToBlockName(meta.content.fileType),+ notification.entity_id+ );+ })+ .with('invite_to_team', () => null)+ .with('task_assigned', () => {+ const meta = notification.notificationMetadata;+ if (meta.tag !== 'task_assigned') return null;+ return async (lm: SplitManager) => {+ openSplitIfNotOpen(lm, 'task', meta.content.taskId);+ };+ })+ .with('mentioned_in_document_comment', () => {+ const meta = notification.notificationMetadata;+ if (meta.tag !== 'mentioned_in_document_comment') return null;+ return async (lm: SplitManager) =>openSplitIfNotOpen(lm,- safeFileTypeToBlockName(getMetadata(n).fileType),- n.entity_id- )- )- .with(- {- notificationEventType: P.union('invite_to_team', 'reject_team_invite'),- },- () => null- )- .with(- { notificationEventType: 'task_assigned' },- (n) => async (lm: SplitManager) => {- openSplitIfNotOpen(lm, 'task', getMetadata(n).taskId);- }- )+ safeFileTypeToBlockName(meta.content.fileType),+ notification.entity_id+ );+ }).exhaustive();}/*** Opens the notification given the layout manager.* Some notifications are not supported and will return an error.- *- * @param notification The notification to open.- * @param layoutManager The layout manager to use.- * @returns A result async that resolves to void if the notification was opened successfully, or an error if the notification is not supported.*/export function openNotification(- notification: TypedNotification<NotificationType>,+ notification: UnifiedNotification,layoutManager: SplitManager): ResultAsync<void, NotSupportedError> {const handler = getSupportedHandler(notification);if (!handler) {return errAsync({tag: 'NotSupportedError',- notificationType: notification.notificationEventType,+ notificationType: notification.notificationMetadata.tag,});}return ResultAsync.fromSafePromise(handler(layoutManager));@@ -201,12 +165,7 @@ export function openNotificationFromId(.notifications().find((n) => n.id === notificationId);if (cached) {- const typed = tryToTypedNotification(cached);- if (!typed) {- const err: NotTypedError = { tag: 'NotTypedError', notificationId };- return errAsync(err);- }- return openNotification(typed, layoutManager);+ return openNotification(cached, layoutManager);}// Fetch if not in notification source@@ -217,13 +176,6 @@ export function openNotificationFromId(const err: NotFoundError = { tag: 'NotFoundError', notificationId };return errAsync(err);}-- const typed = tryToTypedNotification(unified);- if (!typed) {- const err: NotTypedError = { tag: 'NotTypedError', notificationId };- return errAsync(err);- }-- return openNotification(typed, layoutManager);+ return openNotification(unified, layoutManager);});}diff --git a/js/app/packages/notifications/notification-platform.ts b/js/app/packages/notifications/notification-platform.tsindex 32c5db0094..a26155e0e8 100644--- a/js/app/packages/notifications/notification-platform.ts+++ b/js/app/packages/notifications/notification-platform.ts@@ -4,12 +4,13 @@ import { markdownToPlainText } from '@lexical-core';import type { UnifiedNotification } from '@service-notification/client';import { themeReactive } from '../block-theme/signals/themeReactive';import type { PlatformNotificationState } from './components/PlatformNotificationProvider';-import { tryToTypedNotification } from './notification-metadata';-import { openNotification } from './notification-navigation';import {- extractNotificationData,- type NotificationData,-} from './notification-preview';+ getNotificationAction,+ getNotificationContent,+ getNotificationTargetName,+ shouldShowNotificationTarget,+} from './notification-metadata';+import { openNotification } from './notification-navigation';import {DefaultDocumentNameResolver,DefaultUserNameResolver,@@ -37,32 +38,34 @@ function getAccentColorForIcon(): string {}export async function toPlatformNotificationData(- data: NotificationData,+ notification: UnifiedNotification,resolveUserName: UserNameResolver,resolveDocumentName: DocumentNameResolver): Promise<PlatformNotificationData | null> {- if (!data) return null;-+ const actorId = notification.senderId;const actor =- (data.actor ? await resolveUserName(data.actor.id) : undefined) ??+ (actorId ? await resolveUserName(actorId) : undefined) ??USER_NAME_FALLBACK;- const showTarget = data.target?.show ?? false;-+ const showTarget = shouldShowNotificationTarget(notification);const targetName =- data.target?.name ??- (data.target?.id- ? await resolveDocumentName(data.target.id, data.target.type)- : undefined) ??+ getNotificationTargetName(notification) ??+ (await resolveDocumentName(+ notification.entity_id,+ notification.entity_type+ )) ??DOCUMENT_NAME_FALLBACK;+ const content = getNotificationContent(notification);+ const action = getNotificationAction(notification);+const accentColor = getAccentColorForIcon();const icon = getFaviconUrl(accentColor);return {title: `${actor}${showTarget ? ` <${targetName}>` : ''}`,options: {- body: data.content ? markdownToPlainText(data.content) : `${data.action}`,+ body: content ? markdownToPlainText(content) : action,icon,},};@@ -71,22 +74,14 @@ export async function toPlatformNotificationData(/*** Maybe handles a new notification as a platform notification.* If the notification is supported and formattable emit it and handle click events.- * @param notification- * @param notificationInterface- * @param splitLayoutManager*/export async function maybeHandlePlatformNotification(notification: UnifiedNotification,notificationInterface: PlatformNotificationState,splitLayoutManager: SplitManager) {- const nm = tryToTypedNotification(notification);- if (!nm) return;- const data = extractNotificationData(nm);- if (data === 'no_extractor' || data === 'no_extracted_data') return;-const platformNotificationData = await toPlatformNotificationData(- data,+ notification,DefaultUserNameResolver,DefaultDocumentNameResolver);@@ -101,7 +96,7 @@ export async function maybeHandlePlatformNotification() {notificationHandle.onClick(() => {window.focus();- openNotification(nm, splitLayoutManager);+ openNotification(notification, splitLayoutManager);notificationHandle.close();});}diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.tsindex 02e369a0b9..869a11205a 100644--- a/js/app/packages/notifications/notification-preview.ts+++ b/js/app/packages/notifications/notification-preview.ts@@ -1,253 +1,13 @@-import type { BlockName } from '@core/block';-import { type EntityType, NotificationType } from '@core/types';-import type { NotificationEventType } from '@service-notification/generated/schemas';-import { getMetadata, type TypedNotification } from './notification-metadata';--export type NotificationData = {- actor?: { id: string };- action: string;- type: NotificationEventType;- target?: {- type: EntityType;- id?: string;- name?: string | null;- show?: boolean;- };- content?: string | null;- meta?: {- blockName?: BlockName;- messageId?: string;- threadId?: string;- fileType?: string | null;- itemType?: string;- itemId?: string;- permissionLevel?: string | null;- sender?: string | null;- subject?: string;- snippet?: string;- };-};+import type { NotificationType } from '@core/types';export const NOTIFICATION_LABEL_BY_TYPE: Record<NotificationType, string> = {- [NotificationType.channel_mention]: 'MENTION',- [NotificationType.channel_message_send]: 'MESSAGE',- [NotificationType.channel_message_reply]: 'REPLY',- [NotificationType.document_mention]: 'MENTION',- [NotificationType.channel_message_document]: 'DOCUMENT',- [NotificationType.item_shared_user]: 'SHARED',- [NotificationType.item_shared_organization]: 'SHARED',- [NotificationType.channel_invite]: 'INVITE',- [NotificationType.new_email]: 'EMAIL',- [NotificationType.invite_to_team]: 'INVITE',- [NotificationType.reject_team_invite]: 'REJECTED',- [NotificationType.task_assigned]: 'ASSIGNED',+ channel_mention: 'MENTION',+ channel_message_send: 'MESSAGE',+ channel_message_reply: 'REPLY',+ document_mention: 'MENTION',+ mentioned_in_document_comment: 'MENTION',+ channel_invite: 'INVITE',+ new_email: 'EMAIL',+ invite_to_team: 'INVITE',+ task_assigned: 'ASSIGNED',} as const;--const extractors: {- [K in NotificationEventType]: (- n: TypedNotification<K>- ) => NotificationData | null;-} = {- item_shared_user: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: m.sharedBy ? { id: m.sharedBy! } : undefined,- action: 'shared',- target: {- type: m.itemType?.toLowerCase() as EntityType,- id: m.itemId,- name: m.itemName,- },- content: m.itemName ?? undefined,- meta: {- permissionLevel: m.permissionLevel,- itemType: m.itemType,- itemId: m.itemId,- },- };- },- item_shared_organization: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: m.sharedBy ? { id: m.sharedBy! } : undefined,- action: 'shared',- target: {- type: m.itemType?.toLowerCase() as EntityType,- id: m.itemId,- name: m.itemName,- },- content: m.itemName ?? undefined,- meta: {- permissionLevel: m.permissionLevel,- itemType: m.itemType,- itemId: m.itemId,- },- };- },- channel_mention: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: n.senderId ? { id: n.senderId! } : undefined,- action: 'mentioned you in',- target: {- type: 'channel',- id: n.entity_id,- show: m.channelType !== 'directMessage',- },- content: m.messageContent,- meta: {- messageId: m.messageId,- },- };- },- document_mention: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: n.senderId ? { id: n.senderId! } : undefined,- action: 'mentioned you in',- target: { type: 'document', id: n.entity_id, name: m.documentName },- content: m.documentName,- meta: {- fileType: m.fileType,- },- };- },- channel_invite: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: m.invitedBy ? { id: m.invitedBy! } : undefined,- action: 'invited you to',- target: { type: 'channel', id: n.entity_id, name: m.channelName },- content: m.channelName,- };- },- channel_message_send: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: m.sender ? { id: m.sender! } : undefined,- action: 'sent a message in',- target: {- type: 'channel',- id: n.entity_id,- show: m.channelType !== 'directMessage',- },- content: m.messageContent,- meta: {- messageId: m.messageId,- },- };- },- channel_message_reply: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: m.userId ? { id: m.userId! } : undefined,- action: 'replied in',- target: {- type: 'channel',- id: n.entity_id,- show: m.channelType !== 'directMessage',- },- content: m.messageContent,- meta: {- messageId: m.messageId,- threadId: m.threadId,- },- };- },- channel_message_document: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: m.owner ? { id: m.owner! } : undefined,- action: 'shared with you',- target: { type: 'document', id: n.entity_id, name: m.documentName },- content: m.documentName,- meta: {- fileType: m.fileType,- },- };- },- new_email: (n) => {- const m = getMetadata(n);- if (!m) return null;- const actorId = n.senderId ?? m.sender;- return {- type: n.notificationEventType,- actor: actorId ? { id: actorId } : undefined,- action: 'sent a new email',- target: { type: 'email', id: n.entity_id, show: false },- content: m.subject,- meta: {- sender: m.sender,- subject: m.subject,- snippet: m.snippet,- },- };- },- invite_to_team: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: m.invitedBy ? { id: m.invitedBy! } : undefined,- action: 'invited you to',- target: { type: 'team', id: n.entity_id, name: m.teamName },- content: m.teamName,- };- },- reject_team_invite: (n) => {- const m = getMetadata(n);- if (!m) return null;- return {- type: n.notificationEventType,- actor: undefined,- action: 'rejected your team invitation',- target: { type: 'team', id: n.entity_id },- content: undefined,- };- },- task_assigned: (n) => {- const m = getMetadata(n);- 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';--export function extractNotificationData<T extends NotificationEventType>(- notification: TypedNotification<T>-): NotificationData | NotificationDataError {- const extractor = extractors[notification.notificationEventType];- if (!extractor) return 'no_extractor';- return extractor(notification as any) ?? 'no_extracted_data';-}diff --git a/js/app/packages/notifications/notification-stacking.ts b/js/app/packages/notifications/notification-stacking.tsindex 5322b5ad8d..07334c17e8 100644--- a/js/app/packages/notifications/notification-stacking.ts+++ b/js/app/packages/notifications/notification-stacking.ts@@ -1,16 +1,9 @@-import {- getMetadata,- isChannelMention,- isChannelMessageReply,- isChannelMessageSend,- type TypedNotification,- tryToTypedNotification,-} from './notification-metadata';import type { UnifiedNotification } from './types';+import type { NotificationType } from '@core/types';export interface NotificationStack {- type: TypedNotification['notificationEventType'];- notifications: TypedNotification[];+ type: NotificationType;+ notifications: UnifiedNotification[];}/**@@ -36,11 +29,8 @@ export function getAllNotificationsFromGroup(*/export function getThreadId(group: NotificationStack): string {const notification = group.notifications[0];- if (notification.notificationEventType === 'channel_message_reply') {- const metadata = getMetadata(- notification as TypedNotification<'channel_message_reply'>- );- return metadata?.threadId ?? '';+ if (notification.notificationMetadata.tag === 'channel_message_reply') {+ return notification.notificationMetadata.content.threadId ?? '';}return '';}@@ -51,21 +41,32 @@ export function getThreadId(group: NotificationStack): string {export function stackNotifications(notifications: UnifiedNotification[]): NotificationStack[] {+ const isChannelMention = (n: UnifiedNotification) =>+ n.notificationMetadata.tag === 'channel_mention';+ const isChannelMessageSend = (n: UnifiedNotification) =>+ n.notificationMetadata.tag === 'channel_message_send';+ const isChannelMessageReply = (n: UnifiedNotification) =>+ n.notificationMetadata.tag === 'channel_message_reply';+// Collect mention messageIds for shadowingconst mentionedMsgIds = new Set(notifications.filter(isChannelMention)- .map((n) => getMetadata(n).messageId)+ .flatMap((n) =>+ n.notificationMetadata.tag === 'channel_mention'+ ? [n.notificationMetadata.content.messageId]+ : []+ ).filter(Boolean));- const isShadowed = (- n:- | TypedNotification<'channel_message_send'>- | TypedNotification<'channel_message_reply'>- ) => {- const metadata = getMetadata(n);- return metadata.messageId && mentionedMsgIds.has(metadata.messageId);+ const isShadowed = (n: UnifiedNotification) => {+ const tag = n.notificationMetadata.tag;+ if (tag === 'channel_message_send' || tag === 'channel_message_reply') {+ const messageId = n.notificationMetadata.content.messageId;+ return messageId && mentionedMsgIds.has(messageId);+ }+ return false;};// Partition by type@@ -88,11 +89,7 @@ export function stackNotifications(...mentions.flatMap((n) => makeStack('channel_mention', [n])),...makeStack('channel_message_send', newMsgs),...makeReplyStacks(replies),- ...others.flatMap((n) => {- const typed = tryToTypedNotification(n);- if (!typed) return [];- return makeStack(typed.notificationEventType, [typed]);- }),+ ...others.flatMap((n) => makeStack(n.notificationMetadata.tag, [n])),];// Sort: mentions first, then by recency@@ -125,17 +122,20 @@ const groupBy: <T, K>(items: T[], keyFn: (item: T) => K) => Map<K, T[]> =});function makeStack(- type: TypedNotification['notificationEventType'],- notifications: TypedNotification[]+ type: NotificationType,+ notifications: UnifiedNotification[]): NotificationStack[] {if (notifications.length === 0) return [];return [{ type, notifications: sortByRecency(notifications) }];}-function makeReplyStacks(- replies: TypedNotification<'channel_message_reply'>[]-): NotificationStack[] {- const byThread = groupBy(replies, (r) => getMetadata(r)?.threadId ?? '');+function makeReplyStacks(replies: UnifiedNotification[]): NotificationStack[] {+ const byThread = groupBy(replies, (r) => {+ if (r.notificationMetadata.tag === 'channel_message_reply') {+ return r.notificationMetadata.content.threadId ?? '';+ }+ return '';+ });return [...byThread.entries()].filter(([threadId]) => threadId !== '').map(([, group]) => ({diff --git a/js/app/packages/notifications/tests/notification-preview.test.ts b/js/app/packages/notifications/tests/notification-preview.test.tsindex 0519a930c9..7f44878a6f 100644--- a/js/app/packages/notifications/tests/notification-preview.test.ts+++ b/js/app/packages/notifications/tests/notification-preview.test.ts@@ -1,7 +1,4 @@import { describe, expect, it } from 'vitest';-import type { NotificationEventType } from '@service-notification/generated/schemas';-import { extractNotificationData } from '../notification-preview';-import { tryToTypedNotification } from '../notification-metadata';import type { UnifiedNotification } from '../types';function createEmailNotification(@@ -19,7 +16,7 @@ function createEmailNotification(done: false,sent: true,senderId,- notificationEventType: 'new_email' as NotificationEventType,+ notificationEventType: 'new_email',notificationMetadata: {tag: 'new_email',content: {@@ -33,25 +30,26 @@ function createEmailNotification(} as UnifiedNotification;}-describe('new_email extractor', () => {+describe('new_email notification', () => {it('prefers senderId over metadata sender', () => {const notification = createEmailNotification('macro|[email protected]',);- const typed = tryToTypedNotification(notification)!;- const data = extractNotificationData(typed);-- expect(data).toHaveProperty('actor.id', 'macro|[email protected]');+ // senderId is directly available on the notification+ expect(notification.senderId).toBe('macro|[email protected]');});it('falls back to metadata sender when senderId is null', () => {const notification = createEmailNotification(null, '[email protected]');- const typed = tryToTypedNotification(notification)!;- const data = extractNotificationData(typed);-- expect(data).toHaveProperty('actor.id', '[email protected]');+ // When senderId is null, the metadata sender can be used+ expect(notification.senderId).toBeNull();+ // Access the sender field after type assertion since we know this is a new_email notification+ const content = notification.notificationMetadata.content as {+ sender?: string | null;+ };+ expect(content.sender).toBe('[email protected]');});});diff --git a/js/app/packages/notifications/tests/notification-stacking.test.ts b/js/app/packages/notifications/tests/notification-stacking.test.tsindex 08c114e75e..ab1d72faf4 100644--- a/js/app/packages/notifications/tests/notification-stacking.test.ts+++ b/js/app/packages/notifications/tests/notification-stacking.test.ts@@ -1,4 +1,4 @@-import type { NotificationEventType } from '@service-notification/generated/schemas';+import type { NotifEvent } from '@service-notification/generated/schemas';import { describe, expect, it } from 'vitest';import {getAllNotificationsFromGroup,@@ -8,12 +8,11 @@ import {} from '../notification-stacking';import type { UnifiedNotification } from '../types';-// Helper to create a base notification-function createNotification(+// Helper to create a base notification with proper typing+function createBaseNotification(id: string,- type: NotificationEventType,createdAt: number,- metadata: Record<string, unknown> = {}+ notificationMetadata: NotifEvent): UnifiedNotification {return {id,@@ -26,12 +25,9 @@ function createNotification(done: false,sent: true,senderId: 'user-1',- notificationEventType: type,- notificationMetadata: {- tag: type,- content: metadata,- },- } as UnifiedNotification;+ notificationEventType: notificationMetadata.tag,+ notificationMetadata,+ };}function createNewMessageNotification(@@ -39,11 +35,14 @@ function createNewMessageNotification(messageId: string,createdAt: number): UnifiedNotification {- return createNotification(id, 'channel_message_send', createdAt, {- messageId,- messageContent: `Message ${id}`,- sender: 'user-1',- channelType: 'team',+ return createBaseNotification(id, createdAt, {+ tag: 'channel_message_send',+ content: {+ messageId,+ messageContent: `Message ${id}`,+ sender: 'user-1',+ channelType: 'organization',+ },});}@@ -53,12 +52,15 @@ function createReplyNotification(threadId: string,createdAt: number): UnifiedNotification {- return createNotification(id, 'channel_message_reply', createdAt, {- messageId,- threadId,- messageContent: `Reply ${id}`,- userId: 'user-1',- channelType: 'team',+ return createBaseNotification(id, createdAt, {+ tag: 'channel_message_reply',+ content: {+ messageId,+ threadId,+ messageContent: `Reply ${id}`,+ userId: 'user-1',+ channelType: 'organization',+ },});}@@ -68,11 +70,14 @@ function createMentionNotification(createdAt: number,threadId?: string): UnifiedNotification {- return createNotification(id, 'channel_mention', createdAt, {- messageId,- messageContent: `Mention ${id}`,- threadId: threadId ?? null,- channelType: 'team',+ return createBaseNotification(id, createdAt, {+ tag: 'channel_mention',+ content: {+ messageId,+ messageContent: `Mention ${id}`,+ threadId: threadId ?? null,+ channelType: 'organization',+ },});}diff --git a/js/app/packages/service-clients/service-notification/generated/client.ts b/js/app/packages/service-clients/service-notification/generated/client.tsindex 3234a325d3..a5e49ff0fb 100644--- a/js/app/packages/service-clients/service-notification/generated/client.ts+++ b/js/app/packages/service-clients/service-notification/generated/client.ts@@ -8,14 +8,12 @@ import type {ApiUserNotification,BulkGetByEventItemIdsRequest,BulkGetTypedNotificationsByEventItemIdsParams,- CreateNotification,DeviceRequest,EmptyResponse,ErrorResponse,GetAllUserNotificationsResponse,GetTypedNotificationsByEventItemIdParams,ListTypedNotificationsParams,- Notification,NotificationBulkRequest,UserUnsubscribe,} from './schemas';@@ -182,47 +180,6 @@ export const healthHandler = async (} as healthHandlerResponse;};-/**- * @summary Creates a notification.-Will generate an id for the notification.- */-export type createNotificationResponse200 = {- data: Notification;- status: 200;-};--export type createNotificationResponseSuccess =- createNotificationResponse200 & {- headers: Headers;- };--export type createNotificationResponse = createNotificationResponseSuccess;--export const getCreateNotificationUrl = () => {- return `/notifications`;-};--export const createNotification = async (- createNotification: CreateNotification,- options?: RequestInit-): Promise<createNotificationResponse> => {- const res = await fetch(getCreateNotificationUrl(), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(createNotification),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: createNotificationResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as createNotificationResponse;-};-/*** @summary Gets the users unsubscribe items.*/diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageDocumentMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageDocumentMetadata.tsdeleted file mode 100644index c7bc75301d..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageDocumentMetadata.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { DocumentMentionMetadata } from './documentMentionMetadata';--export type ChannelMessageDocumentMetadata = DocumentMentionMetadata;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadata.tsindex e119014e47..f8afe6496b 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadata.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadata.ts@@ -4,6 +4,16 @@* notification_service* OpenAPI spec version: 0.1.0*/-import type { DocumentMentionMetadataAllOf } from './documentMentionMetadataAllOf';+import type { DocumentMentionMetadataFileType } from './documentMentionMetadataFileType';-export type DocumentMentionMetadata = unknown & DocumentMentionMetadataAllOf;+/**+ * Someone mentioned a document in a channel+ */+export interface DocumentMentionMetadata {+ /** The name of the document */+ documentName: string;+ /** The file type of the document */+ fileType?: DocumentMentionMetadataFileType;+ /** The owner of the document */+ owner: 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.tsdeleted file mode 100644index 4189e356da..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOf.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { DocumentMentionMetadataAllOfFileType } from './documentMentionMetadataAllOfFileType';--export type DocumentMentionMetadataAllOf = {- /** The name of the document */- documentName: string;- /** The file type of the document */- fileType?: DocumentMentionMetadataAllOfFileType;- /** The owner of the document */- owner: string;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOfFileType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataFileType.tssimilarity index 71%rename from js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOfFileType.tsrename to js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataFileType.tsindex 11d83aa755..1e95079138 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataAllOfFileType.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/documentMentionMetadataFileType.ts@@ -8,4 +8,4 @@/*** The file type of the document*/-export type DocumentMentionMetadataAllOfFileType = string | null;+export type DocumentMentionMetadataFileType = string | null;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 20366dde80..080727249f 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@@ -18,7 +18,6 @@ export * from './channelInviteMetadataAllOf';export * from './channelMentionMetadata';export * from './channelMentionMetadataAllOf';export * from './channelMentionMetadataAllOfThreadId';-export * from './channelMessageDocumentMetadata';export * from './channelMessageSendMetadata';export * from './channelMessageSendMetadataAllOf';export * from './channelReplyMetadata';@@ -31,8 +30,7 @@ export * from './createNotificationAllOf';export * from './deviceRequest';export * from './deviceType';export * from './documentMentionMetadata';-export * from './documentMentionMetadataAllOf';-export * from './documentMentionMetadataAllOfFileType';+export * from './documentMentionMetadataFileType';export * from './emptyResponse';export * from './entity';export * from './entityType';@@ -45,10 +43,9 @@ export * from './inviteToTeamMetadataRole';export * from './itemSharedMetadata';export * from './itemSharedMetadataItemName';export * from './itemSharedMetadataPermissionLevel';-export * from './itemSharedOrganizationMetadata';-export * from './itemSharedOrganizationMetadataItemName';-export * from './itemSharedOrganizationMetadataPermissionLevel';export * from './listTypedNotificationsParams';+export * from './mentionedInDocumentCommentMetadata';+export * from './mentionedInDocumentCommentMetadataFileType';export * from './newEmailMetadata';export * from './newEmailMetadataSender';export * from './notifEvent';@@ -61,6 +58,8 @@ export * from './notifEventOneOfOnefive';export * from './notifEventOneOfOnefiveTag';export * from './notifEventOneOfOneone';export * from './notifEventOneOfOneoneTag';+export * from './notifEventOneOfOneseven';+export * from './notifEventOneOfOnesevenTag';export * from './notifEventOneOfOnethree';export * from './notifEventOneOfOnethreeTag';export * from './notifEventOneOfSeven';@@ -68,46 +67,10 @@ export * from './notifEventOneOfSevenTag';export * from './notifEventOneOfTag';export * from './notifEventOneOfThree';export * from './notifEventOneOfThreeTag';-export * from './notification';-export * from './notificationAllOf';-export * from './notificationAllOfSenderId';export * from './notificationBulkRequest';-export * from './notificationEvent';-export * from './notificationEventOneOf';-export * from './notificationEventOneOfFive';-export * from './notificationEventOneOfFiveNotificationEventType';-export * from './notificationEventOneOfNine';-export * from './notificationEventOneOfNineNotificationEventType';-export * from './notificationEventOneOfNotificationEventType';-export * from './notificationEventOneOfOnefive';-export * from './notificationEventOneOfOnefiveNotificationEventType';-export * from './notificationEventOneOfOnenine';-export * from './notificationEventOneOfOnenineNotificationEventType';-export * from './notificationEventOneOfOneone';-export * from './notificationEventOneOfOneoneNotificationEventType';-export * from './notificationEventOneOfOneseven';-export * from './notificationEventOneOfOnesevenNotificationEventType';-export * from './notificationEventOneOfOnethree';-export * from './notificationEventOneOfOnethreeNotificationEventType';-export * from './notificationEventOneOfSeven';-export * from './notificationEventOneOfSevenNotificationEventType';-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';-export * from './notificationTemporalDataDeletedAt';-export * from './notificationTemporalDataUpdatedAt';-export * from './notificationTemporalDataViewedAt';export * from './pushNotificationData';export * from './taskAssignedMetadata';export * from './taskAssignedMetadataTaskName';export * from './unsubscribeItemPathParams';-export * from './userNotification';-export * from './userNotificationAllOf';-export * from './userNotificationAllOfSenderId';export * from './userUnsubscribe';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.tsdeleted file mode 100644index d3e023505b..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadata.ts+++ /dev/null@@ -1,28 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { EntityType } from './entityType';-import type { ItemSharedOrganizationMetadataItemName } from './itemSharedOrganizationMetadataItemName';-import type { ItemSharedOrganizationMetadataPermissionLevel } from './itemSharedOrganizationMetadataPermissionLevel';--/**- * Metadata for when a item is shared with an organization- */-export interface ItemSharedOrganizationMetadata {- /** The name/title of the shared item (optional) */- itemId: string;- /** The name/title of the shared item */- itemName?: ItemSharedOrganizationMetadataItemName;- /** The type of item being shared */- itemType: EntityType;- /** List of user IDs that the item is shared with */- orgUserIds: string[];- /** Permission level granted (read, write, admin, etc.) */- permissionLevel?: ItemSharedOrganizationMetadataPermissionLevel;- /** The user who shared the item */- sharedBy: string;-}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadataPermissionLevel.ts b/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadataPermissionLevel.tsdeleted file mode 100644index 9c0001f435..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadataPermissionLevel.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--/**- * Permission level granted (read, write, admin, etc.)- */-export type ItemSharedOrganizationMetadataPermissionLevel = string | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/mentionedInDocumentCommentMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/mentionedInDocumentCommentMetadata.tsnew file mode 100644index 0000000000..518908a8a5--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/mentionedInDocumentCommentMetadata.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */+import type { MentionedInDocumentCommentMetadataFileType } from './mentionedInDocumentCommentMetadataFileType';++/**+ * Notification sent when a user is mentioned in a document comment.+ */+export interface MentionedInDocumentCommentMetadata {+ /** the comment id */+ commentId: number;+ /** The name of the document. */+ documentName: string;+ /** The file type of the document. */+ fileType?: MentionedInDocumentCommentMetadataFileType;+ /** The mention ID. */+ mentionId: string;+ /** The owner of the document. */+ owner: string;+ /** the text of the comment */+ text: string;+ /** the thread id */+ threadId: number;+}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadataItemName.ts b/js/app/packages/service-clients/service-notification/generated/schemas/mentionedInDocumentCommentMetadataFileType.tssimilarity index 55%rename from js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadataItemName.tsrename to js/app/packages/service-clients/service-notification/generated/schemas/mentionedInDocumentCommentMetadataFileType.tsindex 2dd811ba1e..bbfe5fa549 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/itemSharedOrganizationMetadataItemName.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/mentionedInDocumentCommentMetadataFileType.ts@@ -6,6 +6,6 @@*//**- * The name/title of the shared item+ * The file type of the document.*/-export type ItemSharedOrganizationMetadataItemName = string | null;+export type MentionedInDocumentCommentMetadataFileType = string | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.tsindex 485865839b..6d99e56d06 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts@@ -9,6 +9,7 @@ import type { NotifEventOneOfFive } from './notifEventOneOfFive';import type { NotifEventOneOfNine } from './notifEventOneOfNine';import type { NotifEventOneOfOnefive } from './notifEventOneOfOnefive';import type { NotifEventOneOfOneone } from './notifEventOneOfOneone';+import type { NotifEventOneOfOneseven } from './notifEventOneOfOneseven';import type { NotifEventOneOfOnethree } from './notifEventOneOfOnethree';import type { NotifEventOneOfSeven } from './notifEventOneOfSeven';import type { NotifEventOneOfThree } from './notifEventOneOfThree';@@ -29,4 +30,5 @@ export type NotifEvent =| NotifEventOneOfNine| NotifEventOneOfOneone| NotifEventOneOfOnethree- | NotifEventOneOfOnefive;+ | NotifEventOneOfOnefive+ | NotifEventOneOfOneseven;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOf.tsindex a0a1c58702..da0ffcf354 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOf.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOf.ts@@ -4,6 +4,7 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { ChannelMentionMetadata } from './channelMentionMetadata';import type { NotifEventOneOfTag } from './notifEventOneOfTag';/**@@ -11,6 +12,6 @@ import type { NotifEventOneOfTag } from './notifEventOneOfTag';*/export type NotifEventOneOf = {/** Someone mentioned you in a channel. */- content: unknown;+ content: ChannelMentionMetadata;tag: NotifEventOneOfTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFive.tsindex 5e90268405..ac5a95e984 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFive.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFive.ts@@ -4,13 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { MentionedInDocumentCommentMetadata } from './mentionedInDocumentCommentMetadata';import type { NotifEventOneOfFiveTag } from './notifEventOneOfFiveTag';/**- * The user was invited to a channel.+ * User was mentioned in a comment in a document*/export type NotifEventOneOfFive = {- /** The user was invited to a channel. */- content: unknown;+ /** User was mentioned in a comment in a document */+ content: MentionedInDocumentCommentMetadata;tag: NotifEventOneOfFiveTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFiveTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFiveTag.tsindex f150ced342..cec380fdeb 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFiveTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfFiveTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfFiveTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfFiveTag = {- channel_invite: 'channel_invite',+ mentioned_in_document_comment: 'mentioned_in_document_comment',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNine.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNine.tsindex f963be0223..15bcb0404c 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNine.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNine.ts@@ -4,13 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { ChannelMessageSendMetadata } from './channelMessageSendMetadata';import type { NotifEventOneOfNineTag } from './notifEventOneOfNineTag';/**- * Someone replied to a thread in a channel that the user is part of.+ * A user sent a message in a channel.*/export type NotifEventOneOfNine = {- /** Someone replied to a thread in a channel that the user is part of. */- content: unknown;+ /** A user sent a message in a channel. */+ content: ChannelMessageSendMetadata;tag: NotifEventOneOfNineTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNineTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNineTag.tsindex 05a2ac4a0f..cea73469c5 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNineTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfNineTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfNineTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfNineTag = {- channel_message_reply: 'channel_message_reply',+ channel_message_send: 'channel_message_send',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefive.tsindex f7443e4301..4e86c892a4 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefive.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefive.ts@@ -4,13 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { InviteToTeamMetadata } from './inviteToTeamMetadata';import type { NotifEventOneOfOnefiveTag } from './notifEventOneOfOnefiveTag';/**- * A user was assigned to a task.+ * A user was invited to a team.*/export type NotifEventOneOfOnefive = {- /** A user was assigned to a task. */- content: unknown;+ /** A user was invited to a team. */+ content: InviteToTeamMetadata;tag: NotifEventOneOfOnefiveTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefiveTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefiveTag.tsindex 97d8d0e7b5..29fcdc3276 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefiveTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnefiveTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfOnefiveTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfOnefiveTag = {- task_assigned: 'task_assigned',+ invite_to_team: 'invite_to_team',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneone.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneone.tsindex c53e3aaf7c..c16800c192 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneone.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneone.ts@@ -4,13 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { ChannelReplyMetadata } from './channelReplyMetadata';import type { NotifEventOneOfOneoneTag } from './notifEventOneOfOneoneTag';/**- * A new email has been sent to the user.+ * Someone replied to a thread in a channel that the user is part of.*/export type NotifEventOneOfOneone = {- /** A new email has been sent to the user. */- content: unknown;+ /** Someone replied to a thread in a channel that the user is part of. */+ content: ChannelReplyMetadata;tag: NotifEventOneOfOneoneTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneoneTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneoneTag.tsindex af04788408..8cbb2c4e6a 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneoneTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneoneTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfOneoneTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfOneoneTag = {- new_email: 'new_email',+ channel_message_reply: 'channel_message_reply',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneseven.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneseven.tsnew file mode 100644index 0000000000..421cb8131c--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOneseven.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * notification_service+ * OpenAPI spec version: 0.1.0+ */++import type { NotifEventOneOfOnesevenTag } from './notifEventOneOfOnesevenTag';+import type { TaskAssignedMetadata } from './taskAssignedMetadata';++/**+ * A user was assigned to a task.+ */+export type NotifEventOneOfOneseven = {+ /** A user was assigned to a task. */+ content: TaskAssignedMetadata;+ tag: NotifEventOneOfOnesevenTag;+};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnesevenTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnesevenTag.tsnew file mode 100644index 0000000000..4799ebfbce--- /dev/null+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnesevenTag.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 NotifEventOneOfOnesevenTag =+ (typeof NotifEventOneOfOnesevenTag)[keyof typeof NotifEventOneOfOnesevenTag];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const NotifEventOneOfOnesevenTag = {+ task_assigned: 'task_assigned',+} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethree.tsindex e5635943bb..45022594c0 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethree.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethree.ts@@ -4,13 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { NewEmailMetadata } from './newEmailMetadata';import type { NotifEventOneOfOnethreeTag } from './notifEventOneOfOnethreeTag';/**- * A user was invited to a team.+ * A new email has been sent to the user.*/export type NotifEventOneOfOnethree = {- /** A user was invited to a team. */- content: unknown;+ /** A new email has been sent to the user. */+ content: NewEmailMetadata;tag: NotifEventOneOfOnethreeTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethreeTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethreeTag.tsindex 0f32334084..84cacd8992 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethreeTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnethreeTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfOnethreeTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfOnethreeTag = {- invite_to_team: 'invite_to_team',+ new_email: 'new_email',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSeven.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSeven.tsindex 94044d715f..0eccae5d53 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSeven.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSeven.ts@@ -4,13 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { ChannelInviteMetadata } from './channelInviteMetadata';import type { NotifEventOneOfSevenTag } from './notifEventOneOfSevenTag';/**- * A user sent a message in a channel.+ * The user was invited to a channel.*/export type NotifEventOneOfSeven = {- /** A user sent a message in a channel. */- content: unknown;+ /** The user was invited to a channel. */+ content: ChannelInviteMetadata;tag: NotifEventOneOfSevenTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSevenTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSevenTag.tsindex 33521eafb2..0354aa14c0 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSevenTag.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfSevenTag.ts@@ -10,5 +10,5 @@ export type NotifEventOneOfSevenTag =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const NotifEventOneOfSevenTag = {- channel_message_send: 'channel_message_send',+ channel_invite: 'channel_invite',} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThree.tsindex c4e6a4590c..129d1b73af 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThree.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfThree.ts@@ -4,13 +4,14 @@* notification_service* OpenAPI spec version: 0.1.0*/+import type { DocumentMentionMetadata } from './documentMentionMetadata';import type { NotifEventOneOfThreeTag } from './notifEventOneOfThreeTag';/**- * Someone mentioned you in a document.+ * Someone mentioned a document in a channel.*/export type NotifEventOneOfThree = {- /** Someone mentioned you in a document. */- content: unknown;+ /** Someone mentioned a document in a channel. */+ content: DocumentMentionMetadata;tag: NotifEventOneOfThreeTag;};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notification.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notification.tsdeleted file mode 100644index 5dab3666f3..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notification.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { Entity } from './entity';-import type { NotificationAllOf } from './notificationAllOf';-import type { NotificationEvent } from './notificationEvent';-import type { NotificationTemporalData } from './notificationTemporalData';--export type Notification = Entity &- NotificationTemporalData &- NotificationEvent &- NotificationAllOf;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationAllOf.tsdeleted file mode 100644index 7492795b63..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationAllOf.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { NotificationAllOfSenderId } from './notificationAllOfSenderId';--export type NotificationAllOf = {- id: string;- senderId?: NotificationAllOfSenderId;- serviceSender: string;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationAllOfSenderId.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationAllOfSenderId.tsdeleted file mode 100644index 7f5e030d1b..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationAllOfSenderId.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationAllOfSenderId = string | null;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.tsdeleted file mode 100644index cfa8025312..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEvent.ts+++ /dev/null@@ -1,35 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { NotificationEventOneOf } from './notificationEventOneOf';-import type { NotificationEventOneOfFive } from './notificationEventOneOfFive';-import type { NotificationEventOneOfNine } from './notificationEventOneOfNine';-import type { NotificationEventOneOfOnefive } from './notificationEventOneOfOnefive';-import type { NotificationEventOneOfOnenine } from './notificationEventOneOfOnenine';-import type { NotificationEventOneOfOneone } from './notificationEventOneOfOneone';-import type { NotificationEventOneOfOneseven } from './notificationEventOneOfOneseven';-import type { NotificationEventOneOfOnethree } from './notificationEventOneOfOnethree';-import type { NotificationEventOneOfSeven } from './notificationEventOneOfSeven';-import type { NotificationEventOneOfThree } from './notificationEventOneOfThree';-import type { NotificationEventOneOfTwoone } from './notificationEventOneOfTwoone';-import type { NotificationEventOneOfTwothree } from './notificationEventOneOfTwothree';--/**- * The types of events that the notification system is aware of- */-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/notificationEventOneOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOf.tsdeleted file mode 100644index e4baeadac1..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOf.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { ItemSharedMetadata } from './itemSharedMetadata';-import type { NotificationEventOneOfNotificationEventType } from './notificationEventOneOfNotificationEventType';--/**- * An Item was shared with a specific user- */-export type NotificationEventOneOf = {- notificationEventType: NotificationEventOneOfNotificationEventType;- /** An Item was shared with a specific user */- notificationMetadata: ItemSharedMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfFive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfFive.tsdeleted file mode 100644index b69981ca1c..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfFive.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { ChannelMentionMetadata } from './channelMentionMetadata';-import type { NotificationEventOneOfFiveNotificationEventType } from './notificationEventOneOfFiveNotificationEventType';--/**- * Someone mentioned you in a channel- */-export type NotificationEventOneOfFive = {- notificationEventType: NotificationEventOneOfFiveNotificationEventType;- /** Someone mentioned you in a channel */- notificationMetadata: ChannelMentionMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfFiveNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfFiveNotificationEventType.tsdeleted file mode 100644index 7246b9db84..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfFiveNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfFiveNotificationEventType =- (typeof NotificationEventOneOfFiveNotificationEventType)[keyof typeof NotificationEventOneOfFiveNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfFiveNotificationEventType = {- channel_mention: 'channel_mention',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNine.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNine.tsdeleted file mode 100644index a6bef09306..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNine.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { ChannelInviteMetadata } from './channelInviteMetadata';-import type { NotificationEventOneOfNineNotificationEventType } from './notificationEventOneOfNineNotificationEventType';--/**- * The user was invited to a channel- */-export type NotificationEventOneOfNine = {- notificationEventType: NotificationEventOneOfNineNotificationEventType;- /** The user was invited to a channel */- notificationMetadata: ChannelInviteMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNineNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNineNotificationEventType.tsdeleted file mode 100644index 547f826176..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNineNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfNineNotificationEventType =- (typeof NotificationEventOneOfNineNotificationEventType)[keyof typeof NotificationEventOneOfNineNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfNineNotificationEventType = {- channel_invite: 'channel_invite',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNotificationEventType.tsdeleted file mode 100644index 695e24867e..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfNotificationEventType =- (typeof NotificationEventOneOfNotificationEventType)[keyof typeof NotificationEventOneOfNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfNotificationEventType = {- item_shared_user: 'item_shared_user',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnefive.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnefive.tsdeleted file mode 100644index f6b602f292..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnefive.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { DocumentMentionMetadata } from './documentMentionMetadata';-import type { NotificationEventOneOfOnefiveNotificationEventType } from './notificationEventOneOfOnefiveNotificationEventType';--/**- * If a document is included via mention or attachment on a message- */-export type NotificationEventOneOfOnefive = {- notificationEventType: NotificationEventOneOfOnefiveNotificationEventType;- /** If a document is included via mention or attachment on a message */- notificationMetadata: DocumentMentionMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnefiveNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnefiveNotificationEventType.tsdeleted file mode 100644index 59e4a074d9..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnefiveNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfOnefiveNotificationEventType =- (typeof NotificationEventOneOfOnefiveNotificationEventType)[keyof typeof NotificationEventOneOfOnefiveNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfOnefiveNotificationEventType = {- channel_message_document: 'channel_message_document',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnenine.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnenine.tsdeleted file mode 100644index 4fd2118fce..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnenine.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { InviteToTeamMetadata } from './inviteToTeamMetadata';-import type { NotificationEventOneOfOnenineNotificationEventType } from './notificationEventOneOfOnenineNotificationEventType';--/**- * A user was invited to a team- */-export type NotificationEventOneOfOnenine = {- notificationEventType: NotificationEventOneOfOnenineNotificationEventType;- /** A user was invited to a team */- notificationMetadata: InviteToTeamMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnenineNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnenineNotificationEventType.tsdeleted file mode 100644index 33870f4548..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnenineNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfOnenineNotificationEventType =- (typeof NotificationEventOneOfOnenineNotificationEventType)[keyof typeof NotificationEventOneOfOnenineNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfOnenineNotificationEventType = {- invite_to_team: 'invite_to_team',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneone.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneone.tsdeleted file mode 100644index b7994d26bb..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneone.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { ChannelMessageSendMetadata } from './channelMessageSendMetadata';-import type { NotificationEventOneOfOneoneNotificationEventType } from './notificationEventOneOfOneoneNotificationEventType';--/**- * A user sent a message in a channel- */-export type NotificationEventOneOfOneone = {- notificationEventType: NotificationEventOneOfOneoneNotificationEventType;- /** A user sent a message in a channel */- notificationMetadata: ChannelMessageSendMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneoneNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneoneNotificationEventType.tsdeleted file mode 100644index c43b8f7540..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneoneNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfOneoneNotificationEventType =- (typeof NotificationEventOneOfOneoneNotificationEventType)[keyof typeof NotificationEventOneOfOneoneNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfOneoneNotificationEventType = {- channel_message_send: 'channel_message_send',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneseven.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneseven.tsdeleted file mode 100644index 7a8566457a..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOneseven.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { NewEmailMetadata } from './newEmailMetadata';-import type { NotificationEventOneOfOnesevenNotificationEventType } from './notificationEventOneOfOnesevenNotificationEventType';--/**- * A new email has been sent to the user- */-export type NotificationEventOneOfOneseven = {- notificationEventType: NotificationEventOneOfOnesevenNotificationEventType;- /** A new email has been sent to the user */- notificationMetadata: NewEmailMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnesevenNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnesevenNotificationEventType.tsdeleted file mode 100644index 92309eb75e..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnesevenNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfOnesevenNotificationEventType =- (typeof NotificationEventOneOfOnesevenNotificationEventType)[keyof typeof NotificationEventOneOfOnesevenNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfOnesevenNotificationEventType = {- new_email: 'new_email',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnethree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnethree.tsdeleted file mode 100644index 655d644ce3..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnethree.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { ChannelReplyMetadata } from './channelReplyMetadata';-import type { NotificationEventOneOfOnethreeNotificationEventType } from './notificationEventOneOfOnethreeNotificationEventType';--/**- * Someone replied to a thread in a channel that the user is part of- */-export type NotificationEventOneOfOnethree = {- notificationEventType: NotificationEventOneOfOnethreeNotificationEventType;- /** Someone replied to a thread in a channel that the user is part of */- notificationMetadata: ChannelReplyMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnethreeNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnethreeNotificationEventType.tsdeleted file mode 100644index 6cbcda196c..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfOnethreeNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfOnethreeNotificationEventType =- (typeof NotificationEventOneOfOnethreeNotificationEventType)[keyof typeof NotificationEventOneOfOnethreeNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfOnethreeNotificationEventType = {- channel_message_reply: 'channel_message_reply',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfSeven.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfSeven.tsdeleted file mode 100644index fce0f3ddb2..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfSeven.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { DocumentMentionMetadata } from './documentMentionMetadata';-import type { NotificationEventOneOfSevenNotificationEventType } from './notificationEventOneOfSevenNotificationEventType';--/**- * Someone mentioned you in a document- */-export type NotificationEventOneOfSeven = {- notificationEventType: NotificationEventOneOfSevenNotificationEventType;- /** Someone mentioned you in a document */- notificationMetadata: DocumentMentionMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfSevenNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfSevenNotificationEventType.tsdeleted file mode 100644index ec893ffc7e..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfSevenNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfSevenNotificationEventType =- (typeof NotificationEventOneOfSevenNotificationEventType)[keyof typeof NotificationEventOneOfSevenNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfSevenNotificationEventType = {- document_mention: 'document_mention',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfThree.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfThree.tsdeleted file mode 100644index 315a05d3a2..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfThree.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--import type { ItemSharedOrganizationMetadata } from './itemSharedOrganizationMetadata';-import type { NotificationEventOneOfThreeNotificationEventType } from './notificationEventOneOfThreeNotificationEventType';--/**- * A item was shared with an organization- */-export type NotificationEventOneOfThree = {- notificationEventType: NotificationEventOneOfThreeNotificationEventType;- /** A item was shared with an organization */- notificationMetadata: ItemSharedOrganizationMetadata;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfThreeNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfThreeNotificationEventType.tsdeleted file mode 100644index b4b535973e..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfThreeNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfThreeNotificationEventType =- (typeof NotificationEventOneOfThreeNotificationEventType)[keyof typeof NotificationEventOneOfThreeNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfThreeNotificationEventType = {- item_shared_organization: 'item_shared_organization',-} as const;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwoone.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwoone.tsdeleted file mode 100644index b54a7fc292..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwoone.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { NotificationEventOneOfTwooneNotificationEventType } from './notificationEventOneOfTwooneNotificationEventType';--/**- * A team invite was rejected- */-export type NotificationEventOneOfTwoone = {- notificationEventType: NotificationEventOneOfTwooneNotificationEventType;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwooneNotificationEventType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwooneNotificationEventType.tsdeleted file mode 100644index 92dc7dc93f..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwooneNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationEventOneOfTwooneNotificationEventType =- (typeof NotificationEventOneOfTwooneNotificationEventType)[keyof typeof NotificationEventOneOfTwooneNotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventOneOfTwooneNotificationEventType = {- reject_team_invite: 'reject_team_invite',-} as const;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.tsdeleted file mode 100644index 957b77f583..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothree.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * 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.tsdeleted file mode 100644index 0a8530219d..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventOneOfTwothreeNotificationEventType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * 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.tsdeleted file mode 100644index bdb4e2293b..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEventType.ts+++ /dev/null@@ -1,28 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--/**- * Auto-generated discriminant enum variants- */-export type NotificationEventType =- (typeof NotificationEventType)[keyof typeof NotificationEventType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const NotificationEventType = {- item_shared_user: 'item_shared_user',- item_shared_organization: 'item_shared_organization',- channel_mention: 'channel_mention',- document_mention: 'document_mention',- channel_invite: 'channel_invite',- channel_message_send: 'channel_message_send',- channel_message_reply: 'channel_message_reply',- channel_message_document: 'channel_message_document',- 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/notificationTemporalData.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalData.tsdeleted file mode 100644index 95325ef3b7..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalData.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { NotificationTemporalDataDeletedAt } from './notificationTemporalDataDeletedAt';-import type { NotificationTemporalDataUpdatedAt } from './notificationTemporalDataUpdatedAt';-import type { NotificationTemporalDataViewedAt } from './notificationTemporalDataViewedAt';--export interface NotificationTemporalData {- createdAt: number;- deletedAt: NotificationTemporalDataDeletedAt;- updatedAt: NotificationTemporalDataUpdatedAt;- viewedAt: NotificationTemporalDataViewedAt;-}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataDeletedAt.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataDeletedAt.tsdeleted file mode 100644index ff555f726c..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataDeletedAt.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationTemporalDataDeletedAt = number | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataUpdatedAt.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataUpdatedAt.tsdeleted file mode 100644index 07ab4ebe43..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataUpdatedAt.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationTemporalDataUpdatedAt = number | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataViewedAt.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataViewedAt.tsdeleted file mode 100644index e2f013b35b..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationTemporalDataViewedAt.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--export type NotificationTemporalDataViewedAt = number | null;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/userNotification.ts b/js/app/packages/service-clients/service-notification/generated/schemas/userNotification.tsdeleted file mode 100644index 05575280fe..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/userNotification.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { Entity } from './entity';-import type { NotificationEvent } from './notificationEvent';-import type { NotificationTemporalData } from './notificationTemporalData';-import type { UserNotificationAllOf } from './userNotificationAllOf';--export type UserNotification = Entity &- NotificationTemporalData &- NotificationEvent &- UserNotificationAllOf;diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOf.tsdeleted file mode 100644index cc1fa3741d..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOf.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */-import type { UserNotificationAllOfSenderId } from './userNotificationAllOfSenderId';--export type UserNotificationAllOf = {- /** If the notification is "done" */- done: boolean;- /** The id of the notification. Self-generated uuidv7 */- id: string;- /** user id of the macro user who generated the notification */- senderId?: UserNotificationAllOfSenderId;- /** If the notification has been sent */- sent: boolean;-};diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOfSenderId.ts b/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOfSenderId.tsdeleted file mode 100644index fcd0ddb19b..0000000000--- a/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOfSenderId.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * notification_service- * OpenAPI spec version: 0.1.0- */--/**- * user id of the macro user who generated the notification- */-export type UserNotificationAllOfSenderId = string | null;diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex e63b9369d2..b9b92285b4 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -147,35 +147,6 @@}}},- "/notifications": {- "post": {- "tags": ["notification::create_notification"],- "summary": "Creates a notification.\nWill generate an id for the notification.",- "operationId": "create_notification",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/CreateNotification"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/Notification"- }- }- }- }- }- }- },"/unsubscribe": {"get": {"tags": ["unsubscribe::get_unsubscribes"],@@ -1111,9 +1082,6 @@}]},- "ChannelMessageDocumentMetadata": {- "$ref": "#/components/schemas/DocumentMentionMetadata"- },"ChannelMessageSendMetadata": {"allOf": [{@@ -1231,27 +1199,23 @@"enum": ["ios", "android"]},"DocumentMentionMetadata": {- "allOf": [- {},- {- "type": "object",- "required": ["documentName", "owner"],- "properties": {- "documentName": {- "type": "string",- "description": "The name of the document"- },- "fileType": {- "type": ["string", "null"],- "description": "The file type of the document"- },- "owner": {- "type": "string",- "description": "The owner of the document"- }- }+ "type": "object",+ "description": "Someone mentioned a document in a channel",+ "required": ["documentName", "owner"],+ "properties": {+ "documentName": {+ "type": "string",+ "description": "The name of the document"+ },+ "fileType": {+ "type": ["string", "null"],+ "description": "The file type of the document"+ },+ "owner": {+ "type": "string",+ "description": "The owner of the document"}- ]+ }},"EmptyResponse": {"type": "object",@@ -1370,37 +1334,47 @@}}},- "ItemSharedOrganizationMetadata": {+ "MentionedInDocumentCommentMetadata": {"type": "object",- "description": "Metadata for when a item is shared with an organization",- "required": ["orgUserIds", "itemType", "itemId", "sharedBy"],+ "description": "Notification sent when a user is mentioned in a document comment.",+ "required": [+ "documentName",+ "owner",+ "mentionId",+ "commentId",+ "threadId",+ "text"+ ],"properties": {- "itemId": {+ "commentId": {+ "type": "integer",+ "format": "int64",+ "description": "the comment id"+ },+ "documentName": {"type": "string",- "description": "The name/title of the shared item (optional)"+ "description": "The name of the document."},- "itemName": {+ "fileType": {"type": ["string", "null"],- "description": "The name/title of the shared item"- },- "itemType": {- "$ref": "#/components/schemas/EntityType",- "description": "The type of item being shared"+ "description": "The file type of the document."},- "orgUserIds": {- "type": "array",- "items": {- "type": "string"- },- "description": "List of user IDs that the item is shared with"+ "mentionId": {+ "type": "string",+ "description": "The mention ID."},- "permissionLevel": {- "type": ["string", "null"],- "description": "Permission level granted (read, write, admin, etc.)"+ "owner": {+ "type": "string",+ "description": "The owner of the document."},- "sharedBy": {+ "text": {"type": "string",- "description": "The user who shared the item"+ "description": "the text of the comment"+ },+ "threadId": {+ "type": "integer",+ "format": "int64",+ "description": "the thread id"}}},@@ -1433,6 +1407,7 @@"required": ["content", "tag"],"properties": {"content": {+ "$ref": "#/components/schemas/ChannelMentionMetadata","description": "Someone mentioned you in a channel."},"tag": {@@ -1443,11 +1418,12 @@},{"type": "object",- "description": "Someone mentioned you in a document.",+ "description": "Someone mentioned a document in a channel.","required": ["content", "tag"],"properties": {"content": {- "description": "Someone mentioned you in a document."+ "$ref": "#/components/schemas/DocumentMentionMetadata",+ "description": "Someone mentioned a document in a channel."},"tag": {"type": "string",@@ -1455,12 +1431,28 @@}}},+ {+ "type": "object",+ "description": "User was mentioned in a comment in a document",+ "required": ["content", "tag"],+ "properties": {+ "content": {+ "$ref": "#/components/schemas/MentionedInDocumentCommentMetadata",+ "description": "User was mentioned in a comment in a document"+ },+ "tag": {+ "type": "string",+ "enum": ["mentioned_in_document_comment"]+ }+ }+ },{"type": "object","description": "The user was invited to a channel.","required": ["content", "tag"],"properties": {"content": {+ "$ref": "#/components/schemas/ChannelInviteMetadata","description": "The user was invited to a channel."},"tag": {@@ -1475,6 +1467,7 @@"required": ["content", "tag"],"properties": {"content": {+ "$ref": "#/components/schemas/ChannelMessageSendMetadata","description": "A user sent a message in a channel."},"tag": {@@ -1489,6 +1482,7 @@"required": ["content", "tag"],"properties": {"content": {+ "$ref": "#/components/schemas/ChannelReplyMetadata","description": "Someone replied to a thread in a channel that the user is part of."},"tag": {@@ -1503,6 +1497,7 @@"required": ["content", "tag"],"properties": {"content": {+ "$ref": "#/components/schemas/NewEmailMetadata","description": "A new email has been sent to the user."},"tag": {@@ -1517,6 +1512,7 @@"required": ["content", "tag"],"properties": {"content": {+ "$ref": "#/components/schemas/InviteToTeamMetadata","description": "A user was invited to a team."},"tag": {@@ -1531,6 +1527,7 @@"required": ["content", "tag"],"properties": {"content": {+ "$ref": "#/components/schemas/TaskAssignedMetadata","description": "A user was assigned to a task."},"tag": {@@ -1542,35 +1539,6 @@],"description": "Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait."},- "Notification": {- "allOf": [- {- "$ref": "#/components/schemas/Entity"- },- {- "$ref": "#/components/schemas/NotificationTemporalData"- },- {- "$ref": "#/components/schemas/NotificationEvent"- },- {- "type": "object",- "required": ["id", "serviceSender"],- "properties": {- "id": {- "type": "string",- "format": "uuid"- },- "senderId": {- "type": ["string", "null"]- },- "serviceSender": {- "type": "string"- }- }- }- ]- },"NotificationBulkRequest": {"type": "object","description": "the notification ids that we are bulk updating",@@ -1586,231 +1554,10 @@}}},- "NotificationEvent": {- "oneOf": [- {- "type": "object",- "description": "An Item was shared with a specific user",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["item_shared_user"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/ItemSharedMetadata",- "description": "An Item was shared with a specific user"- }- }- },- {- "type": "object",- "description": "A item was shared with an organization",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["item_shared_organization"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/ItemSharedOrganizationMetadata",- "description": "A item was shared with an organization"- }- }- },- {- "type": "object",- "description": "Someone mentioned you in a channel",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["channel_mention"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/ChannelMentionMetadata",- "description": "Someone mentioned you in a channel"- }- }- },- {- "type": "object",- "description": "Someone mentioned you in a document",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["document_mention"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/DocumentMentionMetadata",- "description": "Someone mentioned you in a document"- }- }- },- {- "type": "object",- "description": "The user was invited to a channel",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["channel_invite"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/ChannelInviteMetadata",- "description": "The user was invited to a channel"- }- }- },- {- "type": "object",- "description": "A user sent a message in a channel",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["channel_message_send"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/ChannelMessageSendMetadata",- "description": "A user sent a message in a channel"- }- }- },- {- "type": "object",- "description": "Someone replied to a thread in a channel that the user is part of",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["channel_message_reply"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/ChannelReplyMetadata",- "description": "Someone replied to a thread in a channel that the user is part of"- }- }- },- {- "type": "object",- "description": "If a document is included via mention or attachment on a message",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["channel_message_document"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/ChannelMessageDocumentMetadata",- "description": "If a document is included via mention or attachment on a message"- }- }- },- {- "type": "object",- "description": "A new email has been sent to the user",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["new_email"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/NewEmailMetadata",- "description": "A new email has been sent to the user"- }- }- },- {- "type": "object",- "description": "A user was invited to a team",- "required": ["notificationMetadata", "notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "enum": ["invite_to_team"]- },- "notificationMetadata": {- "$ref": "#/components/schemas/InviteToTeamMetadata",- "description": "A user was invited to a team"- }- }- },- {- "type": "object",- "description": "A team invite was rejected",- "required": ["notificationEventType"],- "properties": {- "notificationEventType": {- "type": "string",- "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"- }- }- }- ],- "description": "The types of events that the notification system is aware of"- },- "NotificationEventType": {- "type": "string",- "description": "Auto-generated discriminant enum variants",- "enum": [- "item_shared_user",- "item_shared_organization",- "channel_mention",- "document_mention",- "channel_invite",- "channel_message_send",- "channel_message_reply",- "channel_message_document",- "new_email",- "invite_to_team",- "reject_team_invite",- "task_assigned"- ]- },"NotificationServiceApiVersion": {"type": "string","enum": ["v1"]},- "NotificationTemporalData": {- "type": "object",- "required": ["createdAt", "viewedAt", "updatedAt", "deletedAt"],- "properties": {- "createdAt": {- "type": "integer",- "format": "int64"- },- "deletedAt": {- "type": ["integer", "null"],- "format": "int64"- },- "updatedAt": {- "type": ["integer", "null"],- "format": "int64"- },- "viewedAt": {- "type": ["integer", "null"],- "format": "int64"- }- }- },"PushNotificationData": {"type": "object","required": ["notificationId"],@@ -1853,42 +1600,6 @@}}},- "UserNotification": {- "allOf": [- {- "$ref": "#/components/schemas/Entity"- },- {- "$ref": "#/components/schemas/NotificationTemporalData"- },- {- "$ref": "#/components/schemas/NotificationEvent"- },- {- "type": "object",- "required": ["id", "sent", "done"],- "properties": {- "done": {- "type": "boolean",- "description": "If the notification is \"done\""- },- "id": {- "type": "string",- "format": "uuid",- "description": "The id of the notification. Self-generated uuidv7"- },- "senderId": {- "type": ["string", "null"],- "description": "user id of the macro user who generated the notification"- },- "sent": {- "type": "boolean",- "description": "If the notification has been sent"- }- }- }- ]- },"UserUnsubscribe": {"type": "object","required": ["item_id", "item_type"],diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 983f441153..5b25f6c7ef 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5501,6 +5501,7 @@ dependencies = ["models_comms","models_pagination","notification",+ "paste","serde","serde_json","sqlx",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 38481bb279..1153385bf5 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -160,6 +160,7 @@ mockall = "0.13"nom = "8"openssl = { version = "0.10.71", features = ["vendored"] }ordered-float = "5"+paste = "1"pdfium-render = { version = "0.8.28" }quote = "1"rand = "0.9.0"diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rsindex d13ef48b73..e374296f42 100644--- a/rust/cloud-storage/comms_service/src/notification.rs+++ b/rust/cloud-storage/comms_service/src/notification.rs@@ -8,17 +8,23 @@ use comms_db_client::{use macro_db_client::notification::BasicCloudStorageItemMetadata;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::comms::ChannelParticipant;-use model_entity::EntityType;+use model_entity::{Entity, EntityType};use model_notifications::{- ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageDocumentMetadata,- ChannelMessageSendMetadata, ChannelReplyMetadata, CommonChannelMetadata,- DocumentMentionMetadata, NotificationEvent, NotificationQueueMessage,+ ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,+ ChannelReplyMetadata, CommonChannelMetadata, DocumentMentionMetadata, NotifEvent,};use notification_hex::domain::models::SendNotificationRequestBuilder;use notification_hex::domain::service::NotificationIngress;use std::{collections::HashSet, iter::once};use uuid::Uuid;+struct NotificationMsg {+ notification_entity: Entity<'static>,+ notification_event: NotifEvent,+ sender_id: Option<MacroUserIdStr<'static>>,+ recipient_ids: Vec<MacroUserIdStr<'static>>,+}+pub struct ChannelMessageEvent<'a> {channel_id: &'a Uuid,message: &'a Message,@@ -41,45 +47,46 @@ pub struct ChannelInviteEvent<'a> {fn recipients_excluding<'a>(recipients: impl IntoIterator<Item = &'a str>,exclude: impl IntoIterator<Item = &'a str>,-) -> Vec<String> {+) -> Vec<MacroUserIdStr<'static>> {let exclude_set: HashSet<&str> = exclude.into_iter().collect();recipients.into_iter().filter(|id| !exclude_set.contains(id))- .map(String::from)+ .filter_map(|id| MacroUserIdStr::parse_from_str(id).ok())+ .map(|u| u.into_owned()).collect()}fn create_notification_queue_message(channel_id: &Uuid,sender_id: MacroUserIdStr<'static>,- recipients: &[String],- notification_event: impl Into<NotificationEvent>,-) -> NotificationQueueMessage {- NotificationQueueMessage {+ recipients: Vec<MacroUserIdStr<'static>>,+ notification_event: NotifEvent,+) -> NotificationMsg {+ NotificationMsg {notification_entity: EntityType::Channel.with_entity_string(channel_id.to_string()),sender_id: Some(sender_id),- recipient_ids: Some(recipients.to_vec()),- notification_event: notification_event.into(),+ recipient_ids: recipients,+ notification_event,}}impl<'a> ChannelInviteEvent<'a> {- fn generate_notifications(&self) -> Vec<NotificationQueueMessage> {- let mut notifications: Vec<NotificationQueueMessage> = vec![];+ fn generate_notifications(&self) -> Vec<NotificationMsg> {+ let mut notifications: Vec<NotificationMsg> = vec![];if !self.recipient_user_ids.is_empty() {notifications.push(create_notification_queue_message(self.channel_id,self.invited_by_user_id.copied().into_owned(),- &recipients_excluding(+ recipients_excluding(self.recipient_user_ids.iter().map(|m| m.as_str()),once(self.invited_by_user_id.as_ref()),),- ChannelInviteMetadata {+ NotifEvent::ChannelInvite(ChannelInviteMetadata {invited_by: self.invited_by_user_id.clone(),common: self.common.clone(),- },+ }),));}@@ -88,23 +95,23 @@ impl<'a> ChannelInviteEvent<'a> {}impl ChannelMessageEvent<'_> {- fn generate_notifications(&self) -> Vec<NotificationQueueMessage> {- let mut notifications: Vec<NotificationQueueMessage> = vec![];+ fn generate_notifications(&self) -> Vec<NotificationMsg> {+ let mut notifications: Vec<NotificationMsg> = vec![];if !self.user_mentions.is_empty() {notifications.push(create_notification_queue_message(self.channel_id,self.message.sender_id.clone(),- &recipients_excluding(+ recipients_excluding(self.user_mentions.iter().map(|m| m.as_str()),once(self.message.sender_id.0.as_ref()),),- ChannelMentionMetadata {+ NotifEvent::ChannelMention(ChannelMentionMetadata {message_content: self.message.content.clone(),message_id: self.message.id.to_string(),thread_id: self.message.thread_id.map(|t| t.to_string()),common: self.channel_metadata.clone(),- },+ }),));}@@ -118,12 +125,11 @@ impl ChannelMessageEvent<'_> {notifications.push(create_notification_queue_message(self.channel_id,self.message.sender_id.clone(),- &recipients_excluding_mentions,- ChannelMessageDocumentMetadata(DocumentMentionMetadata {+ recipients_excluding_mentions.clone(),+ NotifEvent::DocumentMention(DocumentMentionMetadata {document_name: mention.item_name.clone(),owner: mention.item_owner.clone(),file_type: mention.file_type.clone(),- metadata: None,}),));}@@ -147,18 +153,18 @@ impl ChannelMessageEvent<'_> {notifications.push(create_notification_queue_message(self.channel_id,self.message.sender_id.clone(),- &recipients_excluding(+ recipients_excluding(self.thread_participants.iter().map(|p| p.as_ref()),sender_and_mentions,),- ChannelReplyMetadata {+ NotifEvent::ChannelMessageReply(ChannelReplyMetadata {thread_id: thread_id.to_string(),message_id: self.message.id.to_string(),user_id: self.message.sender_id.clone(),message_content: self.message.content.clone(),thread_parent_sender_id: self.thread_parent_sender_id.clone(),common: self.channel_metadata.clone(),- },+ }),));} else {tracing::warn!("thread participants is empty, but message has thread id");@@ -169,11 +175,11 @@ impl ChannelMessageEvent<'_> {notifications.push(create_notification_queue_message(self.channel_id,self.message.sender_id.clone(),- &recipients_without_sender_and_mentions,- ChannelInviteMetadata {+ recipients_without_sender_and_mentions.clone(),+ NotifEvent::ChannelInvite(ChannelInviteMetadata {invited_by: self.message.sender_id.clone(),common: self.channel_metadata.clone(),- },+ }),));}// Channel has messages, send message send notification@@ -181,13 +187,13 @@ impl ChannelMessageEvent<'_> {notifications.push(create_notification_queue_message(self.channel_id,self.message.sender_id.clone(),- &recipients_without_sender_and_mentions,- ChannelMessageSendMetadata {+ recipients_without_sender_and_mentions.clone(),+ NotifEvent::ChannelMessageSend(ChannelMessageSendMetadata {message_id: self.message.id.to_string(),sender: self.message.sender_id.clone(),message_content: self.message.content.to_string(),common: self.channel_metadata.clone(),- },+ }),));}}@@ -198,23 +204,14 @@ impl ChannelMessageEvent<'_> {async fn send_notification_queue_message(ingress: &impl NotificationIngress,- msg: NotificationQueueMessage,+ msg: NotificationMsg,) -> anyhow::Result<()> {let entity = msg.notification_entity;let sender_id = msg.sender_id;- let recipient_ids: HashSet<MacroUserIdStr<'_>> = msg- .recipient_ids- .unwrap_or_default()- .into_iter()- .filter_map(|id| {- MacroUserIdStr::parse_from_str(&id)- .ok()- .map(|u| u.into_owned())- })- .collect();+ let recipient_ids: HashSet<MacroUserIdStr<'_>> = msg.recipient_ids.into_iter().collect();match msg.notification_event {- NotificationEvent::ChannelInvite(metadata) => {+ NotifEvent::ChannelInvite(metadata) => {let req = SendNotificationRequestBuilder {notification_entity: entity,notification: metadata,@@ -229,7 +226,7 @@ async fn send_notification_queue_message(.await.map_err(|e| anyhow::anyhow!("{e}"))?;}- NotificationEvent::ChannelMessageSend(metadata) => {+ NotifEvent::ChannelMessageSend(metadata) => {let req = SendNotificationRequestBuilder {notification_entity: entity,notification: metadata,@@ -244,7 +241,7 @@ async fn send_notification_queue_message(.await.map_err(|e| anyhow::anyhow!("{e}"))?;}- NotificationEvent::ChannelMention(metadata) => {+ NotifEvent::ChannelMention(metadata) => {let req = SendNotificationRequestBuilder {notification_entity: entity,notification: metadata,@@ -259,7 +256,7 @@ async fn send_notification_queue_message(.await.map_err(|e| anyhow::anyhow!("{e}"))?;}- NotificationEvent::ChannelMessageReply(metadata) => {+ NotifEvent::ChannelMessageReply(metadata) => {let req = SendNotificationRequestBuilder {notification_entity: entity,notification: metadata,@@ -274,7 +271,7 @@ async fn send_notification_queue_message(.await.map_err(|e| anyhow::anyhow!("{e}"))?;}- NotificationEvent::ChannelMessageDocument(ChannelMessageDocumentMetadata(metadata)) => {+ NotifEvent::DocumentMention(metadata) => {let req = SendNotificationRequestBuilder {notification_entity: entity,notification: metadata,@@ -398,7 +395,6 @@ pub async fn dispatch_notifications_for_message(mod tests {use super::*;use model::comms::{ChannelId, ParticipantRole};- use model_notifications::NotificationEventType;use std::collections::HashMap;use uuid::Uuid;@@ -448,34 +444,36 @@ mod tests {}}+ fn is_message_notification(event: &NotifEvent) -> bool {+ matches!(+ event,+ NotifEvent::ChannelMessageSend(_)+ | NotifEvent::ChannelMessageReply(_)+ | NotifEvent::ChannelMention(_)+ )+ }++ fn uid(s: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(s).unwrap().into_owned()+ }+// Ensures that each recipient receives only one message notification- fn assert_single_message_notification_per_recipient(- notifications: &[NotificationQueueMessage],- ) {- let mut visited: HashMap<String, Vec<NotificationEventType>> = HashMap::new();-- const MESSAGE_TYPES: &[NotificationEventType] = &[- NotificationEventType::ChannelMessageSend,- NotificationEventType::ChannelMessageReply,- NotificationEventType::ChannelMention,- ];+ fn assert_single_message_notification_per_recipient(notifications: &[NotificationMsg]) {+ let mut visited: HashMap<MacroUserIdStr<'static>, usize> = HashMap::new();for n in notifications {- if !MESSAGE_TYPES.contains(&n.notification_event.event_type()) {+ if !is_message_notification(&n.notification_event) {continue;}- for r in n.recipient_ids.as_ref().unwrap() {- visited- .entry(r.clone())- .or_default()- .push(n.notification_event.event_type());+ for r in &n.recipient_ids {+ *visited.entry(r.clone()).or_default() += 1;}}- let violations = visited+ let violations: Vec<_> = visited.into_iter()- .filter(|(_, v)| v.len() > 1)- .collect::<Vec<_>>();+ .filter(|(_, count)| *count > 1)+ .collect();assert!(violations.is_empty(),@@ -526,9 +524,9 @@ mod tests {assert_single_message_notification_per_recipient(¬ifications);for n in ¬ifications {- let recipients = n.recipient_ids.as_ref().unwrap();+ let recipients = &n.recipient_ids;assert!(- !recipients.contains(&"sender".to_string()),+ !recipients.contains(&uid("macro|[email protected]")),"sender should never receive their own notifications");}@@ -574,7 +572,7 @@ mod tests {assert_eq!(notifications.len(), 1);assert!(matches!(notifications[0].notification_event,- NotificationEvent::ChannelInvite(_)+ NotifEvent::ChannelInvite(_)));}@@ -618,7 +616,7 @@ mod tests {assert_eq!(notifications.len(), 1);assert!(matches!(notifications[0].notification_event,- NotificationEvent::ChannelMessageSend(_)+ NotifEvent::ChannelMessageSend(_)));}@@ -666,26 +664,21 @@ mod tests {let mention = notifications.iter()- .find(|n| matches!(n.notification_event, NotificationEvent::ChannelMention(_)))+ .find(|n| matches!(n.notification_event, NotifEvent::ChannelMention(_))).expect("should have mention notification");- let mention_recipients = mention.recipient_ids.as_ref().unwrap();+ let mention_recipients = &mention.recipient_ids;- assert!(mention_recipients.contains(&"macro|[email protected]".to_string()));+ assert!(mention_recipients.contains(&uid("macro|[email protected]")));let send = notifications.iter()- .find(|n| {- matches!(- n.notification_event,- NotificationEvent::ChannelMessageSend(_)- )- })+ .find(|n| matches!(n.notification_event, NotifEvent::ChannelMessageSend(_))).expect("should have message send notification");- let send_recipients = send.recipient_ids.as_ref().unwrap();- assert!(!send_recipients.contains(&"macro|[email protected]".to_string()));- assert!(send_recipients.contains(&"macro|[email protected]".to_string()));+ let send_recipients = &send.recipient_ids;+ assert!(!send_recipients.contains(&uid("macro|[email protected]")));+ assert!(send_recipients.contains(&uid("macro|[email protected]")));}#[test]@@ -748,19 +741,14 @@ mod tests {let reply = notifications.iter()- .find(|n| {- matches!(- n.notification_event,- NotificationEvent::ChannelMessageReply(_)- )- })+ .find(|n| matches!(n.notification_event, NotifEvent::ChannelMessageReply(_))).expect("should have reply notification");- let recipients = reply.recipient_ids.as_ref().unwrap();- assert!(!recipients.contains(&"macro|[email protected]".to_string()));- assert!(!recipients.contains(&"macro|[email protected]".to_string()));- assert!(recipients.contains(&"macro|[email protected]".to_string()));- assert!(recipients.contains(&"macro|[email protected]".to_string()));+ let recipients = &reply.recipient_ids;+ assert!(!recipients.contains(&uid("macro|[email protected]")));+ assert!(!recipients.contains(&uid("macro|[email protected]")));+ assert!(recipients.contains(&uid("macro|[email protected]")));+ assert!(recipients.contains(&uid("macro|[email protected]")));}#[test]@@ -807,18 +795,13 @@ mod tests {let doc_notif = notifications.iter()- .find(|n| {- matches!(- n.notification_event,- NotificationEvent::ChannelMessageDocument(_)- )- })+ .find(|n| matches!(n.notification_event, NotifEvent::DocumentMention(_))).expect("should have document notification");- let recipients = doc_notif.recipient_ids.as_ref().unwrap();- assert!(!recipients.contains(&"macro|[email protected]".to_string()));- assert!(recipients.contains(&"macro|[email protected]".to_string()));- assert!(recipients.contains(&"macro|[email protected]".to_string()));+ let recipients = &doc_notif.recipient_ids;+ assert!(!recipients.contains(&uid("macro|[email protected]")));+ assert!(recipients.contains(&uid("macro|[email protected]")));+ assert!(recipients.contains(&uid("macro|[email protected]")));}#[test]@@ -860,12 +843,9 @@ mod tests {assert_single_message_notification_per_recipient(¬ifications);// Should not create reply notification with empty thread participants- let has_reply = notifications.iter().any(|n| {- matches!(- n.notification_event,- NotificationEvent::ChannelMessageReply(_)- )- });+ let has_reply = notifications+ .iter()+ .any(|n| matches!(n.notification_event, NotifEvent::ChannelMessageReply(_)));assert!(!has_reply);}diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rsindex 1501392e5c..59aad260e5 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/create_comment.rs@@ -1,10 +1,7 @@use std::sync::Arc;use crate::{- api::{- annotations::{NotifLocationType, build_mention_notif},- context::ApiContext,- },+ api::{annotations::build_mention_notif, context::ApiContext},service::conn_gateway::update_live_comment_state,};use axum::{@@ -74,11 +71,12 @@ pub async fn create_comment_handler(}match create_document_comment(&db, &document_id, &user_id, &req).await {Ok(res) => {- if let Some(Mentions { users, mention_id }) = &req.mentions {+ if let Some(Mentions { users, mention_id }) = &req.mentions+ && let Some(comment) = res.comment_thread.comments.first()+ {let request = build_mention_notif(- NotifLocationType::CreateComment,req.text,- res.comment_thread.comments.first(),+ comment,res.comment_thread.thread.thread_id,users,document_context.document_name.clone(),diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rsindex 36abf15f7f..a08053b412 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/edit_comment.rs@@ -1,8 +1,7 @@use std::sync::Arc;use crate::{- api::annotations::{NotifLocationType, build_mention_notif},- service::conn_gateway::update_live_comment_state,+ api::annotations::build_mention_notif, service::conn_gateway::update_live_comment_state,};use axum::{Json,@@ -61,9 +60,8 @@ pub async fn edit_comment_handler(Ok(res) => {if let Some(Mentions { users, mention_id }) = req.mentions {let request = build_mention_notif(- NotifLocationType::EditComment,req.text.clone().unwrap_or_else(|| "".to_string()),- Some(&res.comment),+ &res.comment,req.thread_id,&users,res.document_name.clone(),diff --git a/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rs b/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rsindex 61d44ac837..9f845b232a 100644--- a/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/annotations/mod.rs@@ -6,7 +6,7 @@ pub mod edit_anchor;pub mod edit_comment;pub mod get;-use std::{collections::HashSet, fmt::Display};+use std::collections::HashSet;use super::context::ApiContext;use axum::{@@ -16,20 +16,12 @@ use axum::{routing::{delete, get, patch, post},};use macro_db_client::annotations::CommentError;-use macro_user_id::email::ReadEmailParts;use macro_user_id::user_id::MacroUserIdStr;use model::{annotations::Comment, response::ErrorResponse};-use model_entity::Entity;use model_entity::EntityType;-use notification::domain::models::{- NotifCollapseKey, Notification, NotificationExtIos, RateLimitConfig, RateLimitKey,- SendNotificationRequestBuilder,- apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},-};-use serde::{Deserialize, Serialize};+use model_notifications::MentionedInDocumentCommentMetadata;+use notification::domain::models::SendNotificationRequestBuilder;use tower::ServiceBuilder;-use utoipa::ToSchema;-use uuid::Uuid;pub fn router(state: ApiContext) -> Router<ApiContext> {Router::new()@@ -130,114 +122,10 @@ pub fn comment_error_response(e: anyhow::Error, default_msg: &str) -> Result<Res}}-#[derive(Debug, Clone, Deserialize, ToSchema)]-pub enum NotifLocationType {- CreateComment,- EditComment,-}-impl Serialize for NotifLocationType {- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>- where- S: serde::Serializer,- {- serializer.collect_str(self)- }-}--// NB: We ulse this Display impl for `impl Serialize for NotifLocationType`.-impl Display for NotifLocationType {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(- f,- "{}",- match self {- NotifLocationType::CreateComment => "create-comment",- NotifLocationType::EditComment => "edit-comment",- }- )- }-}--#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub(in crate::api) struct Location {- r#type: NotifLocationType,- comment_id: Option<i64>,- thread_id: i64,- text: String,-}--/// Notification sent when a user is mentioned in a document comment.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct DocumentMentionNotification {- /// The name of the document.- pub document_name: String,- /// The owner of the document.- pub owner: MacroUserIdStr<'static>,- /// The file type of the document.- pub file_type: Option<String>,- /// The mention ID.- pub mention_id: String,- /// The location metadata for the mention.- pub location: Location,-}--impl Notification for DocumentMentionNotification {- const TYPE_NAME: &'static str = "document_mention";-- fn rate_limit_config() -> Option<RateLimitConfig> {- None- }-- fn rate_limit_key(&self) -> Option<RateLimitKey> {- None- }-}--impl NotificationExtIos for DocumentMentionNotification {- type NotifData = ::notification::domain::models::apple::PushNotificationData;-- fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {- let entity_type: &'static str = entity.entity_type.into();- NotifCollapseKey::new(entity_type).append(&entity.entity_id)- }-- fn into_apns<'a>(- self,- sender_id: Option<MacroUserIdStr<'a>>,- _entity: &Entity<'_>,- notification_id: Uuid,- ) -> Option<APNSPushNotification<Self::NotifData>> {- let sender = sender_id?;- let file_type_str = self.file_type.as_ref()?;- let title = sender.0.email_part().email_str().to_string();- let body = format!(- "You were mentioned in {}.{}",- self.document_name, file_type_str- );-- Some(APNSPushNotification {- aps: Aps {- alert: Some(notification::domain::models::apple::Alert::Dictionary(- AlertDictionary {- title: Some(title),- body: Some(body),- ..Default::default()- },- )),- ..Default::default()- },- push_notification_data: PushNotificationData { notification_id },- })- }-}-#[expect(clippy::too_many_arguments)]fn build_mention_notif<'a>(- notif_location_type: NotifLocationType,text: String,- comment: Option<&Comment>,+ comment: &Comment,thread_id: i64,mentions: &'a [String],document_name: String,@@ -246,18 +134,15 @@ fn build_mention_notif<'a>(sender_id: Option<MacroUserIdStr<'static>>,document_id: String,mention_id: &str,-) -> SendNotificationRequestBuilder<'a, DocumentMentionNotification> {- let notification = DocumentMentionNotification {+) -> SendNotificationRequestBuilder<'a, MentionedInDocumentCommentMetadata> {+ let notification = MentionedInDocumentCommentMetadata {document_name,owner,file_type,mention_id: mention_id.to_string(),- location: Location {- r#type: notif_location_type,- comment_id: comment.map(|c| c.comment_id),- thread_id,- text,- },+ comment_id: comment.comment_id,+ thread_id,+ text,};let recipient_ids: HashSet<MacroUserIdStr<'a>> = mentions@@ -277,35 +162,21 @@ fn build_mention_notif<'a>(mod tests {use super::*;- #[test]- fn check_ser_notif_type() -> Result<(), Box<dyn std::error::Error>> {- let a = NotifLocationType::CreateComment;- let res = serde_json::json!({- r#"type"#: a,- })- .to_string();- assert_eq!(res, r#"{"type":"create-comment"}"#);- Ok(())- }#[test]fn check_ser_meta() -> Result<(), Box<dyn std::error::Error>> {- let m = DocumentMentionNotification {+ let m = MentionedInDocumentCommentMetadata {document_name: "test".to_string(),owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),file_type: None,mention_id: "xxx".to_string(),- location: Location {- r#type: NotifLocationType::EditComment,- thread_id: 42,- comment_id: Some(99),- text: "yy".to_string(),- },+ thread_id: 42,+ comment_id: 99,+ text: "yy".to_string(),};let res = serde_json::to_string(&m).unwrap();assert!(res.contains(r#"mentionId":"xxx""#));assert!(res.contains(r#"threadId":42"#));assert!(res.contains(r#"commentId":99"#));- assert!(res.contains(r#""type":"edit-comment""#));Ok(())}}diff --git a/rust/cloud-storage/macro_env_var/Cargo.toml b/rust/cloud-storage/macro_env_var/Cargo.tomlindex a19b7f5ee7..716ff02fb7 100644--- a/rust/cloud-storage/macro_env_var/Cargo.toml+++ b/rust/cloud-storage/macro_env_var/Cargo.toml@@ -8,6 +8,6 @@ version = "0.1.0"test-comptime = [][dependencies]-paste = "1"+paste = { workspace = true }thiserror = { workspace = true }tracing = { workspace = true }diff --git a/rust/cloud-storage/macro_share_permissions/src/lib.rs b/rust/cloud-storage/macro_share_permissions/src/lib.rsindex 8190a7e5f6..865b2fcc37 100644--- a/rust/cloud-storage/macro_share_permissions/src/lib.rs+++ b/rust/cloud-storage/macro_share_permissions/src/lib.rs@@ -1,2 +1 @@-pub mod notification;pub mod user_item_access;diff --git a/rust/cloud-storage/macro_share_permissions/src/notification.rs b/rust/cloud-storage/macro_share_permissions/src/notification.rsdeleted file mode 100644index 8a8a9416dc..0000000000--- a/rust/cloud-storage/macro_share_permissions/src/notification.rs+++ /dev/null@@ -1,75 +0,0 @@-use anyhow::Context;-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::EntityType;-use model_notifications::{- ItemSharedMetadata, ItemSharedOrganizationMetadata, NotificationEvent, NotificationQueueMessage,-};-use std::str::FromStr;--#[derive(Debug)]-pub struct ItemShareNotifications {- pub user_notification: Option<NotificationQueueMessage>,- pub org_notification: Option<NotificationQueueMessage>,-}--//NOTE: @syneot - This seems to be unused ???--/// Generates a share notification event to be sent to notification queue-/// Returns two notifcaitons (<individual_user_notification>, <organization_notification>)-pub fn create_notifications_from_item_shared(- item_id: &str, // The id of the item that was shared- item_type: &str, // The type of the item that was shared- item_name: Option<String>, // The name/title of the shared item- user_id: MacroUserIdStr<'static>, // The user id that performed the edit- // The user ids that were added to the share permission- user_ids: &[String],- // The user ids that were added to the organization share permission- org_user_ids: &[String],- permission_level: Option<String>, // Permission level granted-) -> anyhow::Result<ItemShareNotifications> {- let entity_type = EntityType::from_str(item_type).context("Failed to parse entity type")?;-- let build_message =- |recipients: &[String], event_type: NotificationEvent| -> NotificationQueueMessage {- NotificationQueueMessage {- notification_entity: entity_type.with_entity_string(item_id.to_string()),- notification_event: event_type,- sender_id: Some(user_id.clone()),- recipient_ids: Some(recipients.to_vec()),- }- };-- let user_notification = if !user_ids.is_empty() {- let metadata = ItemSharedMetadata {- user_ids: user_ids.to_vec(),- item_type: entity_type,- item_id: item_id.to_string(),- item_name: item_name.clone(),- shared_by: user_id.clone(),- permission_level: permission_level.clone(),- };-- Some(build_message(user_ids, metadata.into()))- } else {- None- };-- let org_notification = if !org_user_ids.is_empty() {- let metadata = ItemSharedOrganizationMetadata {- org_user_ids: org_user_ids.to_vec(),- item_type: entity_type,- item_id: item_id.to_string(),- item_name,- shared_by: user_id.clone(),- permission_level,- };- Some(build_message(user_ids, metadata.into()))- } else {- None- };-- Ok(ItemShareNotifications {- user_notification,- org_notification,- })-}diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.tomlindex 8af2ea88ed..f1dff6e06d 100644--- a/rust/cloud-storage/model_notifications/Cargo.toml+++ b/rust/cloud-storage/model_notifications/Cargo.toml@@ -14,6 +14,7 @@ model-entity = { path = "../model-entity" }models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination" }notification = { path = "../notification" }+paste = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex e820d1b385..ef6003af3e 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -1,167 +1,18 @@-use anyhow::Context;-use chrono::{DateTime, serde::ts_seconds_option};-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::Entity;-use models_pagination::{CreatedAt, Identify, SortOn};+use chrono::serde::ts_seconds_option;use serde::{Deserialize, Serialize};-use std::hash::{DefaultHasher, Hash, Hasher};-use strum::{Display, EnumDiscriminants, EnumString};+use std::hash::{DefaultHasher, Hasher};use utoipa::ToSchema;mod device;mod metadata;-mod raw;mod unsubscribe;pub use device::*;pub use metadata::*;-pub use raw::*;pub use unsubscribe::*;-use uuid::Uuid;--#[cfg(test)]-mod tests;--macro_rules! impl_from {- (- $enum_name:ident,- $(- $variant:ident => $metadata:ident- ),* $(,)?- ) => {- $(- impl From<$metadata> for $enum_name {- fn from(value: $metadata) -> Self {- $enum_name::$variant(value)- }- }- )*- };-}--#[derive(Debug, Clone, Serialize, Deserialize, EnumDiscriminants, ToSchema)]-#[deny(missing_docs)]-#[strum_discriminants(name(NotificationEventType))]-#[strum_discriminants(derive(Serialize, Deserialize, ToSchema, EnumString, Display))]-#[strum_discriminants(serde(rename_all = "snake_case"))]-#[strum_discriminants(strum(serialize_all = "snake_case"))]-#[serde(- tag = "notificationEventType",- content = "notificationMetadata",- rename_all = "snake_case"-)]-/// The types of events that the notification system is aware of-pub enum NotificationEvent {- /// An Item was shared with a specific user- ItemSharedUser(ItemSharedMetadata),- /// A item was shared with an organization- ItemSharedOrganization(ItemSharedOrganizationMetadata),- /// Someone mentioned you in a channel- ChannelMention(ChannelMentionMetadata),- /// Someone mentioned you in a document- DocumentMention(DocumentMentionMetadata),- /// The user was invited to a channel- ChannelInvite(ChannelInviteMetadata),- /// A user sent a message in a channel- ChannelMessageSend(ChannelMessageSendMetadata),- /// Someone replied to a thread in a channel that the user is part of- ChannelMessageReply(ChannelReplyMetadata),- /// If a document is included via mention or attachment on a message- ChannelMessageDocument(ChannelMessageDocumentMetadata),- /// A new email has been sent to the user- NewEmail(NewEmailMetadata),- /// A user was invited to a team- InviteToTeam(InviteToTeamMetadata),- /// A team invite was rejected- RejectTeamInvite,- /// A user was assigned to a task- TaskAssigned(TaskAssignedMetadata),-}--impl_from! {- NotificationEvent,- ItemSharedUser => ItemSharedMetadata,- ItemSharedOrganization => ItemSharedOrganizationMetadata,- ChannelMention => ChannelMentionMetadata,- DocumentMention => DocumentMentionMetadata,- ChannelInvite => ChannelInviteMetadata,- ChannelMessageSend => ChannelMessageSendMetadata,- ChannelMessageReply => ChannelReplyMetadata,- ChannelMessageDocument => ChannelMessageDocumentMetadata,- NewEmail => NewEmailMetadata,- InviteToTeam => InviteToTeamMetadata,-}#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]#[serde(transparent)]pub struct ChannelMessageDocumentMetadata(pub DocumentMentionMetadata);-impl NotificationEvent {- pub fn event_type(&self) -> NotificationEventType {- NotificationEventType::from(self)- }-- pub fn metadata_json(&self) -> Option<serde_json::Value> {- match self {- NotificationEvent::ItemSharedUser(meta) => serde_json::to_value(meta).ok(),- NotificationEvent::ItemSharedOrganization(meta) => serde_json::to_value(meta).ok(),- NotificationEvent::ChannelMention(meta) => serde_json::to_value(meta).ok(),- NotificationEvent::DocumentMention(meta) => serde_json::to_value(meta).ok(),- NotificationEvent::ChannelInvite(meta) => serde_json::to_value(meta).ok(),- NotificationEvent::ChannelMessageSend(meta) => serde_json::to_value(meta).ok(),- NotificationEvent::ChannelMessageReply(meta) => serde_json::to_value(meta).ok(),- NotificationEvent::ChannelMessageDocument(meta) => serde_json::to_value(meta).ok(),- 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(),- }- }-- #[tracing::instrument(err)]- pub fn try_from_type_and_meta(- event_type: NotificationEventType,- metadata: Option<serde_json::Value>,- ) -> Result<Self, anyhow::Error> {- use NotificationEventType::*;-- macro_rules! deserialize_meta {- ($variant:ident) => {{- let meta = metadata.ok_or_else(|| {- anyhow::anyhow!(concat!(stringify!($variant), " requires metadata"))- })?;-- serde_json::from_value(meta.clone())- .map(Self::$variant)- .with_context(|| {- format!(- "Failed to deserialize {} metadata. Metadata was: {}",- stringify!($variant),- serde_json::to_string_pretty(&meta)- .unwrap_or_else(|_| format!("{:?}", meta))- )- })- }};- }-- match event_type {- ItemSharedUser => deserialize_meta!(ItemSharedUser),- ItemSharedOrganization => deserialize_meta!(ItemSharedOrganization),- ChannelMention => deserialize_meta!(ChannelMention),- DocumentMention => deserialize_meta!(DocumentMention),- ChannelInvite => deserialize_meta!(ChannelInvite),- ChannelMessageSend => deserialize_meta!(ChannelMessageSend),- ChannelMessageReply => deserialize_meta!(ChannelMessageReply),- ChannelMessageDocument => deserialize_meta!(ChannelMessageDocument),- NewEmail => deserialize_meta!(NewEmail),- InviteToTeam => deserialize_meta!(InviteToTeam),- RejectTeamInvite => match metadata {- None => Ok(Self::RejectTeamInvite),- Some(_) => Err(anyhow::anyhow!("RejectTeamInvite should not have metadata")),- },- TaskAssigned => deserialize_meta!(TaskAssigned),- }- }-}-type TimestampOption = Option<chrono::DateTime<chrono::Utc>>;#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, Default)]@@ -181,54 +32,6 @@ pub struct NotificationTemporalData {pub deleted_at: TimestampOption,}-#[derive(Serialize, Deserialize, Debug, ToSchema, Clone)]-#[serde(rename_all = "camelCase")]-pub struct UserNotification {- /// The id of the notification. Self-generated uuidv7- pub id: Uuid,- #[serde(flatten)]- pub notification_entity: Entity<'static>,- /// If the notification has been sent- pub sent: bool,- /// If the notification is "done"- pub done: bool,- /// user id of the macro user who generated the notification- #[schema(value_type = Option<String>)]- pub sender_id: Option<MacroUserIdStr<'static>>,- #[serde(flatten)]- pub temporal: NotificationTemporalData,- #[serde(flatten)]- pub notification_event: NotificationEvent,-}--impl UserNotification {- pub fn build_key(&self) -> NotifCollapseKey {- match &self.notification_event {- NotificationEvent::ChannelMention(channel_mention_metadata) => {- NotifCollapseKey::new(&channel_mention_metadata.message_id)- }- NotificationEvent::ChannelMessageSend(channel_message_send_metadata) => {- NotifCollapseKey::new(&channel_message_send_metadata.message_id)- }- NotificationEvent::ChannelMessageReply(channel_reply_metadata) => {- NotifCollapseKey::new(&channel_reply_metadata.message_id)- }- NotificationEvent::ItemSharedOrganization(_)- | NotificationEvent::DocumentMention(_)- | NotificationEvent::ChannelInvite(_)- | NotificationEvent::ChannelMessageDocument(_)- | NotificationEvent::ItemSharedUser(_)- | NotificationEvent::RejectTeamInvite- | NotificationEvent::NewEmail(_)- | NotificationEvent::InviteToTeam(_)- | NotificationEvent::TaskAssigned(_) => {- let entity_type: &'static str = self.notification_entity.entity_type.into();- NotifCollapseKey::new(entity_type).append(&self.notification_entity.entity_id)- }- }- }-}-/// used to build up the data to construct a [HashedCollapseKey]pub struct NotifCollapseKey(DefaultHasher);@@ -271,64 +74,6 @@ impl NotifCollapseKey {}}-// CAUTION: for hash map purposes we need Hash+Eq impl on UserNotification-// User notifications are considered equal based only on their id--impl PartialEq for UserNotification {- fn eq(&self, other: &Self) -> bool {- self.id == other.id- }-}--impl Eq for UserNotification {}--impl std::hash::Hash for UserNotification {- fn hash<H: std::hash::Hasher>(&self, state: &mut H) {- self.id.hash(state);- }-}--impl UserNotification {- /// Create a new UserNotification from a Notification- pub fn from_new_notification(notification: Notification, sent: bool, done: bool) -> Self {- Self {- id: notification.id,- notification_entity: notification.notification_entity,- sent,- done,- sender_id: notification.sender_id,- temporal: notification.temporal,- notification_event: notification.notification_event,- }- }-}--#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct Notification {- pub id: Uuid,- #[serde(flatten)]- pub notification_entity: Entity<'static>,- pub service_sender: String,- #[schema(value_type = Option<String>)]- pub sender_id: Option<MacroUserIdStr<'static>>,- #[serde(flatten)]- pub temporal: NotificationTemporalData,- #[serde(flatten)]- pub notification_event: NotificationEvent,-}--#[derive(Serialize, Deserialize, Debug, ToSchema, Hash, PartialEq, Eq, Clone)]-#[serde(rename_all = "camelCase")]-pub struct NotificationWithRecipient {- #[serde(flatten)]- pub inner: UserNotification,- // USER-SPECIFIC FIELDS- /// The user actually receiving the notification. used in intermediary processing- #[serde(skip_serializing)]- pub recipient_id: MacroUserIdStr<'static>,-}-#[derive(Debug, Clone)]pub enum DeviceEndpoint {Android(String),@@ -344,39 +89,109 @@ impl DeviceEndpoint {}}-#[derive(Serialize, Deserialize, Debug)]-#[serde(rename_all = "camelCase")]-pub struct NotificationQueueMessage {- #[serde(flatten)]- pub notification_entity: Entity<'static>,- #[serde(flatten, rename = "metadata")]- pub notification_event: NotificationEvent,- pub sender_id: Option<MacroUserIdStr<'static>>,- pub recipient_ids: Option<Vec<String>>,-}+/// Defines a notification event enum with compile-time safety guarantees.+///+/// The `tag` field in the database row is the `Notification::TYPE_NAME` of the+/// metadata that was stored. When we deserialize that row back into this enum,+/// serde matches the `tag` value against the `snake_case` of the variant name.+/// If those two strings ever diverge, deserialization fails at runtime.+/// This macro prevents that by asserting the invariant at compile time.+///+/// Accepts a standard enum definition and emits it unchanged, then generates+/// `const` assertions that verify two properties for every `Variant(MetadataType)`:+///+/// 1. `MetadataType` implements [`Notification`](::notification::domain::models::Notification).+/// 2. `MetadataType::TYPE_NAME` equals the variant name converted to `snake_case`+/// (via [`paste`]), which is also the serde tag produced by `rename_all = "snake_case"`.+///+/// Because the enum and the assertions share the same variant list, adding a new+/// variant without a matching `Notification` impl — or with a mismatched+/// `TYPE_NAME` — is a compile error.+macro_rules! define_notif_event {+ (+ $(#[$enum_meta:meta])*+ $vis:vis enum $Name:ident {+ $(+ $(#[$variant_meta:meta])*+ $Variant:ident($(#[$field_meta:meta])* $Ty:ty),+ )++ }+ ) => {+ $(#[$enum_meta])*+ $vis enum $Name {+ $(+ $(#[$variant_meta])*+ $Variant($(#[$field_meta])* $Ty),+ )++ }-impl Identify for UserNotification {- type Id = Uuid;- fn id(&self) -> Self::Id {- self.id- }-}+ // Compile-time assertions:+ // 1. Every inner type implements Notification.+ // 2. TYPE_NAME matches the snake_case of the variant name.+ paste::paste! {+ const _: () = {+ const fn str_eq(a: &[u8], b: &[u8]) -> bool {+ if a.len() != b.len() { return false; }+ let mut i = 0;+ while i < a.len() {+ if a[i] != b[i] { return false; }+ i += 1;+ }+ true+ }-impl Identify for Notification {- type Id = Uuid;- fn id(&self) -> Self::Id {- self.id- }+ $(+ const _: () = assert!(+ str_eq(+ <$Ty as ::notification::domain::models::Notification>::TYPE_NAME.as_bytes(),+ stringify!([< $Variant:snake >]).as_bytes(),+ ),+ concat!(+ stringify!($Name), "::", stringify!($Variant),+ " snake_case does not match Notification::TYPE_NAME for ", stringify!($Ty),+ ),+ );+ )++ };+ }+ };}-impl SortOn<CreatedAt> for UserNotification {- fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> models_pagination::CursorVal<CreatedAt> {- move |v| {- let last_val = v.temporal.created_at.unwrap_or(DateTime::UNIX_EPOCH);- models_pagination::CursorVal {- sort_type: sort,- last_val,- }- }+define_notif_event!(+ /// Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`+ /// as the serde adjacently-tagged field names so it can be deserialized from the+ /// shape produced by [`UserNotificationRow::into_tagged`] ++ /// [`UserNotificationRow::into_json`].+ ///+ /// Only includes variants whose metadata types implement the `Notification` trait.+ #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+ #[serde(tag = "tag", content = "content", rename_all = "snake_case")]+ pub enum NotifEvent {+ /// Someone mentioned you in a channel.+ ChannelMention(ChannelMentionMetadata),++ /// Someone mentioned a document in a channel.+ DocumentMention(DocumentMentionMetadata),++ /// User was mentioned in a comment in a document+ MentionedInDocumentComment(MentionedInDocumentCommentMetadata),++ /// The user was invited to a channel.+ ChannelInvite(ChannelInviteMetadata),++ /// A user sent a message in a channel.+ ChannelMessageSend(ChannelMessageSendMetadata),++ /// Someone replied to a thread in a channel that the user is part of.+ ChannelMessageReply(ChannelReplyMetadata),++ /// A new email has been sent to the user.+ NewEmail(NewEmailMetadata),++ /// A user was invited to a team.+ InviteToTeam(InviteToTeamMetadata),++ /// A user was assigned to a task.+ TaskAssigned(TaskAssignedMetadata),}-}+);diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rsindex 1533fad299..935be6c413 100644--- a/rust/cloud-storage/model_notifications/src/metadata.rs+++ b/rust/cloud-storage/model_notifications/src/metadata.rs@@ -1,16 +1,16 @@-use crate::NotificationEventType;use doppleganger::Doppleganger;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::RateLimitConfig;use notification::domain::models::RateLimitKey;use notification::domain::models::{NotifCollapseKey, NotificationExtIos,apple::{APNSPushNotification, AlertDictionary, Aps, PushNotificationData},};-use serde::{Deserialize, Serialize, de::DeserializeOwned};+use serde::{Deserialize, Serialize};use utoipa::ToSchema;use uuid::Uuid;@@ -106,31 +106,6 @@ pub struct ItemSharedMetadata {pub permission_level: Option<String>,}-/// Metadata for when a item is shared with an organization-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct ItemSharedOrganizationMetadata {- /// List of user IDs that the item is shared with- #[serde(alias = "org_user_ids")]- pub org_user_ids: Vec<String>,- /// The type of item being shared- #[serde(alias = "item_type")]- pub item_type: EntityType,- /// The name/title of the shared item (optional)- #[serde(alias = "item_id")]- pub item_id: String,- /// The name/title of the shared item- #[serde(alias = "item_name")]- pub item_name: Option<String>,- /// The user who shared the item- #[serde(alias = "shared_by")]- #[schema(value_type = String)]- pub shared_by: MacroUserIdStr<'static>,- /// Permission level granted (read, write, admin, etc.)- #[serde(alias = "permission_level")]- pub permission_level: Option<String>,-}-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]pub struct InviteToTeamMetadata {@@ -190,6 +165,7 @@ pub struct ChannelReplyMetadata {pub common: CommonChannelMetadata,}+/// Someone mentioned a document in a channel#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]pub struct DocumentMentionMetadata {@@ -202,9 +178,6 @@ pub struct DocumentMentionMetadata {/// The file type of the document#[serde(alias = "file_type")]pub file_type: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- #[serde(flatten)]- pub metadata: Option<serde_json::Value>,}impl From<DocumentMentionMetadata> for serde_json::Value {@@ -325,54 +298,6 @@ pub struct TaskAssignedMetadata {pub assigned_by: MacroUserIdStr<'static>,}-pub trait NotificationMetadata: Serialize + DeserializeOwned + Clone + Sized {- fn event_type() -> NotificationEventType;-- fn to_json(&self) -> Option<serde_json::Value> {- serde_json::to_value(self).ok()- }-- fn from_json(value: serde_json::Value) -> Option<Self> {- serde_json::from_value(value).ok()- }-}--macro_rules! impl_notification_metadata {- ($metadata_type:ty, $event_type:expr) => {- impl NotificationMetadata for $metadata_type {- fn event_type() -> NotificationEventType {- $event_type- }- }- };-}--impl_notification_metadata!(ChannelInviteMetadata, NotificationEventType::ChannelInvite);-impl_notification_metadata!(- ChannelMessageSendMetadata,- NotificationEventType::ChannelMessageSend-);-impl_notification_metadata!(ItemSharedMetadata, NotificationEventType::ItemSharedUser);-impl_notification_metadata!(- ItemSharedOrganizationMetadata,- NotificationEventType::ItemSharedOrganization-);-impl_notification_metadata!(InviteToTeamMetadata, NotificationEventType::InviteToTeam);-impl_notification_metadata!(- ChannelMentionMetadata,- NotificationEventType::ChannelMention-);-impl_notification_metadata!(- DocumentMentionMetadata,- NotificationEventType::DocumentMention-);-impl_notification_metadata!(- ChannelReplyMetadata,- NotificationEventType::ChannelMessageReply-);-impl_notification_metadata!(NewEmailMetadata, NotificationEventType::NewEmail);-impl_notification_metadata!(TaskAssignedMetadata, NotificationEventType::TaskAssigned);-// Plain text formatter for converting XML message content to plain text for APNS payloads.struct PlainTextFormatter;@@ -628,3 +553,74 @@ impl NotificationExtIos for TaskAssignedMetadata {))}}++/// Notification sent when a user is mentioned in a document comment.+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct MentionedInDocumentCommentMetadata {+ /// The name of the document.+ pub document_name: String,+ /// The owner of the document.+ #[schema(value_type = String)]+ pub owner: MacroUserIdStr<'static>,+ /// The file type of the document.+ pub file_type: Option<String>,+ /// The mention ID.+ pub mention_id: String,+ /// the comment id+ pub comment_id: i64,+ /// the thread id+ pub thread_id: i64,+ /// the text of the comment+ pub text: String,+}++impl Notification for MentionedInDocumentCommentMetadata {+ const TYPE_NAME: &'static str = "mentioned_in_document_comment";++ fn rate_limit_config() -> Option<RateLimitConfig> {+ None+ }++ fn rate_limit_key(&self) -> Option<RateLimitKey> {+ None+ }+}++impl NotificationExtIos for MentionedInDocumentCommentMetadata {+ type NotifData = ::notification::domain::models::apple::PushNotificationData;++ fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {+ let entity_type: &'static str = entity.entity_type.into();+ NotifCollapseKey::new(entity_type).append(&entity.entity_id)+ }++ fn into_apns<'a>(+ self,+ sender_id: Option<MacroUserIdStr<'a>>,+ _entity: &Entity<'_>,+ notification_id: Uuid,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ let sender = sender_id?;+ let file_type_str = self.file_type.as_ref()?;+ let title = sender.0.email_part().email_str().to_string();+ let body = format!(+ "You were mentioned in {}.{}",+ self.document_name, file_type_str+ );++ Some(APNSPushNotification {+ aps: Aps {+ alert: Some(notification::domain::models::apple::Alert::Dictionary(+ AlertDictionary {+ title: Some(title),+ body: Some(body),+ ..Default::default()+ },+ )),+ ..Default::default()+ },+ push_notification_data: PushNotificationData { notification_id },+ })+ }+}diff --git a/rust/cloud-storage/model_notifications/src/raw.rs b/rust/cloud-storage/model_notifications/src/raw.rsdeleted file mode 100644index d7dd84dbe7..0000000000--- a/rust/cloud-storage/model_notifications/src/raw.rs+++ /dev/null@@ -1,255 +0,0 @@-use crate::{- Notification, NotificationEvent, NotificationEventType, NotificationTemporalData,- UserNotification,-};-use anyhow::Context;-use chrono::{DateTime, serde::ts_seconds_option};-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::{Entity, EntityType};-use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};-use serde::{Deserialize, Serialize};-use sqlx::types::Uuid;-use std::str::FromStr;-use utoipa::ToSchema;--/// NOTE: This should only be used for deserialization from the db-/// In business logic or api code, use the [UserNotification] type-#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct RawNotification {- /// The id of the notification. Self-generated uuidv7- pub id: Uuid,- /// The type of notification- pub notification_event_type: String,- /// The [Entity] the notification event was created for- #[serde(flatten)]- pub entity: Entity<'static>,- /// The service that created the notification- pub service_sender: String,- /// The time the notification was created- #[serde(with = "ts_seconds_option")]- #[schema(value_type = i64, nullable=false)]- pub created_at: Option<chrono::DateTime<chrono::Utc>>,- /// Custom metadata that may be needed for the notification- pub metadata: Option<serde_json::Value>,- /// user id of the macro user who generated the notification- #[schema(value_type = Option<String>)]- pub sender_id: Option<MacroUserIdStr<'static>>,-}--/// NOTE: This should only be used for deserialization from the db-/// In business logic or api code, use the [UserNotification] type-#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct RawUserNotification {- /// The user id (renamed to owner_id to match the other models for soup)- pub owner_id: String,- /// The id of the notification. Self-generated uuidv7- pub notification_id: Uuid,- /// The type of notification- pub notification_event_type: String,- /// The [Entity] which the notification is related to- #[serde(flatten)]- pub entity: Entity<'static>,- /// If the notification has been sent- pub sent: bool,- /// If the notification is "done"- pub done: bool,- /// The time the notification was created- #[serde(with = "ts_seconds_option")]- #[schema(value_type = i64, nullable = false)]- pub created_at: Option<chrono::DateTime<chrono::Utc>>,- /// The time the notification was seen- #[serde(with = "ts_seconds_option")]- #[schema(value_type = i64, nullable = true)]- pub viewed_at: Option<chrono::DateTime<chrono::Utc>>,- /// The time the notification was deleted- #[serde(with = "ts_seconds_option")]- #[schema(value_type = i64, nullable = true)]- pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,- /// Custom metadata that may be provided from the notification- pub notification_metadata: Option<serde_json::Value>,- /// user id of the macro user who generated the notification- #[schema(value_type = Option<String>)]- pub sender_id: Option<MacroUserIdStr<'static>>,- /// The time the notification was updated.- /// This is the exact same as created_at and only used to make soup- /// bettter on the frontend.- #[serde(with = "ts_seconds_option")]- #[schema(value_type = i64, nullable = true)]- pub updated_at: Option<chrono::DateTime<chrono::Utc>>,-}--// Account for legacy notification event types-impl TryFrom<&RawNotification> for NotificationEventType {- type Error = anyhow::Error;- fn try_from(raw: &RawNotification) -> Result<Self, Self::Error> {- if raw.notification_event_type == "mention" {- match raw.entity.entity_type {- EntityType::Channel => Ok(NotificationEventType::ChannelMention),- EntityType::Document => Ok(NotificationEventType::DocumentMention),- _ => anyhow::bail!("Unknown event item type"),- }- } else {- NotificationEventType::from_str(&raw.notification_event_type).context(format!(- "Failed to parse notification event type {:?}",- &raw.notification_event_type- ))- }- }-}--// Account for legacy notification event types-impl TryFrom<&RawUserNotification> for NotificationEventType {- type Error = anyhow::Error;- #[tracing::instrument(err)]- fn try_from(raw: &RawUserNotification) -> Result<Self, Self::Error> {- if raw.notification_event_type == "mention" {- match &raw.entity.entity_type {- EntityType::Channel => Ok(NotificationEventType::ChannelMention),- EntityType::Document => Ok(NotificationEventType::DocumentMention),- _ => anyhow::bail!("Unknown event item type"),- }- } else {- NotificationEventType::from_str(&raw.notification_event_type).context(format!(- "Failed to parse notification event type {:?}",- &raw.notification_event_type- ))- }- }-}--impl From<UserNotification> for RawUserNotification {- fn from(user_notification: UserNotification) -> Self {- RawUserNotification {- owner_id: String::new(),- notification_id: user_notification.id,- notification_event_type: user_notification- .notification_event- .event_type()- .to_string(),- entity: user_notification.notification_entity,- sent: user_notification.sent,- done: user_notification.done,- created_at: user_notification.temporal.created_at,- viewed_at: user_notification.temporal.viewed_at,- deleted_at: user_notification.temporal.deleted_at,- notification_metadata: user_notification.notification_event.metadata_json(),- sender_id: user_notification.sender_id,- updated_at: user_notification.temporal.updated_at,- }- }-}--impl TryFrom<RawNotification> for Notification {- type Error = anyhow::Error;-- fn try_from(raw: RawNotification) -> Result<Self, Self::Error> {- let event_type = NotificationEventType::try_from(&raw).context(format!(- "Failed to parse notification event type {:?}",- &raw.notification_event_type- ))?;-- let notification_event =- NotificationEvent::try_from_type_and_meta(event_type, raw.metadata)- .context("Failed to parse notification event")?;-- Ok(Notification {- id: raw.id,- notification_entity: raw.entity,- service_sender: raw.service_sender,- sender_id: raw.sender_id,- temporal: NotificationTemporalData {- created_at: raw.created_at,- viewed_at: None,- updated_at: raw.created_at,- deleted_at: None,- },- notification_event,- })- }-}--impl TryFrom<RawUserNotification> for UserNotification {- type Error = anyhow::Error;-- #[tracing::instrument(err)]- fn try_from(raw: RawUserNotification) -> Result<Self, Self::Error> {- let event_type = NotificationEventType::try_from(&raw).context(format!(- "Failed to parse notification event type {:?}",- &raw.notification_event_type- ))?;-- let notification_event =- NotificationEvent::try_from_type_and_meta(event_type, raw.notification_metadata)?;-- Ok(UserNotification {- id: raw.notification_id,- notification_entity: raw.entity,- sent: raw.sent,- done: raw.done,- sender_id: raw.sender_id,- temporal: NotificationTemporalData {- created_at: raw.created_at,- viewed_at: raw.viewed_at,- updated_at: raw.updated_at,- deleted_at: raw.deleted_at,- },- notification_event,- })- }-}--impl From<Notification> for RawNotification {- fn from(notification: Notification) -> Self {- RawNotification {- id: notification.id,- notification_event_type: notification.notification_event.event_type().to_string(),- entity: notification.notification_entity,- service_sender: notification.service_sender,- created_at: notification.temporal.created_at,- metadata: notification.notification_event.metadata_json(),- sender_id: notification.sender_id,- }- }-}--impl Identify for RawUserNotification {- type Id = Uuid;-- fn id(&self) -> Uuid {- self.notification_id- }-}--impl Identify for RawNotification {- type Id = Uuid;-- fn id(&self) -> Self::Id {- self.id- }-}--impl SortOn<CreatedAt> for RawNotification {- fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> models_pagination::CursorVal<CreatedAt> {- move |v| {- let last_val = v.created_at.unwrap_or(DateTime::UNIX_EPOCH);- CursorVal {- sort_type: sort,- last_val,- }- }- }-}--impl SortOn<CreatedAt> for RawUserNotification {- fn sort_on(sort: CreatedAt) -> impl FnMut(&Self) -> models_pagination::CursorVal<CreatedAt> {- move |v| {- let last_val = v.created_at.unwrap_or(DateTime::UNIX_EPOCH);- CursorVal {- sort_type: sort,- last_val,- }- }- }-}diff --git a/rust/cloud-storage/model_notifications/src/tests.rs b/rust/cloud-storage/model_notifications/src/tests.rsdeleted file mode 100644index 6b17c87779..0000000000--- a/rust/cloud-storage/model_notifications/src/tests.rs+++ /dev/null@@ -1,473 +0,0 @@-use super::*;-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::EntityType;--fn make_user_id(email: &str) -> MacroUserIdStr<'static> {- MacroUserIdStr::try_from_email(email).expect("valid test email")-}--fn create_base_notification(- notification_event: NotificationEvent,- entity_type: EntityType,- entity_id: &str,-) -> UserNotification {- UserNotification {- id: Uuid::new_v4(),- notification_entity: entity_type.with_entity_string(entity_id.to_string()),- sent: false,- done: false,- sender_id: Some(make_user_id("[email protected]")),- temporal: NotificationTemporalData::default(),- notification_event,- }-}--#[test]-fn test_build_key_channel_mention_uses_message_id() {- let notif = create_base_notification(- NotificationEvent::ChannelMention(ChannelMentionMetadata {- message_id: "msg_123".to_string(),- message_content: "Hello @user".to_string(),- thread_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "general".to_string(),- },- }),- EntityType::Channel,- "channel_abc",- );-- let key = notif.build_key().into_hashed();-- // Two notifications with the same message_id should produce the same collapse key- let notif2 = create_base_notification(- NotificationEvent::ChannelMention(ChannelMentionMetadata {- message_id: "msg_123".to_string(),- message_content: "Different content".to_string(),- thread_id: Some("thread_1".to_string()),- common: CommonChannelMetadata {- channel_type: ChannelType::Private,- channel_name: "different-channel".to_string(),- },- }),- EntityType::Channel,- "different_channel_id",- );-- let key2 = notif2.build_key().into_hashed();- assert_eq!(key.as_ref(), key2.as_ref());-}--#[test]-fn test_build_key_channel_mention_different_message_ids_produce_different_keys() {- let notif1 = create_base_notification(- NotificationEvent::ChannelMention(ChannelMentionMetadata {- message_id: "msg_123".to_string(),- message_content: "Hello".to_string(),- thread_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "general".to_string(),- },- }),- EntityType::Channel,- "channel_abc",- );-- let notif2 = create_base_notification(- NotificationEvent::ChannelMention(ChannelMentionMetadata {- message_id: "msg_456".to_string(),- message_content: "Hello".to_string(),- thread_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "general".to_string(),- },- }),- EntityType::Channel,- "channel_abc",- );-- let key1 = notif1.build_key().into_hashed();- let key2 = notif2.build_key().into_hashed();- assert_ne!(key1.as_ref(), key2.as_ref());-}--#[test]-fn test_build_key_channel_message_send_uses_message_id() {- let notif = create_base_notification(- NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {- sender: make_user_id("[email protected]"),- message_content: "Hello world".to_string(),- message_id: "msg_send_123".to_string(),- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "general".to_string(),- },- }),- EntityType::Channel,- "channel_abc",- );-- let key = notif.build_key().into_hashed();-- // Same message_id should produce same key regardless of other fields- let notif2 = create_base_notification(- NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {- sender: make_user_id("[email protected]"),- message_content: "Different message".to_string(),- message_id: "msg_send_123".to_string(),- common: CommonChannelMetadata {- channel_type: ChannelType::Private,- channel_name: "other-channel".to_string(),- },- }),- EntityType::Channel,- "different_channel",- );-- let key2 = notif2.build_key().into_hashed();- assert_eq!(key.as_ref(), key2.as_ref());-}--#[test]-fn test_build_key_channel_message_reply_uses_message_id() {- let notif = create_base_notification(- NotificationEvent::ChannelMessageReply(ChannelReplyMetadata {- thread_id: "thread_abc".to_string(),- message_id: "reply_msg_123".to_string(),- user_id: make_user_id("[email protected]"),- message_content: "This is a reply".to_string(),- thread_parent_sender_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "general".to_string(),- },- }),- EntityType::Channel,- "channel_abc",- );-- let key = notif.build_key().into_hashed();-- // Same message_id should produce same key- let notif2 = create_base_notification(- NotificationEvent::ChannelMessageReply(ChannelReplyMetadata {- thread_id: "different_thread".to_string(),- message_id: "reply_msg_123".to_string(),- user_id: make_user_id("[email protected]"),- message_content: "Different reply".to_string(),- thread_parent_sender_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Private,- channel_name: "other".to_string(),- },- }),- EntityType::Channel,- "different_channel",- );-- let key2 = notif2.build_key().into_hashed();- assert_eq!(key.as_ref(), key2.as_ref());-}--#[test]-fn test_build_key_item_shared_user_uses_entity() {- let notif = create_base_notification(- NotificationEvent::ItemSharedUser(ItemSharedMetadata {- user_ids: vec!["user1".to_string()],- item_type: EntityType::Document,- item_id: "doc_123".to_string(),- item_name: Some("My Document".to_string()),- shared_by: make_user_id("[email protected]"),- permission_level: Some("read".to_string()),- }),- EntityType::Document,- "doc_entity_123",- );-- let key = notif.build_key().into_hashed();-- // Same entity_type + entity_id should produce same key- let notif2 = create_base_notification(- NotificationEvent::ItemSharedUser(ItemSharedMetadata {- user_ids: vec!["user2".to_string(), "user3".to_string()],- item_type: EntityType::Project,- item_id: "different_item".to_string(),- item_name: Some("Different Name".to_string()),- shared_by: make_user_id("[email protected]"),- permission_level: Some("write".to_string()),- }),- EntityType::Document,- "doc_entity_123",- );-- let key2 = notif2.build_key().into_hashed();- assert_eq!(key.as_ref(), key2.as_ref());-}--#[test]-fn test_build_key_item_shared_user_different_entities_produce_different_keys() {- let notif1 = create_base_notification(- NotificationEvent::ItemSharedUser(ItemSharedMetadata {- user_ids: vec!["user1".to_string()],- item_type: EntityType::Document,- item_id: "doc_123".to_string(),- item_name: None,- shared_by: make_user_id("[email protected]"),- permission_level: None,- }),- EntityType::Document,- "doc_entity_123",- );-- let notif2 = create_base_notification(- NotificationEvent::ItemSharedUser(ItemSharedMetadata {- user_ids: vec!["user1".to_string()],- item_type: EntityType::Document,- item_id: "doc_123".to_string(),- item_name: None,- shared_by: make_user_id("[email protected]"),- permission_level: None,- }),- EntityType::Document,- "doc_entity_456", // Different entity_id- );-- let key1 = notif1.build_key().into_hashed();- let key2 = notif2.build_key().into_hashed();- assert_ne!(key1.as_ref(), key2.as_ref());-}--#[test]-fn test_build_key_different_entity_types_produce_different_keys() {- let notif1 = create_base_notification(- NotificationEvent::ItemSharedUser(ItemSharedMetadata {- user_ids: vec!["user1".to_string()],- item_type: EntityType::Document,- item_id: "item_123".to_string(),- item_name: None,- shared_by: make_user_id("[email protected]"),- permission_level: None,- }),- EntityType::Document,- "entity_123",- );-- let notif2 = create_base_notification(- NotificationEvent::ItemSharedUser(ItemSharedMetadata {- user_ids: vec!["user1".to_string()],- item_type: EntityType::Document,- item_id: "item_123".to_string(),- item_name: None,- shared_by: make_user_id("[email protected]"),- permission_level: None,- }),- EntityType::Project, // Different entity_type- "entity_123",- );-- let key1 = notif1.build_key().into_hashed();- let key2 = notif2.build_key().into_hashed();- assert_ne!(key1.as_ref(), key2.as_ref());-}--#[test]-fn test_build_key_document_mention_uses_entity() {- let notif = create_base_notification(- NotificationEvent::DocumentMention(DocumentMentionMetadata {- document_name: "My Doc".to_string(),- owner: make_user_id("[email protected]"),- file_type: Some("pdf".to_string()),- metadata: None,- }),- EntityType::Document,- "doc_mention_entity",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_channel_invite_uses_entity() {- let notif = create_base_notification(- NotificationEvent::ChannelInvite(ChannelInviteMetadata {- invited_by: make_user_id("[email protected]"),- common: CommonChannelMetadata {- channel_type: ChannelType::Private,- channel_name: "secret-channel".to_string(),- },- }),- EntityType::Channel,- "channel_invite_entity",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_new_email_uses_entity() {- let notif = create_base_notification(- NotificationEvent::NewEmail(NewEmailMetadata {- sender: Some("[email protected]".to_string()),- to_email: "[email protected]".to_string(),- thread_id: "thread_123".to_string(),- subject: "Test Subject".to_string(),- snippet: "Email snippet...".to_string(),- }),- EntityType::Email,- "email_entity_123",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_invite_to_team_uses_entity() {- let notif = create_base_notification(- NotificationEvent::InviteToTeam(InviteToTeamMetadata {- team_name: "Engineering".to_string(),- team_id: "team_123".to_string(),- invited_by: make_user_id("[email protected]"),- role: Some("member".to_string()),- }),- EntityType::Team,- "team_entity_123",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_reject_team_invite_uses_entity() {- let notif = create_base_notification(- NotificationEvent::RejectTeamInvite,- EntityType::Team,- "team_entity_123",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_task_assigned_uses_entity() {- let notif = create_base_notification(- NotificationEvent::TaskAssigned(TaskAssignedMetadata {- task_id: "task_123".to_string(),- task_name: Some("Complete feature".to_string()),- assigned_by: make_user_id("[email protected]"),- }),- EntityType::Document, // Tasks might be associated with documents- "task_entity_123",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_item_shared_organization_uses_entity() {- let notif = create_base_notification(- NotificationEvent::ItemSharedOrganization(ItemSharedOrganizationMetadata {- org_user_ids: vec!["user1".to_string(), "user2".to_string()],- item_type: EntityType::Project,- item_id: "project_123".to_string(),- item_name: Some("Shared Project".to_string()),- shared_by: make_user_id("[email protected]"),- permission_level: Some("admin".to_string()),- }),- EntityType::Project,- "project_entity_123",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_channel_message_document_uses_entity() {- let notif = create_base_notification(- NotificationEvent::ChannelMessageDocument(ChannelMessageDocumentMetadata(- DocumentMentionMetadata {- document_name: "Attached Doc".to_string(),- owner: make_user_id("[email protected]"),- file_type: Some("docx".to_string()),- metadata: None,- },- )),- EntityType::Document,- "doc_attachment_entity",- );-- let key = notif.build_key().into_hashed();- assert!(!key.as_ref().is_empty());-}--#[test]-fn test_build_key_produces_hex_string() {- let notif = create_base_notification(- NotificationEvent::ChannelMention(ChannelMentionMetadata {- message_id: "msg_123".to_string(),- message_content: "Hello".to_string(),- thread_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "general".to_string(),- },- }),- EntityType::Channel,- "channel_abc",- );-- let key = notif.build_key().into_hashed();- let key_str = key.as_ref();-- // Should be a valid hex string (only hex characters)- assert!(key_str.chars().all(|c| c.is_ascii_hexdigit()));- // Should be 16 hex chars (64-bit hash = 8 bytes = 16 hex chars)- assert_eq!(key_str.len(), 16);-}--#[test]-fn test_build_key_is_deterministic() {- let notif = create_base_notification(- NotificationEvent::ChannelMention(ChannelMentionMetadata {- message_id: "msg_deterministic".to_string(),- message_content: "Test".to_string(),- thread_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "test".to_string(),- },- }),- EntityType::Channel,- "channel_test",- );-- let key1 = notif.build_key().into_hashed();-- // Create an identical notification- let notif2 = create_base_notification(- NotificationEvent::ChannelMention(ChannelMentionMetadata {- message_id: "msg_deterministic".to_string(),- message_content: "Test".to_string(),- thread_id: None,- common: CommonChannelMetadata {- channel_type: ChannelType::Public,- channel_name: "test".to_string(),- },- }),- EntityType::Channel,- "channel_test",- );-- let key2 = notif2.build_key().into_hashed();-- assert_eq!(key1.as_ref(), key2.as_ref());-}diff --git a/rust/cloud-storage/notification/src/domain/models.rs b/rust/cloud-storage/notification/src/domain/models.rsindex 6a0fdc2544..5093974486 100644--- a/rust/cloud-storage/notification/src/domain/models.rs+++ b/rust/cloud-storage/notification/src/domain/models.rs@@ -1,7 +1,7 @@//! Domain models for the notification service.use macro_user_id::user_id::MacroUserIdStr;-use serde::{Serialize, de::DeserializeOwned};+use serde::{Deserialize, Serialize, de::DeserializeOwned};pub(crate) mod android;pub mod apple;@@ -67,12 +67,22 @@ pub struct UserNotificationRow<T> {}/// A notification metadata value tagged with the notification event type.-#[derive(Debug, Serialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct TaggedContent<T> {tag: String,content: T,}+impl<T: Notification> TaggedContent<T> {+ /// create a new value from a notification T+ pub fn new(val: T) -> Self {+ TaggedContent {+ tag: T::TYPE_NAME.to_string(),+ content: val,+ }+ }+}+impl<T> UserNotificationRow<T> {/// Wrap the metadata in a [`TaggedContent`] using the notification event type as the tag.pub fn into_tagged(self) -> UserNotificationRow<TaggedContent<T>> {diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rsindex 25942243e5..f0802799b7 100644--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs@@ -1,8 +1,8 @@use crate::domain::models::{- Notification, RateLimitConfig, RateLimitKey, SendNotificationRequest,+ Notification, RateLimitConfig, RateLimitKey, SendNotificationRequest, TaggedContent,apple::APNSPushNotification, mobile::MessageAttributes,};-use chrono::{DateTime, Utc, serde::ts_seconds_option};+use chrono::{DateTime, Utc};use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_entity::{Entity, as_owned::IntoOwned};use serde::{Deserialize, Serialize};@@ -36,11 +36,10 @@ pub struct EmailNotification<'a> {pub content: EmailContent,}+/// the value of the inner payload inside [ConnGatewayNotification]#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct Notif<T> {+pub struct ConnGatewayInnerNotif<T> {/// The notification ID.- #[serde(rename = "id")]pub(crate) notification_id: uuid::Uuid,/// The notification event type string (e.g. "channel_mention")./// TODO make this a new type@@ -53,53 +52,94 @@ pub struct Notif<T> {/// Whether the notification is marked as done.pub(crate) done: bool,/// When the notification was created.- #[serde(with = "ts_seconds_option")]pub(crate) created_at: Option<DateTime<Utc>>,/// When the notification was viewed/seen.- #[serde(with = "ts_seconds_option")]pub(crate) viewed_at: Option<DateTime<Utc>>,/// When the notification was last updated.- #[serde(with = "ts_seconds_option")]pub(crate) updated_at: Option<DateTime<Utc>>,/// When the notification was deleted.- #[serde(with = "ts_seconds_option")]pub(crate) deleted_at: Option<DateTime<Utc>>,/// Deserialized notification metadata.- pub(crate) notification_metadata: T,+ pub(crate) notification_metadata: TaggedContent<T>,/// The user who triggered the notification.pub(crate) sender_id: Option<MacroUserIdStr<'static>>,}-impl<T> Notif<T>-where- T: Notification + Clone,-{- pub(crate) fn clone_from_request<U>(id: Uuid, req: &SendNotificationRequest<'_, T, U>) -> Self {- Notif {- notification_id: id,- notification_event_type: T::TYPE_NAME.to_string(),- entity: req.req.notification_entity.clone().into_owned(),- sent: true,- done: false,- created_at: None,- viewed_at: None,- updated_at: None,- deleted_at: None,- notification_metadata: req.req.notification.clone(),- sender_id: req.req.sender_id.as_ref().map(|x| x.clone().into_owned()),- }- }-}+impl<T> ConnGatewayInnerNotif<T> where T: Notification + Clone {}/// Connection gateway (WebSocket) notification payload.#[derive(Debug, Serialize, Deserialize)]pub struct ConnGatewayNotification<'a, T> {/// The notification payload to send.- pub notif: Notif<T>,+ pub notif: ConnGatewayInnerNotif<T>,/// The recipients to deliver to.pub recipients: Vec<MacroUserIdStr<'a>>,}+impl<'a, T: Notification + Clone> ConnGatewayNotification<'a, T> {+ pub(crate) fn clone_from_request<U>(id: Uuid, req: &SendNotificationRequest<'a, T, U>) -> Self {+ ConnGatewayNotification {+ notif: ConnGatewayInnerNotif {+ notification_id: id,+ notification_event_type: T::TYPE_NAME.to_string(),+ entity: req.req.notification_entity.clone().into_owned(),+ sent: true,+ done: false,+ created_at: None,+ viewed_at: None,+ updated_at: None,+ deleted_at: None,+ notification_metadata: TaggedContent::new(req.req.notification.clone()),+ sender_id: req.req.sender_id.as_ref().map(|x| x.clone().into_owned()),+ },+ recipients: req.req.recipient_ids.iter().cloned().collect(),+ }+ }+}++#[cfg(test)]+impl<'a, T: Notification> ConnGatewayNotification<'a, T> {+ pub fn testing_to_value(self) -> ConnGatewayNotification<'a, serde_json::Value> {+ let ConnGatewayNotification {+ notif:+ ConnGatewayInnerNotif {+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata: TaggedContent { tag, content },+ sender_id,+ },+ recipients,+ } = self;++ ConnGatewayNotification {+ notif: ConnGatewayInnerNotif {+ notification_id,+ notification_event_type,+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata: TaggedContent {+ tag,+ content: serde_json::to_value(content).unwrap(),+ },+ sender_id,+ },+ recipients,+ }+ }+}+/// The delivery channel variants.#[derive(Debug, Serialize, Deserialize)]pub enum NotificationChannel<'a, T, U> {diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex 66571d7c96..5e6ee2e3ae 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -6,7 +6,7 @@use crate::domain::models::apple::{APNSPushNotification, Aps};use crate::domain::models::mobile::{MessageAttributes, PushType};use crate::domain::models::queue_message::{- APNSTargets, ClearPushIdentifier, ConnGatewayNotification, EmailNotification, Node, Notif,+ APNSTargets, ClearPushIdentifier, ConnGatewayNotification, EmailNotification, Node,NotificationChannel, QueueMessage,};use crate::domain::models::request::{@@ -388,10 +388,9 @@ wheremessage_type: message_type.clone(),rate_limit: rate_limit.clone(),content: Node {- notif: NotificationChannel::ConnGateway(ConnGatewayNotification {- notif: Notif::clone_from_request(notification_id, notification),- recipients: notification.req.recipient_ids.iter().cloned().collect(),- }),+ notif: NotificationChannel::ConnGateway(+ ConnGatewayNotification::clone_from_request(notification_id, notification),+ ),on_failure: None,},});diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex d998828e04..b441dd7ac0 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -3,14 +3,14 @@use crate::domain::models::apple::APNSPushNotification;use crate::domain::models::mobile::NotifCollapseKey;use crate::domain::models::queue_message::{- ConnGatewayNotification, EmailContent, Node, Notif, NotificationChannel, QueueMessage,- RawQueueMessage,+ ConnGatewayInnerNotif, ConnGatewayNotification, EmailContent, Node, NotificationChannel,+ QueueMessage, RawQueueMessage,};use crate::domain::models::request::{NotificationStatus, UpdateNotificationsRequest};use crate::domain::models::{DeviceEndpoint, Notification, NotificationExtEmail, NotificationExtIos,NotificationIdAndCollapseKey, RateLimitConfig, RateLimitExceeded, RateLimitKey,- RateLimitResult, SendNotificationRequestBuilder, UserNotificationRow,+ RateLimitResult, SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,};use crate::domain::ports::{EmailSender, NotificationQueue, NotificationRepository, NotificationSender, RateLimitPort,@@ -936,8 +936,8 @@ fn create_egress_service<R: RateLimitPort>()}-fn create_mock_notif(meta: serde_json::Value) -> Notif<serde_json::Value> {- Notif {+fn create_mock_notif<T: Notification>(meta: T) -> ConnGatewayInnerNotif<T> {+ ConnGatewayInnerNotif {notification_id: Uuid::nil(),notification_event_type: "testing".to_string(),entity: EntityType::Document.with_entity_str("testing"),@@ -947,7 +947,7 @@ fn create_mock_notif(meta: serde_json::Value) -> Notif<serde_json::Value> {viewed_at: None,updated_at: None,deleted_at: None,- notification_metadata: meta,+ notification_metadata: TaggedContent::new(meta),sender_id: None,}}@@ -964,10 +964,15 @@ async fn test_egress_rate_limit_exceeded() {RateLimitConfig::new(10, Duration::from_secs(3600)),)),content: Node {- notif: NotificationChannel::ConnGateway(ConnGatewayNotification {- notif: create_mock_notif(json!({"message": "Hello"})),- recipients: vec![recipient],- }),+ notif: NotificationChannel::ConnGateway(+ ConnGatewayNotification {+ notif: create_mock_notif(TestNotification {+ message: "Hello".to_string(),+ }),+ recipients: vec![recipient],+ }+ .testing_to_value(),+ ),on_failure: None,},};@@ -998,11 +1003,16 @@ async fn test_egress_rate_limit_allowed() {RateLimitConfig::new(10, Duration::from_secs(3600)),)),content: Node {- notif: NotificationChannel::ConnGateway(ConnGatewayNotification {- notif: create_mock_notif(json!({"message": "Hello"})),-- recipients: vec![recipient],- }),+ notif: NotificationChannel::ConnGateway(+ ConnGatewayNotification {+ notif: create_mock_notif(TestNotification {+ message: "Hello".to_string(),+ }),++ recipients: vec![recipient],+ }+ .testing_to_value(),+ ),on_failure: None,},};@@ -1023,10 +1033,15 @@ async fn test_egress_no_rate_limit_configured() {message_type: "test_notification".to_string(),rate_limit: None, // No rate limit configuredcontent: Node {- notif: NotificationChannel::ConnGateway(ConnGatewayNotification {- notif: create_mock_notif(json!({"message": "Hello"})),- recipients: vec![recipient],- }),+ notif: NotificationChannel::ConnGateway(+ ConnGatewayNotification {+ notif: create_mock_notif(TestNotification {+ message: "Hello".to_string(),+ }),+ recipients: vec![recipient],+ }+ .testing_to_value(),+ ),on_failure: None,},};diff --git a/rust/cloud-storage/notification/src/inbound/worker.rs b/rust/cloud-storage/notification/src/inbound/worker.rsindex 40e4115d34..5e75d67aa7 100644--- a/rust/cloud-storage/notification/src/inbound/worker.rs+++ b/rust/cloud-storage/notification/src/inbound/worker.rs@@ -34,7 +34,7 @@ where// Log any failuresfor result in &results {if let Err(e) = result {- tracing::error!(error = ?e, "failed to deliver notification");+ tracing::error!(error = ?e.preformat(), "failed to deliver notification");}}diff --git a/rust/cloud-storage/notification_db_client/src/notification/create.rs b/rust/cloud-storage/notification_db_client/src/notification/create.rsindex 17470ef47d..8b13789179 100644--- a/rust/cloud-storage/notification_db_client/src/notification/create.rs+++ b/rust/cloud-storage/notification_db_client/src/notification/create.rs@@ -1,139 +1 @@-use model_notifications::RawNotification;-use sqlx::{Postgres, Transaction};-/// Takes a notification that does not have a created_at timestamp and inserts it into the database-/// Returns the saved notification with a created_at timestamp-#[tracing::instrument(skip(pool, notification), fields(notification_id=%notification.id))]-pub async fn create_notification(- pool: sqlx::Pool<sqlx::Postgres>,- notification: RawNotification,-) -> anyhow::Result<RawNotification> {- let entity_type: &'static str = notification.entity.entity_type.into();- let created_at: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar!(- r#"- INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)- VALUES ($1, $2, $3, $4, $5, $6, $7)- RETURNING created_at::timestamptz- "#,- ¬ification.id,- notification.notification_event_type.to_string(),- ¬ification.entity.entity_id,- entity_type,- notification.service_sender,- notification.metadata,- notification.sender_id.as_ref().map(|id| id.as_ref()),- )- .fetch_one(&pool)- .await?;-- Ok(RawNotification {- id: notification.id,- notification_event_type: notification.notification_event_type,- entity: notification.entity,- service_sender: notification.service_sender,- created_at,- metadata: notification.metadata,- sender_id: notification.sender_id,- })-}--/// Takes a notification that does not have a created_at timestamp and inserts it into the database-/// Returns the saved notification with a created_at timestamp-/// This is transactional and does not commit the transaction-#[tracing::instrument(skip(transaction, notification), fields(notification_id=%notification.id))]-pub async fn create_notification_transaction(- transaction: &mut Transaction<'_, Postgres>,- notification: RawNotification,-) -> anyhow::Result<RawNotification> {- let entity_type: &'static str = notification.entity.entity_type.into();- let created_at: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar!(- r#"- INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)- VALUES ($1, $2, $3, $4, $5, $6, $7)- RETURNING created_at::timestamptz- "#,- ¬ification.id,- notification.notification_event_type.to_string(),- ¬ification.entity.entity_id,- entity_type,- notification.service_sender,- notification.metadata,- notification.sender_id.as_ref().map(|id| id.as_ref()),- )- .fetch_one( transaction.as_mut())- .await?;-- Ok(RawNotification {- id: notification.id,- notification_event_type: notification.notification_event_type,- entity: notification.entity,- service_sender: notification.service_sender,- created_at,- metadata: notification.metadata,- sender_id: notification.sender_id,- })-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use model_entity::EntityType;- use model_notifications::NotificationEventType;- use serde_json::json;- use sqlx::{Pool, Postgres};-- #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]- async fn test_create_notification(pool: Pool<Postgres>) -> anyhow::Result<()> {- let uuid = macro_uuid::generate_uuid_v7();- let notification = RawNotification {- id: uuid,- notification_event_type: NotificationEventType::ChannelInvite.to_string(),- entity: EntityType::Document.with_entity_str("test"),- service_sender: "test".to_string(),- created_at: None,- metadata: Some(json!({})),- sender_id: None,- };-- let result = create_notification(pool, notification).await?;-- assert!(result.created_at.is_some());-- Ok(())- }-- #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]- async fn test_create_notification_transaction(pool: Pool<Postgres>) -> anyhow::Result<()> {- let uuid = macro_uuid::generate_uuid_v7();- let notification = RawNotification {- id: uuid,- notification_event_type: NotificationEventType::ChannelInvite.to_string(),- entity: EntityType::Document.with_entity_str("test"),- service_sender: "test".to_string(),- created_at: None,- metadata: Some(json!({})),- sender_id: None,- };-- let mut transaction = pool.begin().await?;-- create_notification_transaction(&mut transaction, notification).await?;-- let notification = sqlx::query!("SELECT id FROM notification WHERE id = $1", uuid)- .fetch_optional(&pool)- .await?;-- assert!(notification.is_none());-- transaction.commit().await?;-- let notification = sqlx::query!("SELECT id FROM notification WHERE id = $1", uuid)- .fetch_optional(&pool)- .await?;-- assert!(notification.is_some());-- Ok(())- }-}diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rsdeleted file mode 100644index ca12a1c4c6..0000000000--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/mod.rs+++ /dev/null@@ -1,2 +0,0 @@-pub mod should_email;-pub mod unsent;diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/should_email.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/should_email.rsdeleted file mode 100644index 1ea07e1975..0000000000--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/should_email.rs+++ /dev/null@@ -1,89 +0,0 @@-use std::collections::HashMap;--use model_notifications::NotificationEventType;--#[tracing::instrument(skip(db))]-pub async fn should_email_based_on_user_notification_bulk(- db: &sqlx::PgPool,- notification_event_type: &NotificationEventType,- event_item_id: &str,- event_item_type: &str,- user_ids: &[String],-) -> anyhow::Result<Vec<(String, bool)>> {- // Contains a list of all user notification events that match this criteria- // there may be duplicates for a single user_id and some user_ids may not exist- let result: Vec<(String, i64)> = sqlx::query!(- r#"- SELECT un.user_id, COUNT(*) as count- FROM user_notification un- JOIN notification n ON n.id = un.notification_id- WHERE un.user_id = ANY($1)- AND n.notification_event_type = $2- AND n.event_item_id = $3- AND n.event_item_type = $4- GROUP BY un.user_id- ORDER BY un.user_id- "#,- user_ids,- ¬ification_event_type.to_string(),- event_item_id,- event_item_type- )- .map(|row| (row.user_id, row.count.unwrap_or(0)))- .fetch_all(db)- .await?;-- let should_email_map: HashMap<String, bool> = result- .iter()- .map(|(user_id, count)| (user_id.to_string(), count <= &1)) // If there is more than 1 notification, we should not email them- .collect();-- let result = user_ids- .iter()- .map(|user_id| {- let should_email = should_email_map.get(user_id).unwrap_or(&true);- (user_id.clone(), *should_email)- })- .collect();-- Ok(result)-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../../fixtures", scripts("should_email"))- )]- async fn test_should_email_based_on_user_notification_bulk(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- let user_ids = vec![- "macro|[email protected]".to_string(),- "macro|[email protected]".to_string(),- "macro|[email protected]".to_string(),- ];-- let should_email = should_email_based_on_user_notification_bulk(- &pool,- &NotificationEventType::ItemSharedUser,- "item_id",- "item_type",- &user_ids,- )- .await?;-- assert_eq!(should_email.len(), 3);- assert_eq!(should_email[0].0, "macro|[email protected]");- assert!(should_email[0].1);- assert_eq!(should_email[1].0, "macro|[email protected]");- assert!(should_email[1].1);- assert_eq!(should_email[2].0, "macro|[email protected]");- assert!(should_email[2].1);- Ok(())- }-}diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/unsent.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/unsent.rsdeleted file mode 100644index 3b32d116f2..0000000000--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/unsent.rs+++ /dev/null@@ -1,216 +0,0 @@-use std::str::FromStr;--use model_entity::{Entity, EntityType};-use model_notifications::NotificationEventType;-use sqlx::types::Uuid;--#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]-pub struct UnsentNotification {- pub user_id: String,- #[serde(flatten)]- pub entity: Entity<'static>,- pub notification_id: Uuid,- pub created_at: chrono::NaiveDateTime,-}--/// Gets unsent notifications for users-/// A notification is unsent if it has not been sent, seen or done-#[tracing::instrument(skip(db))]-pub async fn get_unsent_notifications_for_users(- db: &sqlx::PgPool,- notification_event_types: &[NotificationEventType],- limit: i64,- offset: i64,- hours_ago: f64,-) -> anyhow::Result<Vec<UnsentNotification>> {- let notification_event_types = notification_event_types- .iter()- .map(|notification_event_type| notification_event_type.to_string())- .collect::<Vec<String>>();-- let result = sqlx::query!(- r#"- SELECT- DISTINCT ON (un.user_id, n.event_item_id) un.user_id, n.event_item_id,- n.created_at,- n.event_item_type,- n.id- FROM user_notification un- JOIN notification n ON un.notification_id = n.id- WHERE un.sent = false AND un.done = false AND un.seen_at IS NULL AND n.notification_event_type = ANY($1)- AND un.created_at > NOW() - ($4 * interval '1 hour')- ORDER BY un.user_id, n.event_item_id, n.created_at DESC- LIMIT $2- OFFSET $3- "#,- ¬ification_event_types,- limit,- offset,- hours_ago- )- .try_map(|row| {- Ok(UnsentNotification {- user_id: row.user_id,- entity: EntityType::from_str(&row.event_item_type).map_err(|e| sqlx::Error::Decode(Box::new(e)))?.with_entity_string(row.event_item_id),- notification_id: row.id,- created_at: row.created_at,- })- })- .fetch_all(db)- .await?;-- Ok(result)-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- async fn populate_notifications(pool: &Pool<Postgres>) -> anyhow::Result<()> {- let notification_event_type = NotificationEventType::ChannelMessageSend.to_string();-- let notification_event_type = notification_event_type.as_str();-- let notifications = vec![- (- "11111111-1111-1111-1111-111111111111",- "item_id",- "document",- notification_event_type,- ),- (- "22222222-2222-2222-2222-222222222222",- "item_id2",- "document",- notification_event_type,- ),- (- "33333333-3333-3333-3333-333333333333",- "item_id3",- "document",- notification_event_type,- ),- (- "44444444-4444-4444-4444-444444444444",- "item_id4",- "document",- notification_event_type,- ),- ];-- for notification in notifications {- sqlx::query!(- r#"- INSERT INTO notification (id, event_item_id, event_item_type, notification_event_type, service_sender)- VALUES ($1, $2, $3, $4, 'test')- "#,- macro_uuid::string_to_uuid(¬ification.0)?,- notification.1,- notification.2,- notification.3,- )- .execute(pool)- .await?;- }-- let user_notifications = vec![- (- "user_id", // user_id- "11111111-1111-1111-1111-111111111111", // notification_id- false, // sent- false, // done- None, // seen_at- ),- (- "user_id2",- "22222222-2222-2222-2222-222222222222",- false,- false,- Some(chrono::NaiveDateTime::from_timestamp(0, 0)),- ),- (- "user_id3",- "33333333-3333-3333-3333-333333333333",- false,- true,- None,- ),- (- "user_id4",- "44444444-4444-4444-4444-444444444444",- true,- false,- None,- ),- ];-- for user_notification in user_notifications {- sqlx::query!(- r#"- INSERT INTO user_notification (user_id, notification_id, sent, done, seen_at)- VALUES ($1, $2, $3, $4, $5)- "#,- user_notification.0,- macro_uuid::string_to_uuid(&user_notification.1)?,- user_notification.2,- user_notification.3,- user_notification.4,- )- .execute(pool)- .await?;- }-- Ok(())- }-- #[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]- async fn test_get_unsent_notifications_for_users(pool: Pool<Postgres>) -> anyhow::Result<()> {- populate_notifications(&pool).await?;-- let hours_ago = 1.0;- let limit = 100;- let offset = 0;-- let unsent_notifications = get_unsent_notifications_for_users(- &pool,- &[NotificationEventType::ChannelMessageSend],- limit,- offset,- hours_ago,- )- .await?;-- assert_eq!(unsent_notifications.len(), 1);-- assert_eq!(- unsent_notifications[0].notification_id,- "11111111-1111-1111-1111-111111111111".parse::<Uuid>()?- );-- sqlx::query!(- r#"- UPDATE user_notification- SET created_at = NOW() - INTERVAL '2 hours'- WHERE notification_id = $1- "#,- &unsent_notifications[0].notification_id- )- .execute(&pool)- .await?;-- let unsent_notifications = get_unsent_notifications_for_users(- &pool,- &[NotificationEventType::ChannelMessageSend],- limit,- offset,- hours_ago,- )- .await?;-- assert_eq!(unsent_notifications.len(), 0);-- Ok(())- }-}diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/mod.rs b/rust/cloud-storage/notification_db_client/src/user_notification/mod.rsindex 54cee03193..0979e90368 100644--- a/rust/cloud-storage/notification_db_client/src/user_notification/mod.rs+++ b/rust/cloud-storage/notification_db_client/src/user_notification/mod.rs@@ -1,4 +1,2 @@-pub mod create;pub mod delete;-pub mod get;pub mod patch;diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.tomlindex 4e7da3a584..82e905bfbd 100644--- a/rust/cloud-storage/notification_service/Cargo.toml+++ b/rust/cloud-storage/notification_service/Cargo.toml@@ -5,10 +5,6 @@ name = "notification_service"publish = falseversion = "0.1.0"-[[bin]]-name = "notification_email_poller_worker"-path = "src/notification_email_poller_worker.rs"-[[bin]]name = "notification_service"path = "src/main.rs"@@ -55,7 +51,7 @@ models_comms = { path = "../models_comms" }models_pagination = { path = "../models_pagination", features = ["axum"] }notification = { path = "../notification", features = ["axum"] }notification_db_client = { path = "../notification_db_client" }-paste = "1"+paste = { workspace = true }redis = { workspace = true }regex = { workspace = true }secretsmanager_client = { path = "../secretsmanager_client" }diff --git a/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs b/rust/cloud-storage/notification_service/src/api/notification/create_notification.rsdeleted file mode 100644index 0462d0741e..0000000000--- a/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs+++ /dev/null@@ -1,84 +0,0 @@-use crate::{api::context::ApiContext, model::notification::CreateNotification};-use axum::{- Json,- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use model::{response::ErrorResponse, user::axum_extractor::MacroUserExtractor};-use model_notifications::{- Notification, NotificationEvent, NotificationEventType, RawNotification,-};-use std::str::FromStr;--/// Creates a notification.-/// Will generate an id for the notification.-#[utoipa::path(- post,- operation_id = "create_notification",- path = "/notifications",- responses(- (status = 200, body=Notification),- )- )]-#[tracing::instrument(skip(ctx, macro_user, req))]-pub async fn handler(- State(ctx): State<ApiContext>,- macro_user: MacroUserExtractor,- extract::Json(req): extract::Json<CreateNotification>,-) -> Result<Response, Response> {- let id = macro_uuid::generate_uuid_v7();-- let notification_event_type = NotificationEventType::from_str(&req.notification_event_type)- .map_err(|e| {- tracing::error!(error=?e, "invalid notification event type");- (- StatusCode::BAD_REQUEST,- Json(ErrorResponse {- message: "invalid notification event type",- }),- )- .into_response()- })?;-- let notification_event =- NotificationEvent::try_from_type_and_meta(notification_event_type, req.metadata).map_err(- |e| {- tracing::error!(error=?e, "unable to create notification event");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to create notification event",- }),- )- .into_response()- },- )?;-- let notification = Notification {- id,- notification_entity: req.entity,- service_sender: req.service_sender,- sender_id: Some(macro_user.macro_user_id),- temporal: Default::default(),- notification_event,- };-- let notification = notification_db_client::notification::create::create_notification(- ctx.db.clone(),- RawNotification::from(notification),- )- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to create notification");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to create notification",- }),- )- .into_response()- })?;-- Ok((StatusCode::OK, Json(notification)).into_response())-}diff --git a/rust/cloud-storage/notification_service/src/api/notification/mod.rs b/rust/cloud-storage/notification_service/src/api/notification/mod.rsindex 403963c748..b819e8963e 100644--- a/rust/cloud-storage/notification_service/src/api/notification/mod.rs+++ b/rust/cloud-storage/notification_service/src/api/notification/mod.rs@@ -1,15 +1,9 @@-use axum::{- Router,- routing::{delete, post},-};+use axum::{Router, routing::delete};use crate::api::context::ApiContext;-pub(in crate::api) mod create_notification;pub(in crate::api) mod delete_user_notifications;pub fn router() -> Router<ApiContext> {- Router::new()- .route("/", post(create_notification::handler))- .route("/user/:user_id", delete(delete_user_notifications::handler))+ Router::new().route("/user/:user_id", delete(delete_user_notifications::handler))}diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rsindex e8dce0b6df..39d0f6453e 100644--- a/rust/cloud-storage/notification_service/src/api/swagger.rs+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs@@ -8,14 +8,13 @@ use model::{use model_notifications::{ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,ChannelReplyMetadata, CommonChannelMetadata, DeviceType, DocumentMentionMetadata,- InviteToTeamMetadata, ItemSharedMetadata, NewEmailMetadata, Notification, NotificationEvent,- NotificationEventType, UserNotification, UserUnsubscribe,+ InviteToTeamMetadata, ItemSharedMetadata, NewEmailMetadata, UserUnsubscribe,};use utoipa::OpenApi;use crate::{api::{- device, health, notification,+ device, health,unsubscribe::{self, unsubscribe_item::UnsubscribeItemPathParams},user_notification,},@@ -35,8 +34,6 @@ use crate::{/// /healthhealth::health_handler,- /// /notifications- notification::create_notification::handler,/// /user_notificationsuser_notification::list_typed_notifications,@@ -62,9 +59,7 @@ use crate::{NotificationServiceApiVersion,EmptyResponse,ErrorResponse,- Notification,CreateNotification,- UserNotification,UnsubscribeItemPathParams,UserUnsubscribe,DeviceType,@@ -72,8 +67,6 @@ use crate::{PushNotificationData,NewEmailMetadata,- NotificationEvent,- NotificationEventType,// MetadataCommonChannelMetadata,@@ -86,7 +79,7 @@ use crate::{DocumentMentionMetadata,// v2 typed notifications- user_notification::NotifEvent,+ model_notifications::NotifEvent,user_notification::ApiUserNotification,user_notification::GetAllUserNotificationsResponse,notification_crate::inbound::http::BulkGetByEventItemIdsRequest,diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rsindex 2d6d7b7030..e1d44859ac 100644--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs@@ -3,128 +3,13 @@ use chrono::{DateTime, Utc, serde::ts_seconds_option};use macro_user_id::user_id::MacroUserIdStr;use model_entity::Entity;use model_error_response::ErrorResponse;-use model_notifications::{- ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,- ChannelReplyMetadata, DocumentMentionMetadata, InviteToTeamMetadata, NewEmailMetadata,- TaskAssignedMetadata,-};-use serde::{Deserialize, Serialize};+use model_notifications::NotifEvent;+use serde::Serialize;use utoipa::ToSchema;#[cfg(test)]mod test;-/// Defines a notification event enum with compile-time safety guarantees.-///-/// The `tag` field in the database row is the `Notification::TYPE_NAME` of the-/// metadata that was stored. When we deserialize that row back into this enum,-/// serde matches the `tag` value against the `snake_case` of the variant name.-/// If those two strings ever diverge, deserialization fails at runtime.-/// This macro prevents that by asserting the invariant at compile time.-///-/// Accepts a standard enum definition and emits it unchanged, then generates-/// `const` assertions that verify two properties for every `Variant(MetadataType)`:-///-/// 1. `MetadataType` implements [`Notification`](::notification::domain::models::Notification).-/// 2. `MetadataType::TYPE_NAME` equals the variant name converted to `snake_case`-/// (via [`paste`]), which is also the serde tag produced by `rename_all = "snake_case"`.-///-/// Because the enum and the assertions share the same variant list, adding a new-/// variant without a matching `Notification` impl — or with a mismatched-/// `TYPE_NAME` — is a compile error.-macro_rules! define_notif_event {- (- $(#[$enum_meta:meta])*- $vis:vis enum $Name:ident {- $(- $(#[$variant_meta:meta])*- $Variant:ident($(#[$field_meta:meta])* $Ty:ty),- )+- }- ) => {- $(#[$enum_meta])*- $vis enum $Name {- $(- $(#[$variant_meta])*- $Variant($(#[$field_meta])* $Ty),- )+- }-- // Compile-time assertions:- // 1. Every inner type implements Notification.- // 2. TYPE_NAME matches the snake_case of the variant name.- paste::paste! {- const _: () = {- const fn str_eq(a: &[u8], b: &[u8]) -> bool {- if a.len() != b.len() { return false; }- let mut i = 0;- while i < a.len() {- if a[i] != b[i] { return false; }- i += 1;- }- true- }-- $(- const _: () = assert!(- str_eq(- <$Ty as ::notification::domain::models::Notification>::TYPE_NAME.as_bytes(),- stringify!([< $Variant:snake >]).as_bytes(),- ),- concat!(- stringify!($Name), "::", stringify!($Variant),- " snake_case does not match Notification::TYPE_NAME for ", stringify!($Ty),- ),- );- )+- };- }- };-}--define_notif_event!(- /// Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`- /// as the serde adjacently-tagged field names so it can be deserialized from the- /// shape produced by [`UserNotificationRow::into_tagged`] +- /// [`UserNotificationRow::into_json`].- ///- /// Only includes variants whose metadata types implement the `Notification` trait.- #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]- #[serde(tag = "tag", content = "content", rename_all = "snake_case")]- pub enum NotifEvent {- /// Someone mentioned you in a channel.- #[schema(value_type = serde_json::Value)]- ChannelMention(ChannelMentionMetadata),-- /// Someone mentioned you in a document.- #[schema(value_type = serde_json::Value)]- DocumentMention(DocumentMentionMetadata),- /// The user was invited to a channel.- #[schema(value_type = serde_json::Value)]- ChannelInvite(ChannelInviteMetadata),-- /// A user sent a message in a channel.- #[schema(value_type = serde_json::Value)]- ChannelMessageSend(ChannelMessageSendMetadata),-- /// Someone replied to a thread in a channel that the user is part of.- #[schema(value_type = serde_json::Value)]- ChannelMessageReply(ChannelReplyMetadata),-- /// A new email has been sent to the user.- #[schema(value_type = serde_json::Value)]- NewEmail(NewEmailMetadata),-- /// A user was invited to a team.- #[schema(value_type = serde_json::Value)]- InviteToTeam(InviteToTeamMetadata),-- /// A user was assigned to a task.- #[schema(value_type = serde_json::Value)]- TaskAssigned(TaskAssignedMetadata),- }-);-#[derive(Debug, Serialize, ToSchema)]#[serde(rename_all = "camelCase")]pub struct ApiUserNotification {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 b8747e7dec..350ff72e9d 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@@ -2,6 +2,7 @@ use super::*;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;+use model_notifications::ChannelMentionMetadata;use notification::domain::models::UserNotificationRow;/// Build a [`UserNotificationRow<serde_json::Value>`] with the given event type@@ -192,3 +193,58 @@ fn to_typed_row_preserves_row_fields() {_ => panic!("expected TaskAssigned variant"),}}++/// Verifies that `TaggedContent<T>` (used by ConnGatewayInnerNotif for WebSocket delivery)+/// and `NotifEvent` (used by ApiUserNotification for HTTP API) serialize identically.+/// This ensures frontend code can use the same parsing logic for both delivery methods.+#[test]+fn conn_gateway_inner_val_has_identical_serialization() {+ use notification::domain::models::TaggedContent;++ // Create test notification metadata+ let notif_metadata = ChannelMentionMetadata {+ message_id: "testing".to_string(),+ message_content: "some data".to_string(),+ thread_id: Some("threadid".to_string()),+ common: model_notifications::CommonChannelMetadata {+ channel_type: model_notifications::ChannelType::Public,+ channel_name: "my channel".to_string(),+ },+ };++ // TaggedContent<T> is what ConnGatewayInnerNotif uses for notification_metadata+ // when sending via WebSocket+ let tagged_content = TaggedContent::new(notif_metadata.clone());+ let tagged_content_json = serde_json::to_value(&tagged_content).unwrap();++ // NotifEvent is what ApiUserNotification uses for notification_metadata+ // when returning via HTTP API+ let notif_event = NotifEvent::ChannelMention(notif_metadata);+ let notif_event_json = serde_json::to_value(¬if_event).unwrap();++ // Both should serialize to the same JSON structure:+ // { "tag": "channel_mention", "content": { "messageId": "...", ... } }+ assert_eq!(+ tagged_content_json,+ notif_event_json,+ "TaggedContent and NotifEvent should serialize identically.\n\+ TaggedContent (WebSocket): {}\n\+ NotifEvent (HTTP API): {}",+ serde_json::to_string_pretty(&tagged_content_json).unwrap(),+ serde_json::to_string_pretty(¬if_event_json).unwrap(),+ );++ // Verify the expected structure+ assert_eq!(tagged_content_json["tag"], "channel_mention");+ assert_eq!(notif_event_json["tag"], "channel_mention");++ // Verify content fields are serialized in camelCase as expected+ assert_eq!(tagged_content_json["content"]["messageId"], "testing");+ assert_eq!(+ tagged_content_json["content"]["messageContent"],+ "some data"+ );+ assert_eq!(tagged_content_json["content"]["threadId"], "threadid");+ assert_eq!(tagged_content_json["content"]["channelType"], "public");+ assert_eq!(tagged_content_json["content"]["channelName"], "my channel");+}diff --git a/rust/cloud-storage/notification_service/src/notification/metadata_utils/mod.rs b/rust/cloud-storage/notification_service/src/notification/metadata_utils/mod.rsindex 9853359ac9..8b13789179 100644--- a/rust/cloud-storage/notification_service/src/notification/metadata_utils/mod.rs+++ b/rust/cloud-storage/notification_service/src/notification/metadata_utils/mod.rs@@ -1,17 +1 @@-use model_notifications::NotificationWithRecipient;-pub fn get_metadata_value<T: serde::de::DeserializeOwned>(- notification: &NotificationWithRecipient,- key: &str,-) -> anyhow::Result<T> {- if let Some(metadata) = ¬ification.inner.notification_event.metadata_json() {- let value = metadata- .get(key)- .ok_or_else(|| anyhow::anyhow!("metadata key not found"))?;-- return serde_json::from_value(value.clone())- .map_err(|e| anyhow::anyhow!("unable to deserialize metadata value: {e}"));- }-- Err(anyhow::anyhow!("notification does not have metadata"))-}diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/template.rs b/rust/cloud-storage/notification_service/src/notification/send/email/template.rsindex 0e63639a22..480907d838 100644--- a/rust/cloud-storage/notification_service/src/notification/send/email/template.rs+++ b/rust/cloud-storage/notification_service/src/notification/send/email/template.rs@@ -1,17 +1,4 @@-use crate::{- config::BASE_URL,- notification::metadata_utils,- templates::{channel_invite, channel_message, item_share},-};-use anyhow::Context;-use macro_env::{Environment, ext::frontend_url::FrontendUrl};-use macro_user_id::email::ReadEmailParts;-use model_entity::EntityType;-use model_notifications::{- ChannelInviteMetadata, ChannelMessageSendMetadata, NotificationEventType,- NotificationWithRecipient,-};-use url::Url;+use crate::config::BASE_URL;/// Gets the unsubscribe url for an email#[allow(dead_code)]@@ -19,117 +6,3 @@ fn get_email_unsubscribe_url(email_unsubscribe_code: &str) -> String {let base_url = &*BASE_URL;format!("{}/unsubscribe/email/{}", base_url, email_unsubscribe_code)}--/// Returns the url to the item share page-fn get_item_share_url(_notification: &NotificationWithRecipient) -> anyhow::Result<Url> {- Ok(Environment::new_or_prod()- .get_frontend_url()- .join("login")?)- // // Depending on the item type we'll need to construct the url differently...- // let macro_app_url = &*MACRO_APP_URL;- // let item_id: &str = ¬ification.inner.notification_entity.event_item_id;- //- // let macro_app_path = match notification.inner.notification_entity.event_item_type.as_str() {- // "document" => {- // let file_type =- // metadata_utils::get_metadata_value::<String>(notification, "file_type")?;- //- // let file_type = FileType::from_str(&file_type).context("invalid file type")?;- //- // format!("{}/{}", &file_type.macro_app_path(), item_id)- // }- // "chat" => format!("chat/{}", item_id),- // // hack to have- // "channel" => format!("channel/{}", item_id),- // "project" => "".to_string(),- // _ => "".to_string(),- // };- //- // Ok(format!("{}/{}", macro_app_url, ¯o_app_path))-}--/// Returns the filled email template and the subject-pub fn fill_email_template(- notification: &NotificationWithRecipient,-) -> anyhow::Result<(String, String)> {- match notification.inner.notification_event.event_type() {- NotificationEventType::ItemSharedUser | NotificationEventType::ItemSharedOrganization => {- let mut item_name =- metadata_utils::get_metadata_value::<String>(notification, "item_name")?;-- let item_url = get_item_share_url(notification).context("unable to create item url")?;-- if matches!(- notification.inner.notification_entity.entity_type,- EntityType::Document- ) {- let file_type =- metadata_utils::get_metadata_value::<String>(notification, "file_type")?;-- item_name = format!("{}.{}", item_name, file_type);- }-- let sender = notification- .inner- .sender_id- .as_ref()- .context("notification does not have sender id")?- .email_part()- .email_str()- .to_string();-- Ok(item_share::fill_item_share_template(- &item_url,- &sender,- &item_name,- ¬ification- .inner- .notification_entity- .entity_type- .to_string(),- ))- }- NotificationEventType::ChannelInvite => {- let metadata = if let Some(metadata) = notification- .inner- .notification_event- .metadata_json()- .as_ref()- {- metadata.clone()- } else {- return Err(anyhow::anyhow!("notification does not have metadata"));- };-- let metadata: ChannelInviteMetadata = serde_json::from_value(metadata)- .context("unable to deserialize channel invite metadata")?;-- let item_url = get_item_share_url(notification).context("unable to create item url")?;-- channel_invite::fill_channel_invite_template(&item_url, &metadata)- }- NotificationEventType::ChannelMessageSend => {- let metadata = if let Some(metadata) = notification- .inner- .notification_event- .metadata_json()- .as_ref()- {- metadata.clone()- } else {- return Err(anyhow::anyhow!("notification does not have metadata"));- };-- let metadata: ChannelMessageSendMetadata = serde_json::from_value(metadata)- .context("unable to deserialize channel invite metadata")?;-- let item_url = get_item_share_url(notification).context("unable to create item url")?;-- Ok(channel_message::fill_channel_message_template(- &item_url,- &metadata.common.channel_name,- ))- }- _ => Err(anyhow::anyhow!("unsupported notification event type")),- }-}diff --git a/rust/cloud-storage/notification_service/src/notification_email_poller_worker.rs b/rust/cloud-storage/notification_service/src/notification_email_poller_worker.rsdeleted file mode 100644index 451dcb4e82..0000000000--- a/rust/cloud-storage/notification_service/src/notification_email_poller_worker.rs+++ /dev/null@@ -1,418 +0,0 @@-#![allow(warnings, reason = "waiting on #1805 to be merged")]-use std::collections::{HashMap, HashSet};--use anyhow::Context;-use env::SENDER_ADDRESS;-use futures::StreamExt;-use macro_entrypoint::MacroEntrypoint;-use macro_env::{Environment, ext::frontend_url::FrontendUrl};-use model_notifications::NotificationEventType;-use notification_db_client::user_notification::get::unsent::UnsentNotification;-use sqlx::postgres::PgPoolOptions;-use url::Url;--mod env;--#[cfg(test)]-mod poller_tests;--/// Handles polling notifications db for users that have unread channel notifications-#[tokio::main]-pub async fn main() -> anyhow::Result<()> {- MacroEntrypoint::default().init();-- let config = NotificationEmailPollerWorkerConfig::from_env()- .context("expected to be able to generate config")?;-- tracing::trace!("initialized config");-- let (min_connections, max_connections): (u32, u32) = match config.environment {- Environment::Production => (5, 50),- Environment::Develop => (1, 25),- Environment::Local => (1, 10),- };-- let db = PgPoolOptions::new()- .min_connections(min_connections)- .max_connections(max_connections)- .connect(&config.database_url)- .await- .context("could not connect to db")?;-- tracing::trace!(- min_connections,- max_connections,- "initialized db connection"- );-- let aws_config = macro_aws_config::get_macro_aws_config().await;-- let ses_client = ses_client::Ses::new(- aws_sdk_sesv2::Client::new(&aws_config),- &config.environment.to_string(),- );-- let notification_event_types = vec![- NotificationEventType::ChannelMessageSend,- NotificationEventType::ChannelMessageReply,- ];-- process_unsent_notifications_for_users(- &ses_client,- &db,- ¬ification_event_types,- config.unsent_notification_limit,- config.hours_ago,- )- .await?;-- Ok(())-}--async fn process_unsent_notifications_for_users(- ses_client: &ses_client::Ses,- db: &sqlx::Pool<sqlx::Postgres>,- notification_event_types: &[NotificationEventType],- limit: i64,- hours_ago: f64,-) -> anyhow::Result<()> {- let mut offset = 0;- let env = Environment::new_or_prod();-- loop {- // Get the list of unsent notifications for users and a given channel- // NOTE: there is a chance you email a user about unread notifications in 1 loop but get- // more unreads from them in the next. We need to ensure we check if we should email the- // user **EVERY** time.- let unsent_notifications = notification_db_client::user_notification::get::unsent::get_unsent_notifications_for_users(- db,- notification_event_types,- limit,- offset,- hours_ago,- )- .await.context("failed to get unsent notifications")?;-- if unsent_notifications.is_empty() {- break;- }-- // Filter out invalid emails and emails with aliases in dev- let unsent_notifications = unsent_notifications- .into_iter()- .filter(|notification| {- let email = notification.user_id.replace("macro|", "");- if !email_validator::is_valid_email(&email) {- tracing::warn!(notification=?notification, "invalid email {}", email);- false- } else {- match env {- Environment::Develop | Environment::Local => {- // In dev, we don't want to spam all our our alias emails with- // notifications- if email.contains("+") {- tracing::debug!("invalid email {}", email);- false- } else {- true- }- }- Environment::Production => true,- }- }- })- .collect::<Vec<UnsentNotification>>();-- // Filter out users that have notification email sent already- let notification_email_sent_user_ids =- notification_db_client::notification_email_sent::get::get_notification_email_sent_bulk(- db,- &unsent_notifications- .iter()- .map(|n| n.user_id.clone())- .collect::<Vec<String>>(),- )- .await- .context("unable to get notification email sent user ids")?;-- let unsent_notifications = unsent_notifications- .into_iter()- .filter(|notification| {- if notification_email_sent_user_ids.contains(¬ification.user_id) {- tracing::debug!("notification email sent user id");- false- } else {- true- }- })- .collect::<Vec<UnsentNotification>>();-- // Filter out users that have notifications muted- let muted_users =- notification_db_client::user_mute_notification::get_user_mute_notification_bulk(- db,- &unsent_notifications- .iter()- .map(|n| n.user_id.clone())- .collect::<Vec<String>>(),- )- .await- .context("unable to get muted users")?;-- let unsent_notifications = unsent_notifications- .into_iter()- .filter(|notification| {- if muted_users.contains(¬ification.user_id) {- tracing::debug!("muted user {}", notification.user_id);- false- } else {- true- }- })- .collect::<Vec<UnsentNotification>>();-- // Filter out emails that are unsubscribed- let emails = unsent_notifications- .iter()- .map(|n| n.user_id.replace("macro|", ""))- .collect::<Vec<String>>();- // Get unsubscribed status for emails- let email_unsubscribed =- notification_db_client::unsubscribe::email::is_email_unsubscribed_batch(db, &emails)- .await- .context("unable to check if emails are unsubscribed")?;- let email_unsubscribed: HashSet<String> = email_unsubscribed- .into_iter()- .filter_map(- |(email, is_unsubscribed)| {- if is_unsubscribed { Some(email) } else { None }- },- )- .collect();-- let unsent_notifications = unsent_notifications- .into_iter()- .filter(|notification| {- let email = notification.user_id.replace("macro|", "");- if email_unsubscribed.contains(&email) {- tracing::debug!("unsubscribed email {}", email);- false- } else {- true- }- })- .collect::<Vec<UnsentNotification>>();-- let mut user_notifications_map: HashMap<String, Vec<UnsentNotification>> = HashMap::new();-- for notification in unsent_notifications {- let user_id = notification.user_id.clone();- let notifications = user_notifications_map.entry(user_id).or_default();-- notifications.push(notification);- }-- tracing::trace!(user_notifications_map=?user_notifications_map.keys(), "users unsent notifications");-- let result = futures::stream::iter(user_notifications_map.into_iter())- .then(|(user_id, notifications)| async move {- let result =- process_user_notifications(ses_client, db, &user_id, ¬ifications).await;-- match result {- Ok(()) => Ok(()),- Err(e) => Err((user_id, e)),- }- })- .collect::<Vec<Result<(), (String, anyhow::Error)>>>()- .await;-- for result in result {- match result {- Ok(()) => (),- Err((user_id, e)) => {- tracing::error!(user_id=?user_id, error=?e, "unable to process user notifications")- }- }- }-- offset += limit;- }-- Ok(())-}--/// Processes a user's notifications-#[tracing::instrument(skip(ses_client, db, notifications))]-async fn process_user_notifications(- ses_client: &ses_client::Ses,- db: &sqlx::Pool<sqlx::Postgres>,- user_id: &str,- notifications: &[UnsentNotification],-) -> anyhow::Result<()> {- let start_time = std::time::Instant::now();- let email = user_id.replace("macro|", "");- tracing::trace!("processing notifications");-- // Filter out notifications where the channel id is in the `channel_notification_email_sent`- let channel_ids = notifications- .iter()- .map(|n| n.entity.entity_id.to_string())- .collect::<Vec<String>>();- tracing::trace!(channel_ids=?channel_ids, "got channel ids");-- let channel_notification_email_sent = notification_db_client::channel_notification_email_sent::get::get_channel_notification_email_sent_bulk_by_channel_ids(- db,- user_id,- &channel_ids,- ).await.context("unable to get channel notification email sent")?;-- let notifications = notifications- .iter()- .filter(|n| !channel_notification_email_sent.contains(n.entity.entity_id.as_ref()))- .collect::<Vec<&UnsentNotification>>();-- if notifications.is_empty() {- tracing::debug!("no notifications to send");- return Ok(());- }-- // Filter out channels users have unsubscribed to- let user_unsubscribes =- notification_db_client::unsubscribe::get::get_user_unsubscribes(db, user_id)- .await- .context("unable to get user unsubscribes")?;- tracing::trace!(user_unsubscribes=?user_unsubscribes, "got user unsubscribes");-- let user_unsubscribed_channel_ids = user_unsubscribes- .iter()- .filter_map(|unsubscribe| match unsubscribe.item_type.as_str() {- "channel" => Some(unsubscribe.item_id.clone()),- _ => None,- })- .collect::<HashSet<String>>();- tracing::trace!(user_unsubscribed_channel_ids=?user_unsubscribed_channel_ids, "got user unsubscribed channel ids");-- let notifications = notifications- .into_iter()- .filter(|notification| {- if user_unsubscribed_channel_ids.contains(notification.entity.entity_id.as_ref()) {- tracing::debug!(notification=?notification, "unsubscribed channel {}", notification.entity.entity_id);- false- } else {- true- }- })- .collect::<Vec<&UnsentNotification>>();-- if notifications.is_empty() {- tracing::debug!("no notifications to send");- return Ok(());- }-- // Optimistically mark user as having sent email- notification_db_client::notification_email_sent::create::create_notification_email_sent(- db, user_id,- )- .await- .context("unable to mark user as having sent email")?;- tracing::trace!("notification email marked as sent");-- // Send email- let macro_url = get_login_url(Environment::new_or_prod());-- let (email_content, subject) = fill_unread_message_template(¯o_url);-- ses_client- .send_email(&SENDER_ADDRESS, &email, &subject, &email_content)- .await- .context("unable to send email")?;- tracing::trace!("email sent");-- // Mark channel notification email sent for user- notification_db_client::channel_notification_email_sent::upsert::upsert_channel_notification_email_sent_bulk_channel_ids(- db,- user_id,- &channel_ids,- )- .await- .context("unable to mark channel notification email sent")?;- tracing::trace!("channel notification email marked as sent");-- // Mark notifications for event item ids as sent for user- notification_db_client::user_notification::patch::sent::bulk_patch_sent_notification_event_item_ids(- db,- user_id,- &channel_ids,- ).await.context("unable to mark notifications as sent")?;-- tracing::trace!(elasped_time=?start_time.elapsed(), "start time");- Ok(())-}--pub struct NotificationEmailPollerWorkerConfig {- /// The connection URL for the Postgres database this application should use.- pub database_url: String,-- /// The environment we are in- pub environment: Environment,-- /// The sender base address- #[allow(dead_code)]- // Explicitly allowed as it's used to ensure we have a correct sender base address in the lazy env var above- pub sender_base_address: String,-- /// The number of hours we will look back to find unsent notifications- /// Defaults to 1 hour- pub hours_ago: f64,-- /// The limit size for each batch of unsent notifications- /// Defaults to 100- pub unsent_notification_limit: i64,-}--fn get_login_url(env: Environment) -> Url {- env.get_frontend_url().join("login").unwrap()-}--impl NotificationEmailPollerWorkerConfig {- pub fn from_env() -> anyhow::Result<Self> {- let database_url =- std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;-- let environment = Environment::new_or_prod();-- let sender_base_address =- std::env::var("SENDER_BASE_ADDRESS").context("SENDER_BASE_ADDRESS must be provided")?;-- let hours_ago = std::env::var("HOURS_AGO")- .unwrap_or("1".to_string())- .parse::<f64>()- .context("HOURS_AGO must be a valid number")?;-- let unsent_notification_limit = std::env::var("UNSENT_NOTIFICATION_LIMIT")- .unwrap_or("100".to_string())- .parse::<i64>()- .context("UNSENT_NOTIFICATION_LIMIT must be a valid number")?;-- Ok(NotificationEmailPollerWorkerConfig {- database_url,- environment,- sender_base_address,- hours_ago,- unsent_notification_limit,- })- }-}--static TEMPLATE: &str = include_str!("./templates/unread_message/_unread_message_template.html");--static SUBJECT: &str = "Macro Unread Message";--pub fn fill_unread_message_template(macro_url: &Url) -> (String, String) {- let subject = SUBJECT;-- let content = TEMPLATE.replace("{{MACRO_URL}}", macro_url.as_str());-- (content, subject.to_string())-}