diff --git a/apps/web/app/profile/[username]/PersonPageClient.tsx b/apps/web/app/profile/[username]/PersonPageClient.tsx index 688e3ae7..11c170e3 100644 --- a/apps/web/app/profile/[username]/PersonPageClient.tsx +++ b/apps/web/app/profile/[username]/PersonPageClient.tsx @@ -238,7 +238,9 @@ export default function PersonPage({ handle, profile, profileUnavailable }: Pers groupIdAliases.has(item.groupId) && item.type === 'expense' && item.status === 'posted' && - item.deletedAt === undefined, + item.deletedAt === undefined && + Number(item.occurredAt ?? 0) >= startAt && + Number(item.occurredAt ?? 0) < endAt, ) .sort((left, right) => Number(right.occurredAt ?? 0) - Number(left.occurredAt ?? 0)) : []; @@ -285,10 +287,22 @@ export default function PersonPage({ handle, profile, profileUnavailable }: Pers sharedGroups.length === 1 ? `/split/new?groupId=${encodeURIComponent(idOf(sharedGroups[0]!))}` : '/split/new'; + const balanceError = + rangeState === 'error' || + Boolean( + groupsError || + membersError || + transactionsError || + payersError || + participantsError || + settlementsError, + ); const balanceLabel = !balanceAvailable - ? sharedGroups.length - ? 'Loading balance…' - : 'No shared groups' + ? balanceError + ? 'Balance unavailable' + : sharedGroups.length + ? 'Loading balance…' + : 'No shared groups' : bilateralBalance === 0n ? 'You’re even' : bilateralBalance > 0n @@ -444,7 +458,10 @@ export default function PersonPage({ handle, profile, profileUnavailable }: Pers ) : null} - {person.id ? ( + {person.id && + (sharedGroups.length > 0 || + status === 'friends' || + Boolean(analytics?.conversationId)) ? ( sum + person.unreadCount, 0) ?? 0; - const grouped = groups ? Object.values(groups).reduce((sum, count) => sum + count, 0) : 0; - return direct + grouped; + const unread = useQuery(api.social.queries.peopleHubUnreadTotal, live ? {} : 'skip'); + return unread ?? 0; } diff --git a/convex/social/queries.ts b/convex/social/queries.ts index f9aacb3a..64e7984f 100644 --- a/convex/social/queries.ts +++ b/convex/social/queries.ts @@ -1,7 +1,9 @@ import { v } from 'convex/values'; import { query } from '../_generated/server'; import type { Doc, Id } from '../_generated/dataModel'; +import { getAnalyticsDayRange } from '../analytics/domain'; import { getOptionalUser } from '../shared/auth'; +import { loadReadPointers, type ChatScope } from '../shared/chat'; import { avatarUrlForUser } from '../avatars/helpers'; const safeProfile = (user: Doc<'users'>) => ({ @@ -348,12 +350,20 @@ export const peopleHub = query({ ...friendHigh.map((row) => String(row.userLowId)), ...conversationByPeer.keys(), ]); + const candidates = [...peerIds] + .sort( + (a, b) => + (conversationByPeer.get(b)?.updatedAt ?? 0) - + (conversationByPeer.get(a)?.updatedAt ?? 0) || + a.localeCompare(b), + ) + .slice(0, PEOPLE_HUB_LIMIT * 2); const now = Date.now(); const rows = await Promise.all( - [...peerIds].slice(0, PEOPLE_HUB_LIMIT * 2).map(async (rawId) => { + candidates.map(async (rawId) => { const userId = rawId as Id<'users'>; const conversation = conversationByPeer.get(rawId); - const [user, settings, presence, pointer] = await Promise.all([ + const [user, settings, presence] = await Promise.all([ ctx.db.get(userId), ctx.db .query('userSettings') @@ -363,30 +373,43 @@ export const peopleHub = query({ .query('presence') .withIndex('by_user', (q) => q.eq('userId', userId)) .unique(), - conversation - ? ctx.db - .query('chatReadPointers') - .withIndex('by_scope_user', (q) => - q - .eq('scopeType', 'direct') - .eq('scopeId', conversation._id) - .eq('userId', actor._id), - ) - .unique() - : Promise.resolve(null), ]); if (!user || user.deletedAt !== undefined) return null; let unreadCount = 0; + let unreadCapped = false; if (conversation) { - const lastReadAt = pointer?.lastReadAt ?? 0; - const recent = await ctx.db + const pointers = await loadReadPointers( + ctx, + { type: 'direct', id: conversation._id }, + [actor._id], + ); + const lastReadAt = pointers.get(actor._id) ?? 0; + const messageQuery = ctx.db .query('directMessages') .withIndex('by_conversation_createdAt', (q) => q.eq('conversationId', conversation._id).gt('createdAt', lastReadAt), ) - .order('desc') - .take(PEOPLE_HUB_UNREAD_CAP + 1); - unreadCount = recent.filter((message) => message.senderId !== actor._id).length; + .order('desc'); + let cursor: string | null = null; + let done = false; + while (!done && !unreadCapped) { + const page = await messageQuery.paginate({ numItems: 50, cursor }); + for (const message of page.page) { + const expiresAt = 'expiresAt' in message ? message.expiresAt : undefined; + if ( + message.senderId !== actor._id && + !(typeof expiresAt === 'number' && expiresAt <= now) + ) { + unreadCount += 1; + if (unreadCount > PEOPLE_HUB_UNREAD_CAP) { + unreadCapped = true; + break; + } + } + } + cursor = page.continueCursor; + done = page.isDone; + } } const showActive = settings?.showActive ?? true; const showLastSeen = settings?.showLastSeen ?? true; @@ -396,7 +419,7 @@ export const peopleHub = query({ conversationId: conversation?._id ?? null, lastMessageAt: conversation?.updatedAt ?? null, unreadCount: Math.min(unreadCount, PEOPLE_HUB_UNREAD_CAP), - unreadCapped: unreadCount > PEOPLE_HUB_UNREAD_CAP, + unreadCapped, active: showActive ? (presence?.activeUntil ?? 0) > now : null, lastSeenAt: showLastSeen ? (presence?.lastSeenAt ?? null) : null, }; @@ -413,27 +436,127 @@ export const peopleHub = query({ .slice(0, PEOPLE_HUB_LIMIT); }, }); +export const peopleHubUnreadTotal = query({ + args: {}, + handler: async (ctx) => { + const actor = await getOptionalUser(ctx); + if (!actor || actor.deletedAt !== undefined) return 0; + const [convLow, convHigh, memberships] = await Promise.all([ + ctx.db + .query('directConversations') + .withIndex('by_pair', (q) => q.eq('userLowId', actor._id)) + .collect(), + ctx.db + .query('directConversations') + .withIndex('by_high', (q) => q.eq('userHighId', actor._id)) + .collect(), + ctx.db + .query('groupMembers') + .withIndex('by_user', (q) => q.eq('userId', actor._id)) + .collect(), + ]); + const scopes: ChatScope[] = [ + ...[...convLow, ...convHigh].map((conversation) => ({ + type: 'direct' as const, + id: conversation._id, + })), + ...memberships.map((membership) => ({ type: 'group' as const, id: membership.groupId })), + ]; + const now = Date.now(); + const counts = await Promise.all( + scopes.map(async (scope) => { + const pointers = await loadReadPointers(ctx, scope, [actor._id]); + const lastReadAt = pointers.get(actor._id) ?? 0; + const messages = + scope.type === 'direct' + ? await ctx.db + .query('directMessages') + .withIndex('by_conversation_createdAt', (q) => + q.eq('conversationId', scope.id).gt('createdAt', lastReadAt), + ) + .collect() + : await ctx.db + .query('groupMessages') + .withIndex('by_group_createdAt', (q) => + q.eq('groupId', scope.id).gt('createdAt', lastReadAt), + ) + .collect(); + let unread = 0; + for (const message of messages) { + if ( + message.senderId !== actor._id && + !( + 'expiresAt' in message && + typeof message.expiresAt === 'number' && + message.expiresAt <= now + ) + ) { + unread += 1; + } + } + return unread; + }), + ); + return counts.reduce((sum, count) => sum + count, 0); + }, +}); const ACTIVITY_DAYS = 30; const DAY_MS = 24 * 60 * 60 * 1000; /** Messages read per conversation for analytics at most; older ones fall outside the window. */ const ACTIVITY_MESSAGE_LIMIT = 2000; +function activityDayStarts(now: number, timeZone: string | undefined, offsetMinutes: number) { + if (timeZone) { + const current = getAnalyticsDayRange(now, timeZone); + const starts = new Array(ACTIVITY_DAYS); + starts[ACTIVITY_DAYS - 1] = current.startAt; + for (let index = ACTIVITY_DAYS - 2; index >= 0; index -= 1) { + starts[index] = getAnalyticsDayRange(starts[index + 1]! - 1, timeZone).startAt; + } + return { starts, endAt: current.endAt }; + } + const offset = offsetMinutes * 60_000; + const todayStart = Math.floor((now - offset) / DAY_MS) * DAY_MS + offset; + return { + starts: Array.from( + { length: ACTIVITY_DAYS }, + (_, index) => todayStart - (ACTIVITY_DAYS - index - 1) * DAY_MS, + ), + endAt: todayStart + DAY_MS, + }; +} + +function activityDayIndex(starts: readonly number[], timestamp: number) { + let low = 0; + let high = starts.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (starts[middle]! <= timestamp) low = middle + 1; + else high = middle; + } + return low - 1; +} + /** * One person's analytics with you: direct messages per day for the last 30 days (sent and * received), message mix, your shared groups and friendship status. Only for people you * already share a conversation, friendship or group with. */ export const personAnalytics = query({ - args: { userId: v.id('users'), tzOffsetMinutes: v.optional(v.number()) }, - handler: async (ctx, { userId, tzOffsetMinutes = 0 }) => { + args: { + userId: v.id('users'), + tzOffsetMinutes: v.optional(v.number()), + timeZone: v.optional(v.string()), + }, + handler: async (ctx, { userId, tzOffsetMinutes = 0, timeZone }) => { const actor = await getOptionalUser(ctx); if (!actor || actor.deletedAt !== undefined || actor._id === userId) return null; const person = await ctx.db.get(userId); if (!person || person.deletedAt !== undefined) return null; const lowId = String(actor._id) < String(userId) ? actor._id : userId; const highId = lowId === actor._id ? userId : actor._id; - const [friendship, conversation, actorGroups, personGroups, presence, settings] = + const [friendship, conversation, actorGroups, personGroups, presence, settings, actorSettings] = await Promise.all([ ctx.db .query('friendships') @@ -459,6 +582,10 @@ export const personAnalytics = query({ .query('userSettings') .withIndex('by_user', (q) => q.eq('userId', userId)) .unique(), + ctx.db + .query('userSettings') + .withIndex('by_user', (q) => q.eq('userId', actor._id)) + .unique(), ]); const viewerGroupIds = new Set(actorGroups.map((row) => String(row.groupId))); const sharedGroupIds = personGroups @@ -467,26 +594,36 @@ export const personAnalytics = query({ if (!friendship && !conversation && sharedGroupIds.length === 0) return null; const now = Date.now(); - const offset = tzOffsetMinutes * 60_000; - const todayStart = Math.floor((now - offset) / DAY_MS) * DAY_MS + offset; - const windowStart = todayStart - (ACTIVITY_DAYS - 1) * DAY_MS; - const days = Array.from({ length: ACTIVITY_DAYS }, (_, index) => ({ - dayStart: windowStart + index * DAY_MS, - sent: 0, - received: 0, - })); + let validZone: string | undefined; + for (const candidate of [timeZone, actorSettings?.timezone, actor.timezone]) { + if (!candidate) continue; + try { + new Intl.DateTimeFormat('en-US', { timeZone: candidate }); + validZone = candidate; + break; + } catch { + continue; + } + } + const { starts, endAt } = activityDayStarts(now, validZone, tzOffsetMinutes); + const windowStart = starts[0]!; + const days = starts.map((dayStart) => ({ dayStart, sent: 0, received: 0 })); const mix = { text: 0, image: 0, audio: 0, ai: 0 }; let total = 0; + let totalMessagesCapped = false; if (conversation) { const recent = await ctx.db .query('directMessages') .withIndex('by_conversation_createdAt', (q) => - q.eq('conversationId', conversation._id).gte('createdAt', windowStart), + q.eq('conversationId', conversation._id).gte('createdAt', windowStart).lt('createdAt', endAt), ) - .take(ACTIVITY_MESSAGE_LIMIT); - for (const message of recent) { - const index = Math.floor((message.createdAt - windowStart) / DAY_MS); - const day = days[index]; + .order('desc') + .take(ACTIVITY_MESSAGE_LIMIT + 1); + totalMessagesCapped = recent.length > ACTIVITY_MESSAGE_LIMIT; + const includedMessages = Math.min(recent.length, ACTIVITY_MESSAGE_LIMIT); + for (let index = 0; index < includedMessages; index += 1) { + const message = recent[index]!; + const day = days[activityDayIndex(starts, message.createdAt)]; if (!day) continue; if (message.senderId === actor._id && message.kind !== 'ai') day.sent += 1; else day.received += 1; @@ -512,6 +649,7 @@ export const personAnalytics = query({ lastSeenAt: (settings?.showLastSeen ?? true) ? (presence?.lastSeenAt ?? null) : null, days, totalMessages: total, + totalMessagesCapped, mix, sharedGroups: groups.filter((group) => group !== null), }; diff --git a/packages/ui/src/finance/native/PeopleAnalyticsScreens.tsx b/packages/ui/src/finance/native/PeopleAnalyticsScreens.tsx index 934a4098..a216c644 100644 --- a/packages/ui/src/finance/native/PeopleAnalyticsScreens.tsx +++ b/packages/ui/src/finance/native/PeopleAnalyticsScreens.tsx @@ -360,7 +360,7 @@ export function PersonAnalyticsScreen(p: PersonAnalyticsScreenProps) { ['Text', d.mix.text], ['Photos', d.mix.image], ['Voice', d.mix.audio], - ['FinAI', d.mix.ai], + ['FinAI replies', d.mix.ai], ] as const ).filter(([, value]) => value > 0); return ( diff --git a/packages/ui/src/finance/web/PeopleAnalyticsScreens.tsx b/packages/ui/src/finance/web/PeopleAnalyticsScreens.tsx index 97fa9144..e34ae1a5 100644 --- a/packages/ui/src/finance/web/PeopleAnalyticsScreens.tsx +++ b/packages/ui/src/finance/web/PeopleAnalyticsScreens.tsx @@ -242,7 +242,7 @@ export function PersonAnalyticsScreen(p: PersonAnalyticsScreenProps) { ['text', 'Text', d.mix.text], ['image', 'Photos', d.mix.image], ['audio', 'Voice', d.mix.audio], - ['ai', 'FinAI', d.mix.ai], + ['ai', 'FinAI replies', d.mix.ai], ] as const ) .filter(([, , value]) => value > 0) diff --git a/tests/convex/people-hub.test.ts b/tests/convex/people-hub.test.ts index d38dd8e0..833e67c1 100644 --- a/tests/convex/people-hub.test.ts +++ b/tests/convex/people-hub.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest'; import { convexTest } from 'convex-test'; import { api } from '../../convex/_generated/api'; +import type { Id } from '../../convex/_generated/dataModel'; import schema from '../../convex/schema'; import { matchesHubSearch, @@ -31,18 +32,21 @@ async function seed() { createdAt: now - 1000, updatedAt: now, }); - for (const [senderId, text] of [ - [annaId, 'hi'], - [annaId, 'lunch?'], - [meId, 'sure'], + const messageIds: Id<'directMessages'>[] = []; + for (const [senderId, text, createdAt] of [ + [annaId, 'hi', now - 400], + [annaId, 'lunch?', now - 300], + [meId, 'sure', now - 200], ] as const) - await ctx.db.insert('directMessages', { - conversationId, - senderId, - kind: 'text', - text, - createdAt: now - 500, - }); + messageIds.push( + await ctx.db.insert('directMessages', { + conversationId, + senderId, + kind: 'text', + text, + createdAt, + }), + ); await ctx.db.insert('presence', { userId: annaId, activeUntil: now + 60_000, @@ -63,7 +67,7 @@ async function seed() { showActive: false, showLastSeen: false, }); - return { meId, annaId, benId, strangerId, conversationId }; + return { meId, annaId, benId, strangerId, conversationId, messageIds }; }); const me = t.withIdentity({ subject: `${ids.meId}|session` }); return { t, ids, me }; @@ -94,11 +98,141 @@ describe('people hub', () => { expect(await t.query(api.social.queries.peopleHub, {})).toEqual([]); }); + it('uses legacy direct-message receipts as read pointers', async () => { + const { t, ids, me } = await seed(); + await t.run(async (ctx) => { + const now = Date.now(); + await ctx.db.insert('directMessageReads', { + messageId: ids.messageIds[1]!, + conversationId: ids.conversationId, + userId: ids.meId, + seenAt: now, + }); + await ctx.db.insert('directMessages', { + conversationId: ids.conversationId, + senderId: ids.annaId, + kind: 'text', + text: 'new after read', + createdAt: now, + }); + }); + const anna = (await me.query(api.social.queries.peopleHub, {})).find( + (person) => person.id === ids.annaId, + ); + expect(anna).toMatchObject({ unreadCount: 1, unreadCapped: false }); + }); + + it('does not hide older unread messages behind newer sent messages', async () => { + const { t, ids, me } = await seed(); + await t.run(async (ctx) => { + const now = Date.now(); + for (let index = 0; index < 20; index += 1) + await ctx.db.insert('directMessages', { + conversationId: ids.conversationId, + senderId: ids.meId, + kind: 'text', + text: `sent ${index}`, + createdAt: now + index, + }); + }); + const anna = (await me.query(api.social.queries.peopleHub, {})).find( + (person) => person.id === ids.annaId, + ); + expect(anna).toMatchObject({ unreadCount: 2, unreadCapped: false }); + }); + + it('ranks conversations before limiting hub candidates', async () => { + const { t, ids, me } = await seed(); + await t.run(async (ctx) => { + const now = Date.now(); + for (let index = 0; index < 120; index += 1) { + const peerId = await ctx.db.insert('users', { + email: `peer${index}@example.com`, + displayName: `Peer ${index}`, + }); + const [userLowId, userHighId] = [ids.meId, peerId].sort(); + await ctx.db.insert('directConversations', { + userLowId: userLowId!, + userHighId: userHighId!, + createdAt: now - 100_000, + updatedAt: now - 100_000, + }); + } + const [low, high] = await Promise.all([ + ctx.db + .query('directConversations') + .withIndex('by_pair', (q) => q.eq('userLowId', ids.meId)) + .collect(), + ctx.db + .query('directConversations') + .withIndex('by_high', (q) => q.eq('userHighId', ids.meId)) + .collect(), + ]); + const ordered = [...low, ...high]; + for (const conversation of ordered) + await ctx.db.patch(conversation._id, { updatedAt: now - 100_000 }); + const latest = ordered.at(-1)!; + const latestPeer = + latest.userLowId === ids.meId ? latest.userHighId : latest.userLowId; + await ctx.db.patch(latestPeer, { displayName: 'Latest' }); + await ctx.db.patch(latest._id, { updatedAt: now - 1 }); + }); + const people = await me.query(api.social.queries.peopleHub, {}); + expect(people[0]?.displayName).toBe('Latest'); + }); + + it('returns an uncapped unread aggregate across DMs and groups', async () => { + const { t, ids, me } = await seed(); + await t.run(async (ctx) => { + const now = Date.now(); + for (let index = 0; index < 10; index += 1) + await ctx.db.insert('directMessages', { + conversationId: ids.conversationId, + senderId: ids.annaId, + kind: 'text', + text: `unread ${index}`, + createdAt: now + index, + }); + const groupId = await ctx.db.insert('groups', { + ownerId: ids.meId, + name: 'Team', + currency: 'USD', + createdAt: now, + updatedAt: now, + }); + await ctx.db.insert('groupMembers', { + groupId, + userId: ids.meId, + role: 'owner', + joinedAt: now, + }); + await ctx.db.insert('groupMembers', { + groupId, + userId: ids.annaId, + role: 'member', + joinedAt: now, + }); + for (let index = 0; index < 3; index += 1) + await ctx.db.insert('groupMessages', { + groupId, + senderId: ids.annaId, + kind: 'text', + text: `group unread ${index}`, + createdAt: now + index, + }); + }); + const anna = (await me.query(api.social.queries.peopleHub, {})).find( + (person) => person.id === ids.annaId, + ); + expect(anna).toMatchObject({ unreadCount: 9, unreadCapped: true }); + expect(await me.query(api.social.queries.peopleHubUnreadTotal, {})).toBe(15); + }); + it('builds 30-day person analytics only for connected people', async () => { const { ids, me } = await seed(); const anna = await me.query(api.social.queries.personAnalytics, { userId: ids.annaId }); expect(anna?.days).toHaveLength(30); - expect(anna?.totalMessages).toBe(3); + expect(anna?.totalMessagesCapped).toBe(false); const sent = anna!.days.reduce((sum, day) => sum + day.sent, 0); const received = anna!.days.reduce((sum, day) => sum + day.received, 0); expect([sent, received]).toEqual([1, 2]); @@ -108,6 +242,63 @@ describe('people hub', () => { ).toBeNull(); expect(await me.query(api.social.queries.personAnalytics, { userId: ids.meId })).toBeNull(); }); + + it('uses timezone calendar days rather than a fixed offset', async () => { + const { ids, me } = await seed(); + const zone = 'America/Los_Angeles'; + const analytics = await me.query(api.social.queries.personAnalytics, { + userId: ids.annaId, + timeZone: zone, + tzOffsetMinutes: 0, + }); + const formatter = new Intl.DateTimeFormat('en-US', { + timeZone: zone, + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + hourCycle: 'h23', + }); + const localDates = analytics!.days.map((day) => { + const parts = formatter.formatToParts(day.dayStart); + const value = (type: string) => parts.find((part) => part.type === type)?.value; + expect([value('hour'), value('minute')]).toEqual(['00', '00']); + return `${value('year')}-${value('month')}-${value('day')}`; + }); + expect(new Set(localDates).size).toBe(30); + for (let index = 1; index < analytics!.days.length; index += 1) { + const duration = analytics!.days[index]!.dayStart - analytics!.days[index - 1]!.dayStart; + expect(duration).toBeGreaterThanOrEqual(23 * 60 * 60_000); + expect(duration).toBeLessThanOrEqual(25 * 60 * 60_000); + } + }); + + it('keeps newest analytics messages and marks capped totals as lower bounds', async () => { + const { t, ids, me } = await seed(); + await t.run(async (ctx) => { + const now = Date.now(); + for (let index = 0; index < 2000; index += 1) + await ctx.db.insert('directMessages', { + conversationId: ids.conversationId, + senderId: ids.annaId, + kind: 'text', + text: `older ${index}`, + createdAt: now - 10 * 24 * 60 * 60_000 + index, + }); + await ctx.db.insert('directMessages', { + conversationId: ids.conversationId, + senderId: ids.annaId, + kind: 'text', + text: 'newest', + createdAt: now, + }); + }); + const anna = await me.query(api.social.queries.personAnalytics, { userId: ids.annaId }); + expect(anna?.totalMessages).toBe(2000); + expect(anna?.totalMessagesCapped).toBe(true); + expect(anna?.days[29]?.received).toBeGreaterThan(0); + }); }); describe('people hub model', () => {