mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(notification): add email notification infrastructure, smtp configuration, and periodic background delivery job (#431)
* feat(notification): add email notification support and dedicated workflow * feat(webui): add team email notification settings and test email dialog * refactor(webui): remove redundant card header from email notification settings * fix(notification): prevent sending notification emails to AI agents * feat(notification): display project, avatar, upload time and resolve mention names in notification emails * refactor(notification): remove uploadDebounceSeconds and naive workflow sleep * refactor(notification): remove temporal notification workflow and keep email infrastructure * fix(team): prevent leaking email notification settings and credentials in team settings * feat(notification): add periodic background job for batched email notification delivery * fix(notification): embed avatars and thumbnails as inline cid attachments
This commit is contained in:
@@ -0,0 +1,598 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import nodemailer from 'nodemailer'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import { emailService, DEFAULT_EMAIL_SETTINGS } from './email'
|
||||
|
||||
const mockSendMail = vi.fn().mockResolvedValue({ messageId: '<mock-msg-id@shumai.test>' })
|
||||
const mockVerify = vi.fn().mockResolvedValue(true)
|
||||
const mockClose = vi.fn()
|
||||
|
||||
vi.mock('nodemailer', () => ({
|
||||
default: {
|
||||
createTransport: vi.fn(() => ({
|
||||
sendMail: mockSendMail,
|
||||
verify: mockVerify,
|
||||
close: mockClose,
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('EmailService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSendMail.mockResolvedValue({ messageId: '<mock-msg-id@shumai.test>' })
|
||||
mockVerify.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
describe('getEmailSettings', () => {
|
||||
it('returns default settings when team settings are not set', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Team Alpha' } })
|
||||
const settings = await emailService.getEmailSettings(team.id)
|
||||
|
||||
expect(settings).toEqual(DEFAULT_EMAIL_SETTINGS)
|
||||
expect(settings.enabled).toBe(false)
|
||||
expect(settings.port).toBe(587)
|
||||
})
|
||||
|
||||
it('returns saved email settings when configured', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Team Beta',
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.beta.test',
|
||||
port: 465,
|
||||
username: 'beta_user',
|
||||
password: 'secret_password',
|
||||
smtps: true,
|
||||
ignoreCert: false,
|
||||
from: 'beta@shumai.test',
|
||||
replyTo: 'reply@shumai.test',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const settings = await emailService.getEmailSettings(team.id)
|
||||
expect(settings.enabled).toBe(true)
|
||||
expect(settings.host).toBe('smtp.beta.test')
|
||||
expect(settings.port).toBe(465)
|
||||
expect(settings.password).toBe('secret_password')
|
||||
})
|
||||
|
||||
it('throws 404 if team does not exist', async () => {
|
||||
await expect(emailService.getEmailSettings('non-existent-team-id')).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('updateEmailSettings', () => {
|
||||
it('updates email settings and saves to team.settings', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Team Gamma' } })
|
||||
|
||||
const updated = await emailService.updateEmailSettings(team.id, {
|
||||
enabled: true,
|
||||
host: 'smtp.gamma.test',
|
||||
port: 587,
|
||||
username: 'gamma',
|
||||
password: 'gamma_password',
|
||||
smtps: false,
|
||||
ignoreCert: true,
|
||||
from: 'gamma@shumai.test',
|
||||
replyTo: '',
|
||||
})
|
||||
|
||||
expect(updated.enabled).toBe(true)
|
||||
expect(updated.host).toBe('smtp.gamma.test')
|
||||
expect(updated.password).toBe('gamma_password')
|
||||
expect(updated.ignoreCert).toBe(true)
|
||||
|
||||
const reloaded = await prisma.team.findUnique({ where: { id: team.id } })
|
||||
expect(reloaded?.settings?.emailNotification?.host).toBe('smtp.gamma.test')
|
||||
})
|
||||
|
||||
it('preserves existing password if empty string or undefined is provided in update', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Team Delta',
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.delta.test',
|
||||
port: 587,
|
||||
username: 'delta',
|
||||
password: 'original_super_secret',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: 'delta@shumai.test',
|
||||
replyTo: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const updated = await emailService.updateEmailSettings(team.id, {
|
||||
enabled: true,
|
||||
host: 'smtp.delta-updated.test',
|
||||
port: 587,
|
||||
username: 'delta_new',
|
||||
password: '', // Empty password should retain existing
|
||||
smtps: true,
|
||||
ignoreCert: false,
|
||||
from: 'delta@shumai.test',
|
||||
})
|
||||
|
||||
expect(updated.host).toBe('smtp.delta-updated.test')
|
||||
expect(updated.password).toBe('original_super_secret')
|
||||
|
||||
const reloaded = await prisma.team.findUnique({ where: { id: team.id } })
|
||||
expect(reloaded?.settings?.emailNotification?.password).toBe('original_super_secret')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sendMail and verifySmtp', () => {
|
||||
it('verifySmtp calls transport.verify and closes transport', async () => {
|
||||
const config = { ...DEFAULT_EMAIL_SETTINGS, host: 'smtp.test' }
|
||||
const ok = await emailService.verifySmtp(config)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(mockVerify).toHaveBeenCalled()
|
||||
expect(mockClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sendMail sends email using nodemailer transport', async () => {
|
||||
const config = { ...DEFAULT_EMAIL_SETTINGS, host: 'smtp.test', from: 'shumai@test.com' }
|
||||
const res = await emailService.sendMail(config, {
|
||||
to: 'user@test.com',
|
||||
subject: 'Hello',
|
||||
html: '<p>Hello World</p>',
|
||||
text: 'Hello World',
|
||||
})
|
||||
|
||||
expect(res.messageId).toBe('<mock-msg-id@shumai.test>')
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
from: 'shumai@test.com',
|
||||
to: 'user@test.com',
|
||||
subject: 'Hello',
|
||||
}),
|
||||
)
|
||||
expect(mockClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sendMail forwards attachments to nodemailer transport', async () => {
|
||||
const config = { ...DEFAULT_EMAIL_SETTINGS, host: 'smtp.test', from: 'shumai@test.com' }
|
||||
const attachments = [
|
||||
{
|
||||
filename: 'avatar.png',
|
||||
content: Buffer.from('image-data'),
|
||||
cid: 'avatar-123@shumai.internal',
|
||||
contentType: 'image/png',
|
||||
},
|
||||
]
|
||||
await emailService.sendMail(config, {
|
||||
to: 'user@test.com',
|
||||
subject: 'Hello',
|
||||
html: '<img src="cid:avatar-123@shumai.internal" />',
|
||||
text: 'Hello',
|
||||
attachments,
|
||||
})
|
||||
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
attachments,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sendTestEmail', () => {
|
||||
it('sends test email to the current admin user', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Test Team',
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.test.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pw',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: 'sender@test.com',
|
||||
replyTo: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const currentUser = { id: 'admin1', email: 'admin@shumai.test', name: 'Admin' }
|
||||
const result = await emailService.sendTestEmail(team.id, currentUser)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.messageId).toBe('<mock-msg-id@shumai.test>')
|
||||
expect(mockVerify).toHaveBeenCalled()
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
to: 'admin@shumai.test',
|
||||
subject: 'Test email from Shumai',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('allows overriding settings with input draft', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team 2' } })
|
||||
const currentUser = { id: 'admin2', email: 'admin2@shumai.test', name: 'Admin 2' }
|
||||
|
||||
const result = await emailService.sendTestEmail(team.id, currentUser, {
|
||||
host: 'smtp.draft.com',
|
||||
from: 'draft@test.com',
|
||||
password: 'draft-password',
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(nodemailer.createTransport).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
host: 'smtp.draft.com',
|
||||
}),
|
||||
)
|
||||
expect(mockSendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
from: 'draft@test.com',
|
||||
to: 'admin2@shumai.test',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('throws error when host is missing', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Empty Host Team' } })
|
||||
const currentUser = { id: 'admin3', email: 'admin3@shumai.test', name: 'Admin 3' }
|
||||
|
||||
await expect(
|
||||
emailService.sendTestEmail(team.id, currentUser, { host: '', from: 'a@b.com' }),
|
||||
).rejects.toThrow('SMTP host is required')
|
||||
})
|
||||
|
||||
it('throws error when from address is missing', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Empty From Team' } })
|
||||
const currentUser = { id: 'admin4', email: 'admin4@shumai.test', name: 'Admin 4' }
|
||||
|
||||
await expect(
|
||||
emailService.sendTestEmail(team.id, currentUser, { host: 'smtp.test', from: '' }),
|
||||
).rejects.toThrow('From address is required')
|
||||
})
|
||||
|
||||
it('throws 400 when verify fails', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Failing Team' } })
|
||||
const currentUser = { id: 'admin5', email: 'admin5@shumai.test', name: 'Admin 5' }
|
||||
|
||||
mockVerify.mockRejectedValueOnce(new Error('Connection refused'))
|
||||
|
||||
await expect(
|
||||
emailService.sendTestEmail(team.id, currentUser, {
|
||||
host: 'smtp.down.com',
|
||||
from: 'admin@down.com',
|
||||
}),
|
||||
).rejects.toThrow('SMTP verification failed: Connection refused')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderNotificationEmail', () => {
|
||||
it('renders comment notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.comment_created,
|
||||
creatorName: 'Alice',
|
||||
teamName: 'Designers',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
assetId: 'asset-1',
|
||||
assetName: 'logo.png',
|
||||
commentMessage: 'Please make it bigger',
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Alice commented on "logo.png"')
|
||||
expect(rendered.html).toContain('Please make it bigger')
|
||||
expect(rendered.html).toContain('logo.png')
|
||||
expect(rendered.text).toContain('Alice commented on "logo.png"')
|
||||
})
|
||||
|
||||
it('renders mention notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.mention,
|
||||
creatorName: 'Bob',
|
||||
teamName: 'Developers',
|
||||
teamId: 'team-2',
|
||||
projectId: 'proj-2',
|
||||
assetId: 'asset-2',
|
||||
assetName: 'architecture.pdf',
|
||||
commentMessage: 'Take a look at this',
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Bob mentioned you')
|
||||
expect(rendered.html).toContain('Bob mentioned you')
|
||||
expect(rendered.html).toContain('Take a look at this')
|
||||
})
|
||||
|
||||
it('replaces user mentions with user names instead of user ID in comment emails', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.comment_created,
|
||||
creatorName: 'Bob',
|
||||
teamName: 'Designers',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
assetId: 'asset-1',
|
||||
assetName: 'logo.png',
|
||||
commentMessage: '<@kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy> nice',
|
||||
mentionedUserNames: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy: 'Alice',
|
||||
},
|
||||
})
|
||||
|
||||
expect(rendered.html).toContain('@Alice nice')
|
||||
expect(rendered.html).not.toContain('<@kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy>')
|
||||
expect(rendered.text).toContain('@Alice nice')
|
||||
expect(rendered.text).not.toContain('<@kUFrm1W4fKLCaLpw2XQP1OPe0gKACJpy>')
|
||||
})
|
||||
|
||||
it('renders asset upload notification with project name, creator profile image, and upload time', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Charlie',
|
||||
creatorAvatarUrl: 'https://example.com/avatar.jpg',
|
||||
teamName: 'Media',
|
||||
teamId: 'team-3',
|
||||
projectName: 'Marketing Campaign',
|
||||
projectId: 'proj-3',
|
||||
assetId: 'asset-3',
|
||||
assetName: 'video.mp4',
|
||||
fileCount: 1,
|
||||
uploadTime: new Date('2026-09-27T15:20:00Z'),
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Charlie uploaded "video.mp4" to Marketing Campaign')
|
||||
expect(rendered.html).toContain('Marketing Campaign')
|
||||
expect(rendered.html).toContain('https://example.com/avatar.jpg')
|
||||
expect(rendered.html).toContain('Sep 27, 2026')
|
||||
expect(rendered.text).toContain('Marketing Campaign')
|
||||
expect(rendered.text).toContain('Sep 27, 2026')
|
||||
})
|
||||
|
||||
it('renders single file uploaded notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Charlie',
|
||||
teamName: 'Media',
|
||||
teamId: 'team-3',
|
||||
projectId: 'proj-3',
|
||||
assetId: 'asset-3',
|
||||
assetName: 'video.mp4',
|
||||
fileCount: 1,
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Charlie uploaded "video.mp4"')
|
||||
expect(rendered.html).toContain('video.mp4')
|
||||
})
|
||||
|
||||
it('renders consolidated batch file upload notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Charlie',
|
||||
teamName: 'Media',
|
||||
teamId: 'team-3',
|
||||
projectName: 'Videos',
|
||||
projectId: 'proj-3',
|
||||
fileCount: 5,
|
||||
fileNames: ['img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png'],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Charlie uploaded 5 files to Videos')
|
||||
expect(rendered.html).toContain('img1.png')
|
||||
expect(rendered.html).toContain('and 2 more')
|
||||
})
|
||||
|
||||
it('renders user joined team notification', () => {
|
||||
const rendered = emailService.renderNotificationEmail({
|
||||
type: NotificationType.new_user_join_team,
|
||||
creatorName: 'Dave',
|
||||
teamName: 'Acme Corp',
|
||||
teamId: 'team-4',
|
||||
})
|
||||
|
||||
expect(rendered.subject).toContain('Dave joined Acme Corp')
|
||||
expect(rendered.html).toContain('Dave is now a member of Acme Corp')
|
||||
})
|
||||
|
||||
it('renders kanban task notifications', () => {
|
||||
const created = emailService.renderNotificationEmail({
|
||||
type: NotificationType.kanban_task_created,
|
||||
creatorName: 'Eva',
|
||||
teamName: 'Engineering',
|
||||
teamId: 'team-5',
|
||||
kanbanTaskId: 'kt-1',
|
||||
kanbanTaskTitle: 'Fix login bug',
|
||||
})
|
||||
expect(created.subject).toContain('Eva created task "Fix login bug"')
|
||||
|
||||
const assigned = emailService.renderNotificationEmail({
|
||||
type: NotificationType.kanban_task_assigned,
|
||||
creatorName: 'Frank',
|
||||
teamName: 'Engineering',
|
||||
teamId: 'team-5',
|
||||
kanbanTaskId: 'kt-2',
|
||||
kanbanTaskTitle: 'Design DB schema',
|
||||
})
|
||||
expect(assigned.subject).toContain('Frank assigned you to task "Design DB schema"')
|
||||
|
||||
const status = emailService.renderNotificationEmail({
|
||||
type: NotificationType.kanban_task_status_updated,
|
||||
creatorName: 'Grace',
|
||||
teamName: 'Engineering',
|
||||
teamId: 'team-5',
|
||||
kanbanTaskId: 'kt-3',
|
||||
kanbanTaskTitle: 'Refactor auth',
|
||||
commentMessage: 'Moved to In Progress',
|
||||
})
|
||||
expect(status.subject).toContain('Grace updated status of task "Refactor auth"')
|
||||
expect(status.html).toContain('Moved to In Progress')
|
||||
})
|
||||
})
|
||||
|
||||
describe('renderBatchedNotificationEmail', () => {
|
||||
it('renders single notification with specific subject and detailed row', () => {
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items: [
|
||||
{
|
||||
id: 'n-1',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
creatorAvatarUrl: 'https://example.com/alice.png',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: 'a-1',
|
||||
assetName: 'hero.png',
|
||||
assetThumbnailUrl: 'https://example.com/hero-thumb.png',
|
||||
createdAt: new Date('2026-09-27T10:00:00Z'),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] Alice uploaded "hero.png" to Website Redesign')
|
||||
expect(rendered.html).toContain('Alice')
|
||||
expect(rendered.html).toContain('Uploaded "hero.png" to Website Redesign')
|
||||
expect(rendered.html).toContain('https://example.com/hero-thumb.png')
|
||||
expect(rendered.html).toContain('https://example.com/alice.png')
|
||||
expect(rendered.text).toContain('Alice: Uploaded "hero.png" to Website Redesign')
|
||||
})
|
||||
|
||||
it('renders detailed rows with thumbnail when event count <= 3', () => {
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items: [
|
||||
{
|
||||
id: 'n-1',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: 'a-1',
|
||||
assetName: 'img1.png',
|
||||
assetThumbnailUrl: 'https://example.com/img1.png',
|
||||
createdAt: new Date('2026-09-27T10:00:00Z'),
|
||||
},
|
||||
{
|
||||
id: 'n-2',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: 'a-2',
|
||||
assetName: 'img2.png',
|
||||
createdAt: new Date('2026-09-27T10:01:00Z'),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] 2 new notifications in Designers')
|
||||
expect(rendered.html).toContain('img1.png')
|
||||
expect(rendered.html).toContain('img2.png')
|
||||
// img1 has thumbnail, img2 does not
|
||||
expect(rendered.html).toContain('https://example.com/img1.png')
|
||||
expect(rendered.text).toContain('img1.png')
|
||||
expect(rendered.text).toContain('img2.png')
|
||||
})
|
||||
|
||||
it('collapses events into one summary row and omits thumbnails when count > 3', () => {
|
||||
const items = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: `n-${i}`,
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'Alice',
|
||||
creatorAvatarUrl: 'https://example.com/alice.png',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Website Redesign',
|
||||
assetId: `a-${i}`,
|
||||
assetName: `photo_${i}.png`,
|
||||
assetThumbnailUrl: `https://example.com/thumb_${i}.png`,
|
||||
createdAt: new Date(`2026-09-27T10:0${i}:00Z`),
|
||||
}))
|
||||
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Bob',
|
||||
items,
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] 5 new notifications in Designers')
|
||||
expect(rendered.html).toContain('Alice uploaded 5 assets to Website Redesign')
|
||||
// Thumbnails must be omitted for collapsed groups (> 3)
|
||||
expect(rendered.html).not.toContain('https://example.com/thumb_')
|
||||
expect(rendered.text).toContain('Alice uploaded 5 assets to Website Redesign')
|
||||
})
|
||||
|
||||
it('batches mixed events in 1 email, collapsing groups > 3 while showing <= 3 in detail', () => {
|
||||
// 4 comments by UserB in Project Alpha (> 3)
|
||||
const commentItems = Array.from({ length: 4 }, (_, i) => ({
|
||||
id: `c-${i}`,
|
||||
type: NotificationType.comment_created,
|
||||
creatorName: 'UserB',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Project Alpha',
|
||||
assetId: `a-${i}`,
|
||||
assetName: `asset_${i}`,
|
||||
commentMessage: `Comment number ${i}`,
|
||||
createdAt: new Date(`2026-09-27T11:0${i}:00Z`),
|
||||
}))
|
||||
|
||||
// 1 upload by UserC in Project Alpha (<= 3)
|
||||
const uploadItem = {
|
||||
id: 'u-1',
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
creatorName: 'UserC',
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
projectId: 'p-1',
|
||||
projectName: 'Project Alpha',
|
||||
assetId: 'a-upload',
|
||||
assetName: 'diagram.png',
|
||||
assetThumbnailUrl: 'https://example.com/diagram.png',
|
||||
createdAt: new Date('2026-09-27T11:05:00Z'),
|
||||
}
|
||||
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Designers',
|
||||
recipientName: 'Alice',
|
||||
items: [...commentItems, uploadItem],
|
||||
})
|
||||
|
||||
expect(rendered.subject).toBe('[Shumai] 5 new notifications in Designers')
|
||||
// Collapsed comment group
|
||||
expect(rendered.html).toContain('UserB left 4 comments in Project Alpha')
|
||||
// Detailed upload item with thumbnail
|
||||
expect(rendered.html).toContain('UserC')
|
||||
expect(rendered.html).toContain('diagram.png')
|
||||
expect(rendered.html).toContain('https://example.com/diagram.png')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,919 @@
|
||||
import nodemailer, { type Transporter } from 'nodemailer'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { prisma, NotificationType } from '@shumai/db'
|
||||
import type { EmailNotificationSettings, UpdateEmailNotificationSettings } from '@shumai/dtos'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export interface EmailAttachment {
|
||||
filename: string
|
||||
content?: Buffer | string
|
||||
path?: string
|
||||
cid?: string
|
||||
contentType?: string
|
||||
}
|
||||
|
||||
export interface SendMailOptions {
|
||||
to: string
|
||||
subject: string
|
||||
html: string
|
||||
text: string
|
||||
attachments?: EmailAttachment[]
|
||||
}
|
||||
|
||||
export interface NotificationEmailContext {
|
||||
type: NotificationType
|
||||
creatorName: string
|
||||
creatorAvatarUrl?: string
|
||||
teamName: string
|
||||
teamId: string
|
||||
projectName?: string
|
||||
projectId?: string
|
||||
assetName?: string
|
||||
assetId?: string
|
||||
kanbanTaskTitle?: string
|
||||
kanbanTaskId?: string
|
||||
commentMessage?: string
|
||||
mentionedUserNames?: Record<string, string>
|
||||
fileCount?: number
|
||||
fileNames?: string[]
|
||||
uploadTime?: string | Date
|
||||
}
|
||||
|
||||
export interface BatchedNotificationItem {
|
||||
id: string
|
||||
type: NotificationType
|
||||
creatorName: string
|
||||
creatorAvatarUrl?: string
|
||||
teamId: string
|
||||
teamName: string
|
||||
projectId?: string
|
||||
projectName?: string
|
||||
assetId?: string
|
||||
assetName?: string
|
||||
assetThumbnailUrl?: string
|
||||
kanbanTaskId?: string
|
||||
kanbanTaskTitle?: string
|
||||
commentMessage?: string
|
||||
mentionedUserNames?: Record<string, string>
|
||||
uploadTime?: string | Date
|
||||
createdAt: Date
|
||||
}
|
||||
|
||||
export interface BatchedEmailContext {
|
||||
teamId: string
|
||||
teamName: string
|
||||
recipientName: string
|
||||
items: BatchedNotificationItem[]
|
||||
}
|
||||
|
||||
export function getNotificationBatchGroupKey(item: BatchedNotificationItem): string {
|
||||
return `${item.type}_${item.creatorName || ''}_${item.projectId || ''}_${item.teamId}`
|
||||
}
|
||||
|
||||
export const DEFAULT_EMAIL_SETTINGS: EmailNotificationSettings = {
|
||||
enabled: false,
|
||||
host: '',
|
||||
port: 587,
|
||||
username: '',
|
||||
password: '',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: '',
|
||||
replyTo: '',
|
||||
}
|
||||
|
||||
export class EmailService {
|
||||
getBaseUrl(): string {
|
||||
const raw =
|
||||
process.env.APP_URL ||
|
||||
process.env.BETTER_AUTH_URL ||
|
||||
`http://localhost:${process.env.SHUMAI_SERVER_PORT || '3000'}`
|
||||
return raw.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
createTransport(config: EmailNotificationSettings): Transporter {
|
||||
return nodemailer.createTransport({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: config.smtps,
|
||||
tls: {
|
||||
rejectUnauthorized: !config.ignoreCert,
|
||||
},
|
||||
auth:
|
||||
config.username || config.password
|
||||
? {
|
||||
user: config.username,
|
||||
pass: config.password,
|
||||
}
|
||||
: undefined,
|
||||
connectionTimeout: 10000,
|
||||
})
|
||||
}
|
||||
|
||||
async verifySmtp(config: EmailNotificationSettings): Promise<boolean> {
|
||||
const transport = this.createTransport(config)
|
||||
try {
|
||||
await transport.verify()
|
||||
return true
|
||||
} finally {
|
||||
transport.close()
|
||||
}
|
||||
}
|
||||
|
||||
async sendMail(
|
||||
config: EmailNotificationSettings,
|
||||
options: SendMailOptions,
|
||||
): Promise<{ messageId: string }> {
|
||||
const transport = this.createTransport(config)
|
||||
try {
|
||||
logger.debug(
|
||||
{ to: options.to, from: config.from, subject: options.subject },
|
||||
'Sending email via nodemailer',
|
||||
)
|
||||
const info = await transport.sendMail({
|
||||
from: config.from,
|
||||
replyTo: config.replyTo || config.from,
|
||||
to: options.to,
|
||||
subject: options.subject,
|
||||
html: options.html,
|
||||
text: options.text,
|
||||
attachments: options.attachments,
|
||||
})
|
||||
logger.info({ messageId: info.messageId, to: options.to }, 'Email sent successfully')
|
||||
return { messageId: info.messageId }
|
||||
} finally {
|
||||
transport.close()
|
||||
}
|
||||
}
|
||||
|
||||
async getEmailSettings(teamId: string): Promise<EmailNotificationSettings> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
if (!team) {
|
||||
throw new HTTPException(404, { message: 'Team not found' })
|
||||
}
|
||||
|
||||
const saved = team.settings?.emailNotification
|
||||
return {
|
||||
enabled: saved?.enabled ?? DEFAULT_EMAIL_SETTINGS.enabled,
|
||||
host: saved?.host ?? DEFAULT_EMAIL_SETTINGS.host,
|
||||
port: saved?.port ?? DEFAULT_EMAIL_SETTINGS.port,
|
||||
username: saved?.username ?? DEFAULT_EMAIL_SETTINGS.username,
|
||||
password: saved?.password ?? DEFAULT_EMAIL_SETTINGS.password,
|
||||
smtps: saved?.smtps ?? DEFAULT_EMAIL_SETTINGS.smtps,
|
||||
ignoreCert: saved?.ignoreCert ?? DEFAULT_EMAIL_SETTINGS.ignoreCert,
|
||||
from: saved?.from ?? DEFAULT_EMAIL_SETTINGS.from,
|
||||
replyTo: saved?.replyTo ?? DEFAULT_EMAIL_SETTINGS.replyTo,
|
||||
}
|
||||
}
|
||||
|
||||
async updateEmailSettings(
|
||||
teamId: string,
|
||||
input: UpdateEmailNotificationSettings,
|
||||
): Promise<EmailNotificationSettings> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
select: { settings: true },
|
||||
})
|
||||
if (!team) {
|
||||
throw new HTTPException(404, { message: 'Team not found' })
|
||||
}
|
||||
|
||||
const currentSettings = (team.settings || {}) as PrismaJson.Settings
|
||||
const existingEmailConfig = currentSettings.emailNotification
|
||||
|
||||
// If password is not provided or empty, retain existing password
|
||||
const password =
|
||||
input.password !== undefined && input.password !== ''
|
||||
? input.password
|
||||
: existingEmailConfig?.password || ''
|
||||
|
||||
const updatedEmailConfig: PrismaJson.EmailNotificationSettings = {
|
||||
enabled: input.enabled,
|
||||
host: input.host,
|
||||
port: input.port,
|
||||
username: input.username || '',
|
||||
password,
|
||||
smtps: input.smtps,
|
||||
ignoreCert: input.ignoreCert,
|
||||
from: input.from,
|
||||
replyTo: input.replyTo || '',
|
||||
}
|
||||
|
||||
currentSettings.emailNotification = updatedEmailConfig
|
||||
|
||||
const updatedTeam = await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: { settings: currentSettings as PrismaJson.Settings },
|
||||
select: { settings: true },
|
||||
})
|
||||
|
||||
return updatedTeam.settings?.emailNotification as EmailNotificationSettings
|
||||
}
|
||||
|
||||
async sendTestEmail(
|
||||
teamId: string,
|
||||
currentUser: { id: string; email: string; name: string },
|
||||
overrides?: Partial<EmailNotificationSettings>,
|
||||
): Promise<{ success: boolean; messageId: string }> {
|
||||
const saved = await this.getEmailSettings(teamId)
|
||||
const effectiveConfig: EmailNotificationSettings = {
|
||||
...saved,
|
||||
...overrides,
|
||||
// If override password is empty, fall back to saved
|
||||
password:
|
||||
overrides?.password !== undefined && overrides.password !== ''
|
||||
? overrides.password
|
||||
: saved.password,
|
||||
}
|
||||
|
||||
if (!effectiveConfig.host) {
|
||||
throw new HTTPException(400, { message: 'SMTP host is required' })
|
||||
}
|
||||
if (!effectiveConfig.from) {
|
||||
throw new HTTPException(400, { message: 'From address is required' })
|
||||
}
|
||||
|
||||
try {
|
||||
await this.verifySmtp(effectiveConfig)
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
logger.warn({ teamId, err: errMsg }, 'SMTP verification failed during test email')
|
||||
throw new HTTPException(400, { message: `SMTP verification failed: ${errMsg}` })
|
||||
}
|
||||
|
||||
const baseUrl = this.getBaseUrl()
|
||||
const subject = 'Test email from Shumai'
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Test Email from Shumai</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f9fafb; margin: 0; padding: 24px; color: #111827; }
|
||||
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; border: 1px solid #e5e7eb; padding: 32px; }
|
||||
.header { font-size: 20px; font-weight: 700; margin-bottom: 16px; color: #111827; }
|
||||
.content { font-size: 14px; line-height: 1.6; color: #4b5563; margin-bottom: 24px; }
|
||||
.badge { display: inline-block; background-color: #ecfdf5; color: #065f46; font-size: 12px; font-weight: 600; padding: 4px 10px; border-radius: 9999px; margin-bottom: 16px; }
|
||||
.footer { font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 16px; margin-top: 24px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">Shumai Notification System</div>
|
||||
<div class="badge">SMTP Verified</div>
|
||||
<div class="content">
|
||||
<p>Hello ${escapeHtml(currentUser.name || 'Admin')},</p>
|
||||
<p>This is a test email confirming that your SMTP server settings are correctly configured for team notifications in Shumai.</p>
|
||||
<p>Notifications for new comments, mentions, uploads, and Kanban tasks will now be delivered via this email service.</p>
|
||||
</div>
|
||||
<div class="footer">
|
||||
Sent from Shumai at <a href="${baseUrl}" style="color: #6366f1; text-decoration: none;">${baseUrl}</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`.trim()
|
||||
|
||||
const text = `
|
||||
Shumai Notification System - Test Email
|
||||
|
||||
Hello ${currentUser.name || 'Admin'},
|
||||
|
||||
This is a test email confirming that your SMTP server settings are correctly configured for team notifications in Shumai.
|
||||
|
||||
Sent from Shumai at ${baseUrl}
|
||||
`.trim()
|
||||
|
||||
try {
|
||||
const res = await this.sendMail(effectiveConfig, {
|
||||
to: currentUser.email,
|
||||
subject,
|
||||
html,
|
||||
text,
|
||||
})
|
||||
return { success: true, messageId: res.messageId }
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : String(err)
|
||||
logger.error({ teamId, err: errMsg }, 'Failed to send test email')
|
||||
throw new HTTPException(400, { message: `Failed to send test email: ${errMsg}` })
|
||||
}
|
||||
}
|
||||
|
||||
renderNotificationEmail(ctx: NotificationEmailContext): {
|
||||
subject: string
|
||||
html: string
|
||||
text: string
|
||||
} {
|
||||
const baseUrl = this.getBaseUrl()
|
||||
let actionUrl = baseUrl
|
||||
let actionText = 'View in Shumai'
|
||||
|
||||
if (ctx.teamId) {
|
||||
if (ctx.projectId && ctx.assetId) {
|
||||
actionUrl = `${baseUrl}/teams/${ctx.teamId}/projects/${ctx.projectId}?assetId=${ctx.assetId}`
|
||||
actionText = 'View Asset'
|
||||
} else if (ctx.projectId) {
|
||||
actionUrl = `${baseUrl}/teams/${ctx.teamId}/projects/${ctx.projectId}`
|
||||
actionText = 'View Project'
|
||||
} else if (ctx.kanbanTaskId) {
|
||||
actionUrl = `${baseUrl}/teams/${ctx.teamId}?kanbanTaskId=${ctx.kanbanTaskId}`
|
||||
actionText = 'View Task'
|
||||
} else {
|
||||
actionUrl = `${baseUrl}/teams/${ctx.teamId}`
|
||||
actionText = 'Open Team'
|
||||
}
|
||||
}
|
||||
|
||||
let subject = '[Shumai] Notification'
|
||||
let headline = 'You have a new notification'
|
||||
let detail = ''
|
||||
|
||||
const actor = ctx.creatorName || 'Someone'
|
||||
const actorInitial = (actor.trim()[0] || 'U').toUpperCase()
|
||||
const formattedUploadTime = formatUploadTime(ctx.uploadTime)
|
||||
|
||||
let commentMessage = ctx.commentMessage
|
||||
if (commentMessage) {
|
||||
commentMessage = commentMessage.replace(/<@([^>]+)>/g, (match, uid) => {
|
||||
const name = ctx.mentionedUserNames?.[uid]
|
||||
return name ? `@${name}` : `@${uid}`
|
||||
})
|
||||
}
|
||||
|
||||
switch (ctx.type) {
|
||||
case NotificationType.comment_created: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'an asset'
|
||||
subject = `[Shumai] ${actor} commented on ${target}`
|
||||
headline = `${actor} left a comment`
|
||||
detail = commentMessage ? `"${commentMessage}"` : `New comment on ${target}`
|
||||
break
|
||||
}
|
||||
case NotificationType.reply_created: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'an asset'
|
||||
subject = `[Shumai] ${actor} replied to your comment on ${target}`
|
||||
headline = `${actor} replied to your comment`
|
||||
detail = commentMessage ? `"${commentMessage}"` : `Reply on ${target}`
|
||||
break
|
||||
}
|
||||
case NotificationType.mention: {
|
||||
subject = `[Shumai] ${actor} mentioned you`
|
||||
headline = `${actor} mentioned you`
|
||||
detail = commentMessage ? `"${commentMessage}"` : 'You were mentioned in a comment'
|
||||
break
|
||||
}
|
||||
case NotificationType.successful_file_uploaded: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'a file'
|
||||
const projectInfo = ctx.projectName ? ` to ${ctx.projectName}` : ''
|
||||
if (ctx.fileCount && ctx.fileCount > 1) {
|
||||
subject = `[Shumai] ${actor} uploaded ${ctx.fileCount} files${projectInfo}`
|
||||
headline = `${actor} uploaded ${ctx.fileCount} new files${projectInfo}`
|
||||
let filesSummary: string
|
||||
if (ctx.fileNames && ctx.fileNames.length > 0) {
|
||||
const previewList = ctx.fileNames.slice(0, 3).join(', ')
|
||||
const remaining = ctx.fileNames.length - 3
|
||||
filesSummary = remaining > 0 ? `${previewList}, and ${remaining} more` : previewList
|
||||
} else {
|
||||
filesSummary = `${ctx.fileCount} new files were uploaded`
|
||||
}
|
||||
const details: string[] = []
|
||||
if (ctx.projectName) details.push(`Project: ${ctx.projectName}`)
|
||||
if (formattedUploadTime) details.push(`Uploaded at: ${formattedUploadTime}`)
|
||||
details.push(`Files: ${filesSummary}`)
|
||||
detail = details.join('\n')
|
||||
} else {
|
||||
subject = `[Shumai] ${actor} uploaded ${target}${projectInfo}`
|
||||
headline = `${actor} uploaded ${target}${projectInfo}`
|
||||
const details: string[] = []
|
||||
if (ctx.assetName) details.push(`Asset: ${ctx.assetName}`)
|
||||
if (ctx.projectName) details.push(`Project: ${ctx.projectName}`)
|
||||
if (formattedUploadTime) details.push(`Uploaded at: ${formattedUploadTime}`)
|
||||
detail = details.join('\n')
|
||||
}
|
||||
break
|
||||
}
|
||||
case NotificationType.metadata_field_updated_status: {
|
||||
const target = ctx.assetName ? `"${ctx.assetName}"` : 'an asset'
|
||||
subject = `[Shumai] ${actor} updated status of ${target}`
|
||||
headline = `${actor} updated status of ${target}`
|
||||
detail = `Status update on ${target}`
|
||||
break
|
||||
}
|
||||
case NotificationType.new_user_join_team: {
|
||||
subject = `[Shumai] ${actor} joined ${ctx.teamName}`
|
||||
headline = `${actor} joined the team`
|
||||
detail = `${actor} is now a member of ${ctx.teamName}`
|
||||
break
|
||||
}
|
||||
case NotificationType.new_user_join_project: {
|
||||
const project = ctx.projectName || 'a project'
|
||||
subject = `[Shumai] ${actor} joined project ${project}`
|
||||
headline = `${actor} joined project ${project}`
|
||||
detail = `${actor} is now a member of ${project}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_created: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} created task ${task}`
|
||||
headline = `${actor} created task ${task}`
|
||||
detail = commentMessage || `Task ${task} was created`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_assigned: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} assigned you to task ${task}`
|
||||
headline = `${actor} assigned you to task ${task}`
|
||||
detail = `You have been assigned to ${task}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_status_updated: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} updated status of task ${task}`
|
||||
headline = `${actor} updated status of ${task}`
|
||||
detail = commentMessage || `Status changed for ${task}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_updated: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} updated task ${task}`
|
||||
headline = `${actor} updated task ${task}`
|
||||
detail = commentMessage || `Task ${task} was updated`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_deleted: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} deleted task ${task}`
|
||||
headline = `${actor} deleted task ${task}`
|
||||
detail = `Task ${task} was deleted`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_comment_created: {
|
||||
const task = ctx.kanbanTaskTitle ? `"${ctx.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} commented on task ${task}`
|
||||
headline = `${actor} commented on task ${task}`
|
||||
detail = commentMessage ? `"${commentMessage}"` : `New comment on ${task}`
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const avatarHtml = ctx.creatorAvatarUrl
|
||||
? `<img src="${escapeHtml(ctx.creatorAvatarUrl)}" alt="${escapeHtml(actor)}" width="36" height="36" style="width: 36px; height: 36px; border-radius: 50%; object-fit: cover; display: block; border: 1px solid #e5e7eb;" />`
|
||||
: `<table cellpadding="0" cellspacing="0" border="0" style="width: 36px; height: 36px; border-radius: 50%; background-color: #4f46e5; text-align: center;"><tr><td style="color: #ffffff; font-weight: 600; font-size: 14px; text-align: center; vertical-align: middle;">${escapeHtml(actorInitial)}</td></tr></table>`
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f9fafb; margin: 0; padding: 24px; color: #111827; }
|
||||
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; border: 1px solid #e5e7eb; padding: 32px; }
|
||||
.header { font-size: 18px; font-weight: 700; margin-bottom: 8px; color: #111827; }
|
||||
.content { font-size: 14px; line-height: 1.6; color: #374151; margin-bottom: 24px; }
|
||||
.detail-box { background-color: #f3f4f6; border-left: 4px solid #4f46e5; padding: 12px 16px; border-radius: 4px; margin: 16px 0; font-size: 14px; color: #1f2937; white-space: pre-wrap; }
|
||||
.btn { display: inline-block; background-color: #4f46e5; color: #ffffff !important; padding: 10px 20px; border-radius: 6px; text-decoration: none; font-size: 14px; font-weight: 500; margin-top: 12px; }
|
||||
.footer { font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 16px; margin-top: 24px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<table cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 16px;">
|
||||
<tr>
|
||||
<td style="vertical-align: middle; padding-right: 12px; width: 36px;">
|
||||
${avatarHtml}
|
||||
</td>
|
||||
<td style="vertical-align: middle;">
|
||||
<div style="font-weight: 600; font-size: 15px; color: #111827; line-height: 1.2;">${escapeHtml(actor)}</div>
|
||||
${formattedUploadTime ? `<div style="font-size: 12px; color: #6b7280; margin-top: 2px;">Uploaded at ${escapeHtml(formattedUploadTime)}</div>` : ''}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<div class="header">${escapeHtml(headline)}</div>
|
||||
<div class="content">
|
||||
${detail ? `<div class="detail-box">${escapeHtml(detail)}</div>` : ''}
|
||||
<a href="${actionUrl}" class="btn">${escapeHtml(actionText)}</a>
|
||||
</div>
|
||||
<div class="footer">
|
||||
Team: ${escapeHtml(ctx.teamName)} • Sent from <a href="${baseUrl}" style="color: #6366f1; text-decoration: none;">Shumai</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`.trim()
|
||||
|
||||
const text = `
|
||||
${subject}
|
||||
|
||||
${headline}
|
||||
${formattedUploadTime ? `Uploaded at: ${formattedUploadTime}\n` : ''}${detail ? `\n${detail}\n` : ''}
|
||||
${actionText}: ${actionUrl}
|
||||
|
||||
Team: ${ctx.teamName}
|
||||
`.trim()
|
||||
|
||||
return { subject, html, text }
|
||||
}
|
||||
|
||||
renderBatchedNotificationEmail(ctx: BatchedEmailContext): {
|
||||
subject: string
|
||||
html: string
|
||||
text: string
|
||||
} {
|
||||
const baseUrl = this.getBaseUrl()
|
||||
const teamUrl = `${baseUrl}/teams/${ctx.teamId}`
|
||||
|
||||
if (ctx.items.length === 0) {
|
||||
return {
|
||||
subject: `[Shumai] Notifications in ${ctx.teamName}`,
|
||||
html: `<p>No new notifications.</p>`,
|
||||
text: `No new notifications.`,
|
||||
}
|
||||
}
|
||||
|
||||
// Determine subject
|
||||
let subject = `[Shumai] ${ctx.items.length} new notifications in ${ctx.teamName}`
|
||||
if (ctx.items.length === 1) {
|
||||
const single = ctx.items[0]
|
||||
const actor = single.creatorName || 'Someone'
|
||||
const target = single.assetName ? `"${single.assetName}"` : 'a file'
|
||||
const projectInfo = single.projectName ? ` to ${single.projectName}` : ''
|
||||
switch (single.type) {
|
||||
case NotificationType.successful_file_uploaded:
|
||||
subject = `[Shumai] ${actor} uploaded ${target}${projectInfo}`
|
||||
break
|
||||
case NotificationType.comment_created:
|
||||
subject = `[Shumai] ${actor} commented on ${target}`
|
||||
break
|
||||
case NotificationType.reply_created:
|
||||
subject = `[Shumai] ${actor} replied to your comment on ${target}`
|
||||
break
|
||||
case NotificationType.mention:
|
||||
subject = `[Shumai] ${actor} mentioned you`
|
||||
break
|
||||
case NotificationType.kanban_task_assigned: {
|
||||
const task = single.kanbanTaskTitle ? `"${single.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} assigned you to task ${task}`
|
||||
break
|
||||
}
|
||||
case NotificationType.kanban_task_created: {
|
||||
const task = single.kanbanTaskTitle ? `"${single.kanbanTaskTitle}"` : 'a task'
|
||||
subject = `[Shumai] ${actor} created task ${task}`
|
||||
break
|
||||
}
|
||||
default:
|
||||
subject = `[Shumai] 1 new notification in ${ctx.teamName}`
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Group items: same type + actor + project
|
||||
const groups = new Map<string, BatchedNotificationItem[]>()
|
||||
for (const item of ctx.items) {
|
||||
const key = getNotificationBatchGroupKey(item)
|
||||
const list = groups.get(key)
|
||||
if (list) {
|
||||
list.push(item)
|
||||
} else {
|
||||
groups.set(key, [item])
|
||||
}
|
||||
}
|
||||
|
||||
const htmlRows: string[] = []
|
||||
const textRows: string[] = []
|
||||
|
||||
for (const [, cluster] of groups) {
|
||||
const first = cluster[0]
|
||||
const actor = first.creatorName || 'Someone'
|
||||
const avatarHtml = renderAvatarHtml(actor, first.creatorAvatarUrl)
|
||||
|
||||
if (cluster.length <= 3) {
|
||||
// Render detailed individual rows
|
||||
for (const item of cluster) {
|
||||
const action = getItemAction(baseUrl, item)
|
||||
const timeStr = formatUploadTime(item.uploadTime || item.createdAt)
|
||||
const detail = getNotificationItemDetail(item)
|
||||
|
||||
const thumbHtml = item.assetThumbnailUrl
|
||||
? `<div style="margin-top: 8px;"><img src="${escapeHtml(item.assetThumbnailUrl)}" alt="${escapeHtml(item.assetName || 'Thumbnail')}" width="140" style="max-width: 140px; max-height: 90px; border-radius: 6px; border: 1px solid #e5e7eb; object-fit: cover; display: block;" /></div>`
|
||||
: ''
|
||||
|
||||
htmlRows.push(
|
||||
`
|
||||
<div style="padding: 16px 0; border-bottom: 1px solid #f3f4f6;">
|
||||
<table cellpadding="0" cellspacing="0" border="0" style="width: 100%;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; width: 44px; padding-right: 12px;">
|
||||
${avatarHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top;">
|
||||
<div style="font-weight: 600; font-size: 14px; color: #111827;">${escapeHtml(actor)}</div>
|
||||
<div style="font-size: 13px; color: #374151; margin-top: 2px;">${escapeHtml(detail.headline)}</div>
|
||||
${timeStr ? `<div style="font-size: 12px; color: #6b7280; margin-top: 2px;">${escapeHtml(timeStr)}</div>` : ''}
|
||||
${detail.message ? `<div style="background-color: #f9fafb; border-left: 3px solid #6366f1; padding: 8px 12px; border-radius: 4px; font-size: 13px; color: #4b5563; margin-top: 6px; white-space: pre-wrap;">${escapeHtml(detail.message)}</div>` : ''}
|
||||
${thumbHtml}
|
||||
<div style="margin-top: 8px;">
|
||||
<a href="${action.url}" style="display: inline-block; font-size: 12px; font-weight: 500; color: #4f46e5; text-decoration: none;">${escapeHtml(action.text)} →</a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
`.trim(),
|
||||
)
|
||||
|
||||
textRows.push(
|
||||
`- ${actor}: ${detail.headline}${timeStr ? ` (${timeStr})` : ''}${detail.message ? `\n "${detail.message}"` : ''}\n Link: ${action.url}`,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Grouped summary row (count > 3, NO thumbnails)
|
||||
const count = cluster.length
|
||||
let summaryHeadline = `${actor} triggered ${count} updates`
|
||||
const projectName = first.projectName
|
||||
|
||||
switch (first.type) {
|
||||
case NotificationType.successful_file_uploaded:
|
||||
summaryHeadline = `${actor} uploaded ${count} assets${projectName ? ` to ${projectName}` : ''}`
|
||||
break
|
||||
case NotificationType.comment_created:
|
||||
summaryHeadline = `${actor} left ${count} comments${projectName ? ` in ${projectName}` : ''}`
|
||||
break
|
||||
case NotificationType.reply_created:
|
||||
summaryHeadline = `${actor} replied ${count} times to your comments`
|
||||
break
|
||||
case NotificationType.mention:
|
||||
summaryHeadline = `${actor} mentioned you ${count} times`
|
||||
break
|
||||
case NotificationType.metadata_field_updated_status:
|
||||
summaryHeadline = `${actor} updated status of ${count} assets`
|
||||
break
|
||||
case NotificationType.kanban_task_created:
|
||||
summaryHeadline = `${actor} created ${count} tasks${projectName ? ` in ${projectName}` : ''}`
|
||||
break
|
||||
case NotificationType.kanban_task_assigned:
|
||||
summaryHeadline = `${actor} assigned you to ${count} tasks`
|
||||
break
|
||||
case NotificationType.kanban_task_status_updated:
|
||||
summaryHeadline = `${actor} updated status of ${count} tasks`
|
||||
break
|
||||
case NotificationType.kanban_task_updated:
|
||||
summaryHeadline = `${actor} updated ${count} tasks`
|
||||
break
|
||||
case NotificationType.kanban_task_comment_created:
|
||||
summaryHeadline = `${actor} commented on ${count} tasks`
|
||||
break
|
||||
}
|
||||
|
||||
const latestTime = cluster.reduce((latest, it) => {
|
||||
const t = new Date(it.uploadTime || it.createdAt).getTime()
|
||||
return t > latest ? t : latest
|
||||
}, 0)
|
||||
const timeStr = latestTime > 0 ? formatUploadTime(new Date(latestTime)) : undefined
|
||||
const targetUrl = first.projectId
|
||||
? `${baseUrl}/teams/${ctx.teamId}/projects/${first.projectId}`
|
||||
: teamUrl
|
||||
|
||||
htmlRows.push(
|
||||
`
|
||||
<div style="padding: 16px 0; border-bottom: 1px solid #f3f4f6;">
|
||||
<table cellpadding="0" cellspacing="0" border="0" style="width: 100%;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; width: 44px; padding-right: 12px;">
|
||||
${avatarHtml}
|
||||
</td>
|
||||
<td style="vertical-align: top;">
|
||||
<div style="font-weight: 600; font-size: 14px; color: #111827;">${escapeHtml(summaryHeadline)}</div>
|
||||
${timeStr ? `<div style="font-size: 12px; color: #6b7280; margin-top: 2px;">Latest activity: ${escapeHtml(timeStr)}</div>` : ''}
|
||||
<div style="margin-top: 8px;">
|
||||
<a href="${targetUrl}" style="display: inline-block; font-size: 12px; font-weight: 500; color: #4f46e5; text-decoration: none;">View Project →</a>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
`.trim(),
|
||||
)
|
||||
|
||||
textRows.push(
|
||||
`- ${summaryHeadline}${timeStr ? ` (Latest: ${timeStr})` : ''}\n Link: ${targetUrl}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${escapeHtml(subject)}</title>
|
||||
<style>
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f9fafb; margin: 0; padding: 24px; color: #111827; }
|
||||
.container { max-width: 600px; margin: 0 auto; background: #ffffff; border-radius: 8px; border: 1px solid #e5e7eb; padding: 32px; }
|
||||
.header { font-size: 18px; font-weight: 700; color: #111827; }
|
||||
.subtitle { font-size: 14px; color: #6b7280; margin-top: 4px; margin-bottom: 20px; }
|
||||
.btn { display: inline-block; background-color: #4f46e5; color: #ffffff !important; padding: 10px 20px; border-radius: 6px; text-decoration: none; font-size: 14px; font-weight: 500; margin-top: 20px; }
|
||||
.footer { font-size: 12px; color: #9ca3af; border-top: 1px solid #f3f4f6; padding-top: 16px; margin-top: 24px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">Shumai Notifications</div>
|
||||
<div class="subtitle">You have ${ctx.items.length} new update${ctx.items.length > 1 ? 's' : ''} in <strong>${escapeHtml(ctx.teamName)}</strong>:</div>
|
||||
<div>
|
||||
${htmlRows.join('\n')}
|
||||
</div>
|
||||
<div style="text-align: center; margin-top: 20px;">
|
||||
<a href="${teamUrl}" class="btn">Open ${escapeHtml(ctx.teamName)}</a>
|
||||
</div>
|
||||
<div class="footer">
|
||||
Team: ${escapeHtml(ctx.teamName)} • Sent from <a href="${baseUrl}" style="color: #6366f1; text-decoration: none;">Shumai</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`.trim()
|
||||
|
||||
const text = `
|
||||
Shumai Notifications
|
||||
|
||||
You have ${ctx.items.length} new update(s) in ${ctx.teamName}:
|
||||
|
||||
${textRows.join('\n\n')}
|
||||
|
||||
Open Team: ${teamUrl}
|
||||
Sent from Shumai at ${baseUrl}
|
||||
`.trim()
|
||||
|
||||
return { subject, html, text }
|
||||
}
|
||||
}
|
||||
|
||||
function getNotificationItemDetail(item: BatchedNotificationItem): {
|
||||
headline: string
|
||||
message?: string
|
||||
} {
|
||||
const actor = item.creatorName || 'Someone'
|
||||
const asset = item.assetName ? `"${item.assetName}"` : 'an asset'
|
||||
const task = item.kanbanTaskTitle ? `"${item.kanbanTaskTitle}"` : 'a task'
|
||||
const project = item.projectName ? ` in ${item.projectName}` : ''
|
||||
|
||||
let commentMessage = item.commentMessage
|
||||
if (commentMessage && item.mentionedUserNames) {
|
||||
commentMessage = commentMessage.replace(/<@([^>]+)>/g, (match, uid) => {
|
||||
const name = item.mentionedUserNames?.[uid]
|
||||
return name ? `@${name}` : `@${uid}`
|
||||
})
|
||||
}
|
||||
|
||||
switch (item.type) {
|
||||
case NotificationType.successful_file_uploaded:
|
||||
return {
|
||||
headline: `Uploaded ${asset}${item.projectName ? ` to ${item.projectName}` : ''}`,
|
||||
}
|
||||
case NotificationType.comment_created:
|
||||
return {
|
||||
headline: `Commented on ${asset}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.reply_created:
|
||||
return {
|
||||
headline: `Replied to your comment on ${asset}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.mention:
|
||||
return {
|
||||
headline: `Mentioned you on ${item.kanbanTaskTitle ? `task ${task}` : asset}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.metadata_field_updated_status:
|
||||
return {
|
||||
headline: `Updated status of ${asset}${project}`,
|
||||
}
|
||||
case NotificationType.kanban_task_created:
|
||||
return {
|
||||
headline: `Created task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.kanban_task_assigned:
|
||||
return {
|
||||
headline: `Assigned you to task ${task}${project}`,
|
||||
}
|
||||
case NotificationType.kanban_task_status_updated:
|
||||
return {
|
||||
headline: `Updated status of task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.kanban_task_updated:
|
||||
return {
|
||||
headline: `Updated task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.kanban_task_deleted:
|
||||
return {
|
||||
headline: `Deleted task ${task}${project}`,
|
||||
}
|
||||
case NotificationType.kanban_task_comment_created:
|
||||
return {
|
||||
headline: `Commented on task ${task}${project}`,
|
||||
message: commentMessage,
|
||||
}
|
||||
case NotificationType.new_user_join_team:
|
||||
return {
|
||||
headline: `Joined the team ${item.teamName}`,
|
||||
}
|
||||
case NotificationType.new_user_join_project:
|
||||
return {
|
||||
headline: `Joined project ${item.projectName || 'a project'}`,
|
||||
}
|
||||
default:
|
||||
return {
|
||||
headline: `New activity from ${actor}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getItemAction(
|
||||
baseUrl: string,
|
||||
item: BatchedNotificationItem,
|
||||
): { url: string; text: string } {
|
||||
if (item.teamId) {
|
||||
if (item.projectId && item.assetId) {
|
||||
return {
|
||||
url: `${baseUrl}/teams/${item.teamId}/projects/${item.projectId}?assetId=${item.assetId}`,
|
||||
text: 'View Asset',
|
||||
}
|
||||
} else if (item.projectId) {
|
||||
return {
|
||||
url: `${baseUrl}/teams/${item.teamId}/projects/${item.projectId}`,
|
||||
text: 'View Project',
|
||||
}
|
||||
} else if (item.kanbanTaskId) {
|
||||
return {
|
||||
url: `${baseUrl}/teams/${item.teamId}?kanbanTaskId=${item.kanbanTaskId}`,
|
||||
text: 'View Task',
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
url: `${baseUrl}/teams/${item.teamId}`,
|
||||
text: 'Open Team',
|
||||
}
|
||||
}
|
||||
}
|
||||
return { url: baseUrl, text: 'Open Shumai' }
|
||||
}
|
||||
|
||||
function renderAvatarHtml(actor: string, avatarUrl?: string): string {
|
||||
const actorInitial = (actor.trim()[0] || 'U').toUpperCase()
|
||||
if (avatarUrl) {
|
||||
return `<img src="${escapeHtml(avatarUrl)}" alt="${escapeHtml(actor)}" width="36" height="36" style="width: 36px; height: 36px; border-radius: 50%; object-fit: cover; display: block; border: 1px solid #e5e7eb;" />`
|
||||
}
|
||||
return `<table cellpadding="0" cellspacing="0" border="0" style="width: 36px; height: 36px; border-radius: 50%; background-color: #4f46e5; text-align: center;"><tr><td style="color: #ffffff; font-weight: 600; font-size: 14px; text-align: center; vertical-align: middle;">${escapeHtml(actorInitial)}</td></tr></table>`
|
||||
}
|
||||
|
||||
function formatUploadTime(time: string | Date | undefined): string | undefined {
|
||||
if (!time) return undefined
|
||||
if (time instanceof Date) {
|
||||
if (isNaN(time.getTime())) return undefined
|
||||
return (
|
||||
new Intl.DateTimeFormat('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
hour12: true,
|
||||
timeZone: 'UTC',
|
||||
}).format(time) + ' UTC'
|
||||
)
|
||||
}
|
||||
const parsed = new Date(time)
|
||||
if (!isNaN(parsed.getTime())) {
|
||||
return (
|
||||
new Intl.DateTimeFormat('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
hour12: true,
|
||||
timeZone: 'UTC',
|
||||
}).format(parsed) + ' UTC'
|
||||
)
|
||||
}
|
||||
return time
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
export const emailService = new EmailService()
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './notification'
|
||||
export * from './email'
|
||||
export * from './notification-job'
|
||||
@@ -0,0 +1,576 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { prisma, NotificationType, NotificationEmailStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { emailService, type EmailAttachment } from './email'
|
||||
import { notificationJobService } from './notification-job'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
|
||||
describe('NotificationJobService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let sendMailSpy: ReturnType<typeof vi.spyOn>
|
||||
|
||||
beforeEach(() => {
|
||||
sendMailSpy = vi
|
||||
.spyOn(emailService, 'sendMail')
|
||||
.mockResolvedValue({ messageId: '<mock-id@shumai.test>' })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
sendMailSpy.mockRestore()
|
||||
notificationJobService.stop()
|
||||
})
|
||||
|
||||
async function createTeamWithEmail(name = 'Email Team') {
|
||||
return prisma.team.create({
|
||||
data: {
|
||||
name,
|
||||
settings: {
|
||||
emailNotification: {
|
||||
enabled: true,
|
||||
host: 'smtp.test.com',
|
||||
port: 587,
|
||||
username: 'user',
|
||||
password: 'pw',
|
||||
smtps: false,
|
||||
ignoreCert: false,
|
||||
from: 'noreply@test.com',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
it('picks up pending notifications, sends batched email, and marks them processed', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice@test.com', password: 'p' },
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Alpha Project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'design.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
|
||||
// Create 2 pending notifications
|
||||
const n1 = await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
const n2 = await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const processedCount = await notificationJobService.processPendingNotifications(500)
|
||||
expect(processedCount).toBe(2)
|
||||
|
||||
// Verify Bob received exactly 1 batched email containing both items
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
expect(sendMailSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ host: 'smtp.test.com' }),
|
||||
expect.objectContaining({
|
||||
to: 'bob@test.com',
|
||||
subject: '[Shumai] 2 new notifications in Email Team',
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify notifications are marked processed in DB
|
||||
const updated1 = await prisma.notification.findUnique({ where: { id: n1.id } })
|
||||
const updated2 = await prisma.notification.findUnique({ where: { id: n2.id } })
|
||||
expect(updated1?.emailStatus).toBe(NotificationEmailStatus.processed)
|
||||
expect(updated2?.emailStatus).toBe(NotificationEmailStatus.processed)
|
||||
})
|
||||
|
||||
it('skips already processed notifications', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice2@test.com', password: 'p' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.processed,
|
||||
},
|
||||
})
|
||||
|
||||
const processedCount = await notificationJobService.processPendingNotifications(500)
|
||||
expect(processedCount).toBe(0)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('marks notifications processed without sending email if team SMTP is disabled', async () => {
|
||||
// Team without emailNotification configured
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'No Email Team' },
|
||||
})
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice3@test.com', password: 'p' },
|
||||
})
|
||||
|
||||
const notif = await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const processedCount = await notificationJobService.processPendingNotifications(500)
|
||||
expect(processedCount).toBe(1)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
|
||||
const updated = await prisma.notification.findUnique({ where: { id: notif.id } })
|
||||
expect(updated?.emailStatus).toBe(NotificationEmailStatus.processed)
|
||||
})
|
||||
|
||||
it('excludes the actor from receiving notification about their own action', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const alice = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-self@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: alice.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Alice is the creator and only member
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
creatorId: alice.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
// Alice should not receive an email for her own comment
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('excludes AI agent users from receiving email notifications', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-agent-test@test.com', password: 'p' },
|
||||
})
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'AutoAgent',
|
||||
email: 'agent-bot@shumai.ai',
|
||||
password: 'p',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: agentUser.id, role: 'editor' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('respects user notification preferences', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-pref@test.com', password: 'p' },
|
||||
})
|
||||
const bob = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob-pref@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: bob.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Bob disabled comments in his notification settings
|
||||
await userMetadataService.upsertMetadata(bob.id, team.id, 'notification_settings', {
|
||||
comments: false,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: true,
|
||||
kanbanComments: true,
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('filters notifications by project scope for project-scoped members', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'Alice', email: 'alice-scope@test.com', password: 'p' },
|
||||
})
|
||||
const project1 = await prisma.project.create({
|
||||
data: { name: 'Project 1', teamId: team.id },
|
||||
})
|
||||
const project2 = await prisma.project.create({
|
||||
data: { name: 'Project 2', teamId: team.id },
|
||||
})
|
||||
|
||||
const bob = await prisma.user.create({
|
||||
data: { name: 'Bob', email: 'bob-scope@test.com', password: 'p' },
|
||||
})
|
||||
const bobMember = await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: bob.id, role: 'editor', scope: 'project' },
|
||||
})
|
||||
// Bob only belongs to Project 1
|
||||
await prisma.projectMember.create({
|
||||
data: { projectId: project1.id, teamMemberId: bobMember.id, role: 'editor' },
|
||||
})
|
||||
|
||||
// Notification in Project 2
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project2.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
await notificationJobService.processPendingNotifications(500)
|
||||
// Bob should not receive notification for Project 2
|
||||
expect(sendMailSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('batches 5 uploads and 1 comment into 1 email with collapsed upload summary', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: { name: 'UserB', email: 'userb@test.com', password: 'p' },
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Recipient', email: 'recip@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project Alpha', teamId: team.id },
|
||||
})
|
||||
|
||||
// 5 uploads by UserB in Project Alpha
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: `img_${i}.png`,
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
},
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 1 comment by UserB
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.comment_created,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(6)
|
||||
|
||||
// Recipient receives exactly 1 email containing all 6 events
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const call = sendMailSpy.mock.calls[0]
|
||||
expect(call[1].to).toBe('recip@test.com')
|
||||
expect(call[1].subject).toBe('[Shumai] 6 new notifications in Email Team')
|
||||
// Uploads collapsed into 1 row because count > 3
|
||||
expect(call[1].html).toContain('UserB uploaded 5 assets to Project Alpha')
|
||||
// Comment rendered as individual row
|
||||
expect(call[1].html).toContain('Commented on')
|
||||
})
|
||||
|
||||
it('embeds creator avatar and asset thumbnail as inline cid attachments', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Alice Artist',
|
||||
email: 'alice.artist@test.com',
|
||||
password: 'p',
|
||||
image: 'avatars/alice.png',
|
||||
},
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Bob Reviewer', email: 'bob.reviewer@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Artwork Project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'poster.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
media: {
|
||||
thumbnail: { key: 'thumbnails/poster.jpg' },
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const getObjectSpy = vi
|
||||
.spyOn(s3Service, 'getObject')
|
||||
.mockImplementation(async (_bucket, key) => {
|
||||
if (key === 'avatars/alice.png') {
|
||||
return { buffer: Buffer.from('alice-avatar-bytes'), contentType: 'image/png' }
|
||||
}
|
||||
if (key === 'thumbnails/poster.jpg') {
|
||||
return { buffer: Buffer.from('poster-thumb-bytes'), contentType: 'image/jpeg' }
|
||||
}
|
||||
throw new Error('Not found')
|
||||
})
|
||||
|
||||
try {
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(1)
|
||||
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const call = sendMailSpy.mock.calls[0]
|
||||
const options = call[1]
|
||||
expect(options.to).toBe('bob.reviewer@test.com')
|
||||
|
||||
// Check attachments
|
||||
expect(options.attachments).toHaveLength(2)
|
||||
const avatarAtt = options.attachments.find((a: EmailAttachment) =>
|
||||
a.cid?.startsWith('avatar-'),
|
||||
)
|
||||
const thumbAtt = options.attachments.find((a: EmailAttachment) => a.cid?.startsWith('thumb-'))
|
||||
expect(avatarAtt).toBeDefined()
|
||||
expect(avatarAtt.content).toEqual(Buffer.from('alice-avatar-bytes'))
|
||||
expect(avatarAtt.cid).toBe(`avatar-${sender.id}@shumai.internal`)
|
||||
|
||||
expect(thumbAtt).toBeDefined()
|
||||
expect(thumbAtt.content).toEqual(Buffer.from('poster-thumb-bytes'))
|
||||
expect(thumbAtt.cid).toBe(`thumb-${asset.id}@shumai.internal`)
|
||||
|
||||
// Check HTML references the exact cid
|
||||
expect(options.html).toContain(`src="cid:${avatarAtt.cid}"`)
|
||||
expect(options.html).toContain(`src="cid:${thumbAtt.cid}"`)
|
||||
} finally {
|
||||
getObjectSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('omits thumbnail attachments when cluster has count > 3', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Bulk Uploader',
|
||||
email: 'bulk@test.com',
|
||||
password: 'p',
|
||||
image: 'avatars/bulk.png',
|
||||
},
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Recipient', email: 'bulk-recip@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Bulk Project', teamId: team.id },
|
||||
})
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: `bulk_${i}.png`,
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
media: {
|
||||
thumbnail: { key: `thumbnails/bulk_${i}.jpg` },
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const getObjectSpy = vi
|
||||
.spyOn(s3Service, 'getObject')
|
||||
.mockImplementation(async (_bucket, key) => {
|
||||
if (key === 'avatars/bulk.png') {
|
||||
return { buffer: Buffer.from('bulk-avatar-bytes'), contentType: 'image/png' }
|
||||
}
|
||||
return { buffer: Buffer.from('thumb-bytes'), contentType: 'image/jpeg' }
|
||||
})
|
||||
|
||||
try {
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(4)
|
||||
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const options = sendMailSpy.mock.calls[0][1]
|
||||
|
||||
// Count > 3, so only avatar attachment is included, NO thumbnail attachments!
|
||||
expect(options.attachments).toHaveLength(1)
|
||||
expect(options.attachments[0].cid).toBe(`avatar-${sender.id}@shumai.internal`)
|
||||
expect(options.html).toContain(`src="cid:avatar-${sender.id}@shumai.internal"`)
|
||||
expect(options.html).not.toContain('src="cid:thumb-')
|
||||
} finally {
|
||||
getObjectSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('gracefully handles missing images or S3 failure with fallback badge', async () => {
|
||||
const team = await createTeamWithEmail()
|
||||
const sender = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Broken Image User',
|
||||
email: 'broken@test.com',
|
||||
password: 'p',
|
||||
image: 'avatars/non-existent.png',
|
||||
},
|
||||
})
|
||||
const recipient = await prisma.user.create({
|
||||
data: { name: 'Recipient', email: 'broken-recip@test.com', password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: recipient.id, role: 'editor' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'broken.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
project: { connect: { id: project.id } },
|
||||
media: {
|
||||
thumbnail: { key: 'thumbnails/missing.jpg' },
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
assetId: asset.id,
|
||||
creatorId: sender.id,
|
||||
emailStatus: NotificationEmailStatus.pending,
|
||||
},
|
||||
})
|
||||
|
||||
const getObjectSpy = vi.spyOn(s3Service, 'getObject').mockRejectedValue(new Error('S3 error'))
|
||||
|
||||
try {
|
||||
const count = await notificationJobService.processPendingNotifications(500)
|
||||
expect(count).toBe(1)
|
||||
|
||||
expect(sendMailSpy).toHaveBeenCalledTimes(1)
|
||||
const options = sendMailSpy.mock.calls[0][1]
|
||||
|
||||
// No attachments because both avatar and thumb failed to load
|
||||
expect(options.attachments).toBeUndefined()
|
||||
// HTML falls back to letter badge "B" for "Broken Image User"
|
||||
expect(options.html).toContain('>B</td>')
|
||||
expect(options.html).not.toContain('<img')
|
||||
} finally {
|
||||
getObjectSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('starts and stops gracefully', () => {
|
||||
expect(() => {
|
||||
notificationJobService.start(100000, 100000)
|
||||
notificationJobService.stop()
|
||||
}).not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,496 @@
|
||||
import { prisma, NotificationType, NotificationEmailStatus } from '@shumai/db'
|
||||
import { emailService, getNotificationBatchGroupKey } from '@shumai/core/src/notification/email'
|
||||
import type { BatchedNotificationItem, EmailAttachment } from '@shumai/core/src/notification/email'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import type { NotificationSettings } from '@shumai/dtos'
|
||||
import '@shumai/db/src/prisma-json-types'
|
||||
|
||||
function getExtensionFromMime(mime?: string): string {
|
||||
if (!mime) return 'jpg'
|
||||
if (mime.includes('png')) return 'png'
|
||||
if (mime.includes('webp')) return 'webp'
|
||||
if (mime.includes('gif')) return 'gif'
|
||||
if (mime.includes('svg')) return 'svg'
|
||||
return 'jpg'
|
||||
}
|
||||
|
||||
export class NotificationJobService {
|
||||
private isRunning = false
|
||||
private timer: NodeJS.Timeout | null = null
|
||||
private isProcessing = false
|
||||
|
||||
start(initialDelayMs = 5000, intervalMs = 3 * 60 * 1000): void {
|
||||
if (this.isRunning) return
|
||||
this.isRunning = true
|
||||
logger.info('Starting notification email background job')
|
||||
|
||||
const run = async () => {
|
||||
if (!this.isRunning) return
|
||||
try {
|
||||
await this.processPendingNotifications()
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ err: err instanceof Error ? err.message : String(err) },
|
||||
'Error in notification email background job',
|
||||
)
|
||||
}
|
||||
|
||||
if (this.isRunning) {
|
||||
this.timer = setTimeout(run, intervalMs)
|
||||
}
|
||||
}
|
||||
|
||||
this.timer = setTimeout(run, initialDelayMs)
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.isRunning = false
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
logger.info('Stopped notification email background job')
|
||||
}
|
||||
|
||||
async processPendingNotifications(limit = 500): Promise<number> {
|
||||
if (this.isProcessing) {
|
||||
logger.debug('Notification job turn already in progress, skipping')
|
||||
return 0
|
||||
}
|
||||
|
||||
this.isProcessing = true
|
||||
let batchIds: string[] = []
|
||||
|
||||
try {
|
||||
// 1. Concurrency control: atomically lock up to limit pending notifications
|
||||
const locked = await prisma.$queryRaw<{ id: string }[]>`
|
||||
WITH candidates AS (
|
||||
SELECT id
|
||||
FROM notifications
|
||||
WHERE email_status = 'pending'::"NotificationEmailStatus"
|
||||
ORDER BY id ASC
|
||||
LIMIT ${limit}
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
UPDATE notifications
|
||||
SET email_status = 'processing'::"NotificationEmailStatus", updated_at = NOW()
|
||||
FROM candidates
|
||||
WHERE notifications.id = candidates.id
|
||||
RETURNING notifications.id;
|
||||
`
|
||||
|
||||
if (!locked || locked.length === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
batchIds = locked.map((r) => r.id)
|
||||
logger.info({ count: batchIds.length }, 'Picked up pending notifications for processing')
|
||||
|
||||
// 2. Fetch full records with relations
|
||||
const notifications = await prisma.notification.findMany({
|
||||
where: { id: { in: batchIds } },
|
||||
include: {
|
||||
creator: { select: { id: true, name: true, image: true, type: true } },
|
||||
team: { select: { id: true, name: true } },
|
||||
project: { select: { id: true, name: true } },
|
||||
asset: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
media: true,
|
||||
projectId: true,
|
||||
createdAt: true,
|
||||
project: { select: { id: true, name: true } },
|
||||
},
|
||||
},
|
||||
user: { select: { id: true, name: true, email: true, type: true } },
|
||||
kanbanTask: { select: { id: true, title: true, projectId: true } },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
// 3. Group notifications by teamId
|
||||
const byTeam = new Map<string, typeof notifications>()
|
||||
for (const n of notifications) {
|
||||
const list = byTeam.get(n.teamId)
|
||||
if (list) {
|
||||
list.push(n)
|
||||
} else {
|
||||
byTeam.set(n.teamId, [n])
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Process each team
|
||||
for (const [teamId, teamNotifs] of byTeam) {
|
||||
const emailSettings = await emailService.getEmailSettings(teamId)
|
||||
if (!emailSettings.enabled || !emailSettings.host || !emailSettings.from) {
|
||||
logger.debug(
|
||||
{ teamId },
|
||||
'Team email notifications disabled or unconfigured, skipping delivery',
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
// Fetch team members excluding AI agents
|
||||
const members = await prisma.teamMember.findMany({
|
||||
where: {
|
||||
teamId,
|
||||
user: {
|
||||
type: { not: 'agent' },
|
||||
agent: null,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true, type: true } },
|
||||
projectMembers: { select: { projectId: true } },
|
||||
},
|
||||
})
|
||||
|
||||
const avatarCache = new Map<
|
||||
string,
|
||||
{ cidUrl: string; attachment: EmailAttachment } | null
|
||||
>()
|
||||
const thumbCache = new Map<string, { cidUrl: string; attachment: EmailAttachment } | null>()
|
||||
const cidAttachmentMap = new Map<string, EmailAttachment>()
|
||||
|
||||
const resolveAvatar = async (
|
||||
creatorId?: string | null,
|
||||
image?: string | null,
|
||||
): Promise<string | undefined> => {
|
||||
if (!image) return undefined
|
||||
if (creatorId && avatarCache.has(creatorId)) {
|
||||
const cached = avatarCache.get(creatorId)
|
||||
return cached ? cached.cidUrl : undefined
|
||||
}
|
||||
|
||||
const cid = `avatar-${creatorId || Math.random().toString(36).slice(2)}@shumai.internal`
|
||||
const cidUrl = `cid:${cid}`
|
||||
|
||||
try {
|
||||
if (image.startsWith('http://') || image.startsWith('https://')) {
|
||||
const res = await fetch(image, { signal: AbortSignal.timeout(5000) })
|
||||
if (res.ok) {
|
||||
const arrayBuffer = await res.arrayBuffer()
|
||||
const buffer = Buffer.from(arrayBuffer)
|
||||
const contentType = res.headers.get('content-type') || 'image/jpeg'
|
||||
const ext = getExtensionFromMime(contentType)
|
||||
const resolved = {
|
||||
cidUrl,
|
||||
attachment: {
|
||||
filename: `avatar-${creatorId || 'user'}.${ext}`,
|
||||
content: buffer,
|
||||
cid,
|
||||
contentType,
|
||||
},
|
||||
}
|
||||
if (creatorId) avatarCache.set(creatorId, resolved)
|
||||
cidAttachmentMap.set(cidUrl, resolved.attachment)
|
||||
return cidUrl
|
||||
}
|
||||
} else {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const obj = await s3Service.getObject(bucket, image)
|
||||
if (obj && obj.buffer && obj.buffer.length > 0) {
|
||||
const contentType = obj.contentType || 'image/jpeg'
|
||||
const ext = getExtensionFromMime(contentType)
|
||||
const resolved = {
|
||||
cidUrl,
|
||||
attachment: {
|
||||
filename: `avatar-${creatorId || 'user'}.${ext}`,
|
||||
content: obj.buffer,
|
||||
cid,
|
||||
contentType,
|
||||
},
|
||||
}
|
||||
if (creatorId) avatarCache.set(creatorId, resolved)
|
||||
cidAttachmentMap.set(cidUrl, resolved.attachment)
|
||||
return cidUrl
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
{ err: err instanceof Error ? err.message : String(err), image, creatorId },
|
||||
'Failed to resolve avatar image for inline email attachment',
|
||||
)
|
||||
}
|
||||
|
||||
if (creatorId) avatarCache.set(creatorId, null)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const resolveThumbnail = async (
|
||||
assetId?: string | null,
|
||||
media?: unknown,
|
||||
): Promise<string | undefined> => {
|
||||
if (!assetId || !media) return undefined
|
||||
if (thumbCache.has(assetId)) {
|
||||
const cached = thumbCache.get(assetId)
|
||||
return cached ? cached.cidUrl : undefined
|
||||
}
|
||||
|
||||
const m = media as PrismaJson.MediaInfo | null
|
||||
const key = m?.thumbnail?.key || m?.poster?.key
|
||||
if (!key) return undefined
|
||||
|
||||
const cid = `thumb-${assetId}@shumai.internal`
|
||||
const cidUrl = `cid:${cid}`
|
||||
|
||||
try {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const obj = await s3Service.getObject(bucket, key)
|
||||
if (obj && obj.buffer && obj.buffer.length > 0) {
|
||||
const contentType = obj.contentType || 'image/jpeg'
|
||||
const ext = getExtensionFromMime(contentType)
|
||||
const resolved = {
|
||||
cidUrl,
|
||||
attachment: {
|
||||
filename: `thumb-${assetId}.${ext}`,
|
||||
content: obj.buffer,
|
||||
cid,
|
||||
contentType,
|
||||
},
|
||||
}
|
||||
thumbCache.set(assetId, resolved)
|
||||
cidAttachmentMap.set(cidUrl, resolved.attachment)
|
||||
return cidUrl
|
||||
}
|
||||
} catch (err) {
|
||||
logger.debug(
|
||||
{ err: err instanceof Error ? err.message : String(err), assetId, key },
|
||||
'Failed to resolve thumbnail image for inline email attachment',
|
||||
)
|
||||
}
|
||||
|
||||
thumbCache.set(assetId, null)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const userItemsMap = new Map<
|
||||
string,
|
||||
{ user: (typeof members)[0]['user']; items: BatchedNotificationItem[] }
|
||||
>()
|
||||
|
||||
for (const member of members) {
|
||||
if (!member.user.email) continue
|
||||
if (
|
||||
member.user.type === 'agent' ||
|
||||
member.user.email.endsWith('@shumai.ai') ||
|
||||
member.user.email.startsWith('agent-')
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
const settingsMeta = await userMetadataService.getMetadata(
|
||||
member.userId,
|
||||
teamId,
|
||||
'notification_settings',
|
||||
)
|
||||
const settings: NotificationSettings = settingsMeta
|
||||
? (settingsMeta.value as NotificationSettings)
|
||||
: {
|
||||
comments: true,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: true,
|
||||
kanbanComments: true,
|
||||
}
|
||||
|
||||
for (const n of teamNotifs) {
|
||||
// Actor check (do not notify self unless it's their upload and yourUploads is enabled)
|
||||
if (n.creatorId === member.userId) {
|
||||
if (n.type !== NotificationType.successful_file_uploaded || !settings.yourUploads) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Targeted notification check
|
||||
if (n.userId && n.userId !== member.userId) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Project scope check
|
||||
if (member.scope === 'project' && n.projectId) {
|
||||
if (n.type !== NotificationType.mention && n.userId !== member.userId) {
|
||||
const inProject = member.projectMembers.some((pm) => pm.projectId === n.projectId)
|
||||
if (!inProject) continue
|
||||
}
|
||||
}
|
||||
|
||||
// Settings preference check
|
||||
let allowed = false
|
||||
switch (n.type) {
|
||||
case NotificationType.comment_created:
|
||||
allowed = settings.comments ?? true
|
||||
break
|
||||
case NotificationType.reply_created:
|
||||
allowed = settings.replies ?? true
|
||||
break
|
||||
case NotificationType.mention:
|
||||
allowed = settings.mentions ?? true
|
||||
break
|
||||
case NotificationType.successful_file_uploaded:
|
||||
allowed =
|
||||
member.userId === n.creatorId
|
||||
? (settings.yourUploads ?? false)
|
||||
: (settings.otherUploads ?? true)
|
||||
break
|
||||
case NotificationType.metadata_field_updated_status:
|
||||
allowed = settings.statusUpdates ?? true
|
||||
break
|
||||
case NotificationType.kanban_task_created:
|
||||
case NotificationType.kanban_task_assigned:
|
||||
case NotificationType.kanban_task_status_updated:
|
||||
case NotificationType.kanban_task_updated:
|
||||
case NotificationType.kanban_task_deleted:
|
||||
allowed = settings.kanbanTasks ?? true
|
||||
break
|
||||
case NotificationType.kanban_task_comment_created:
|
||||
allowed = settings.kanbanComments ?? true
|
||||
break
|
||||
case NotificationType.new_user_join_team:
|
||||
case NotificationType.new_user_join_project:
|
||||
allowed = true
|
||||
break
|
||||
default:
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
|
||||
if (!allowed) continue
|
||||
|
||||
const creatorAvatarUrl = await resolveAvatar(n.creatorId, n.creator?.image)
|
||||
const assetThumbnailUrl = await resolveThumbnail(n.assetId, n.asset?.media)
|
||||
|
||||
const item: BatchedNotificationItem = {
|
||||
id: n.id,
|
||||
type: n.type || NotificationType.successful_file_uploaded,
|
||||
creatorName: n.creator?.name || 'Someone',
|
||||
creatorAvatarUrl,
|
||||
teamId: n.teamId,
|
||||
teamName: n.team?.name || 'Team',
|
||||
projectId: n.projectId || n.asset?.projectId || undefined,
|
||||
projectName: n.project?.name || n.asset?.project?.name || undefined,
|
||||
assetId: n.assetId || undefined,
|
||||
assetName: n.asset?.name || undefined,
|
||||
assetThumbnailUrl,
|
||||
kanbanTaskId: n.kanbanTaskId || undefined,
|
||||
kanbanTaskTitle: n.kanbanTask?.title || undefined,
|
||||
uploadTime: n.asset?.createdAt || n.createdAt,
|
||||
createdAt: n.createdAt,
|
||||
}
|
||||
|
||||
let entry = userItemsMap.get(member.userId)
|
||||
if (!entry) {
|
||||
entry = { user: member.user, items: [] }
|
||||
userItemsMap.set(member.userId, entry)
|
||||
}
|
||||
entry.items.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
// Deliver batched email to each user with pending items
|
||||
for (const [userId, { user, items }] of userItemsMap) {
|
||||
if (items.length === 0 || !user.email) continue
|
||||
try {
|
||||
const rendered = emailService.renderBatchedNotificationEmail({
|
||||
teamId,
|
||||
teamName: teamNotifs[0].team?.name || 'Team',
|
||||
recipientName: user.name || 'Member',
|
||||
items,
|
||||
})
|
||||
// Collect attachments for this email based on rendered items
|
||||
const attachmentsMap = new Map<string, EmailAttachment>()
|
||||
|
||||
// Group items exactly as renderBatchedNotificationEmail does
|
||||
const groups = new Map<string, BatchedNotificationItem[]>()
|
||||
for (const item of items) {
|
||||
const key = getNotificationBatchGroupKey(item)
|
||||
const list = groups.get(key)
|
||||
if (list) {
|
||||
list.push(item)
|
||||
} else {
|
||||
groups.set(key, [item])
|
||||
}
|
||||
}
|
||||
|
||||
for (const [, cluster] of groups) {
|
||||
const first = cluster[0]
|
||||
if (first.creatorAvatarUrl) {
|
||||
const att = cidAttachmentMap.get(first.creatorAvatarUrl)
|
||||
if (att?.cid) attachmentsMap.set(att.cid, att)
|
||||
}
|
||||
|
||||
if (cluster.length <= 3) {
|
||||
// Detailed rows: individual avatars and thumbnails are rendered
|
||||
for (const item of cluster) {
|
||||
if (item.creatorAvatarUrl) {
|
||||
const att = cidAttachmentMap.get(item.creatorAvatarUrl)
|
||||
if (att?.cid) attachmentsMap.set(att.cid, att)
|
||||
}
|
||||
if (item.assetThumbnailUrl) {
|
||||
const att = cidAttachmentMap.get(item.assetThumbnailUrl)
|
||||
if (att?.cid) attachmentsMap.set(att.cid, att)
|
||||
}
|
||||
}
|
||||
}
|
||||
// If cluster.length > 3, thumbnails are not rendered, so we do not attach them
|
||||
}
|
||||
|
||||
const attachments = Array.from(attachmentsMap.values())
|
||||
|
||||
await emailService.sendMail(emailSettings, {
|
||||
to: user.email,
|
||||
subject: rendered.subject,
|
||||
html: rendered.html,
|
||||
text: rendered.text,
|
||||
attachments: attachments.length > 0 ? attachments : undefined,
|
||||
})
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{
|
||||
userId,
|
||||
email: user.email,
|
||||
err: err instanceof Error ? err.message : String(err),
|
||||
},
|
||||
'Failed to deliver batched notification email to user',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Update batch status to processed
|
||||
await prisma.notification.updateMany({
|
||||
where: { id: { in: batchIds } },
|
||||
data: { emailStatus: NotificationEmailStatus.processed },
|
||||
})
|
||||
|
||||
return batchIds.length
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
{ err: err instanceof Error ? err.message : String(err), batchCount: batchIds.length },
|
||||
'Unexpected failure in processPendingNotifications',
|
||||
)
|
||||
if (batchIds.length > 0) {
|
||||
// Mark as processed so subsequent turns aren't permanently blocked
|
||||
await prisma.notification
|
||||
.updateMany({
|
||||
where: { id: { in: batchIds } },
|
||||
data: { emailStatus: NotificationEmailStatus.processed },
|
||||
})
|
||||
.catch((cleanErr) =>
|
||||
logger.error({ cleanErr }, 'Failed to mark notifications processed on error'),
|
||||
)
|
||||
}
|
||||
throw err
|
||||
} finally {
|
||||
this.isProcessing = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const notificationJobService = new NotificationJobService()
|
||||
Reference in New Issue
Block a user