mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 19:04:23 +00:00
refactor: extract core service domain layer to @shumai/core
This commit is contained in:
@@ -0,0 +1,365 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import { notificationService } from './notification'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
describe('NotificationService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('Create basic notification', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const p = await prisma.project.create({ data: { name: 'Project 1', teamId: tm.id } })
|
||||
|
||||
const svc = notificationService
|
||||
|
||||
await svc['createAsync']({
|
||||
type: NotificationType.comment_created,
|
||||
teamId: tm.id,
|
||||
projectId: p.id,
|
||||
creatorId: u1.id,
|
||||
})
|
||||
|
||||
const count = await prisma.notification.count()
|
||||
expect(count).toBe(1)
|
||||
|
||||
const n = await prisma.notification.findFirst()
|
||||
expect(n?.type).toBe(NotificationType.comment_created)
|
||||
expect(n?.teamId).toBe(tm.id)
|
||||
expect(n?.projectId).toBe(p.id)
|
||||
expect(n?.creatorId).toBe(u1.id)
|
||||
})
|
||||
|
||||
it('Create mention notification', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: 'u1-mention@example.com', password: 'p' },
|
||||
})
|
||||
const u2 = await prisma.user.create({
|
||||
data: { name: 'u2', email: 'u2-mention@example.com', password: 'p' },
|
||||
})
|
||||
const p = await prisma.project.create({ data: { name: 'Project 1', teamId: tm.id } })
|
||||
|
||||
const svc = notificationService
|
||||
const msg = `Hello <@${u2.id}>`
|
||||
|
||||
await svc['createAsync']({
|
||||
type: NotificationType.comment_created,
|
||||
teamId: tm.id,
|
||||
projectId: p.id,
|
||||
creatorId: u1.id,
|
||||
commentMessage: msg,
|
||||
})
|
||||
|
||||
const count = await prisma.notification.count()
|
||||
expect(count).toBe(2) // 1 comment, 1 mention
|
||||
|
||||
const mentions = await prisma.notification.findMany({
|
||||
where: { type: NotificationType.mention },
|
||||
})
|
||||
expect(mentions).toHaveLength(1)
|
||||
expect(mentions[0].userId).toBe(u2.id)
|
||||
})
|
||||
|
||||
it('Disabled project notification', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: 'u1-disabled@example.com', password: 'p' },
|
||||
})
|
||||
const p2 = await prisma.project.create({
|
||||
data: { name: 'Project 2', teamId: tm.id, enableNotification: false },
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
|
||||
await svc['createAsync']({
|
||||
type: NotificationType.comment_created,
|
||||
teamId: tm.id,
|
||||
projectId: p2.id,
|
||||
creatorId: u1.id,
|
||||
})
|
||||
|
||||
const count = await prisma.notification.count({ where: { projectId: p2.id } })
|
||||
expect(count).toBe(0)
|
||||
})
|
||||
|
||||
it('List all and Mark Read', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: 'u1-list@example.com', password: 'p' },
|
||||
})
|
||||
const member = await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
|
||||
})
|
||||
|
||||
// Create notifications directly
|
||||
// Using string IDs that are sorted correctly
|
||||
const n1 = await prisma.notification.create({
|
||||
data: {
|
||||
id: '001',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.comment_created,
|
||||
createdAt: new Date(Date.now() - 3000),
|
||||
},
|
||||
})
|
||||
const n2 = await prisma.notification.create({
|
||||
data: {
|
||||
id: '002',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.reply_created,
|
||||
createdAt: new Date(Date.now() - 2000),
|
||||
},
|
||||
})
|
||||
const n3 = await prisma.notification.create({
|
||||
data: {
|
||||
id: '003',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.mention,
|
||||
userId: u1.id,
|
||||
createdAt: new Date(Date.now() - 1000),
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
|
||||
// List all
|
||||
const resAll = await svc.list(tm.id, u1.id, {})
|
||||
expect(resAll.data).toHaveLength(3)
|
||||
// Ordered by desc createdAt
|
||||
expect(resAll.data[0].id).toBe(n3.id)
|
||||
expect(resAll.data[1].id).toBe(n2.id)
|
||||
expect(resAll.data[2].id).toBe(n1.id)
|
||||
expect(resAll.data[0].isRead).toBe(false)
|
||||
|
||||
// Mark Read
|
||||
await svc.markRead(tm.id, u1.id, n2.id)
|
||||
|
||||
const m = await prisma.teamMember.findUnique({
|
||||
where: { id: member.id },
|
||||
include: { lastReadNotification: true },
|
||||
})
|
||||
expect(m?.lastReadNotification?.id).toBe(n2.id)
|
||||
|
||||
// List again
|
||||
const resRead = await svc.list(tm.id, u1.id, {})
|
||||
expect(resRead.data[0].isRead).toBe(false) // n3
|
||||
expect(resRead.data[1].isRead).toBe(true) // n2
|
||||
expect(resRead.data[2].isRead).toBe(true) // n1 (read because n2 is newer)
|
||||
})
|
||||
|
||||
it('List Unread Only', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
id: '001',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.comment_created,
|
||||
createdAt: new Date(Date.now() - 3000),
|
||||
},
|
||||
})
|
||||
const n2 = await prisma.notification.create({
|
||||
data: {
|
||||
id: '002',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.reply_created,
|
||||
createdAt: new Date(Date.now() - 2000),
|
||||
},
|
||||
})
|
||||
const n3 = await prisma.notification.create({
|
||||
data: {
|
||||
id: '003',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.mention,
|
||||
userId: u1.id,
|
||||
createdAt: new Date(Date.now() - 1000),
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
await svc.markRead(tm.id, u1.id, n2.id)
|
||||
|
||||
const resUnread = await svc.list(tm.id, u1.id, { unreadOnly: true })
|
||||
expect(resUnread.data).toHaveLength(1)
|
||||
expect(resUnread.data[0].id).toBe(n3.id)
|
||||
})
|
||||
|
||||
it('Filter Self Notifications', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
|
||||
})
|
||||
|
||||
const nSelf = await prisma.notification.create({
|
||||
data: { id: '004', teamId: tm.id, type: NotificationType.comment_created, creatorId: u1.id },
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
const res = await svc.list(tm.id, u1.id, {})
|
||||
|
||||
const containsSelf = res.data.some((n) => n.id === nSelf.id)
|
||||
expect(containsSelf).toBe(false)
|
||||
})
|
||||
|
||||
it('Project Member scoping', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const p1 = await prisma.project.create({ data: { name: 'p1', teamId: tm.id } })
|
||||
const p2 = await prisma.project.create({ data: { name: 'p2', teamId: tm.id } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
|
||||
const member = await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'reviewer', scope: 'project' },
|
||||
})
|
||||
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: p1.id, teamMemberId: member.id, role: 'editor' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: { id: '001', teamId: tm.id, projectId: p1.id, type: NotificationType.comment_created },
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: { id: '002', teamId: tm.id, projectId: p2.id, type: NotificationType.comment_created },
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: { id: '003', teamId: tm.id, type: NotificationType.mention, userId: u1.id },
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
const res = await svc.list(tm.id, u1.id, {})
|
||||
|
||||
// Should see p1 and the targeted mention, but not p2
|
||||
expect(res.data).toHaveLength(2)
|
||||
const p2Notification = res.data.find((n) => n.id === '002')
|
||||
expect(p2Notification).toBeUndefined()
|
||||
})
|
||||
|
||||
it('Respects user metadata notification settings', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const u2 = await prisma.user.create({
|
||||
data: { name: 'u2', email: `u2-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
|
||||
})
|
||||
|
||||
// Create comments, replies, mentions, uploads, etc.
|
||||
const commentNotif = await prisma.notification.create({
|
||||
data: { id: '001', teamId: tm.id, type: NotificationType.comment_created },
|
||||
})
|
||||
const replyNotif = await prisma.notification.create({
|
||||
data: { id: '002', teamId: tm.id, type: NotificationType.reply_created, userId: u1.id },
|
||||
})
|
||||
const uploadNotifOther = await prisma.notification.create({
|
||||
data: {
|
||||
id: '003',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorId: u2.id,
|
||||
},
|
||||
})
|
||||
const uploadNotifSelf = await prisma.notification.create({
|
||||
data: {
|
||||
id: '004',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorId: u1.id,
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
|
||||
// Default settings: comments=true, replies=true, mentions=true, yourUploads=false, otherUploads=true
|
||||
const resDefault = await svc.list(tm.id, u1.id, {})
|
||||
expect(resDefault.data.some((n) => n.id === commentNotif.id)).toBe(true)
|
||||
expect(resDefault.data.some((n) => n.id === replyNotif.id)).toBe(true)
|
||||
expect(resDefault.data.some((n) => n.id === uploadNotifOther.id)).toBe(true)
|
||||
expect(resDefault.data.some((n) => n.id === uploadNotifSelf.id)).toBe(false) // yourUploads is false by default
|
||||
|
||||
// Disable comments and replies, but enable yourUploads
|
||||
await userMetadataService.upsertMetadata(u1.id, tm.id, 'notification_settings', {
|
||||
comments: false,
|
||||
replies: false,
|
||||
mentions: true,
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
})
|
||||
|
||||
const resCustom = await svc.list(tm.id, u1.id, {})
|
||||
expect(resCustom.data.some((n) => n.id === commentNotif.id)).toBe(false)
|
||||
expect(resCustom.data.some((n) => n.id === replyNotif.id)).toBe(false)
|
||||
expect(resCustom.data.some((n) => n.id === uploadNotifOther.id)).toBe(false) // otherUploads is now false
|
||||
expect(resCustom.data.some((n) => n.id === uploadNotifSelf.id)).toBe(true) // yourUploads is now true
|
||||
})
|
||||
|
||||
it('getUnreadCount retrieves correct count of unread notifications', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team 2' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'u3', email: `u3-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const u2 = await prisma.user.create({
|
||||
data: { name: 'u4', email: `u4-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const member = await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
|
||||
})
|
||||
|
||||
// No notifications initially
|
||||
let count = await notificationService.getUnreadCount(tm.id, u1.id)
|
||||
expect(count).toBe(0)
|
||||
|
||||
// Create unread notifications from other user
|
||||
const n1 = await prisma.notification.create({
|
||||
data: { id: '101', teamId: tm.id, type: NotificationType.comment_created, creatorId: u2.id },
|
||||
})
|
||||
const n2 = await prisma.notification.create({
|
||||
data: {
|
||||
id: '102',
|
||||
teamId: tm.id,
|
||||
type: NotificationType.reply_created,
|
||||
userId: u1.id,
|
||||
creatorId: u2.id,
|
||||
},
|
||||
})
|
||||
|
||||
count = await notificationService.getUnreadCount(tm.id, u1.id)
|
||||
expect(count).toBe(2)
|
||||
|
||||
// Mark up to n1 as read
|
||||
await prisma.teamMember.update({
|
||||
where: { id: member.id },
|
||||
data: { lastReadNotificationId: n1.id },
|
||||
})
|
||||
|
||||
count = await notificationService.getUnreadCount(tm.id, u1.id)
|
||||
expect(count).toBe(1) // n2 is still unread
|
||||
|
||||
// Mark all as read (up to n2)
|
||||
await prisma.teamMember.update({
|
||||
where: { id: member.id },
|
||||
data: { lastReadNotificationId: n2.id },
|
||||
})
|
||||
|
||||
count = await notificationService.getUnreadCount(tm.id, u1.id)
|
||||
expect(count).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,403 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import {
|
||||
NotificationInfo,
|
||||
CreateNotificationRequest,
|
||||
ListNotificationParams,
|
||||
NotificationSettings,
|
||||
} from '@shumai/dtos'
|
||||
import { paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
const mentionRegex = /<@([^>]+)>/g
|
||||
|
||||
export class NotificationService {
|
||||
async create(req: CreateNotificationRequest) {
|
||||
// Note: Do not await this, we fire and forget similarly to Go
|
||||
this.createAsync(req).catch((err) => {
|
||||
console.error('Failed to create notification asynchronously:', err)
|
||||
})
|
||||
}
|
||||
|
||||
private async createAsync(req: CreateNotificationRequest) {
|
||||
let projectId = req.projectId
|
||||
|
||||
// Resolve ProjectID from AssetID if missing
|
||||
if (!projectId && req.assetId) {
|
||||
const asset = await prisma.asset.findUnique({
|
||||
where: { id: req.assetId },
|
||||
include: { project: true },
|
||||
})
|
||||
if (asset?.projectId) {
|
||||
projectId = asset.projectId
|
||||
}
|
||||
}
|
||||
|
||||
// Check project notification settings
|
||||
if (projectId) {
|
||||
const project = await prisma.project.findUnique({
|
||||
where: { id: projectId },
|
||||
})
|
||||
if (project && !project.enableNotification) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to create a notification
|
||||
const create = async (t: NotificationType, targetUserId?: string) => {
|
||||
try {
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: t,
|
||||
teamId: req.teamId,
|
||||
projectId: projectId,
|
||||
creatorId: req.creatorId,
|
||||
assetId: req.assetId,
|
||||
taskId: req.taskId,
|
||||
userId: targetUserId,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Failed to save notification', { type: t, err })
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Create the primary notification
|
||||
await create(req.type, req.userId)
|
||||
|
||||
// 2. Handle Mentions for Comment/Reply types
|
||||
if (
|
||||
(req.type === NotificationType.comment_created ||
|
||||
req.type === NotificationType.reply_created) &&
|
||||
req.commentMessage
|
||||
) {
|
||||
const matches = [...req.commentMessage.matchAll(mentionRegex)]
|
||||
const mentionedIds = new Set<string>()
|
||||
|
||||
for (const match of matches) {
|
||||
if (match.length > 1) {
|
||||
const userId = match[1]
|
||||
if (mentionedIds.has(userId)) {
|
||||
continue
|
||||
}
|
||||
mentionedIds.add(userId)
|
||||
|
||||
// Don't notify self
|
||||
if (req.creatorId === userId) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Create mention notification
|
||||
await create(NotificationType.mention, userId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async getListWhere(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
teamMember: Prisma.TeamMemberGetPayload<{ include: { lastReadNotification: true } }>,
|
||||
unreadOnly: boolean,
|
||||
): Promise<Prisma.NotificationWhereInput> {
|
||||
// Permission Filtering based on Scope
|
||||
let projectFilter: string[] = []
|
||||
if (teamMember.scope === 'project') {
|
||||
const pms = await prisma.projectMember.findMany({
|
||||
where: { teamMemberId: teamMember.id },
|
||||
include: { project: true },
|
||||
})
|
||||
projectFilter = pms.filter((pm) => pm.project).map((pm) => pm.projectId)
|
||||
}
|
||||
|
||||
// Load notification settings
|
||||
const settingsMeta = await userMetadataService.getMetadata(
|
||||
userId,
|
||||
teamId,
|
||||
'notification_settings',
|
||||
)
|
||||
const settings: NotificationSettings = settingsMeta
|
||||
? (settingsMeta.value as NotificationSettings)
|
||||
: {
|
||||
comments: true,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
}
|
||||
|
||||
const typeConditions: Prisma.NotificationWhereInput[] = []
|
||||
|
||||
// 1. Comments
|
||||
if (settings.comments) {
|
||||
typeConditions.push({ type: NotificationType.comment_created, userId: null })
|
||||
}
|
||||
|
||||
// 2. Replies
|
||||
if (settings.replies) {
|
||||
typeConditions.push({ type: NotificationType.reply_created, userId: userId })
|
||||
typeConditions.push({ type: NotificationType.reply_created, userId: null })
|
||||
}
|
||||
|
||||
// 3. Mentions
|
||||
if (settings.mentions) {
|
||||
typeConditions.push({ type: NotificationType.mention, userId: userId })
|
||||
}
|
||||
|
||||
// 4. Uploads
|
||||
if (settings.yourUploads && settings.otherUploads) {
|
||||
typeConditions.push({ type: NotificationType.successful_file_uploaded })
|
||||
} else if (settings.yourUploads) {
|
||||
typeConditions.push({ type: NotificationType.successful_file_uploaded, creatorId: userId })
|
||||
} else if (settings.otherUploads) {
|
||||
typeConditions.push({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorId: { not: userId },
|
||||
})
|
||||
}
|
||||
|
||||
// 5. Status Updates
|
||||
if (settings.statusUpdates) {
|
||||
typeConditions.push({ type: NotificationType.metadata_field_updated_status })
|
||||
}
|
||||
|
||||
// 6. Always include team/project join notifications
|
||||
typeConditions.push({ type: NotificationType.new_user_join_team })
|
||||
typeConditions.push({ type: NotificationType.new_user_join_project })
|
||||
|
||||
const where: Prisma.NotificationWhereInput = {
|
||||
teamId,
|
||||
OR: typeConditions,
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
...(settings.yourUploads
|
||||
? [{ type: NotificationType.successful_file_uploaded, creatorId: userId }]
|
||||
: []),
|
||||
{ creatorId: null },
|
||||
{ creatorId: { not: userId } },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
if (teamMember.scope === 'project') {
|
||||
// Must be AND applied after the general rules
|
||||
const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : []
|
||||
where.AND = [
|
||||
...currentAnd,
|
||||
{
|
||||
OR: [
|
||||
{ type: NotificationType.mention }, // Always allow mentions (targeted)
|
||||
{ projectId: { in: projectFilter } }, // Only show notifications for projects user is member of
|
||||
],
|
||||
},
|
||||
] as Prisma.NotificationWhereInput[]
|
||||
}
|
||||
|
||||
if (unreadOnly && teamMember.lastReadNotification) {
|
||||
// We want notifications NEWER than the last read one.
|
||||
// String comparison works for ULID/KSUID.
|
||||
const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : []
|
||||
where.AND = [
|
||||
...currentAnd,
|
||||
{ id: { gt: teamMember.lastReadNotification.id } },
|
||||
] as Prisma.NotificationWhereInput[]
|
||||
}
|
||||
|
||||
return where
|
||||
}
|
||||
|
||||
async getUnreadCount(teamId: string, userId: string): Promise<number> {
|
||||
const teamMember = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
lastReadNotification: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!teamMember) {
|
||||
return 0
|
||||
}
|
||||
|
||||
const where = await this.getListWhere(teamId, userId, teamMember, true)
|
||||
return prisma.notification.count({ where })
|
||||
}
|
||||
|
||||
async list(
|
||||
teamId: string,
|
||||
userId: string,
|
||||
params: ListNotificationParams,
|
||||
): Promise<PaginatedData<NotificationInfo[]>> {
|
||||
// Get user's last read notification
|
||||
const teamMember = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
lastReadNotification: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!teamMember) {
|
||||
throw new Error('failed to get team member')
|
||||
}
|
||||
|
||||
const where = await this.getListWhere(teamId, userId, teamMember, !!params.unreadOnly)
|
||||
|
||||
return paginateQuery<NotificationInfo>(
|
||||
async (skip, take) => {
|
||||
const notifications = await prisma.notification.findMany({
|
||||
where,
|
||||
orderBy: { id: 'desc' },
|
||||
skip,
|
||||
take,
|
||||
include: {
|
||||
creator: true,
|
||||
team: true,
|
||||
project: true,
|
||||
asset: true,
|
||||
user: true,
|
||||
},
|
||||
})
|
||||
|
||||
return Promise.all(
|
||||
notifications.map(async (n) => {
|
||||
return this.toNotificationInfo(n, teamMember.lastReadNotification)
|
||||
}),
|
||||
)
|
||||
},
|
||||
null, // we don't need count
|
||||
{
|
||||
after: params.after,
|
||||
first: params.pageSize,
|
||||
includeCount: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
async markRead(teamId: string, userId: string, notificationId: string) {
|
||||
const teamMember = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
lastReadNotification: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!teamMember) {
|
||||
throw new Error('failed to get team member')
|
||||
}
|
||||
|
||||
const notificationExists = await prisma.notification.findUnique({
|
||||
where: { id: notificationId },
|
||||
})
|
||||
|
||||
if (!notificationExists) {
|
||||
throw new Error('notification not found')
|
||||
}
|
||||
|
||||
let shouldUpdate = true
|
||||
if (teamMember.lastReadNotification) {
|
||||
if (notificationId <= teamMember.lastReadNotification.id) {
|
||||
shouldUpdate = false
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldUpdate) {
|
||||
await prisma.teamMember.update({
|
||||
where: { id: teamMember.id },
|
||||
data: { lastReadNotificationId: notificationId },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private async toNotificationInfo(
|
||||
n: Prisma.NotificationGetPayload<{
|
||||
include: { creator: true; team: true; project: true; asset: true; user: true }
|
||||
}>,
|
||||
lastRead: Prisma.NotificationGetPayload<Record<string, never>> | null,
|
||||
): Promise<NotificationInfo> {
|
||||
const info: NotificationInfo = {
|
||||
id: n.id,
|
||||
type: n.type || undefined,
|
||||
createdAt: n.createdAt.toISOString(),
|
||||
isRead: lastRead !== null && n.id <= lastRead.id,
|
||||
}
|
||||
|
||||
if (n.creator) {
|
||||
info.creator = {
|
||||
id: n.creator.id,
|
||||
name: n.creator.name,
|
||||
}
|
||||
}
|
||||
|
||||
if (n.team) {
|
||||
info.team = {
|
||||
id: n.team.id,
|
||||
name: n.team.name,
|
||||
}
|
||||
}
|
||||
|
||||
if (n.project) {
|
||||
info.project = {
|
||||
id: n.project.id,
|
||||
name: n.project.name,
|
||||
}
|
||||
}
|
||||
|
||||
if (n.user) {
|
||||
info.user = {
|
||||
id: n.user.id,
|
||||
name: n.user.name,
|
||||
}
|
||||
}
|
||||
|
||||
if (n.asset) {
|
||||
const a = n.asset
|
||||
let previewUrl = ''
|
||||
|
||||
const media = a.media as PrismaJson.MediaInfo | null
|
||||
|
||||
if (media) {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
try {
|
||||
if (media.sprite) {
|
||||
previewUrl = await s3Service.presign(bucket, media.sprite.key, 'GET')
|
||||
} else if (media.thumbnail) {
|
||||
previewUrl = await s3Service.presign(bucket, media.thumbnail.key || '', 'GET')
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to generate presigned url for notification asset preview:', e)
|
||||
}
|
||||
}
|
||||
|
||||
info.asset = {
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
mediaType: a.mediaType || undefined,
|
||||
preview: previewUrl || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
}
|
||||
|
||||
export const notificationService = new NotificationService()
|
||||
Reference in New Issue
Block a user