-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/poly 12 inbox query #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3b14921
feat: add linkedin
Taye-Staats 13ec9d7
WIP: messaging changes
Taye-Staats dfabcd9
Merge branch 'dev' of github.com:codebox-calpoly/PolyBuys into featur…
Taye-Staats c5b1e0b
feat(POLY-12): Inbox Query List All User Conversations (sub-issue #6)
Taye-Staats 0987206
chore: update generated files and configs
Taye-Staats d0ee133
feat: fixing pull request
Taye-Staats 1a4d6a1
fixed coderabbit issues
Taye-Staats File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| // Mock for Convex _generated/server module for testing | ||
|
|
||
| module.exports = { | ||
| query: (config) => { | ||
| return async (...args) => { | ||
| if (config.handler) { | ||
| return config.handler(...args); | ||
| } | ||
| return config; | ||
| }; | ||
| }, | ||
| mutation: (config) => { | ||
| return async (...args) => { | ||
| if (config.handler) { | ||
| return config.handler(...args); | ||
| } | ||
| return config; | ||
| }; | ||
| }, | ||
| action: (config) => { | ||
| return async (...args) => { | ||
| if (config.handler) { | ||
| return config.handler(...args); | ||
| } | ||
| return config; | ||
| }; | ||
| }, | ||
| internalQuery: (config) => config, | ||
| internalMutation: (config) => config, | ||
| internalAction: (config) => config, | ||
| httpAction: (config) => config, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import { listUserConversationsHandler } from '../messages'; | ||
|
|
||
| function buildCtx({ | ||
| userId, | ||
| participantRows, | ||
| docsById, | ||
| }: { | ||
| userId: string | null; | ||
| participantRows?: any[]; | ||
| docsById?: Record<string, any>; | ||
| }) { | ||
| return { | ||
| auth: { | ||
| getUserIdentity: async () => (userId ? { subject: userId } : null), | ||
| }, | ||
| db: { | ||
| get: async (id: string) => docsById?.[id] ?? null, | ||
| query: (table: any) => { | ||
| if (table === 'conversationParticipants') { | ||
| return { | ||
| withIndex: (_index: string, filterBuilder: any) => { | ||
| const state: { requestedUserId?: string; cursor?: number } = {}; | ||
| filterBuilder({ | ||
| eq: (_field: string, value: string) => { | ||
| state.requestedUserId = value; | ||
| return { | ||
| lt: (_ltField: string, ltValue: number) => { | ||
| state.cursor = ltValue; | ||
| return null; | ||
| }, | ||
| }; | ||
| }, | ||
| }); | ||
|
|
||
| const filtered = (participantRows ?? []) | ||
| .filter((row: any) => row.userId === state.requestedUserId) | ||
| .filter( | ||
| (row: any) => state.cursor === undefined || row.lastActivityAt < state.cursor | ||
| ) | ||
| .sort((a: any, b: any) => b.lastActivityAt - a.lastActivityAt); | ||
|
|
||
| return { | ||
| order: () => ({ | ||
| take: async (count: number) => filtered.slice(0, count), | ||
| }), | ||
| }; | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| throw new Error(`Unexpected query table: ${table}`); | ||
| }, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| describe('listUserConversations', () => { | ||
| it('returns empty list for user with no conversations', async () => { | ||
| const ctx = buildCtx({ | ||
| userId: 'user_123', | ||
| participantRows: [], | ||
| }); | ||
|
|
||
| const result = await listUserConversationsHandler(ctx, {}); | ||
|
|
||
| expect(result.conversations).toEqual([]); | ||
| expect(result.nextCursor).toBeNull(); | ||
| }); | ||
|
|
||
| it('returns only conversations for the authenticated user', async () => { | ||
| const userId = 'user_123'; | ||
| const ctx = buildCtx({ | ||
| userId, | ||
| participantRows: [ | ||
| { conversationId: 'conv_2', userId, lastActivityAt: 2000, unreadCount: 0 }, | ||
| { conversationId: 'conv_1', userId: 'other_user', lastActivityAt: 3000 }, | ||
| ], | ||
| docsById: { | ||
| conv_2: { | ||
| _id: 'conv_2', | ||
| buyerId: userId, | ||
| sellerId: 'user_999', | ||
| lastMessageAt: 2000, | ||
| createdAt: 1500, | ||
| listingId: 'listing_2', | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| const result = await listUserConversationsHandler(ctx, {}); | ||
|
|
||
| expect(result.conversations).toHaveLength(1); | ||
| expect(result.conversations[0].conversationId).toBe('conv_2'); | ||
| }); | ||
|
|
||
| it('throws Unauthorized when no auth identity', async () => { | ||
| const ctx = buildCtx({ | ||
| userId: null, | ||
| participantRows: [], | ||
| }); | ||
|
|
||
| await expect(listUserConversationsHandler(ctx, {})).rejects.toThrow('Unauthorized'); | ||
| }); | ||
|
|
||
| it('calculates unread count correctly', async () => { | ||
| const userId = 'user_123'; | ||
|
|
||
| const ctx = buildCtx({ | ||
| userId, | ||
| participantRows: [{ conversationId: 'conv_1', userId, lastActivityAt: 2000, unreadCount: 1 }], | ||
| docsById: { | ||
| conv_1: { | ||
| _id: 'conv_1', | ||
| buyerId: userId, | ||
| sellerId: 'user_999', | ||
| lastMessageAt: 2000, | ||
| lastMessageId: 'msg_1', | ||
| createdAt: 1500, | ||
| listingId: 'listing_2', | ||
| }, | ||
| msg_1: { | ||
| _id: 'msg_1', | ||
| senderId: 'user_999', | ||
| body: 'Hi there', | ||
| read: false, | ||
| createdAt: 2000, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| const result = await listUserConversationsHandler(ctx, {}); | ||
|
|
||
| expect(result.conversations[0].unreadCount).toBe(1); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| import { mutation, query } from './_generated/server'; | ||
| import { v } from 'convex/values'; | ||
|
|
||
| export const sendMessage = mutation({ | ||
| args: { | ||
| conversationId: v.id('conversations'), | ||
| body: v.string(), | ||
| }, | ||
| handler: async (ctx, args) => { | ||
| // Get the authenticated user's identity | ||
| const identity = await ctx.auth.getUserIdentity(); | ||
| if (!identity) { | ||
| throw new Error('Unauthorized'); | ||
| } | ||
| const senderId = identity.subject; | ||
|
|
||
| // Fetch the conversation | ||
| const conversation = await ctx.db.get(args.conversationId); | ||
| if (!conversation) { | ||
| throw new Error('Conversation not found'); | ||
| } | ||
|
|
||
| // Verify the authenticated user is a participant | ||
| if (!conversation.participantIds.includes(senderId)) { | ||
| throw new Error('User is not a participant in this conversation'); | ||
| } | ||
|
|
||
| const now = Date.now(); | ||
|
|
||
| // Insert the message | ||
| const messageId = await ctx.db.insert('messages', { | ||
| conversationId: args.conversationId, | ||
| senderId: senderId, | ||
| body: args.body, | ||
| type: 'text', | ||
| createdAt: now, | ||
| read: false, | ||
| }); | ||
|
|
||
| // Update the conversation's metadata | ||
| await ctx.db.patch(args.conversationId, { | ||
| lastMessageAt: now, | ||
| lastMessageId: messageId, | ||
| updatedAt: now, | ||
| }); | ||
|
|
||
| // Keep participant lookup rows in sync for server-side indexed conversation queries. | ||
| const participantRows = await ctx.db | ||
| .query('conversationParticipants') | ||
| .withIndex('by_conversationId', (q: any) => q.eq('conversationId', args.conversationId)) | ||
| .collect(); | ||
|
|
||
| const participantRowByUserId = new Map(participantRows.map((row: any) => [row.userId, row])); | ||
|
|
||
| for (const participantId of conversation.participantIds) { | ||
| const existingRow = participantRowByUserId.get(participantId); | ||
| if (existingRow) { | ||
| await ctx.db.patch(existingRow._id, { | ||
| lastActivityAt: now, | ||
| unreadCount: | ||
| participantId === senderId | ||
| ? (existingRow.unreadCount ?? 0) | ||
| : (existingRow.unreadCount ?? 0) + 1, | ||
| updatedAt: now, | ||
| }); | ||
| } else { | ||
| await ctx.db.insert('conversationParticipants', { | ||
| conversationId: args.conversationId, | ||
| userId: participantId, | ||
| lastActivityAt: now, | ||
| unreadCount: participantId === senderId ? 0 : 1, | ||
| createdAt: now, | ||
| updatedAt: now, | ||
| }); | ||
| } | ||
| } | ||
| }, | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }); | ||
|
|
||
| // Export handler separately for testing | ||
| export const listUserConversationsHandler = async (ctx: any, args: any) => { | ||
| // Step 1: Get userId from auth context | ||
| const identity = await ctx.auth.getUserIdentity(); | ||
| if (!identity) { | ||
| throw new Error('Unauthorized'); | ||
| } | ||
| const userId = identity.subject; | ||
|
|
||
| // Step 2: Query participant rows by indexed userId + activity timestamp. | ||
| const limit = args.limit || 20; | ||
| let cursorValue: number | undefined; | ||
| if (args.cursor) { | ||
| const parsedCursor = Number.parseInt(args.cursor, 10); | ||
| if (!Number.isNaN(parsedCursor)) { | ||
| cursorValue = parsedCursor; | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| const participantRows = await ctx.db | ||
| .query('conversationParticipants') | ||
| .withIndex('by_user_lastActivityAt', (q: any) => | ||
| cursorValue === undefined | ||
| ? q.eq('userId', userId) | ||
| : q.eq('userId', userId).lt('lastActivityAt', cursorValue) | ||
| ) | ||
| .order('desc') | ||
| .take(limit + 1); | ||
|
|
||
| // Step 3: For each conversation (up to limit): | ||
| const conversationList = []; | ||
| const displayedParticipantRows = participantRows.slice(0, limit); | ||
| const displayedConversations = ( | ||
| await Promise.all( | ||
| displayedParticipantRows.map(async (participantRow: any) => ({ | ||
| participantRow, | ||
| conversation: await ctx.db.get(participantRow.conversationId), | ||
| })) | ||
| ) | ||
| ).filter((row: any) => row.conversation !== null); | ||
|
|
||
| const lastMessageByConversationId = new Map(); | ||
| await Promise.all( | ||
| displayedConversations.map(async ({ conversation }: any) => { | ||
| if (!conversation.lastMessageId) { | ||
| return; | ||
| } | ||
| const lastMessage = await ctx.db.get(conversation.lastMessageId); | ||
| if (lastMessage) { | ||
| lastMessageByConversationId.set(conversation._id, lastMessage); | ||
| } | ||
| }) | ||
| ); | ||
|
|
||
| for (const { participantRow, conversation: conv } of displayedConversations) { | ||
| // - Calculate otherUserId | ||
| const otherUserId = userId === conv.buyerId ? conv.sellerId : conv.buyerId; | ||
|
|
||
| // - Get lastMessagePreview | ||
| const lastMsg = lastMessageByConversationId.get(conv._id); | ||
|
|
||
| // - Calculate unreadCount | ||
| const unreadCount = participantRow.unreadCount ?? 0; | ||
|
|
||
| // - Build response object | ||
| conversationList.push({ | ||
| conversationId: conv._id, | ||
| listingId: conv.listingId, | ||
| otherUserId, | ||
| lastMessageAt: conv.lastMessageAt, | ||
| lastMessagePreview: lastMsg?.body || 'No messages yet', | ||
| unreadCount, | ||
| createdAt: conv.createdAt, | ||
| }); | ||
| } | ||
|
|
||
| // Step 4: Determine nextCursor | ||
| let nextCursor = null; | ||
| if (participantRows.length > limit && displayedParticipantRows.length > 0) { | ||
| const lastParticipantRow = displayedParticipantRows[displayedParticipantRows.length - 1]; | ||
| nextCursor = String(lastParticipantRow.lastActivityAt); | ||
| } | ||
|
|
||
| return { | ||
| conversations: conversationList, | ||
| nextCursor, | ||
| }; | ||
| }; | ||
|
|
||
| export const listUserConversations = query({ | ||
| args: { | ||
| limit: v.optional(v.number()), | ||
| cursor: v.optional(v.string()), // lastMessageAt value from previous page | ||
| }, | ||
| handler: listUserConversationsHandler, | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.