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
Blake1/bac 45 comment thread reply notification service support (#722)
cowlicks1c315c16afd0
diff --git a/js/app/packages/block-md/comments/commentOperations.ts b/js/app/packages/block-md/comments/commentOperations.tsindex 4aa1583e85..1ba3979dc7 100644--- a/js/app/packages/block-md/comments/commentOperations.ts+++ b/js/app/packages/block-md/comments/commentOperations.ts@@ -1,11 +1,7 @@import { mdStore } from '@block-md/signal/markdownBlockData';import { withAnalytics } from '@coparse/analytics';import { useBlockId } from '@core/block';-import type {- CreateCommentInfo,- DeleteCommentInfo,- UpdateCommentInfo,-} from '@core/collab/comments/commentType';+import type { DeleteCommentInfo } from '@core/collab/comments/commentType';import { threadMeasureContainerId } from '@core/collab/comments/Thread';import {CREATE_COMMENT_COMMAND,@@ -14,6 +10,10 @@ import {SET_COMMENT_THREAD_ID_COMMAND,} from '@core/component/LexicalMarkdown/plugins/comments/commentPlugin';import { blockElementSignal } from '@core/signal/blockElement';+import type {+ CreateCommentRequest,+ EditCommentRequest,+} from '@service-storage/generated/schemas';import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';import { createCallback } from '@solid-primitives/rootless';import {@@ -41,7 +41,7 @@ export function useCreateComment() {const editor = mdStore.get.editor;return createCallback(- async (info: CreateCommentInfo & { markId: string }) => {+ async (info: CreateCommentRequest & { threadId: number }) => {track(TrackingEvents.BLOCKMARKDOWN.COMMENT.CREATE);const { threadId, text } = info;@@ -71,7 +71,7 @@ export function useCreateComment() {return response;}- return await createThreadReply(text, threadId);+ return await createThreadReply(info);});}@@ -79,12 +79,10 @@ export function useCreateComment() {export function useUpdateComment() {const editComment = useEditCommentResource();- return createCallback((info: UpdateCommentInfo) => {+ return createCallback((commentId: number, info: EditCommentRequest) => {track(TrackingEvents.BLOCKMARKDOWN.COMMENT.UPDATE);- return editComment(info.commentId, {- text: info.text,- });+ return editComment(commentId, info);});}diff --git a/js/app/packages/block-md/comments/commentsResource.ts b/js/app/packages/block-md/comments/commentsResource.tsindex b1d2e52796..b1261a765c 100644--- a/js/app/packages/block-md/comments/commentsResource.ts+++ b/js/app/packages/block-md/comments/commentsResource.ts@@ -222,17 +222,12 @@ export function useCreateHighlightCommentResource() {export function useCreateThreadReplyResource() {const createComment = useCreateComment();- return async (text: string, threadId: number) => {- if (threadId < 0) {+ return async (body: CreateCommentRequest & { threadId: number }) => {+ if (body.threadId < 0) {console.error('Provide a valid thread id');return null;}- const body: CreateCommentRequest = {- text: text,- threadId,- };-return createComment(body);};}diff --git a/js/app/packages/block-pdf/store/comments/commentOperations.ts b/js/app/packages/block-pdf/store/comments/commentOperations.tsindex b6c6039c78..71d77a06eb 100644--- a/js/app/packages/block-pdf/store/comments/commentOperations.ts+++ b/js/app/packages/block-pdf/store/comments/commentOperations.ts@@ -4,13 +4,15 @@ import type { PdfRootLayout } from '@block-pdf/type/comments';import { withAnalytics } from '@coparse/analytics';import { useBlockId } from '@core/block';import {- type CreateCommentInfo,type DeleteCommentInfo,isRoot,- type UpdateCommentInfo,} from '@core/collab/comments/commentType';import { threadMeasureContainerId } from '@core/collab/comments/Thread';import { blockElementSignal } from '@core/signal/blockElement';+import type {+ CreateCommentRequest,+ EditCommentRequest,+} from '@service-storage/generated/schemas';import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';import { createCallback } from '@solid-primitives/rootless';import {@@ -34,69 +36,69 @@ export function useCreateComment() {const attachHighlightComment = useAttachHighlightCommentResource();const createThreadReply = useCreateThreadReplyResource();- return createCallback(async (info: CreateCommentInfo) => {- track(TrackingEvents.BLOCKPDF.COMMENT.CREATE);- const { threadId, text } = info;-- // new thread + anchor- if (threadId === -1) {- const comment = commentsStore.get.find((c) => c.threadId === threadId);- if (!comment) {- console.error('Unable to comment');- return null;- }-- let response: CreateCommentResponse | null = null;- switch (comment.type) {- case 'highlight':- const highlight = highlightsUuidMap()?.[comment.anchorId];- if (!highlight) {- console.error('Unable to find highlight');- return response;- }+ return createCallback(+ async (info: CreateCommentRequest & { threadId: number }) => {+ track(TrackingEvents.BLOCKPDF.COMMENT.CREATE);+ const { threadId, text } = info;++ // new thread + anchor+ if (threadId === -1) {+ const comment = commentsStore.get.find((c) => c.threadId === threadId);+ if (!comment) {+ console.error('Unable to comment');+ return null;+ }- if (highlight.existsOnServer) {- response = await attachHighlightComment(text, highlight.uuid);- } else {- response = await createHighlightComment(text, highlight);- }- break;- case 'free':- const newThreadPlaceable_ = newThreadPlaceable();- if (- !newThreadPlaceable_ ||- newThreadPlaceable_.internalId !== comment.anchorId- ) {- console.error('Unable to find new thread placeable');+ let response: CreateCommentResponse | null = null;+ switch (comment.type) {+ case 'highlight':+ const highlight = highlightsUuidMap()?.[comment.anchorId];+ if (!highlight) {+ console.error('Unable to find highlight');+ return response;+ }++ if (highlight.existsOnServer) {+ response = await attachHighlightComment(text, highlight.uuid);+ } else {+ response = await createHighlightComment(text, highlight);+ }+ break;+ case 'free':+ const newThreadPlaceable_ = newThreadPlaceable();+ if (+ !newThreadPlaceable_ ||+ newThreadPlaceable_.internalId !== comment.anchorId+ ) {+ console.error('Unable to find new thread placeable');+ return response;+ }++ response = await createFreeComment(text, newThreadPlaceable_);+ break;+ default:+ console.error('invalid comment type', comment.type);return response;- }+ }- response = await createFreeComment(text, newThreadPlaceable_);- break;- default:- console.error('invalid comment type', comment.type);- return response;- }+ if (response) {+ deleteNewComments();+ }- if (response) {- deleteNewComments();+ return response;}- return response;+ return await createThreadReply(info);}-- return await createThreadReply(text, threadId);- });+ );}export function useUpdateComment() {const editComment = useEditCommentResource();- return createCallback((info: UpdateCommentInfo) => {+ return createCallback((commentId: number, info: EditCommentRequest) => {track(TrackingEvents.BLOCKPDF.COMMENT.UPDATE);- return editComment(info.commentId, {- text: info.text,- });+ return editComment(commentId, info);});}diff --git a/js/app/packages/block-pdf/store/commentsResource.ts b/js/app/packages/block-pdf/store/commentsResource.tsindex 2ef28830d5..e556e81925 100644--- a/js/app/packages/block-pdf/store/commentsResource.ts+++ b/js/app/packages/block-pdf/store/commentsResource.ts@@ -472,17 +472,12 @@ export function useDeleteUnthreadedHighlightResource() {export function useCreateThreadReplyResource() {const createComment = useCreateComment();- return async (text: string, threadId: number) => {- if (threadId < 0) {+ return async (body: CreateCommentRequest & { threadId: number }) => {+ if (body.threadId < 0) {console.error('Provide a valid thread id');return null;}- const body: CreateCommentRequest = {- text: text,- threadId,- };-return createComment(body);};}diff --git a/js/app/packages/core/collab/comments/Comment.tsx b/js/app/packages/core/collab/comments/Comment.tsxindex fa623c2a3b..9caa4bf163 100644--- a/js/app/packages/core/collab/comments/Comment.tsx+++ b/js/app/packages/core/collab/comments/Comment.tsx@@ -9,10 +9,11 @@ import {untrack,useContext,} from 'solid-js';+import { getAndClearCommentMentions } from '.';import type { Root } from './commentType';import { EditInput } from './Inputs';import { MessageTopRow } from './MessageTopRow';-import { CommentsContext, sendMentions, ThreadContext } from './Thread';+import { CommentsContext, ThreadContext } from './Thread';const ThreadLine = () => {return (@@ -119,19 +120,11 @@ export function Comment(setIsEditing(false);setTextValue(newText);Promise.all([- commentOperations.updateComment({+ commentOperations.updateComment(props.comment.id, {text: newText,- commentId: props.comment.id,+ threadId: props.comment.threadId,+ mentions: getAndClearCommentMentions(mentionsSignal),}),- sendMentions(- {- type: 'edit-comment',- commentId: props.comment.id,- threadId: props.comment.threadId,- text: newText,- },- mentionsSignal- ),]);}}handleCancel={() => {diff --git a/js/app/packages/core/collab/comments/Thread.tsx b/js/app/packages/core/collab/comments/Thread.tsxindex bbe1de2179..53ebac9b96 100644--- a/js/app/packages/core/collab/comments/Thread.tsx+++ b/js/app/packages/core/collab/comments/Thread.tsx@@ -2,8 +2,6 @@ import { BozzyBracketInnerSibling } from '@core/component/BozzyBracket';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { createTheme } from '@core/component/LexicalMarkdown/theme';import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';-import type { DocumentMentionLocation } from '@service-notification/client';-import { storageServiceClient } from '@service-storage/client';import type { EditorThemeClasses } from 'lexical';import {type Accessor,@@ -19,6 +17,7 @@ import {type Signal,useContext,} from 'solid-js';+import { getAndClearCommentMentions } from '.';import { Comment, CommentReply } from './Comment';import type { CommentOperations, Layout, Reply, Root } from './commentType';import { EditInput, NewReplyInput } from './Inputs';@@ -88,25 +87,6 @@ export const CommentsContext = createContext<CommentsContextType>({inComment: false,});-export const sendMentions = (- data: DocumentMentionLocation,- mentionsSignal: Signal<UserMentionRecord[]>-) => {- const [mentions, setMentions] = mentionsSignal;- const mentions_ = mentions();- setMentions([]);- if (mentions_.length === 0) return;- const aggregatedMention: UserMentionRecord = {- documentId: mentions_[0].documentId,- mentions: mentions_.flatMap((m) => m.mentions),- metadata: {- mention_id: mentions_[0].metadata.mention_id,- location: data,- },- };- return storageServiceClient.upsertUserMentions(aggregatedMention);-};-export function Thread(props: {comment: Root;layout: Layout;@@ -223,23 +203,11 @@ export function Thread(props: {onSend={(content: string) => {if (content.trim() === '') return;// NOTE: we need the server to return the thread id first- commentOperations- .createComment({- threadId: props.comment.threadId,- text: content,- })- .then((response) => {- if (!response) return;- sendMentions(- {- type: 'create-comment',- commentId: response.comments[0].commentId,- threadId: response.thread.threadId,- text: content,- },- mentionsSignal- );- });+ commentOperations.createComment({+ threadId: props.comment.threadId,+ text: content,+ mentions: getAndClearCommentMentions(mentionsSignal),+ });}}isNewThread/>@@ -292,19 +260,12 @@ export function Thread(props: {}updateReply={(content) => {Promise.all([- commentOperations.updateComment({+ commentOperations.updateComment(replyId, {text: content,- commentId: replyId,+ threadId: props.comment.threadId,+ mentions:+ getAndClearCommentMentions(mentionsSignal),}),- sendMentions(- {- type: 'edit-comment',- commentId: replyId,- threadId: props.comment.threadId,- text: content,- },- mentionsSignal- ),]);}}/>@@ -320,25 +281,11 @@ export function Thread(props: {createReply={(content) => {if (content.trim() === '') return;dispatch({ action: 'hard', editing: false });- commentOperations- .createComment({- threadId: props.comment.threadId,- text: content,- })- .then((response) => {- if (!response) return;- sendMentions(- {- type: 'create-comment',- commentId:- response.comments[response.comments.length - 1]- .commentId,- threadId: props.comment.threadId,- text: content,- },- mentionsSignal- );- });+ commentOperations.createComment({+ threadId: props.comment.threadId,+ text: content,+ mentions: getAndClearCommentMentions(mentionsSignal),+ });}}isEditing={isEditingNewReply()}setEditing={(editing) =>diff --git a/js/app/packages/core/collab/comments/commentType.ts b/js/app/packages/core/collab/comments/commentType.tsindex 32205b5d72..0bc3a09fc6 100644--- a/js/app/packages/core/collab/comments/commentType.ts+++ b/js/app/packages/core/collab/comments/commentType.ts@@ -1,3 +1,7 @@+import type {+ CreateCommentRequest,+ EditCommentRequest,+} from '@service-storage/generated/schemas';import type { Comment } from '@service-storage/generated/schemas/comment';import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';@@ -29,16 +33,6 @@ export type Root = ThreadedComment & {export type Reply = ThreadedComment & {};-export type CreateCommentInfo = {- threadId: number;- text: string;-};--export type UpdateCommentInfo = {- commentId: number;- text: string;-};-export type DeleteCommentInfo = {commentId: number;removeAnchorThreadOnly?: boolean;@@ -50,10 +44,13 @@ export type Layout = {export type CommentOperations = {createComment: (- info: CreateCommentInfo+ info: CreateCommentRequest) => Promise<CreateCommentResponse | null>;deleteComment: (info: DeleteCommentInfo) => Promise<boolean> | undefined;- updateComment: (info: UpdateCommentInfo) => Promise<boolean>;+ updateComment: (+ commentId: number,+ info: EditCommentRequest+ ) => Promise<boolean>;};export function isRoot(comment: Root | Reply): comment is Root {diff --git a/js/app/packages/core/collab/comments/index.ts b/js/app/packages/core/collab/comments/index.tsnew file mode 100644index 0000000000..b35da856f5--- /dev/null+++ b/js/app/packages/core/collab/comments/index.ts@@ -0,0 +1,16 @@+import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';+import type { Signal } from 'solid-js';++export const getAndClearCommentMentions = (+ mentionsSignal: Signal<UserMentionRecord[]>+) => {+ const [mentions, setMentions] = mentionsSignal;+ const mentions_ = mentions();+ setMentions([]);+ return typeof mentions_[0] === 'undefined'+ ? undefined+ : {+ users: mentions_.flatMap((m) => m.mentions),+ mentionId: mentions_[0].metadata.mention_id,+ };+};diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.tsindex 0ad10daab5..93dadba1cd 100644--- a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts@@ -6,7 +6,6 @@ import type { ParsedDate } from '@core/util/dateParser';import type { EmailEntity } from '@macro-entity';import { waitBulkUploadStatus } from '@service-connection/bulkUpload';import type { DocumentMentionMetadata } from '@service-notification/client';-import { storageServiceClient } from '@service-storage/client';import type { BasicDocument } from '@service-storage/generated/schemas/basicDocument';import type { Item } from '@service-storage/generated/schemas/item';import type { Project } from '@service-storage/generated/schemas/project';@@ -166,8 +165,6 @@ export async function handleUserMention(};if (onUserMention) {onUserMention(record);- } else {- storageServiceClient.upsertUserMentions(record);}if (!disableMentionTracking) {mentionId = await trackMention(blockId, 'user', user.id);diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex edced7625a..8f27be3c03 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -1110,16 +1110,6 @@ export const storageServiceClient = {);},- async upsertUserMentions(args) {- const { documentId, mentions, metadata } = args;- return ok(- await dssFetch<{}>(`/mentions/${documentId}`, {- method: 'POST',- body: JSON.stringify({ mentions, metadata }),- })- );- },-projects: {async getAll() {return mapOk(diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createCommentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createCommentRequest.tsindex e6315bac3f..1180c1cb67 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createCommentRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createCommentRequest.ts@@ -5,10 +5,12 @@* OpenAPI spec version: 0.1.0*/import type { CreateCommentRequestAnchor } from './createCommentRequestAnchor';+import type { CreateCommentRequestMentions } from './createCommentRequestMentions';import type { CreateCommentRequestThreadId } from './createCommentRequestThreadId';export interface CreateCommentRequest {anchor?: CreateCommentRequestAnchor;+ mentions?: CreateCommentRequestMentions;metadata?: unknown;text: string;threadId?: CreateCommentRequestThreadId;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createCommentRequestMentions.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createCommentRequestMentions.tsnew file mode 100644index 0000000000..2f730e79b4--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createCommentRequestMentions.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { Mentions } from './mentions';++export type CreateCommentRequestMentions = null | Mentions;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/editCommentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentRequest.tsindex 4925691f26..2826d8e787 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/editCommentRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentRequest.ts@@ -4,9 +4,12 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { EditCommentRequestMentions } from './editCommentRequestMentions';import type { EditCommentRequestText } from './editCommentRequestText';export interface EditCommentRequest {+ mentions?: EditCommentRequestMentions;metadata?: unknown;text?: EditCommentRequestText;+ threadId: number;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/editCommentRequestMentions.ts b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentRequestMentions.tsnew file mode 100644index 0000000000..9fdbfe2ddc--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentRequestMentions.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { Mentions } from './mentions';++export type EditCommentRequestMentions = null | Mentions;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/editCommentResponseAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentResponseAllOf.tsindex c89702b798..6290c6cb1b 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/editCommentResponseAllOf.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentResponseAllOf.ts@@ -4,7 +4,11 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { EditCommentResponseAllOfFileType } from './editCommentResponseAllOfFileType';export type EditCommentResponseAllOf = {documentId: string;+ documentName: string;+ documentOwner: string;+ fileType?: EditCommentResponseAllOfFileType;};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/editCommentResponseAllOfFileType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentResponseAllOfFileType.tsnew file mode 100644index 0000000000..941f3ea8c0--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/editCommentResponseAllOfFileType.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type EditCommentResponseAllOfFileType = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex d96c9834f2..36efedee58 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -90,6 +90,7 @@ export * from './createBulkDocumentResponseDataDocumentMetadata';export * from './createBulkDocumentResponseDataPresignedUrl';export * from './createCommentRequest';export * from './createCommentRequestAnchor';+export * from './createCommentRequestMentions';export * from './createCommentRequestThreadId';export * from './createCommentResponse';export * from './createCommentResponseAllOf';@@ -201,9 +202,11 @@ export * from './editAnchorRequestOneOfAllOfFileType';export * from './editAnchorResponse';export * from './editAnchorResponseAllOf';export * from './editCommentRequest';+export * from './editCommentRequestMentions';export * from './editCommentRequestText';export * from './editCommentResponse';export * from './editCommentResponseAllOf';+export * from './editCommentResponseAllOfFileType';export * from './editDocumentRequestV2';export * from './editDocumentRequestV2DocumentName';export * from './editDocumentRequestV2ProjectId';@@ -304,6 +307,7 @@ export * from './latestMessageLatestNonThreadMessage';export * from './locationResponseData';export * from './locationResponseDataOneOf';export * from './locationResponseDataOneOfTwo';+export * from './mentions';export * from './params';export * from './paramsExpand';export * from './paramsLimit';@@ -502,7 +506,6 @@ export * from './uploadFolderHandler200DataOneOf';export * from './uploadFolderRequest';export * from './uploadFolderRequestParentId';export * from './upsertUserDocumentViewLocationRequest';-export * from './upsertUserMentionsRequest';export * from './userActivitiesResponse';export * from './userActivitiesResponseNextOffset';export * from './userDocumentsResponse';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/mentions.ts b/js/app/packages/service-clients/service-storage/generated/schemas/mentions.tsnew file mode 100644index 0000000000..773efc0f59--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/mentions.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export interface Mentions {+ mentionId: string;+ users: string[];+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/upsertUserMentionsRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/upsertUserMentionsRequest.tsdeleted file mode 100644index 1bcda72a06..0000000000--- a/js/app/packages/service-clients/service-storage/generated/schemas/upsertUserMentionsRequest.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * document_storage_service- * OpenAPI spec version: 0.1.0- */--export interface UpsertUserMentionsRequest {- /** List of user ids that are mentioned for this notification */- mentions: string[];- /** Custom metadata that may be needed for the notification */- metadata?: unknown;-}diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 96315ea786..360b1044cc 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -527,8 +527,18 @@ export const editCommentParams = zod.object({});export const editCommentBody = zod.object({+ mentions: zod+ .union([+ zod.null(),+ zod.object({+ mentionId: zod.string(),+ users: zod.array(zod.string()),+ }),+ ])+ .optional(),metadata: zod.any().optional(),text: zod.string().nullish(),+ threadId: zod.number(),});export const editCommentResponse = zod@@ -547,6 +557,9 @@ export const editCommentResponse = zod.and(zod.object({documentId: zod.string(),+ documentName: zod.string(),+ documentOwner: zod.string(),+ fileType: zod.string().nullish(),}));@@ -633,6 +646,15 @@ export const createCommentBody = zod.object({),]).optional(),+ mentions: zod+ .union([+ zod.null(),+ zod.object({+ mentionId: zod.string(),+ users: zod.array(zod.string()),+ }),+ ])+ .optional(),metadata: zod.any().optional(),text: zod.string(),threadId: zod.number().nullish(),@@ -3100,26 +3122,6 @@ export const postItemsSoupResponse = zod.object({next_cursor: zod.string().nullish(),});-export const upsertUserMentionsParams = zod.object({- document_id: zod.string().describe('Document ID'),-});--export const upsertUserMentionsBody = zod.object({- mentions: zod- .array(zod.string())- .describe('List of user ids that are mentioned for this notification'),- metadata: zod- .any()- .optional()- .describe('Custom metadata that may be needed for the notification'),-});--export const upsertUserMentionsResponse = zod- .object({})- .describe(- 'Empty response is required due to custom fetch forcing `response.json()`'- );-/*** @summary Gets the users pinned items*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex a49292135c..cc96cb3731 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -2502,75 +2502,6 @@}}},- "/mentions/{document_id}": {- "post": {- "tags": ["mentions::upsert_user_mentions"],- "operationId": "upsert_user_mentions",- "parameters": [- {- "name": "document_id",- "in": "path",- "description": "Document ID",- "required": true,- "schema": {- "type": "string"- }- }- ],- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/UpsertUserMentionsRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/EmptyResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/GenericErrorResponse"- }- }- }- },- "401": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/GenericErrorResponse"- }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/GenericErrorResponse"- }- }- }- }- }- }- },"/pins": {"get": {"tags": ["pins::get_pins"],@@ -5092,6 +5023,16 @@}]},+ "mentions": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/Mentions"+ }+ ]+ },"metadata": {},"text": {"type": "string"@@ -5900,10 +5841,25 @@},"EditCommentRequest": {"type": "object",+ "required": ["threadId"],"properties": {+ "mentions": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/Mentions"+ }+ ]+ },"metadata": {},"text": {"type": ["string", "null"]+ },+ "threadId": {+ "type": "integer",+ "format": "int64"}}},@@ -5914,10 +5870,19 @@},{"type": "object",- "required": ["documentId"],+ "required": ["documentId", "documentName", "documentOwner"],"properties": {"documentId": {"type": "string"+ },+ "documentName": {+ "type": "string"+ },+ "documentOwner": {+ "type": "string"+ },+ "fileType": {+ "type": ["string", "null"]}}}@@ -7226,6 +7191,21 @@}]},+ "Mentions": {+ "type": "object",+ "required": ["users", "mentionId"],+ "properties": {+ "mentionId": {+ "type": "string"+ },+ "users": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },"Params": {"type": "object","properties": {@@ -9214,22 +9194,6 @@}}},- "UpsertUserMentionsRequest": {- "type": "object",- "required": ["mentions"],- "properties": {- "mentions": {- "type": "array",- "items": {- "type": "string"- },- "description": "List of user ids that are mentioned for this notification"- },- "metadata": {- "description": "Custom metadata that may be needed for the notification"- }- }- },"UserActivitiesResponse": {"type": "object","required": ["recent", "total"],diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.tsindex 6adc371a20..c1e77514cd 100644--- a/js/app/packages/service-clients/service-storage/service.ts+++ b/js/app/packages/service-clients/service-storage/service.ts@@ -7,7 +7,6 @@ import {Svc,withFetchErrors,} from '@core/service';-import { documentMentionMetadata } from '@service-notification/client';import { z } from 'zod';import * as schemas from './generated/zod';@@ -671,17 +670,6 @@ export const StorageService = new Svc('Document++ Storage Service API')modifies: true,throws: withFetchErrors(),})- .fn('upsertUserMentions', {- description: 'Upsert the user mentions for a document',- args: {- documentId: schemas.upsertUserMentionsParams.shape.document_id,- mentions: schemas.upsertUserMentionsBody.shape.mentions,- metadata: documentMentionMetadata,- },- result: schemas.upsertUserMentionsResponse.shape,- modifies: true,- throws: withFetchErrors(),- }).fn('getDeletedItems', {description: 'Get the list of deleted items',result: schemas.recentlyDeletedResponse.shape.data.shape,diff --git a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rsindex 8b6e82e695..b31c64fc49 100644--- a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs+++ b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs@@ -25,7 +25,7 @@ use crate::api::{use model::{response::ErrorResponse, tracking::IPContext};-use model_notifications::{InviteToTeamMetadata, NotificationEvent, NotificationQueueMessage};+use model_notifications::{InviteToTeamMetadata, NotificationQueueMessage};/// The request body to invite a user to a team#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]@@ -184,7 +184,7 @@ pub(in crate::api::team) async fn notify_team_invite(let notification_queue_message = NotificationQueueMessage {notification_entity: EntityType::Team.with_entity_string(team_invite.team_invite_id.to_string()),- notification_event: NotificationEvent::InviteToTeam(notification_metadata.clone()),+ notification_event: notification_metadata.clone().into(),sender_id: Some(invited_by.clone()),recipient_ids: Some(vec![format!("macro|{}", team_invite.email.as_ref())]),};diff --git a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rsindex 3ae6a5da96..4203ffdc50 100644--- a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs+++ b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs@@ -6,7 +6,7 @@ use axum::{};use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;-use model_notifications::{InviteToTeamMetadata, NotificationEvent, NotificationQueueMessage};+use model_notifications::{InviteToTeamMetadata, NotificationQueueMessage};use crate::api::{context::ApiContext,@@ -141,7 +141,7 @@ async fn notify_team_invite(let notification_queue_message = NotificationQueueMessage {notification_entity: EntityType::Team.with_entity_string(team_invite_id.to_string()),- notification_event: NotificationEvent::InviteToTeam(notification_metadata),+ notification_event: notification_metadata.into(),sender_id: Some(invited_by),recipient_ids: Some(vec![format!("macro|{normalized_email}")]),};diff --git a/rust/cloud-storage/comms_service/src/api/swagger.rs b/rust/cloud-storage/comms_service/src/api/swagger.rsindex e117002e64..e7a49f0f75 100644--- a/rust/cloud-storage/comms_service/src/api/swagger.rs+++ b/rust/cloud-storage/comms_service/src/api/swagger.rs@@ -13,14 +13,13 @@ use crate::api::{post_typing::PostTypingRequest,remove_participants::RemoveParticipantsRequest,},+ extractors::ParticipantAccess,mentions::{CreateEntityMentionRequest, CreateEntityMentionResponse, DeleteEntityMentionRequest,DeleteEntityMentionResponse,},preview::get_batch_preview::{GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse},};--use crate::api::extractors::ParticipantAccess;use comms::inbound::{ApiActivity, ApiChannelWithLatest};use comms_db_client::channels::patch_channel::PatchChannelOptions;use comms_db_client::model::{diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rsindex 1443c4546b..4f4a9c184b 100644--- a/rust/cloud-storage/comms_service/src/notification.rs+++ b/rust/cloud-storage/comms_service/src/notification.rs@@ -49,13 +49,13 @@ fn create_notification_queue_message(channel_id: &Uuid,sender_id: MacroUserIdStr<'static>,recipients: &[String],- notification_event: NotificationEvent,+ notification_event: impl Into<NotificationEvent>,) -> NotificationQueueMessage {NotificationQueueMessage {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: notification_event.into(),}}@@ -71,10 +71,10 @@ impl<'a> ChannelInviteEvent<'a> {self.recipient_user_ids.iter().map(|m| m.as_str()),once(self.invited_by_user_id.as_ref()),),- NotificationEvent::ChannelInvite(ChannelInviteMetadata {+ ChannelInviteMetadata {invited_by: self.invited_by_user_id.clone(),common: self.common.clone(),- }),+ },));}@@ -94,12 +94,12 @@ impl ChannelMessageEvent<'_> {self.user_mentions.iter().map(|m| m.as_str()),once(self.message.sender_id.0.as_ref()),),- NotificationEvent::ChannelMention(ChannelMentionMetadata {+ 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(),- }),+ },));}@@ -114,14 +114,12 @@ impl ChannelMessageEvent<'_> {self.channel_id,self.message.sender_id.clone(),&recipients_excluding_mentions,- NotificationEvent::ChannelMessageDocument(ChannelMessageDocumentMetadata(- DocumentMentionMetadata {- document_name: mention.item_name.clone(),- owner: mention.item_owner.clone(),- file_type: mention.file_type.clone(),- metadata: None,- },- )),+ ChannelMessageDocumentMetadata(DocumentMentionMetadata {+ document_name: mention.item_name.clone(),+ owner: mention.item_owner.clone(),+ file_type: mention.file_type.clone(),+ metadata: None,+ }),));}}@@ -148,13 +146,13 @@ impl ChannelMessageEvent<'_> {self.thread_participants.iter().map(|p| p.as_ref()),sender_and_mentions,),- NotificationEvent::ChannelMessageReply(ChannelReplyMetadata {+ 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(),common: self.channel_metadata.clone(),- }),+ },));} else {tracing::warn!("thread participants is empty, but message has thread id");@@ -166,10 +164,10 @@ impl ChannelMessageEvent<'_> {self.channel_id,self.message.sender_id.clone(),&recipients_without_sender_and_mentions,- NotificationEvent::ChannelInvite(ChannelInviteMetadata {+ ChannelInviteMetadata {invited_by: self.message.sender_id.clone(),common: self.channel_metadata.clone(),- }),+ },));}// Channel has messages, send message send notification@@ -178,12 +176,12 @@ impl ChannelMessageEvent<'_> {self.channel_id,self.message.sender_id.clone(),&recipients_without_sender_and_mentions,- NotificationEvent::ChannelMessageSend(ChannelMessageSendMetadata {+ 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(),- }),+ },));}}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 a23166209e..606192304b 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,6 +1,12 @@use std::sync::Arc;-use crate::{api::context::ApiContext, service::conn_gateway::update_live_comment_state};+use crate::{+ api::{+ annotations::{NotifLocationType, build_mention_notif},+ context::ApiContext,+ },+ service::conn_gateway::update_live_comment_state,+};use axum::{Json,extract::{Extension, Path, State},@@ -9,17 +15,15 @@ use axum::{};use connection_gateway_client::ConnectionGatewayClient;use macro_db_client::annotations::create_comment::create_document_comment;-use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;use model::{annotations::{- AnnotationIncrementalUpdate,+ AnnotationIncrementalUpdate, Mentions,create::{CreateCommentRequest, CreateCommentResponse},},document::DocumentBasic,response::ErrorResponse,user::UserContext,};-use models_permissions::share_permission::access_level::CommentAccessLevel;use sqlx::PgPool;use super::comment_error_response;@@ -47,10 +51,10 @@ pub struct Params {)]#[axum::debug_handler(state = ApiContext)]pub async fn create_comment_handler(- _access: DocumentAccessExtractor<CommentAccessLevel>,+ State(macro_notify_client): State<Arc<macro_notify::MacroNotify>>,State(db): State<PgPool>,State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,- user_context: Extension<UserContext>,+ Extension(UserContext { user_id, .. }): Extension<UserContext>,document_context: Extension<DocumentBasic>,Path(Params { document_id }): Path<Params>,Json(req): Json<CreateCommentRequest>,@@ -64,22 +68,38 @@ pub async fn create_comment_handler().into_response());}- let user_id = user_context.user_id.as_str();- let document_id = document_id.as_str();- match create_document_comment(&db, document_id, user_id, req).await {+ match create_document_comment(&db, &document_id, &user_id, &req).await {Ok(res) => {- let response: CreateCommentResponse = res;+ if let Some(Mentions { users, mention_id }) = &req.mentions {+ let notif = build_mention_notif(+ NotifLocationType::CreateComment,+ req.text,+ res.comment_thread.comments.first(),+ res.comment_thread.thread.thread_id,+ users,+ document_context.document_name.clone(),+ document_context.owner.clone(),+ document_context.file_type.clone(),+ user_id.clone().try_into().ok(),+ document_id.to_string(),+ mention_id,+ );+ _ = macro_notify_client+ .send_notification(notif)+ .await+ .inspect_err(|e| tracing::error!(error =? e, "coundn't send document mention notification"));+ }update_live_comment_state(&conn_gateway_client,- document_id,+ &document_id,AnnotationIncrementalUpdate::CreateComment {- sender: user_id,- document_id,- response: &response,+ sender: &user_id,+ document_id: &document_id,+ response: &res,},).await;- Ok((StatusCode::OK, Json(response)).into_response())+ Ok((StatusCode::OK, Json(res)).into_response())}Err(e) => comment_error_response(e, "Error creating comment"),}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 f32cc73818..cc6b554534 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,6 +1,9 @@use std::sync::Arc;-use crate::service::conn_gateway::update_live_comment_state;+use crate::{+ api::annotations::{NotifLocationType, build_mention_notif},+ service::conn_gateway::update_live_comment_state,+};use axum::{Json,extract::{Extension, Path, State},@@ -11,7 +14,7 @@ use connection_gateway_client::ConnectionGatewayClient;use macro_db_client::annotations::edit_comment::edit_document_comment;use model::{annotations::{- AnnotationIncrementalUpdate,+ AnnotationIncrementalUpdate, Mentions,edit::{EditCommentRequest, EditCommentResponse},},response::ErrorResponse,@@ -43,29 +46,45 @@ pub struct Params {)]pub async fn edit_comment_handler(State(db): State<PgPool>,+ State(macro_notify_client): State<Arc<macro_notify::MacroNotify>>,State(conn_gateway_client): State<Arc<ConnectionGatewayClient>>,- user_context: Extension<UserContext>,+ Extension(UserContext { user_id, .. }): Extension<UserContext>,Path(Params { comment_id }): Path<Params>,Json(req): Json<EditCommentRequest>,) -> Result<Response, Response> {- let user_id = user_context.user_id.as_str();-// TODO: check if the user has comment access to the document- match edit_document_comment(&db, comment_id, user_id, req).await {+ match edit_document_comment(&db, comment_id, &user_id, &req).await {Ok(res) => {- let response: EditCommentResponse = res;- let document_id = response.document_id.as_str();+ if let Some(Mentions { users, mention_id }) = req.mentions {+ let notif = build_mention_notif(+ NotifLocationType::EditComment,+ req.text.clone().unwrap_or_else(|| "".to_string()),+ Some(&res.comment),+ req.thread_id,+ &users,+ res.document_name.clone(),+ res.document_owner.clone(),+ res.file_type.clone(),+ user_id.clone().try_into().ok(),+ res.document_id.to_string(),+ &mention_id,+ );+ _ = macro_notify_client+ .send_notification(notif)+ .await+ .inspect_err(|e| tracing::error!(error =? e, "coundn't send document mention notification"));+ }update_live_comment_state(&conn_gateway_client,- document_id,+ &res.document_id,AnnotationIncrementalUpdate::EditComment {- sender: user_id,- document_id,- response: &response,+ sender: &user_id,+ document_id: &res.document_id,+ response: &res,},).await;- Ok((StatusCode::OK, Json(response)).into_response())+ Ok((StatusCode::OK, Json(res)).into_response())}Err(e) => comment_error_response(e, "Error editing comment"),}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 5274cf531e..4ba6794adc 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,6 +6,8 @@ pub mod edit_anchor;pub mod edit_comment;pub mod get;+use std::fmt::Display;+use super::context::ApiContext;use axum::{Json, Router,@@ -14,8 +16,13 @@ use axum::{routing::{delete, get, patch, post},};use macro_db_client::annotations::CommentError;-use model::response::ErrorResponse;+use macro_user_id::user_id::MacroUserIdStr;+use model::{annotations::Comment, response::ErrorResponse};+use model_entity::EntityType;+use model_notifications::{DocumentMentionMetadata, NotificationQueueMessage};+use serde::Serialize;use tower::ServiceBuilder;+use utoipa::ToSchema;pub fn router(state: ApiContext) -> Router<ApiContext> {Router::new()@@ -115,3 +122,122 @@ pub fn comment_error_response(e: anyhow::Error, default_msg: &str) -> Result<Res}}}++#[derive(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(Serialize)]+#[serde(rename_all = "camelCase")]+struct Location {+ r#type: NotifLocationType,+ comment_id: Option<i64>,+ thread_id: i64,+ text: String,+}++// TODO: This is consumed in the frontend. It should be shared.+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct Metadata {+ mention_id: String,+ location: Location,+}++#[expect(clippy::too_many_arguments)]+fn build_mention_notif(+ notif_location_type: NotifLocationType,+ text: String,+ comment: Option<&Comment>,+ thread_id: i64,+ mentions: &[String],+ document_name: String,+ owner: MacroUserIdStr<'static>,+ file_type: Option<String>,+ sender_id: Option<MacroUserIdStr<'static>>,+ document_id: String,+ mention_id: &str,+) -> NotificationQueueMessage {+ let metadata = DocumentMentionMetadata {+ document_name,+ owner,+ file_type,+ metadata: Some(+ serde_json::to_value(Metadata {+ mention_id: mention_id.to_string(),+ location: Location {+ r#type: notif_location_type,+ comment_id: comment.map(|c| c.comment_id),+ thread_id,+ text,+ },+ })+ .expect("always works"),+ ),+ };++ NotificationQueueMessage {+ notification_entity: EntityType::Document.with_entity_string(document_id),+ notification_event: metadata.into(),+ sender_id,+ recipient_ids: Some(mentions.to_vec()),+ }+}++#[cfg(test)]+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 = Metadata {+ mention_id: "xxx".to_string(),+ location: Location {+ r#type: NotifLocationType::EditComment,+ thread_id: 42,+ comment_id: Some(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/document_storage_service/src/api/mentions/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mentions/mod.rsdeleted file mode 100644index c94f0f9f51..0000000000--- a/rust/cloud-storage/document_storage_service/src/api/mentions/mod.rs+++ /dev/null@@ -1,14 +0,0 @@-use super::context::ApiContext;-use axum::{Router, routing::post};--pub(in crate::api) mod upsert_user_mentions;--pub fn router(state: ApiContext) -> Router<ApiContext> {- Router::new().route(- "/:document_id",- post(upsert_user_mentions::handler).layer(axum::middleware::from_fn_with_state(- state,- macro_middleware::cloud_storage::document::ensure_document_exists::handler,- )),- )-}diff --git a/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs b/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rsdeleted file mode 100644index 2c875910e0..0000000000--- a/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs+++ /dev/null@@ -1,92 +0,0 @@-use std::sync::Arc;--use crate::model::request::documents::user_mentions::UpsertUserMentionsRequest;-use axum::{- Extension,- extract::{Json, Path, State},- http::StatusCode,- response::IntoResponse,-};-use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use model::user::UserContext;-use model::{- document::DocumentBasic,- response::{EmptyResponse, GenericErrorResponse, GenericResponse},-};-use model_entity::EntityType;-use model_notifications::{DocumentMentionMetadata, NotificationEvent, NotificationQueueMessage};-use models_permissions::share_permission::access_level::CommentAccessLevel;--#[derive(serde::Deserialize)]-pub struct Params {- pub document_id: String,-}--#[utoipa::path(- post,- operation_id="upsert_user_mentions",- path = "/mentions/{document_id}",- params(- ("document_id" = String, Path, description = "Document ID")- ),- responses(- (status = 200, body=EmptyResponse),- (status = 400, body=GenericErrorResponse),- (status = 401, body=GenericErrorResponse),- (status = 500, body=GenericErrorResponse),- )-)]-#[tracing::instrument(skip(macro_notify_client, user_context, req), fields(user_id=?user_context.user_id))]-pub async fn handler(- axxess: DocumentAccessExtractor<CommentAccessLevel>,- State(macro_notify_client): State<Arc<macro_notify::MacroNotify>>,- user_context: Extension<UserContext>,- document_context: Extension<DocumentBasic>,- Path(Params { document_id }): Path<Params>,- Json(req): Json<UpsertUserMentionsRequest>,-) -> impl IntoResponse {- if document_context.deleted_at.is_some() {- return GenericResponse::builder()- .message("cannot modify deleted document")- .is_error(true)- .send(StatusCode::BAD_REQUEST);- }-- if !req.mentions.is_empty() {- let metadata = DocumentMentionMetadata {- document_name: document_context.0.document_name,- owner: document_context.0.owner,- file_type: document_context.0.file_type,- metadata: req.metadata,- };-- let Ok(sender_id) =- MacroUserIdStr::parse_from_str(&user_context.user_id).map(CowLike::into_owned)- else {- return GenericResponse::builder()- .message("invalid macro user id")- .is_error(true)- .send(StatusCode::BAD_REQUEST);- };- let notification_queue_message = NotificationQueueMessage {- notification_entity: EntityType::Document.with_entity_string(document_id),- notification_event: NotificationEvent::DocumentMention(metadata),- sender_id: Some(sender_id),- recipient_ids: Some(req.mentions.clone()),- };-- if let Err(err) = macro_notify_client- .send_notification(notification_queue_message)- .await- {- tracing::error!(error=?err, "unable to send notification");- return GenericResponse::builder()- .message("unable to send notification")- .is_error(true)- .send(StatusCode::INTERNAL_SERVER_ERROR);- }- }-- (StatusCode::OK, Json(EmptyResponse::default())).into_response()-}diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex fc14725882..26565363eb 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -30,7 +30,6 @@ mod health;mod history;mod instructions;mod internal;-mod mentions;mod notification;mod pins;mod projects;@@ -143,7 +142,6 @@ fn api_router(state: ApiContext) -> Router {}),)),)- .nest("/mentions", mentions::router(state.clone())).nest("/annotations",annotations::router(state.clone()).layer(axum::middleware::from_fn(diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 65ebeee405..fd25573698 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -18,7 +18,7 @@ use crate::{validate_permissions_token::DocumentPermissionsTokenRequest,},},- health, history, instructions, mentions, pins,+ health, history, instructions, pins,projects::{self,delete_project::{ProjectDeleteResponse, ProjectDeleteResponseData},@@ -37,7 +37,6 @@ use crate::{preview::GetBatchPreviewRequest,save::{PreSaveDocumentRequest, SaveDocumentRequest},user_document_view_location::UpsertUserDocumentViewLocationRequest,- user_mentions::UpsertUserMentionsRequest,},pins::{AddPinRequest, PinRequest},},@@ -162,9 +161,6 @@ use utoipa::OpenApi;instructions::create_instructions::create_instructions_handler,instructions::get_instructions::get_instructions_handler,- // mentions- mentions::upsert_user_mentions::handler,-// user_document_view_locationuser_document_view_location::get_user_document_view_location::handler,user_document_view_location::upsert_user_document_view_location::handler,@@ -338,9 +334,6 @@ use utoipa::OpenApi;UpsertUserDocumentViewLocationRequest,UserDocumentViewLocationResponse,- // Mentions- UpsertUserMentionsRequest,-// AnnotationsAnnotationIncrementalUpdate,diff --git a/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rsindex ab31b4fdf1..2996d8fd72 100644--- a/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rs@@ -5,4 +5,3 @@ pub mod location;pub mod preview;pub mod save;pub mod user_document_view_location;-pub mod user_mentions;diff --git a/rust/cloud-storage/document_storage_service/src/model/request/documents/user_mentions.rs b/rust/cloud-storage/document_storage_service/src/model/request/documents/user_mentions.rsdeleted file mode 100644index 0b427becfa..0000000000--- a/rust/cloud-storage/document_storage_service/src/model/request/documents/user_mentions.rs+++ /dev/null@@ -1,11 +0,0 @@-use serde::Deserialize;-use utoipa::ToSchema;--// TODO: add support for mention location-#[derive(Debug, Deserialize, ToSchema)]-pub struct UpsertUserMentionsRequest {- /// List of user ids that are mentioned for this notification- pub mentions: Vec<String>,- /// Custom metadata that may be needed for the notification- pub metadata: Option<serde_json::Value>,-}diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rsindex 54a5393330..023a67a009 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs@@ -10,7 +10,7 @@ use email_utils::dedupe_emails;use macro_user_id::user_id::MacroUserIdStr;use model::contacts::ConnectionsMessage;use model_entity::EntityType;-use model_notifications::{NewEmailMetadata, NotificationEvent, NotificationQueueMessage};+use model_notifications::{NewEmailMetadata, NotificationQueueMessage};use models_email::db::address::EmailRecipientType;use models_email::email::service;use models_email::email::service::link;@@ -505,7 +505,7 @@ async fn send_notifications(let notification_queue_message = NotificationQueueMessage {notification_entity: EntityType::Email.with_entity_string(message.db_id.to_string()),- notification_event: NotificationEvent::NewEmail(notification_metadata),+ notification_event: notification_metadata.into(),sender_id,recipient_ids: Some(vec![link.macro_id.to_string()]),};diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex b18532dd0b..8b79de2070 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -70,6 +70,7 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./email_contact_search/.envsetup_macrodb:+ just macro_db_client/create_dbjust macro_db_client/migrate_dbjust document_cognition_service/prepare-testdiff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-4ffa9cfbefb9f75c3964db40d92d40085e0093d476d8b3d8aab8e81e575e1897.json b/rust/cloud-storage/macro_db_client/.sqlx/query-4ffa9cfbefb9f75c3964db40d92d40085e0093d476d8b3d8aab8e81e575e1897.jsonnew file mode 100644index 0000000000..1e340576fa--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-4ffa9cfbefb9f75c3964db40d92d40085e0093d476d8b3d8aab8e81e575e1897.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.owner, t.\"documentId\" as document_id, d.name as document_name, d.\"fileType\" as file_type, d.owner as document_owner\n FROM \"Comment\" c\n JOIN \"Thread\" t ON c.\"threadId\" = t.id\n JOIN \"Document\" d ON t.\"documentId\" = d.id\n WHERE c.id = $1 and c.\"deletedAt\" IS NULL AND t.\"deletedAt\" IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "document_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "document_name",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "file_type",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "document_owner",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ false+ ]+ },+ "hash": "4ffa9cfbefb9f75c3964db40d92d40085e0093d476d8b3d8aab8e81e575e1897"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-da15e17a523e1f2d4a3716f6d9c3f305cd7a9607209f65bb62acf6fce7e08284.json b/rust/cloud-storage/macro_db_client/.sqlx/query-da15e17a523e1f2d4a3716f6d9c3f305cd7a9607209f65bb62acf6fce7e08284.jsondeleted file mode 100644index eefd937514..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-da15e17a523e1f2d4a3716f6d9c3f305cd7a9607209f65bb62acf6fce7e08284.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT c.owner, t.\"documentId\" as document_id\n FROM \"Comment\" c\n JOIN \"Thread\" t ON c.\"threadId\" = t.id\n WHERE c.id = $1 and c.\"deletedAt\" IS NULL AND t.\"deletedAt\" IS NULL\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "document_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Int8"- ]- },- "nullable": [- false,- false- ]- },- "hash": "da15e17a523e1f2d4a3716f6d9c3f305cd7a9607209f65bb62acf6fce7e08284"-}diff --git a/rust/cloud-storage/macro_db_client/src/annotations/create_anchor.rs b/rust/cloud-storage/macro_db_client/src/annotations/create_anchor.rsindex 2581d97e2f..e359008622 100644--- a/rust/cloud-storage/macro_db_client/src/annotations/create_anchor.rs+++ b/rust/cloud-storage/macro_db_client/src/annotations/create_anchor.rs@@ -45,10 +45,10 @@ pub async fn create_comment_anchor(transaction: &mut Transaction<'_, Postgres>,owner: &str,document_id: &str,- req: AnchorRequest,+ req: &AnchorRequest,thread_id: i64,) -> Result<Anchor> {- match req {+ match &req {AnchorRequest::Pdf(anchor) => match anchor {PdfAnchorRequest::Attachment(attachment) => match attachment {UnthreadedPdfUuidRequest::Highlight(uuid) => {@@ -63,7 +63,7 @@ pub async fn create_comment_anchor(attach_anchor_to_thread(transaction,thread_id,- anchor.uuid,+ &anchor.uuid,AnchorTableName::PdfPlaceableCommentAnchor,).await?;@@ -81,7 +81,7 @@ pub async fn create_comment_anchor(attach_anchor_to_thread(transaction,thread_id,- anchor.uuid,+ &anchor.uuid,AnchorTableName::PdfHighlightAnchor,).await?;@@ -94,7 +94,7 @@ pub async fn create_comment_anchor(pub async fn attach_pdf_highlight_anchor(transaction: &mut Transaction<'_, Postgres>,thread_id: i64,- uuid: Uuid,+ uuid: &Uuid,) -> Result<PdfHighlightAnchor> {validate_thread_exists(transaction.as_mut(), thread_id).await?;@@ -154,7 +154,7 @@ pub async fn attach_pdf_highlight_anchor(async fn attach_anchor_to_thread(transaction: &mut Transaction<'_, Postgres>,thread_id: i64,- anchor_id: Uuid,+ anchor_id: &Uuid,anchor_table_name: AnchorTableName,) -> Result<()> {println!("{:?} {:?}", thread_id, anchor_id);@@ -183,9 +183,14 @@ pub async fn create_unthreaded_anchor(match req {CreateUnthreadedAnchorRequest::Pdf(anchor) => match anchor {CreateUnthreadedPdfAnchorRequest::Highlight(anchor) => {- let anchor =- create_pdf_highlight_anchor(&mut transaction, owner, document_id, None, anchor)- .await?;+ let anchor = create_pdf_highlight_anchor(+ &mut transaction,+ owner,+ document_id,+ None,+ &anchor,+ )+ .await?;transaction.commit().await?;Ok(CreateUnthreadedAnchorResponse {document_id: document_id.to_string(),@@ -201,7 +206,7 @@ async fn create_pdf_placeable_anchor(owner: &str,document_id: &str,thread_id: i64,- anchor: PdfPlaceableCommentAnchorRequest,+ anchor: &PdfPlaceableCommentAnchorRequest,) -> Result<PdfPlaceableCommentAnchor> {validate_thread_exists(transaction.as_mut(), thread_id).await?;@@ -259,7 +264,7 @@ async fn create_pdf_highlight_anchor(owner: &str,document_id: &str,thread_id: Option<i64>,- anchor: PdfHighlightAnchorRequest,+ anchor: &PdfHighlightAnchorRequest,) -> Result<PdfHighlightAnchor> {if let Some(thread_id) = thread_id {validate_thread_exists(transaction.as_mut(), thread_id).await?;@@ -393,9 +398,14 @@ mod create_comment_anchor_tests {should_lock_on_save: true,};- let result =- create_pdf_placeable_anchor(&mut transaction, owner, document_id, 1001, anchor_request)- .await;+ let result = create_pdf_placeable_anchor(+ &mut transaction,+ owner,+ document_id,+ 1001,+ &anchor_request,+ )+ .await;let anchor = result.unwrap();assert_eq!(anchor.owner, "macro|[email protected]");@@ -454,7 +464,7 @@ mod create_comment_anchor_tests {owner,document_id,Some(1001),- highlight_anchor_request,+ &highlight_anchor_request,).await;assert!(result.is_ok(), "Failed to create highlight anchor");@@ -488,7 +498,8 @@ mod create_comment_anchor_tests {));let result =- create_comment_anchor(&mut transaction, owner, document_id, anchor_request, 9849).await;+ create_comment_anchor(&mut transaction, owner, document_id, &anchor_request, 9849)+ .await;assert!(result.is_err(), "Should fail when thread IDs do not match");}@@ -525,7 +536,7 @@ mod create_comment_anchor_tests {&mut transaction,owner,document_id,- anchor_request,+ &anchor_request,deleted_thread_id,).await;@@ -562,7 +573,8 @@ mod create_comment_anchor_tests {}));let result =- create_comment_anchor(&mut transaction, owner, document_id, anchor_request, 9849).await;+ create_comment_anchor(&mut transaction, owner, document_id, &anchor_request, 9849)+ .await;assert!(result.is_err(),@@ -604,7 +616,7 @@ mod create_comment_anchor_tests {&mut transaction,owner,document_id,- anchor_request,+ &anchor_request,deleted_thread_id,).await;@@ -692,7 +704,7 @@ mod create_comment_anchor_tests {}let mut transaction = pool.begin().await.unwrap();- let result = attach_pdf_highlight_anchor(&mut transaction, 1005, uuid).await;+ let result = attach_pdf_highlight_anchor(&mut transaction, 1005, &uuid).await;transaction.commit().await.unwrap();let highlight_anchor = result.unwrap();@@ -751,7 +763,7 @@ mod create_comment_anchor_tests {}let mut transaction = pool.begin().await.unwrap();- let result = attach_pdf_highlight_anchor(&mut transaction, 1001, uuid).await;+ let result = attach_pdf_highlight_anchor(&mut transaction, 1001, &uuid).await;transaction.commit().await.unwrap();assert!(result.is_err());@@ -796,7 +808,7 @@ mod create_comment_anchor_tests {}let mut transaction = pool.begin().await.unwrap();- let result = attach_pdf_highlight_anchor(&mut transaction, 1001, Uuid::new_v4()).await;+ let result = attach_pdf_highlight_anchor(&mut transaction, 1001, &Uuid::new_v4()).await;transaction.commit().await.unwrap();// TODO: this should fail because the uuid is different?diff --git a/rust/cloud-storage/macro_db_client/src/annotations/create_comment.rs b/rust/cloud-storage/macro_db_client/src/annotations/create_comment.rsindex eaa3d0d0d9..2dd827cbed 100644--- a/rust/cloud-storage/macro_db_client/src/annotations/create_comment.rs+++ b/rust/cloud-storage/macro_db_client/src/annotations/create_comment.rs@@ -9,37 +9,29 @@ use sqlx::{Pool, Postgres};use crate::annotations::CommentError;use super::{create_anchor::create_comment_anchor, get::get_comment_thread};-fn map_value_to_option(maybe_value: Option<Value>) -> Option<Value> {- match maybe_value {- Some(value) => {- let empty = match &value {- Value::Null => true,- Value::String(s) => s.is_empty(),- Value::Array(arr) => arr.is_empty(),- Value::Object(map) => map.is_empty(),- _ => false,- };-- match empty {- true => None,- false => Some(value),- }- }- None => None,- }+ maybe_value.and_then(|value| {+ (match &value {+ Value::Null => false,+ Value::String(s) => !s.is_empty(),+ Value::Array(arr) => !arr.is_empty(),+ Value::Object(map) => !map.is_empty(),+ _ => true,+ })+ .then_some(value)+ })}pub async fn create_document_comment(db: &Pool<Postgres>,document_id: &str,owner: &str,- req: CreateCommentRequest,+ req: &CreateCommentRequest,) -> Result<CreateCommentResponse> {let mut transaction = db.begin().await?;let thread = match req.thread_id {- Some(thread_id) => match map_value_to_option(req.thread_metadata) {+ Some(thread_id) => match map_value_to_option(req.thread_metadata.clone()) {Some(thread_metadata) => sqlx::query_as!(Thread,r#"@@ -66,6 +58,7 @@ pub async fn create_document_comment(sqlx::Error::RowNotFound => anyhow::anyhow!(CommentError::ThreadNotFound),e => anyhow::anyhow!(e),})?,+ // TODO we should automatically be setting updatedAt etcNone => sqlx::query_as!(Thread,r#"@@ -119,7 +112,7 @@ pub async fn create_document_comment(};let mut anchor: Option<Anchor> = None;- if let Some(anchor_req) = req.anchor {+ if let Some(anchor_req) = &req.anchor {let res = create_comment_anchor(&mut transaction,owner,@@ -193,10 +186,11 @@ mod tests {thread_metadata: Some(json!({"test": "test"})),anchor: None,metadata: None,+ mentions: None,};let CreateCommentResponse { comment_thread, .. } =- create_document_comment(&pool, document_id, owner, req).await?;+ create_document_comment(&pool, document_id, owner, &req).await?;// Verify the thread and comment were createdassert_eq!(comment_thread.comments.len(), 1);@@ -235,10 +229,11 @@ mod tests {thread_metadata: None,anchor: None,metadata: None,+ mentions: None,};let CreateCommentResponse { comment_thread, .. } =- create_document_comment(&pool, document_id, owner, req).await?;+ create_document_comment(&pool, document_id, owner, &req).await?;// Verify the comment was added to the existing threadassert_eq!(comment_thread.thread.thread_id, 1001);diff --git a/rust/cloud-storage/macro_db_client/src/annotations/edit_comment.rs b/rust/cloud-storage/macro_db_client/src/annotations/edit_comment.rsindex 8559967632..7e793e20bd 100644--- a/rust/cloud-storage/macro_db_client/src/annotations/edit_comment.rs+++ b/rust/cloud-storage/macro_db_client/src/annotations/edit_comment.rs@@ -1,4 +1,5 @@use anyhow::{Result, bail};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::annotations::{Comment,edit::{EditCommentRequest, EditCommentResponse},@@ -11,18 +12,19 @@ pub async fn edit_document_comment(db: &Pool<Postgres>,comment_id: i64,user_id: &str,- req: EditCommentRequest,+ req: &EditCommentRequest,) -> Result<EditCommentResponse> {- let (comment_owner, document_id) = sqlx::query!(+ let (comment_owner, document_id, document_name, file_type, document_owner) = sqlx::query!(r#"- SELECT c.owner, t."documentId" as document_id+ SELECT c.owner, t."documentId" as document_id, d.name as document_name, d."fileType" as file_type, d.owner as document_ownerFROM "Comment" cJOIN "Thread" t ON c."threadId" = t.id+ JOIN "Document" d ON t."documentId" = d.idWHERE c.id = $1 and c."deletedAt" IS NULL AND t."deletedAt" IS NULL"#,comment_id)- .map(|row| (row.owner, row.document_id))+ .map(|row| (row.owner, row.document_id, row.document_name, row.file_type, row.document_owner)).fetch_one(db).await.map_err(|e| match e {@@ -61,6 +63,9 @@ pub async fn edit_document_comment(Ok(EditCommentResponse {document_id,+ document_name,+ file_type,+ document_owner: MacroUserIdStr::parse_from_str(&document_owner)?.into_owned(),comment,})}@@ -80,15 +85,26 @@ mod tests {let req = EditCommentRequest {text: Some("Updated comment text".to_string()),metadata: None,+ mentions: None,+ thread_id: 42,};- let result = edit_document_comment(&pool, comment_id, owner, req).await;+ let result = edit_document_comment(&pool, comment_id, owner, &req).await;let EditCommentResponse {comment,document_id,+ document_name,+ file_type,+ document_owner,} = result.unwrap();assert_eq!(comment.text, "Updated comment text");assert_eq!(document_id, "document-with-comments");+ assert_eq!(document_name, "Document With Comments");+ assert_eq!(file_type, Some("pdf".to_string()));+ assert_eq!(+ document_owner,+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+ );}#[sqlx::test(fixtures(@@ -99,11 +115,13 @@ mod tests {let comment_id = 6543024; // should not existlet owner = "macro|[email protected]";let req = EditCommentRequest {+ mentions: None,text: Some("Updated comment text".to_string()),metadata: None,+ thread_id: 42,};- let result = edit_document_comment(&pool, comment_id, owner, req).await;+ let result = edit_document_comment(&pool, comment_id, owner, &req).await;assert_eq!(result.unwrap_err().to_string(), "Comment not found");}@@ -115,11 +133,13 @@ mod tests {let comment_id = 10007;let document_owner = "macro|[email protected]";let req = EditCommentRequest {+ mentions: None,text: Some("Updated comment text".to_string()),metadata: None,+ thread_id: 42,};- let result = edit_document_comment(&pool, comment_id, document_owner, req).await;+ let result = edit_document_comment(&pool, comment_id, document_owner, &req).await;assert!(result.is_err());assert_eq!(result.unwrap_err().to_string(), "Invalid permissions");}@@ -132,11 +152,13 @@ mod tests {let comment_id = 10007;let owner = "macro|[email protected]";let req = EditCommentRequest {+ mentions: None,text: Some("Updated comment text".to_string()),metadata: None,+ thread_id: 42,};- let result = edit_document_comment(&pool, comment_id, owner, req).await;+ let result = edit_document_comment(&pool, comment_id, owner, &req).await;assert!(result.is_ok());assert_eq!(result.unwrap().comment.text, "Updated comment text");}@@ -149,11 +171,13 @@ mod tests {let comment_id = 10007;let non_owner = "macro|[email protected]";let req = EditCommentRequest {+ mentions: None,text: Some("Updated comment text".to_string()),metadata: None,+ thread_id: 42,};- let result = edit_document_comment(&pool, comment_id, non_owner, req).await;+ let result = edit_document_comment(&pool, comment_id, non_owner, &req).await;assert!(result.is_err());assert_eq!(result.unwrap_err().to_string(), "Invalid permissions");}diff --git a/rust/cloud-storage/macro_notify/src/lib.rs b/rust/cloud-storage/macro_notify/src/lib.rsindex 7c4ca2a433..3368996ac4 100644--- a/rust/cloud-storage/macro_notify/src/lib.rs+++ b/rust/cloud-storage/macro_notify/src/lib.rs@@ -4,7 +4,6 @@ mod message_attribute;use std::collections::HashMap;use std::fmt::Debug;-use anyhow::Context;use message_attribute::build_string_message_attribute;use model_notifications::{NotificationEventType, NotificationQueueMessage};@@ -55,12 +54,11 @@ impl MacroNotifyClient {let notification_id = macro_uuid::generate_uuid_v7();let NotificationMessageAttributes(message_attributes) =- NotificationMessageAttributes::try_from_message(+ NotificationMessageAttributes::from_message(¬ification_id.to_string(),&message,self.service.as_str(),- )- .context("Failed to build message attributes")?;+ );let body = serde_json::to_string(&message)?;enqueue::enqueue(@@ -80,11 +78,11 @@ struct NotificationMessageAttributes();impl NotificationMessageAttributes {- fn try_from_message(+ fn from_message(notification_id: &str,message: &NotificationQueueMessage,service: &str,- ) -> anyhow::Result<Self> {+ ) -> Self {const ATTRIBUTES: &[&str] = &["notification_id","notification_event_type",@@ -99,11 +97,9 @@ impl NotificationMessageAttributes {let attributes = ATTRIBUTES.iter().zip(values.iter())- .map(|(key, value)| {- build_string_message_attribute(value).map(|attr| ((*key).to_string(), attr))- })- .collect::<anyhow::Result<HashMap<_, _>>>()?;+ .map(|(key, value)| (key.to_string(), build_string_message_attribute(value)))+ .collect::<HashMap<_, _>>();- Ok(Self(attributes))+ Self(attributes)}}diff --git a/rust/cloud-storage/macro_notify/src/message_attribute.rs b/rust/cloud-storage/macro_notify/src/message_attribute.rsindex 5064b5402b..c76061ddcb 100644--- a/rust/cloud-storage/macro_notify/src/message_attribute.rs+++ b/rust/cloud-storage/macro_notify/src/message_attribute.rs@@ -1,11 +1,13 @@/// Builds a string message attribute+// TODO this would only fail from programmer error: when "data_type" not set.+// it should not return a result.#[tracing::instrument]pub(crate) fn build_string_message_attribute(attr: &str,-) -> anyhow::Result<aws_sdk_sqs::types::MessageAttributeValue> {- let result = aws_sdk_sqs::types::MessageAttributeValue::builder()+) -> aws_sdk_sqs::types::MessageAttributeValue {+ aws_sdk_sqs::types::MessageAttributeValue::builder().data_type("String").string_value(attr)- .build()?;- Ok(result)+ .build()+ .expect("only fails when `data_type` is not set. it is set above")}diff --git a/rust/cloud-storage/macro_share_permissions/src/notification.rs b/rust/cloud-storage/macro_share_permissions/src/notification.rsindex 9d14e840bc..8a8a9416dc 100644--- a/rust/cloud-storage/macro_share_permissions/src/notification.rs+++ b/rust/cloud-storage/macro_share_permissions/src/notification.rs@@ -49,10 +49,7 @@ pub fn create_notifications_from_item_shared(permission_level: permission_level.clone(),};- Some(build_message(- user_ids,- NotificationEvent::ItemSharedUser(metadata),- ))+ Some(build_message(user_ids, metadata.into()))} else {None};@@ -66,10 +63,7 @@ pub fn create_notifications_from_item_shared(shared_by: user_id.clone(),permission_level,};- Some(build_message(- user_ids,- NotificationEvent::ItemSharedOrganization(metadata),- ))+ Some(build_message(user_ids, metadata.into()))} else {None};diff --git a/rust/cloud-storage/model/src/annotations/create.rs b/rust/cloud-storage/model/src/annotations/create.rsindex 61f5abbf47..5a18accb40 100644--- a/rust/cloud-storage/model/src/annotations/create.rs+++ b/rust/cloud-storage/model/src/annotations/create.rs@@ -3,6 +3,8 @@ use serde_json::Value;use utoipa::ToSchema;use uuid::Uuid;+use crate::annotations::Mentions;+use super::{Anchor, CommentThread, HighlightType};#[derive(Deserialize, ToSchema)]@@ -14,6 +16,7 @@ pub struct CreateCommentRequest {pub anchor: Option<AnchorRequest>,pub text: String,pub metadata: Option<Value>,+ pub mentions: Option<Mentions>,}#[derive(Deserialize, PartialEq, Debug, Clone, ToSchema)]diff --git a/rust/cloud-storage/model/src/annotations/edit.rs b/rust/cloud-storage/model/src/annotations/edit.rsindex e950abb396..5eaa32918e 100644--- a/rust/cloud-storage/model/src/annotations/edit.rs+++ b/rust/cloud-storage/model/src/annotations/edit.rs@@ -1,8 +1,11 @@+use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};use serde_json::Value;use utoipa::ToSchema;use uuid::Uuid;+use crate::annotations::Mentions;+use super::{Anchor, Comment};#[derive(Deserialize, ToSchema)]@@ -10,6 +13,8 @@ use super::{Anchor, Comment};pub struct EditCommentRequest {pub text: Option<String>,pub metadata: Option<Value>,+ pub mentions: Option<Mentions>,+ pub thread_id: i64,}#[derive(Deserialize, ToSchema)]@@ -48,6 +53,10 @@ pub enum EditAnchorRequest {#[serde(rename_all = "camelCase")]pub struct EditCommentResponse {pub document_id: String,+ pub document_name: String,+ pub file_type: Option<String>,+ #[schema(value_type = String)]+ pub document_owner: MacroUserIdStr<'static>,#[serde(flatten)]pub comment: Comment,}diff --git a/rust/cloud-storage/model/src/annotations/mod.rs b/rust/cloud-storage/model/src/annotations/mod.rsindex 9d6220ed6a..3b6e606bb2 100644--- a/rust/cloud-storage/model/src/annotations/mod.rs+++ b/rust/cloud-storage/model/src/annotations/mod.rs@@ -225,3 +225,10 @@ pub enum AnnotationIncrementalUpdate<'a> {response: &'a DeleteUnthreadedAnchorResponse,},}++#[derive(Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct Mentions {+ pub users: Vec<String>,+ pub mention_id: String,+}diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rsindex 261cda33f4..e820d1b385 100644--- a/rust/cloud-storage/model_notifications/src/lib.rs+++ b/rust/cloud-storage/model_notifications/src/lib.rs@@ -20,6 +20,23 @@ 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))]@@ -59,6 +76,20 @@ pub enum NotificationEvent {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);