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:
Yiling-J
2026-09-28 09:58:59 +08:00
committed by GitHub
parent 94ea4c917a
commit d98f486c9d
33 changed files with 4021 additions and 20 deletions
+6
View File
@@ -8,11 +8,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- **notification**: Add periodic background job that batches notifications into single digest emails per user, with smart collapsing for high-volume events, user preference filtering, and presigned thumbnails
- **webui**: Add team email notification settings page with SMTP configuration and test email dialog
- **notification**: Add email notification infrastructure with team-level SMTP configuration, test email delivery, and rich HTML templates
- **transcode**: Add VA-API hardware acceleration support for Linux hosts and Docker environments with Intel and AMD GPUs, featuring automatic DRI render node discovery, variable bitrate control, and structured transcoding observability logs
- **docker**: Add modular hardware-accelerated transcoding presets matching Immich's compose configuration via `hwaccel.transcoding.yaml` with support for NVENC, QuickSync, RKMPP, and VA-API
### Fixed
- **notification**: Embed avatars and asset thumbnails as inline CID attachments in notification digest emails for reliable image display across email providers without external link blocking
- **team**: Prevent email notification configuration and SMTP credentials from being exposed through general team settings
### Changed
- **transcode**: Improve video poster selection using intelligent scene detection and color variance filtering to automatically skip black frames, fade-ins, and blank intros in favor of representative video content
+2
View File
@@ -16,6 +16,7 @@ import { migrateLegacyAgentAvatars } from '@shumai/core/src/agent/migration'
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
import { authService } from '@shumai/core/src/auth/auth'
import { sandboxService } from '@shumai/core'
import { notificationJobService } from '@shumai/core/src/notification/notification-job'
if (process.argv.includes('--check')) {
console.log('✅ Web app evaluated successfully!')
@@ -58,6 +59,7 @@ async function run() {
await metadataService.syncSystemFields().catch(console.error)
await migrateLegacyAgentAvatars().catch(console.error)
assetService.startCleanupJob()
notificationJobService.start()
workflowService.start()
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
const args = process.argv.slice(2)
+36
View File
@@ -214,6 +214,8 @@
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@sinclair/typebox": "0.34.52",
"@temporalio/activity": "1.24.0",
"@temporalio/workflow": "1.24.0",
"adm-zip": "0.6.0",
"ai": "7.0.84",
"better-auth": "1.6.11",
@@ -224,6 +226,7 @@
"extract-zip": "2.0.1",
"hono": "4.13.5",
"jittered-fractional-indexing": "1.0.1",
"nodemailer": "10.0.10",
"pdfkit": "0.20.1",
"pino": "10.3.1",
"sharp": "0.35.4",
@@ -237,6 +240,7 @@
"@modelcontextprotocol/server": "2.0.0",
"@types/adm-zip": "0.5.8",
"@types/extract-zip": "2.0.3",
"@types/nodemailer": "8.0.2",
"@types/pdfkit": "0.17.6",
},
},
@@ -1563,6 +1567,8 @@
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
"@types/nodemailer": ["@types/nodemailer@8.0.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA=="],
"@types/pdfkit": ["@types/pdfkit@0.17.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-tIwzxk2uWKp0Cq9JIluQXJid77lYhF52EsIOwhsMF4iWLA6YneoBR1xVKYYdAysHuepUB0OX4tdwMiUDdGKmig=="],
"@types/pg": ["@types/pg@8.23.1", "", { "dependencies": { "@types/node": "*", "pg-protocol": "*", "pg-types": "^2.2.0" } }, "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A=="],
@@ -2591,6 +2597,8 @@
"node-releases": ["node-releases@2.0.54", "", {}, "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ=="],
"nodemailer": ["nodemailer@10.0.10", "", {}, "sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A=="],
"normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
@@ -3239,6 +3247,10 @@
"@reduxjs/toolkit/reselect": ["reselect@5.3.0", "", {}, "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg=="],
"@shumai/core/@temporalio/activity": ["@temporalio/activity@1.24.0", "", { "dependencies": { "@temporalio/client": "1.24.0", "@temporalio/common": "1.24.0" } }, "sha512-eBBho/r9XHe2KczYGzmaSp6e9+6c9ta/GGOBldIBr00D/cV34kJ76iAY3Ue1pQTaP7YaX3phMuOz07uUg/IKyA=="],
"@shumai/core/@temporalio/workflow": ["@temporalio/workflow@1.24.0", "", { "dependencies": { "@temporalio/common": "1.24.0", "@temporalio/proto": "1.24.0", "nexus-rpc": "^0.0.3" } }, "sha512-pIA9nxkDCCbBnNuMSffQ44HWHYe3zXFfrDpDLwzh/FUSx8uLbsBM8jwf5oUMf+5eV/qVW9PknZhOu9IFO4XnPA=="],
"@shumai/webui/@types/react-dom": ["@types/react-dom@19.2.5", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-fMPwH9v7r/pp43yUd2/Mbiex5KouJwwR3dzHkhLREUC6764VyDsqxhAxv6OFEYR1RhjOyD1naqba8ECDBe7ZQg=="],
"@spectrum-web-components/action-button/@spectrum-web-components/icon": ["@spectrum-web-components/icon@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0", "@spectrum-web-components/iconset": "^0.37.0" } }, "sha512-DZ1yOKHxNQygzIJ7u9akYComDnMmxuTzfmYxxt9sHdUXmc1NbMkCJqEaAG/LYsdb+hc4xWaDTT9SzArLKZ/btA=="],
@@ -3489,6 +3501,14 @@
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="],
"@shumai/core/@temporalio/activity/@temporalio/client": ["@temporalio/client@1.24.0", "", { "dependencies": { "@grpc/grpc-js": "^1.12.4", "@temporalio/common": "1.24.0", "@temporalio/proto": "1.24.0", "abort-controller": "^3.0.0", "long": "^5.3.2", "nexus-rpc": "^0.0.3", "uuid": "^11.1.0" } }, "sha512-/GGg6ZYl+pN/bQEvq414CyjDvyM+MM1WsMzi/7SCYb3UlivVXx9nOmH/6BGx8OfYFayp11fkmfSh6rt7vW/ePQ=="],
"@shumai/core/@temporalio/activity/@temporalio/common": ["@temporalio/common@1.24.0", "", { "dependencies": { "@temporalio/proto": "1.24.0", "long": "^5.3.2", "ms": "3.0.0-canary.1", "nexus-rpc": "^0.0.3", "protobufjs": "^8.7.1" } }, "sha512-jXp77fXwynBcVNc/CaGMT33TVYnhcN26S959HDv7Q71oc0rN6d8RHWR5z0nRCDAu5CQwZQRRhVK0TRdyAiEg7Q=="],
"@shumai/core/@temporalio/workflow/@temporalio/common": ["@temporalio/common@1.24.0", "", { "dependencies": { "@temporalio/proto": "1.24.0", "long": "^5.3.2", "ms": "3.0.0-canary.1", "nexus-rpc": "^0.0.3", "protobufjs": "^8.7.1" } }, "sha512-jXp77fXwynBcVNc/CaGMT33TVYnhcN26S959HDv7Q71oc0rN6d8RHWR5z0nRCDAu5CQwZQRRhVK0TRdyAiEg7Q=="],
"@shumai/core/@temporalio/workflow/@temporalio/proto": ["@temporalio/proto@1.24.0", "", { "dependencies": { "long": "^5.3.2", "protobufjs": "^8.7.1" } }, "sha512-vhlhB9GpoyJx+78r3lDahHywpdri6LKx7kt7djLIw6XzHyb8FQTIi4lX8DSJBqKp3+HVfL1CLwiqO26KFRzg/g=="],
"@spectrum-web-components/action-button/@spectrum-web-components/icon/@spectrum-web-components/iconset": ["@spectrum-web-components/iconset@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0" } }, "sha512-s1TBjWeQtGdGf6n+r+aG2glv77IgR0pNs0HLusGyYt6jzWFkP276fE7Neqq/2XvG9a9zvAwngffnWS3td/Gtmg=="],
"@spectrum-web-components/action-group/@spectrum-web-components/icons-workflow/@spectrum-web-components/icon": ["@spectrum-web-components/icon@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0", "@spectrum-web-components/iconset": "^0.37.0" } }, "sha512-DZ1yOKHxNQygzIJ7u9akYComDnMmxuTzfmYxxt9sHdUXmc1NbMkCJqEaAG/LYsdb+hc4xWaDTT9SzArLKZ/btA=="],
@@ -3599,6 +3619,20 @@
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-use-controllable-state/@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
"@shumai/core/@temporalio/activity/@temporalio/client/@temporalio/proto": ["@temporalio/proto@1.24.0", "", { "dependencies": { "long": "^5.3.2", "protobufjs": "^8.7.1" } }, "sha512-vhlhB9GpoyJx+78r3lDahHywpdri6LKx7kt7djLIw6XzHyb8FQTIi4lX8DSJBqKp3+HVfL1CLwiqO26KFRzg/g=="],
"@shumai/core/@temporalio/activity/@temporalio/common/@temporalio/proto": ["@temporalio/proto@1.24.0", "", { "dependencies": { "long": "^5.3.2", "protobufjs": "^8.7.1" } }, "sha512-vhlhB9GpoyJx+78r3lDahHywpdri6LKx7kt7djLIw6XzHyb8FQTIi4lX8DSJBqKp3+HVfL1CLwiqO26KFRzg/g=="],
"@shumai/core/@temporalio/activity/@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="],
"@shumai/core/@temporalio/activity/@temporalio/common/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
"@shumai/core/@temporalio/workflow/@temporalio/common/ms": ["ms@3.0.0-canary.1", "", {}, "sha512-kh8ARjh8rMN7Du2igDRO9QJnqCb2xYTJxyQYK7vJJS4TvLLmsbyhiKpSW+t+y26gyOyMd0riphX0GeWKU3ky5g=="],
"@shumai/core/@temporalio/workflow/@temporalio/common/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
"@shumai/core/@temporalio/workflow/@temporalio/proto/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
"@spectrum-web-components/action-group/@spectrum-web-components/icons-workflow/@spectrum-web-components/icon/@spectrum-web-components/iconset": ["@spectrum-web-components/iconset@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0" } }, "sha512-s1TBjWeQtGdGf6n+r+aG2glv77IgR0pNs0HLusGyYt6jzWFkP276fE7Neqq/2XvG9a9zvAwngffnWS3td/Gtmg=="],
"@spectrum-web-components/card/@spectrum-web-components/icons-workflow/@spectrum-web-components/icon/@spectrum-web-components/iconset": ["@spectrum-web-components/iconset@0.37.0", "", { "dependencies": { "@spectrum-web-components/base": "^0.37.0" } }, "sha512-s1TBjWeQtGdGf6n+r+aG2glv77IgR0pNs0HLusGyYt6jzWFkP276fE7Neqq/2XvG9a9zvAwngffnWS3td/Gtmg=="],
@@ -3620,5 +3654,7 @@
"readdir-glob/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"@prisma/studio-core/@radix-ui/react-toggle/@radix-ui/react-primitive/@radix-ui/react-slot/@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
"@shumai/core/@temporalio/activity/@temporalio/client/@temporalio/proto/protobufjs": ["protobufjs@8.8.0", "", { "dependencies": { "long": "^5.3.2" } }, "sha512-N3xhQ5yyBx3vQq4gubBfASzYhJGNzeDbjqBpu61g7UVylsN/qyffU96TKWD3GbbLOKF82VGNRNvv1+BFgE31Eg=="],
}
}
+110 -7
View File
@@ -2,27 +2,34 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import notificationRoute from './notification'
import { notificationService } from '@shumai/core/src/notification/notification'
import { emailService } from '@shumai/core/src/notification/email'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
const mockUser = { id: 'user1', name: 'Test User', email: 'test@example.com' }
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
c: Context<{ Variables: { user: { id: string; name: string } } }>,
next: Next,
) => {
c.set('user', { id: 'user1', name: 'Test User' })
authMiddleware: async (c: Context<{ Variables: { user: typeof mockUser } }>, next: Next) => {
c.set('user', mockUser)
await next()
},
}))
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/notification/notification')
vi.mock('@shumai/core/src/notification/email', () => ({
emailService: {
getEmailSettings: vi.fn(),
updateEmailSettings: vi.fn(),
sendTestEmail: vi.fn(),
},
}))
vi.mock('@shumai/core/src/user-metadata/user-metadata')
describe('notification api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
const app = new Hono<{ Variables: { user: typeof mockUser } }>()
.use('*', async (c, next) => {
c.set('user', { id: 'user1', name: 'Test User' })
c.set('user', mockUser)
await next()
})
.route('/', notificationRoute)
@@ -155,4 +162,100 @@ describe('notification api', () => {
},
)
})
it('GET /teams/:teamId/notifications/email - requires admin and returns settings', async () => {
const mockSettings = {
enabled: true,
host: 'smtp.example.com',
port: 587,
username: 'user',
password: 'secret-password',
smtps: true,
ignoreCert: false,
from: 'noreply@example.com',
replyTo: '',
}
vi.mocked(emailService.getEmailSettings).mockResolvedValue(mockSettings)
const res = await app.request('/teams/t1/notifications/email')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual(mockSettings)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.objectContaining({ id: 'user1' }),
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
})
expect(emailService.getEmailSettings).toHaveBeenCalledWith('t1')
})
it('PUT /teams/:teamId/notifications/email - requires admin and updates settings', async () => {
const updateInput = {
enabled: true,
host: 'mail.example.com',
port: 465,
username: 'user',
password: 'new-password',
smtps: true,
ignoreCert: false,
from: 'shumai@example.com',
replyTo: 'support@example.com',
}
vi.mocked(emailService.updateEmailSettings).mockResolvedValue(updateInput)
const res = await app.request('/teams/t1/notifications/email', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updateInput),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual(updateInput)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.objectContaining({ id: 'user1' }),
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
})
expect(emailService.updateEmailSettings).toHaveBeenCalledWith('t1', updateInput)
})
it('POST /teams/:teamId/notifications/email/test - requires admin and sends test email', async () => {
const testReq = {
host: 'smtp.example.com',
port: 587,
from: 'noreply@example.com',
}
vi.mocked(emailService.sendTestEmail).mockResolvedValue({
success: true,
messageId: '<test-msg-id@example.com>',
})
const res = await app.request('/teams/t1/notifications/email/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(testReq),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({
success: true,
messageId: '<test-msg-id@example.com>',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.objectContaining({ id: 'user1' }),
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
})
expect(emailService.sendTestEmail).toHaveBeenCalledWith(
't1',
expect.objectContaining({ id: 'user1', email: 'test@example.com' }),
testReq,
)
})
})
+55
View File
@@ -1,11 +1,14 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { notificationService } from '@shumai/core/src/notification/notification'
import { emailService } from '@shumai/core/src/notification/email'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import {
listNotificationsRequestSchema,
markNotificationReadRequestSchema,
notificationSettingsSchema,
updateEmailNotificationSettingsSchema,
testEmailRequestSchema,
} from '@shumai/dtos'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import type { Prisma } from '@shumai/db'
@@ -109,5 +112,57 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json({ success: true })
},
)
.get('/teams/:teamId/notifications/email', async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const settings = await emailService.getEmailSettings(teamId)
return c.json(settings)
})
.put(
'/teams/:teamId/notifications/email',
zValidator('json', updateEmailNotificationSettingsSchema),
async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const settings = await emailService.updateEmailSettings(teamId, req)
return c.json(settings)
},
)
.post(
'/teams/:teamId/notifications/email/test',
zValidator('json', testEmailRequestSchema),
async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const result = await emailService.sendTestEmail(teamId, user, req)
return c.json(result)
},
)
export default route
+21
View File
@@ -223,6 +223,27 @@ describe('team api', () => {
expect(mockGetSettings).toHaveBeenCalledWith('t1')
})
it('GET /teams/:teamId/settings does not return emailNotification to readers', async () => {
mockGetSettings.mockResolvedValue({
semanticSearchEnabled: false,
transcode: { videoStrategy: 'best_match', hardwareAcceleration: 'off', threads: 0 },
appearance: { hideAgent: false },
})
const res = await app.request('/teams/t1/settings')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.emailNotification).toBeUndefined()
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
})
it('PATCH /teams/:teamId/settings updates settings', async () => {
mockUpdateSettings.mockResolvedValue({ transcode: { videoStrategy: 'all' } })
+3 -1
View File
@@ -105,15 +105,17 @@ const route = new Hono<{ Variables: { user: User } }>()
await uploadService.confirmFileUpload(user.id, taskId, req)
if (!req.errorMessage) {
const context = await assetService.getAssetContext(req.fileId)
await notificationService.create({
type: NotificationType.successful_file_uploaded,
teamId: teamId,
projectId: context.projectId,
creatorId: user.id,
assetId: req.fileId,
taskId: taskId,
})
const context = await assetService.getAssetContext(req.fileId)
await auditLogService.logAction({
action: AuditAction.file_create,
teamId: teamId,
+4
View File
@@ -33,6 +33,8 @@
"@shumai/db": "workspace:*",
"@shumai/dtos": "workspace:*",
"@sinclair/typebox": "0.34.52",
"@temporalio/activity": "1.24.0",
"@temporalio/workflow": "1.24.0",
"adm-zip": "0.6.0",
"ai": "7.0.84",
"better-auth": "1.6.11",
@@ -43,6 +45,7 @@
"extract-zip": "2.0.1",
"hono": "4.13.5",
"jittered-fractional-indexing": "1.0.1",
"nodemailer": "10.0.10",
"pdfkit": "0.20.1",
"pino": "10.3.1",
"sharp": "0.35.4",
@@ -56,6 +59,7 @@
"@modelcontextprotocol/server": "2.0.0",
"@types/adm-zip": "0.5.8",
"@types/extract-zip": "2.0.3",
"@types/nodemailer": "8.0.2",
"@types/pdfkit": "0.17.6"
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ export * from './authz/authz'
export * from './collection/collection'
export * from './invite/invite'
export * from './metadata/metadata'
export * from './notification/notification'
export * from './notification/index'
export * from './project/project'
export * from './provider/provider'
export * from './s3/s3'
@@ -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 &quot;hero.png&quot; 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')
})
})
})
+919
View File
@@ -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)} &bull; 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)} &rarr;</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 &rarr;</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)} &bull; 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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
}
export const emailService = new EmailService()
+3
View File
@@ -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()
+32
View File
@@ -521,4 +521,36 @@ describe('TeamService', () => {
expect(result).toBe(false)
})
})
it('should not leak emailNotification or credentials in getSettings', async () => {
const team = await prisma.team.create({
data: {
name: 'Team With Credentials',
settings: {
transcode: {
videoStrategy: 'best_match',
hardwareAcceleration: 'off',
threads: 4,
},
appearance: {
hideAgent: true,
},
emailNotification: {
enabled: true,
host: 'smtp.secret.com',
port: 587,
password: 'super-secret-smtp-password',
from: 'noreply@secret.com',
},
},
},
})
const settings = await teamService.getSettings(team.id)
expect(settings).toBeDefined()
expect(settings.transcode?.threads).toBe(4)
expect(settings.appearance?.hideAgent).toBe(true)
expect((settings as Record<string, unknown>).emailNotification).toBeUndefined()
})
})
+7 -3
View File
@@ -298,7 +298,11 @@ export class TeamService {
where: { id: teamId },
})
if (!team) throw new HTTPException(404, { message: 'team not found' })
const settings = (team.settings || {}) as TeamSettingsResponse
const rawSettings = { ...(team.settings || {}) } as PrismaJson.Settings & {
[key: string]: unknown
}
delete rawSettings.emailNotification
const settings = rawSettings as TeamSettingsResponse
const embeddingAgent = await prisma.agent.findFirst({
where: { teamId, type: 'embedding', enabled: true },
@@ -360,12 +364,12 @@ export class TeamService {
settings[key] = value
}
const updated = await prisma.team.update({
await prisma.team.update({
where: { id: teamId },
data: { settings: settings as unknown as PrismaJson.Settings },
})
return (updated.settings || {}) as TeamSettingsResponse
return this.getSettings(teamId)
}
async getSandboxSettings(teamId: string): Promise<SandboxSettings> {
@@ -0,0 +1,11 @@
-- CreateEnum
CREATE TYPE "NotificationEmailStatus" AS ENUM ('pending', 'processing', 'processed', 'failed');
-- AlterTable
ALTER TABLE "notifications" ADD COLUMN "email_status" "NotificationEmailStatus" NOT NULL DEFAULT 'pending';
-- Update legacy rows to processed
UPDATE "notifications" SET "email_status" = 'processed';
-- CreateIndex
CREATE INDEX "notifications_email_status_created_at_idx" ON "notifications"("email_status", "created_at");
+10
View File
@@ -76,6 +76,13 @@ enum NotificationType {
kanban_task_comment_created
}
enum NotificationEmailStatus {
pending
processing
processed
failed
}
enum ProjectMemberRole {
owner
editor
@@ -776,9 +783,12 @@ model Notification {
userId String? @map("user_id")
user User? @relation("UserToNotification", fields: [userId], references: [id])
emailStatus NotificationEmailStatus @default(pending) @map("email_status")
readByMembers TeamMember? @relation("TeamMemberToLastReadNotification")
@@index([kanbanTaskId])
@@index([emailStatus, createdAt])
@@map("notifications")
}
+34
View File
@@ -538,6 +538,13 @@ export type EnumNotificationTypeNullableFilter<$PrismaModel = never> = {
not?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel> | $Enums.NotificationType | null
}
export type EnumNotificationEmailStatusFilter<$PrismaModel = never> = {
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel> | $Enums.NotificationEmailStatus
}
export type EnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.NotificationType | Prisma.EnumNotificationTypeFieldRefInput<$PrismaModel> | null
in?: $Enums.NotificationType[] | Prisma.ListEnumNotificationTypeFieldRefInput<$PrismaModel> | null
@@ -548,6 +555,16 @@ export type EnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel = neve
_max?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel>
}
export type EnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel> | $Enums.NotificationEmailStatus
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
_max?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
}
export type EnumTaskTypeNullableFilter<$PrismaModel = never> = {
equals?: $Enums.TaskType | Prisma.EnumTaskTypeFieldRefInput<$PrismaModel> | null
in?: $Enums.TaskType[] | Prisma.ListEnumTaskTypeFieldRefInput<$PrismaModel> | null
@@ -1367,6 +1384,13 @@ export type NestedEnumNotificationTypeNullableFilter<$PrismaModel = never> = {
not?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel> | $Enums.NotificationType | null
}
export type NestedEnumNotificationEmailStatusFilter<$PrismaModel = never> = {
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel> | $Enums.NotificationEmailStatus
}
export type NestedEnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.NotificationType | Prisma.EnumNotificationTypeFieldRefInput<$PrismaModel> | null
in?: $Enums.NotificationType[] | Prisma.ListEnumNotificationTypeFieldRefInput<$PrismaModel> | null
@@ -1377,6 +1401,16 @@ export type NestedEnumNotificationTypeNullableWithAggregatesFilter<$PrismaModel
_max?: Prisma.NestedEnumNotificationTypeNullableFilter<$PrismaModel>
}
export type NestedEnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel = never> = {
equals?: $Enums.NotificationEmailStatus | Prisma.EnumNotificationEmailStatusFieldRefInput<$PrismaModel>
in?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
notIn?: $Enums.NotificationEmailStatus[] | Prisma.ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel>
not?: Prisma.NestedEnumNotificationEmailStatusWithAggregatesFilter<$PrismaModel> | $Enums.NotificationEmailStatus
_count?: Prisma.NestedIntFilter<$PrismaModel>
_min?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
_max?: Prisma.NestedEnumNotificationEmailStatusFilter<$PrismaModel>
}
export type NestedEnumTaskTypeNullableFilter<$PrismaModel = never> = {
equals?: $Enums.TaskType | Prisma.EnumTaskTypeFieldRefInput<$PrismaModel> | null
in?: $Enums.TaskType[] | Prisma.ListEnumTaskTypeFieldRefInput<$PrismaModel> | null
+10
View File
@@ -87,6 +87,16 @@ export const NotificationType = {
export type NotificationType = (typeof NotificationType)[keyof typeof NotificationType]
export const NotificationEmailStatus = {
pending: 'pending',
processing: 'processing',
processed: 'processed',
failed: 'failed'
} as const
export type NotificationEmailStatus = (typeof NotificationEmailStatus)[keyof typeof NotificationEmailStatus]
export const ProjectMemberRole = {
owner: 'owner',
editor: 'editor',
File diff suppressed because one or more lines are too long
+16 -1
View File
@@ -4724,7 +4724,8 @@ export const NotificationScalarFieldEnum = {
assetId: 'assetId',
taskId: 'taskId',
kanbanTaskId: 'kanbanTaskId',
userId: 'userId'
userId: 'userId',
emailStatus: 'emailStatus'
} as const
export type NotificationScalarFieldEnum = (typeof NotificationScalarFieldEnum)[keyof typeof NotificationScalarFieldEnum]
@@ -5421,6 +5422,20 @@ export type ListEnumNotificationTypeFieldRefInput<$PrismaModel> = FieldRefInputT
/**
* Reference to a field of type 'NotificationEmailStatus'
*/
export type EnumNotificationEmailStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationEmailStatus'>
/**
* Reference to a field of type 'NotificationEmailStatus[]'
*/
export type ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationEmailStatus[]'>
/**
* Reference to a field of type 'TaskType'
*/
@@ -490,7 +490,8 @@ export const NotificationScalarFieldEnum = {
assetId: 'assetId',
taskId: 'taskId',
kanbanTaskId: 'kanbanTaskId',
userId: 'userId'
userId: 'userId',
emailStatus: 'emailStatus'
} as const
export type NotificationScalarFieldEnum = (typeof NotificationScalarFieldEnum)[keyof typeof NotificationScalarFieldEnum]
+80 -1
View File
@@ -38,6 +38,7 @@ export type NotificationMinAggregateOutputType = {
taskId: string | null
kanbanTaskId: string | null
userId: string | null
emailStatus: $Enums.NotificationEmailStatus | null
}
export type NotificationMaxAggregateOutputType = {
@@ -52,6 +53,7 @@ export type NotificationMaxAggregateOutputType = {
taskId: string | null
kanbanTaskId: string | null
userId: string | null
emailStatus: $Enums.NotificationEmailStatus | null
}
export type NotificationCountAggregateOutputType = {
@@ -66,6 +68,7 @@ export type NotificationCountAggregateOutputType = {
taskId: number
kanbanTaskId: number
userId: number
emailStatus: number
_all: number
}
@@ -82,6 +85,7 @@ export type NotificationMinAggregateInputType = {
taskId?: true
kanbanTaskId?: true
userId?: true
emailStatus?: true
}
export type NotificationMaxAggregateInputType = {
@@ -96,6 +100,7 @@ export type NotificationMaxAggregateInputType = {
taskId?: true
kanbanTaskId?: true
userId?: true
emailStatus?: true
}
export type NotificationCountAggregateInputType = {
@@ -110,6 +115,7 @@ export type NotificationCountAggregateInputType = {
taskId?: true
kanbanTaskId?: true
userId?: true
emailStatus?: true
_all?: true
}
@@ -197,6 +203,7 @@ export type NotificationGroupByOutputType = {
taskId: string | null
kanbanTaskId: string | null
userId: string | null
emailStatus: $Enums.NotificationEmailStatus
_count: NotificationCountAggregateOutputType | null
_min: NotificationMinAggregateOutputType | null
_max: NotificationMaxAggregateOutputType | null
@@ -232,6 +239,7 @@ export type NotificationWhereInput = {
taskId?: Prisma.StringNullableFilter<"Notification"> | string | null
kanbanTaskId?: Prisma.StringNullableFilter<"Notification"> | string | null
userId?: Prisma.StringNullableFilter<"Notification"> | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFilter<"Notification"> | $Enums.NotificationEmailStatus
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
project?: Prisma.XOR<Prisma.ProjectNullableScalarRelationFilter, Prisma.ProjectWhereInput> | null
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
@@ -254,6 +262,7 @@ export type NotificationOrderByWithRelationInput = {
taskId?: Prisma.SortOrderInput | Prisma.SortOrder
kanbanTaskId?: Prisma.SortOrderInput | Prisma.SortOrder
userId?: Prisma.SortOrderInput | Prisma.SortOrder
emailStatus?: Prisma.SortOrder
team?: Prisma.TeamOrderByWithRelationInput
project?: Prisma.ProjectOrderByWithRelationInput
creator?: Prisma.UserOrderByWithRelationInput
@@ -279,6 +288,7 @@ export type NotificationWhereUniqueInput = Prisma.AtLeast<{
taskId?: Prisma.StringNullableFilter<"Notification"> | string | null
kanbanTaskId?: Prisma.StringNullableFilter<"Notification"> | string | null
userId?: Prisma.StringNullableFilter<"Notification"> | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFilter<"Notification"> | $Enums.NotificationEmailStatus
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
project?: Prisma.XOR<Prisma.ProjectNullableScalarRelationFilter, Prisma.ProjectWhereInput> | null
creator?: Prisma.XOR<Prisma.UserNullableScalarRelationFilter, Prisma.UserWhereInput> | null
@@ -301,6 +311,7 @@ export type NotificationOrderByWithAggregationInput = {
taskId?: Prisma.SortOrderInput | Prisma.SortOrder
kanbanTaskId?: Prisma.SortOrderInput | Prisma.SortOrder
userId?: Prisma.SortOrderInput | Prisma.SortOrder
emailStatus?: Prisma.SortOrder
_count?: Prisma.NotificationCountOrderByAggregateInput
_max?: Prisma.NotificationMaxOrderByAggregateInput
_min?: Prisma.NotificationMinOrderByAggregateInput
@@ -321,6 +332,7 @@ export type NotificationScalarWhereWithAggregatesInput = {
taskId?: Prisma.StringNullableWithAggregatesFilter<"Notification"> | string | null
kanbanTaskId?: Prisma.StringNullableWithAggregatesFilter<"Notification"> | string | null
userId?: Prisma.StringNullableWithAggregatesFilter<"Notification"> | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusWithAggregatesFilter<"Notification"> | $Enums.NotificationEmailStatus
}
export type NotificationCreateInput = {
@@ -328,6 +340,7 @@ export type NotificationCreateInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
@@ -350,6 +363,7 @@ export type NotificationUncheckedCreateInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -358,6 +372,7 @@ export type NotificationUpdateInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
@@ -380,6 +395,7 @@ export type NotificationUncheckedUpdateInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -395,6 +411,7 @@ export type NotificationCreateManyInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationUpdateManyMutationInput = {
@@ -402,6 +419,7 @@ export type NotificationUpdateManyMutationInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationUncheckedUpdateManyInput = {
@@ -416,6 +434,7 @@ export type NotificationUncheckedUpdateManyInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationListRelationFilter = {
@@ -445,6 +464,7 @@ export type NotificationCountOrderByAggregateInput = {
taskId?: Prisma.SortOrder
kanbanTaskId?: Prisma.SortOrder
userId?: Prisma.SortOrder
emailStatus?: Prisma.SortOrder
}
export type NotificationMaxOrderByAggregateInput = {
@@ -459,6 +479,7 @@ export type NotificationMaxOrderByAggregateInput = {
taskId?: Prisma.SortOrder
kanbanTaskId?: Prisma.SortOrder
userId?: Prisma.SortOrder
emailStatus?: Prisma.SortOrder
}
export type NotificationMinOrderByAggregateInput = {
@@ -473,6 +494,7 @@ export type NotificationMinOrderByAggregateInput = {
taskId?: Prisma.SortOrder
kanbanTaskId?: Prisma.SortOrder
userId?: Prisma.SortOrder
emailStatus?: Prisma.SortOrder
}
export type NotificationCreateNestedManyWithoutCreatorInput = {
@@ -705,6 +727,10 @@ export type NullableEnumNotificationTypeFieldUpdateOperationsInput = {
set?: $Enums.NotificationType | null
}
export type EnumNotificationEmailStatusFieldUpdateOperationsInput = {
set?: $Enums.NotificationEmailStatus
}
export type NotificationCreateNestedManyWithoutTaskInput = {
create?: Prisma.XOR<Prisma.NotificationCreateWithoutTaskInput, Prisma.NotificationUncheckedCreateWithoutTaskInput> | Prisma.NotificationCreateWithoutTaskInput[] | Prisma.NotificationUncheckedCreateWithoutTaskInput[]
connectOrCreate?: Prisma.NotificationCreateOrConnectWithoutTaskInput | Prisma.NotificationCreateOrConnectWithoutTaskInput[]
@@ -794,6 +820,7 @@ export type NotificationCreateWithoutCreatorInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
asset?: Prisma.AssetCreateNestedOneWithoutNotificationsInput
@@ -814,6 +841,7 @@ export type NotificationUncheckedCreateWithoutCreatorInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -832,6 +860,7 @@ export type NotificationCreateWithoutUserInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
@@ -852,6 +881,7 @@ export type NotificationUncheckedCreateWithoutUserInput = {
assetId?: string | null
taskId?: string | null
kanbanTaskId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -896,6 +926,7 @@ export type NotificationScalarWhereInput = {
taskId?: Prisma.StringNullableFilter<"Notification"> | string | null
kanbanTaskId?: Prisma.StringNullableFilter<"Notification"> | string | null
userId?: Prisma.StringNullableFilter<"Notification"> | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFilter<"Notification"> | $Enums.NotificationEmailStatus
}
export type NotificationUpsertWithWhereUniqueWithoutUserInput = {
@@ -919,6 +950,7 @@ export type NotificationCreateWithoutTeamInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
asset?: Prisma.AssetCreateNestedOneWithoutNotificationsInput
@@ -939,6 +971,7 @@ export type NotificationUncheckedCreateWithoutTeamInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -973,6 +1006,7 @@ export type NotificationCreateWithoutReadByMembersInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
@@ -994,6 +1028,7 @@ export type NotificationUncheckedCreateWithoutReadByMembersInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationCreateOrConnectWithoutReadByMembersInput = {
@@ -1017,6 +1052,7 @@ export type NotificationUpdateWithoutReadByMembersInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
@@ -1038,6 +1074,7 @@ export type NotificationUncheckedUpdateWithoutReadByMembersInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationCreateWithoutProjectInput = {
@@ -1045,6 +1082,7 @@ export type NotificationCreateWithoutProjectInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
asset?: Prisma.AssetCreateNestedOneWithoutNotificationsInput
@@ -1065,6 +1103,7 @@ export type NotificationUncheckedCreateWithoutProjectInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -1099,6 +1138,7 @@ export type NotificationCreateWithoutAssetInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
@@ -1119,6 +1159,7 @@ export type NotificationUncheckedCreateWithoutAssetInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -1153,6 +1194,7 @@ export type NotificationCreateWithoutTaskInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
@@ -1173,6 +1215,7 @@ export type NotificationUncheckedCreateWithoutTaskInput = {
assetId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -1207,6 +1250,7 @@ export type NotificationCreateWithoutKanbanTaskInput = {
type?: $Enums.NotificationType | null
createdAt?: Date | string
updatedAt?: Date | string
emailStatus?: $Enums.NotificationEmailStatus
team: Prisma.TeamCreateNestedOneWithoutNotificationsInput
project?: Prisma.ProjectCreateNestedOneWithoutNotificationsInput
creator?: Prisma.UserCreateNestedOneWithoutCreatedNotificationsInput
@@ -1227,6 +1271,7 @@ export type NotificationUncheckedCreateWithoutKanbanTaskInput = {
assetId?: string | null
taskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedCreateNestedOneWithoutLastReadNotificationInput
}
@@ -1267,6 +1312,7 @@ export type NotificationCreateManyCreatorInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationCreateManyUserInput = {
@@ -1280,6 +1326,7 @@ export type NotificationCreateManyUserInput = {
assetId?: string | null
taskId?: string | null
kanbanTaskId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationUpdateWithoutCreatorInput = {
@@ -1287,6 +1334,7 @@ export type NotificationUpdateWithoutCreatorInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
asset?: Prisma.AssetUpdateOneWithoutNotificationsNestedInput
@@ -1307,6 +1355,7 @@ export type NotificationUncheckedUpdateWithoutCreatorInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -1321,6 +1370,7 @@ export type NotificationUncheckedUpdateManyWithoutCreatorInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationUpdateWithoutUserInput = {
@@ -1328,6 +1378,7 @@ export type NotificationUpdateWithoutUserInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
@@ -1348,6 +1399,7 @@ export type NotificationUncheckedUpdateWithoutUserInput = {
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -1362,6 +1414,7 @@ export type NotificationUncheckedUpdateManyWithoutUserInput = {
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationCreateManyTeamInput = {
@@ -1375,6 +1428,7 @@ export type NotificationCreateManyTeamInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationUpdateWithoutTeamInput = {
@@ -1382,6 +1436,7 @@ export type NotificationUpdateWithoutTeamInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
asset?: Prisma.AssetUpdateOneWithoutNotificationsNestedInput
@@ -1402,6 +1457,7 @@ export type NotificationUncheckedUpdateWithoutTeamInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -1416,6 +1472,7 @@ export type NotificationUncheckedUpdateManyWithoutTeamInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationCreateManyProjectInput = {
@@ -1429,6 +1486,7 @@ export type NotificationCreateManyProjectInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationUpdateWithoutProjectInput = {
@@ -1436,6 +1494,7 @@ export type NotificationUpdateWithoutProjectInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
asset?: Prisma.AssetUpdateOneWithoutNotificationsNestedInput
@@ -1456,6 +1515,7 @@ export type NotificationUncheckedUpdateWithoutProjectInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -1470,6 +1530,7 @@ export type NotificationUncheckedUpdateManyWithoutProjectInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationCreateManyAssetInput = {
@@ -1483,6 +1544,7 @@ export type NotificationCreateManyAssetInput = {
taskId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationUpdateWithoutAssetInput = {
@@ -1490,6 +1552,7 @@ export type NotificationUpdateWithoutAssetInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
@@ -1510,6 +1573,7 @@ export type NotificationUncheckedUpdateWithoutAssetInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -1524,6 +1588,7 @@ export type NotificationUncheckedUpdateManyWithoutAssetInput = {
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationCreateManyTaskInput = {
@@ -1537,6 +1602,7 @@ export type NotificationCreateManyTaskInput = {
assetId?: string | null
kanbanTaskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationUpdateWithoutTaskInput = {
@@ -1544,6 +1610,7 @@ export type NotificationUpdateWithoutTaskInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
@@ -1564,6 +1631,7 @@ export type NotificationUncheckedUpdateWithoutTaskInput = {
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -1578,6 +1646,7 @@ export type NotificationUncheckedUpdateManyWithoutTaskInput = {
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
kanbanTaskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
export type NotificationCreateManyKanbanTaskInput = {
@@ -1591,6 +1660,7 @@ export type NotificationCreateManyKanbanTaskInput = {
assetId?: string | null
taskId?: string | null
userId?: string | null
emailStatus?: $Enums.NotificationEmailStatus
}
export type NotificationUpdateWithoutKanbanTaskInput = {
@@ -1598,6 +1668,7 @@ export type NotificationUpdateWithoutKanbanTaskInput = {
type?: Prisma.NullableEnumNotificationTypeFieldUpdateOperationsInput | $Enums.NotificationType | null
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
team?: Prisma.TeamUpdateOneRequiredWithoutNotificationsNestedInput
project?: Prisma.ProjectUpdateOneWithoutNotificationsNestedInput
creator?: Prisma.UserUpdateOneWithoutCreatedNotificationsNestedInput
@@ -1618,6 +1689,7 @@ export type NotificationUncheckedUpdateWithoutKanbanTaskInput = {
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
readByMembers?: Prisma.TeamMemberUncheckedUpdateOneWithoutLastReadNotificationNestedInput
}
@@ -1632,6 +1704,7 @@ export type NotificationUncheckedUpdateManyWithoutKanbanTaskInput = {
assetId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
taskId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
userId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
emailStatus?: Prisma.EnumNotificationEmailStatusFieldUpdateOperationsInput | $Enums.NotificationEmailStatus
}
@@ -1648,6 +1721,7 @@ export type NotificationSelect<ExtArgs extends runtime.Types.Extensions.Internal
taskId?: boolean
kanbanTaskId?: boolean
userId?: boolean
emailStatus?: boolean
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
creator?: boolean | Prisma.Notification$creatorArgs<ExtArgs>
@@ -1670,6 +1744,7 @@ export type NotificationSelectCreateManyAndReturn<ExtArgs extends runtime.Types.
taskId?: boolean
kanbanTaskId?: boolean
userId?: boolean
emailStatus?: boolean
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
creator?: boolean | Prisma.Notification$creatorArgs<ExtArgs>
@@ -1691,6 +1766,7 @@ export type NotificationSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.
taskId?: boolean
kanbanTaskId?: boolean
userId?: boolean
emailStatus?: boolean
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
creator?: boolean | Prisma.Notification$creatorArgs<ExtArgs>
@@ -1712,9 +1788,10 @@ export type NotificationSelectScalar = {
taskId?: boolean
kanbanTaskId?: boolean
userId?: boolean
emailStatus?: boolean
}
export type NotificationOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "createdAt" | "updatedAt" | "teamId" | "projectId" | "creatorId" | "assetId" | "taskId" | "kanbanTaskId" | "userId", ExtArgs["result"]["notification"]>
export type NotificationOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "createdAt" | "updatedAt" | "teamId" | "projectId" | "creatorId" | "assetId" | "taskId" | "kanbanTaskId" | "userId" | "emailStatus", ExtArgs["result"]["notification"]>
export type NotificationInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
project?: boolean | Prisma.Notification$projectArgs<ExtArgs>
@@ -1768,6 +1845,7 @@ export type $NotificationPayload<ExtArgs extends runtime.Types.Extensions.Intern
taskId: string | null
kanbanTaskId: string | null
userId: string | null
emailStatus: $Enums.NotificationEmailStatus
}, ExtArgs["result"]["notification"]>
composites: {}
}
@@ -2210,6 +2288,7 @@ export interface NotificationFieldRefs {
readonly taskId: Prisma.FieldRef<"Notification", 'String'>
readonly kanbanTaskId: Prisma.FieldRef<"Notification", 'String'>
readonly userId: Prisma.FieldRef<"Notification", 'String'>
readonly emailStatus: Prisma.FieldRef<"Notification", 'NotificationEmailStatus'>
}
+14 -1
View File
@@ -85,10 +85,23 @@ declare global {
hideAgent?: boolean
}
export interface EmailNotificationSettings {
enabled: boolean
host?: string
port?: number
username?: string
password?: string
smtps?: boolean
ignoreCert?: boolean
from?: string
replyTo?: string
}
export interface Settings {
transcode: TranscodeSettings
transcode?: TranscodeSettings
mediaGeneration?: MediaGenerationSettings
appearance?: AppearanceSettings
emailNotification?: EmailNotificationSettings
}
// ----------------------------------------------------------------------
+48
View File
@@ -99,3 +99,51 @@ export const notificationSettingsSchema = z.object({
})
export type NotificationSettings = z.infer<typeof notificationSettingsSchema>
export const emailNotificationSettingsSchema = z.object({
enabled: z.boolean(),
host: z.string().default(''),
port: z.number().int().min(1).max(65535).default(587),
username: z.string().optional(),
password: z.string().optional(),
smtps: z.boolean().default(false),
ignoreCert: z.boolean().default(false),
from: z.string().default(''),
replyTo: z.string().optional(),
})
export type EmailNotificationSettings = z.infer<typeof emailNotificationSettingsSchema>
export const updateEmailNotificationSettingsSchema = z.object({
enabled: z.boolean(),
host: z.string().default(''),
port: z.number().int().min(1).max(65535).default(587),
username: z.string().optional(),
password: z.string().optional(),
smtps: z.boolean().default(false),
ignoreCert: z.boolean().default(false),
from: z.string().default(''),
replyTo: z.string().optional(),
})
export type UpdateEmailNotificationSettings = z.input<typeof updateEmailNotificationSettingsSchema>
export const testEmailRequestSchema = z.object({
host: z.string().optional(),
port: z.number().int().min(1).max(65535).optional(),
username: z.string().optional(),
password: z.string().optional(),
smtps: z.boolean().optional(),
ignoreCert: z.boolean().optional(),
from: z.string().optional(),
replyTo: z.string().optional(),
})
export type TestEmailRequest = z.infer<typeof testEmailRequestSchema>
export const testEmailResponseSchema = z.object({
success: z.boolean(),
messageId: z.string(),
})
export type TestEmailResponse = z.infer<typeof testEmailResponseSchema>
@@ -0,0 +1,239 @@
// @vitest-environment happy-dom
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { EmailNotificationSettings } from './EmailNotificationSettings'
import type { EmailNotificationSettings as Settings } from '@shumai/dtos'
import { toast } from 'sonner'
const mockGetSettings = vi.fn()
const mockPutSettings = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
notifications: {
email: {
$get: () => mockGetSettings(),
$put: (args: unknown) => mockPutSettings(args),
},
},
},
},
},
},
}))
vi.mock('./TestEmailDialog', () => ({
TestEmailDialog: ({
isOpen,
defaultFrom,
}: {
isOpen: boolean
onClose: () => void
teamId: string
defaultFrom?: string
}) =>
isOpen ? (
<div data-testid="mock-test-email-dialog" data-from={defaultFrom}>
Test Email Dialog Content
</div>
) : null,
}))
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
describe('EmailNotificationSettings', () => {
const initialSettings: Settings = {
enabled: false,
host: 'smtp.example.com',
port: 587,
username: 'smtpuser',
password: '••••••••',
smtps: false,
ignoreCert: false,
from: 'Shumai <noreply@example.com>',
replyTo: 'support@example.com',
}
beforeEach(() => {
vi.clearAllMocks()
mockGetSettings.mockResolvedValue({
ok: true,
json: async () => initialSettings,
})
mockPutSettings.mockResolvedValue({
ok: true,
json: async () => ({ ...initialSettings, enabled: true }),
})
})
afterEach(() => {
cleanup()
})
function renderComponent() {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
return render(
<QueryClientProvider client={queryClient}>
<EmailNotificationSettings teamId="team-1" />
</QueryClientProvider>,
)
}
it('renders initial settings properly', async () => {
renderComponent()
await waitFor(() => {
expect(screen.getByText(/enable email notifications/i)).toBeDefined()
})
expect(screen.getByText(/smtp server settings/i)).toBeDefined()
expect(screen.getByText(/sender information/i)).toBeDefined()
// Host input should have the value from initial settings
const hostInput = screen.getByLabelText(/smtp host/i) as HTMLInputElement
expect(hostInput.value).toBe('smtp.example.com')
expect(hostInput.disabled).toBe(true) // Disabled because enabled is false
// Buttons
expect(screen.getByRole('button', { name: /^save$/i })).toBeDefined()
expect(screen.getByRole('button', { name: /save & send test email/i })).toBeDefined()
})
it('enables form inputs when enable switch is toggled', async () => {
renderComponent()
await waitFor(() => {
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
})
const hostInput = screen.getByLabelText(/smtp host/i) as HTMLInputElement
expect(hostInput.disabled).toBe(true)
// Toggle the enable switch
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
fireEvent.click(enableSwitch)
await waitFor(() => {
expect(hostInput.disabled).toBe(false)
})
})
it('saves settings successfully when Save button is clicked', async () => {
renderComponent()
await waitFor(() => {
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
})
// Enable first
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
fireEvent.click(enableSwitch)
// Edit host
const hostInput = screen.getByLabelText(/smtp host/i)
fireEvent.change(hostInput, { target: { value: 'mail.mycompany.com' } })
// Click Save
const saveButton = screen.getByRole('button', { name: /^save$/i })
fireEvent.click(saveButton)
await waitFor(() => {
expect(mockPutSettings).toHaveBeenCalledWith({
param: { teamId: 'team-1' },
json: expect.objectContaining({
enabled: true,
host: 'mail.mycompany.com',
port: 587,
}),
})
expect(toast.success).toHaveBeenCalled()
})
})
it('shows error toast when save fails', async () => {
mockPutSettings.mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'Invalid SMTP configuration' }),
})
renderComponent()
await waitFor(() => {
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
})
const saveButton = screen.getByRole('button', { name: /^save$/i })
fireEvent.click(saveButton)
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith('Invalid SMTP configuration')
})
})
it('saves settings first and opens TestEmailDialog on "Save & Send Test Email"', async () => {
renderComponent()
await waitFor(() => {
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
})
// Enable switch so button is active
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
fireEvent.click(enableSwitch)
const saveAndTestButton = screen.getByRole('button', { name: /save & send test email/i })
fireEvent.click(saveAndTestButton)
// Should call save first
await waitFor(() => {
expect(mockPutSettings).toHaveBeenCalled()
expect(toast.success).toHaveBeenCalled()
})
// Mock dialog should be opened with defaultFrom
await waitFor(() => {
const dialog = screen.getByTestId('mock-test-email-dialog')
expect(dialog).toBeDefined()
expect(dialog.getAttribute('data-from')).toBe('Shumai <noreply@example.com>')
})
})
it('validates required host when clicking "Save & Send Test Email"', async () => {
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => ({ ...initialSettings, host: '' }),
})
renderComponent()
await waitFor(() => {
expect(screen.getByLabelText(/smtp host/i)).toBeDefined()
})
const enableSwitch = screen.getByRole('switch', { name: /enable email notifications/i })
fireEvent.click(enableSwitch)
const saveAndTestButton = screen.getByRole('button', { name: /save & send test email/i })
fireEvent.click(saveAndTestButton)
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/host is required/i))
expect(mockPutSettings).not.toHaveBeenCalled()
})
})
})
@@ -0,0 +1,348 @@
import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { Card, CardContent, CardFooter } from '@/ui/components/ui/card'
import { Switch } from '@/ui/components/ui/switch'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import type { EmailNotificationSettings as Settings } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import { TestEmailDialog } from '@/ui/components/settings/TestEmailDialog'
interface EmailNotificationSettingsProps {
teamId: string
}
export function EmailNotificationSettings({ teamId }: EmailNotificationSettingsProps) {
const queryClient = useQueryClient()
const [formData, setFormData] = useState<Settings>({
enabled: false,
host: '',
port: 587,
username: '',
password: '',
smtps: false,
ignoreCert: false,
from: '',
replyTo: '',
})
const [isTestDialogOpen, setIsTestDialogOpen] = useState(false)
const {
data: settings,
isLoading,
error,
} = useQuery<Settings>({
queryKey: ['teams', teamId, 'email-settings'],
queryFn: async () => {
const res = await client.api.teams[':teamId'].notifications.email.$get({
param: { teamId },
})
if (!res.ok) throw new Error(m.failed_to_load_email_settings())
return (await res.json()) as Settings
},
enabled: !!teamId,
})
useEffect(() => {
if (settings) {
setFormData({
enabled: settings.enabled ?? false,
host: settings.host ?? '',
port: settings.port ?? 587,
username: settings.username ?? '',
password: '',
smtps: settings.smtps ?? false,
ignoreCert: settings.ignoreCert ?? false,
from: settings.from ?? '',
replyTo: settings.replyTo ?? '',
})
}
}, [settings])
const { mutateAsync: saveSettings, isPending: isSaving } = useMutation({
mutationFn: async (dataToSave: Settings) => {
const res = await client.api.teams[':teamId'].notifications.email.$put({
param: { teamId },
json: {
enabled: dataToSave.enabled,
host: dataToSave.host,
port: dataToSave.port,
username: dataToSave.username || '',
password: dataToSave.password || '',
smtps: dataToSave.smtps,
ignoreCert: dataToSave.ignoreCert,
from: dataToSave.from,
replyTo: dataToSave.replyTo || '',
},
})
if (!res.ok) {
const err = (await res.json().catch(() => null)) as { message?: string } | null
throw new Error(err?.message || m.failed_to_save_email_settings())
}
return (await res.json()) as Settings
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'email-settings'] })
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'settings'] })
},
})
const handleSave = async () => {
try {
await saveSettings(formData)
toast.success(m.email_settings_saved())
} catch (err) {
toast.error(err instanceof Error ? err.message : m.failed_to_save_email_settings())
}
}
const handleSaveAndTest = async () => {
if (!formData.host.trim()) {
toast.error(m.smtp_host_required())
return
}
try {
await saveSettings(formData)
toast.success(m.email_settings_saved())
setIsTestDialogOpen(true)
} catch (err) {
toast.error(err instanceof Error ? err.message : m.failed_to_save_email_settings())
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)
}
if (error) {
return (
<div className="p-8 text-center text-destructive">
{error instanceof Error ? error.message : m.failed_to_load_email_settings()}
</div>
)
}
return (
<>
<ScrollArea className="h-full">
<div className="space-y-6 pr-4 pb-8">
<Card>
<CardContent className="space-y-6 pt-6">
{/* Enable Switch */}
<div className="flex items-center justify-between space-x-4 rounded-lg border border-border p-4">
<div className="space-y-1">
<label
htmlFor="enable-email-switch"
className="text-sm font-medium leading-none cursor-pointer"
>
{m.enable_email_notifications()}
</label>
<p className="text-xs text-muted-foreground">
{m.enable_email_notifications_description()}
</p>
</div>
<Switch
id="enable-email-switch"
checked={formData.enabled}
onCheckedChange={(checked) => setFormData({ ...formData, enabled: checked })}
/>
</div>
{/* SMTP Server Settings */}
<div className="space-y-4 pt-2">
<h4 className="text-sm font-semibold text-foreground">{m.smtp_settings()}</h4>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2 md:col-span-2">
<label
htmlFor="smtp-host-input"
className="text-sm font-medium text-foreground"
>
{m.smtp_host()}
</label>
<Input
id="smtp-host-input"
value={formData.host}
onChange={(e) => setFormData({ ...formData, host: e.target.value })}
placeholder={m.smtp_host_placeholder()}
disabled={!formData.enabled}
/>
</div>
<div className="space-y-2">
<label
htmlFor="smtp-port-input"
className="text-sm font-medium text-foreground"
>
{m.smtp_port()}
</label>
<Input
id="smtp-port-input"
type="number"
value={formData.port}
onChange={(e) =>
setFormData({
...formData,
port: parseInt(e.target.value, 10) || 587,
})
}
disabled={!formData.enabled}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<label
htmlFor="smtp-username-input"
className="text-sm font-medium text-foreground"
>
{m.smtp_username()}
</label>
<Input
id="smtp-username-input"
value={formData.username || ''}
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
placeholder={m.smtp_username_placeholder()}
disabled={!formData.enabled}
autoComplete="off"
/>
</div>
<div className="space-y-2">
<label
htmlFor="smtp-password-input"
className="text-sm font-medium text-foreground"
>
{m.smtp_password()}
</label>
<Input
id="smtp-password-input"
type="password"
value={formData.password || ''}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
placeholder={
settings?.password
? m.smtp_password_keep_placeholder()
: m.smtp_password_placeholder()
}
disabled={!formData.enabled}
autoComplete="new-password"
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
<div className="flex items-center justify-between space-x-4 rounded-lg border border-border p-4">
<div className="space-y-1">
<label
htmlFor="smtps-switch"
className="text-sm font-medium leading-none cursor-pointer"
>
{m.smtp_secure()}
</label>
<p className="text-xs text-muted-foreground">{m.smtp_secure_description()}</p>
</div>
<Switch
id="smtps-switch"
checked={formData.smtps}
onCheckedChange={(checked) => setFormData({ ...formData, smtps: checked })}
disabled={!formData.enabled}
/>
</div>
<div className="flex items-center justify-between space-x-4 rounded-lg border border-border p-4">
<div className="space-y-1">
<label
htmlFor="ignore-cert-switch"
className="text-sm font-medium leading-none cursor-pointer"
>
{m.smtp_ignore_cert()}
</label>
<p className="text-xs text-muted-foreground">
{m.smtp_ignore_cert_description()}
</p>
</div>
<Switch
id="ignore-cert-switch"
checked={formData.ignoreCert}
onCheckedChange={(checked) =>
setFormData({ ...formData, ignoreCert: checked })
}
disabled={!formData.enabled}
/>
</div>
</div>
</div>
{/* Sender Information */}
<div className="space-y-4 pt-4 border-t border-border">
<h4 className="text-sm font-semibold text-foreground">{m.sender_settings()}</h4>
<div className="space-y-2">
<label
htmlFor="sender-from-input"
className="text-sm font-medium text-foreground"
>
{m.sender_from()}
</label>
<Input
id="sender-from-input"
value={formData.from}
onChange={(e) => setFormData({ ...formData, from: e.target.value })}
placeholder="Shumai <noreply@example.com>"
disabled={!formData.enabled}
/>
<p className="text-xs text-muted-foreground">{m.sender_from_description()}</p>
</div>
<div className="space-y-2">
<label
htmlFor="sender-reply-to-input"
className="text-sm font-medium text-foreground"
>
{m.sender_reply_to()}
</label>
<Input
id="sender-reply-to-input"
value={formData.replyTo || ''}
onChange={(e) => setFormData({ ...formData, replyTo: e.target.value })}
placeholder="noreply@example.com"
disabled={!formData.enabled}
/>
<p className="text-xs text-muted-foreground">{m.sender_reply_to_description()}</p>
</div>
</div>
</CardContent>
<CardFooter className="flex flex-col sm:flex-row items-center justify-end gap-3 border-t border-border p-6 bg-muted/20">
<Button variant="outline" onClick={handleSave} disabled={isSaving}>
{isSaving && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
{m.save()}
</Button>
<Button onClick={handleSaveAndTest} disabled={isSaving || !formData.enabled}>
{isSaving && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
{m.save_and_send_test_email()}
</Button>
</CardFooter>
</Card>
</div>
</ScrollArea>
<TestEmailDialog
isOpen={isTestDialogOpen}
onClose={() => setIsTestDialogOpen(false)}
teamId={teamId}
defaultFrom={formData.from}
/>
</>
)
}
@@ -0,0 +1,139 @@
// @vitest-environment happy-dom
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { TestEmailDialog } from './TestEmailDialog'
import { toast } from 'sonner'
const mockPostTestEmail = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
notifications: {
email: {
test: {
$post: (args: unknown) => mockPostTestEmail(args),
},
},
},
},
},
},
},
}))
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
describe('TestEmailDialog', () => {
const mockOnClose = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
mockPostTestEmail.mockResolvedValue({
ok: true,
json: async () => ({ success: true, messageId: '<msg-123@example.com>' }),
})
})
afterEach(() => {
cleanup()
})
function renderDialog(props?: Partial<React.ComponentProps<typeof TestEmailDialog>>) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
return render(
<QueryClientProvider client={queryClient}>
<TestEmailDialog
isOpen={true}
onClose={mockOnClose}
teamId="team-1"
defaultFrom="Shumai <noreply@example.com>"
{...props}
/>
</QueryClientProvider>,
)
}
it('renders dialog title, description and pre-filled from address', () => {
renderDialog()
expect(screen.getByRole('heading', { name: /send test email/i })).toBeDefined()
expect(
screen.getByText(
/Sender email address, for example: "Shumai <noreply@example\.com>"\. Make sure to use an address you're allowed to send emails from\./i,
),
).toBeDefined()
const input = screen.getByLabelText(/from address/i) as HTMLInputElement
expect(input.value).toBe('Shumai <noreply@example.com>')
})
it('validates from address when empty', async () => {
renderDialog({ defaultFrom: '' })
const sendBtn = screen.getByRole('button', { name: /send test email/i })
fireEvent.click(sendBtn)
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/from address is required/i))
expect(mockPostTestEmail).not.toHaveBeenCalled()
})
})
it('sends test email successfully and calls onClose', async () => {
renderDialog()
const input = screen.getByLabelText(/from address/i)
fireEvent.change(input, { target: { value: 'Admin <admin@test.com>' } })
const sendBtn = screen.getByRole('button', { name: /send test email/i })
fireEvent.click(sendBtn)
await waitFor(() => {
expect(mockPostTestEmail).toHaveBeenCalledWith({
param: { teamId: 'team-1' },
json: { from: 'Admin <admin@test.com>' },
})
expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/test email sent/i))
expect(mockOnClose).toHaveBeenCalled()
})
})
it('handles send test email API error', async () => {
mockPostTestEmail.mockResolvedValueOnce({
ok: false,
json: async () => ({ message: 'SMTP verification failed: Connection refused' }),
})
renderDialog()
const sendBtn = screen.getByRole('button', { name: /send test email/i })
fireEvent.click(sendBtn)
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith('SMTP verification failed: Connection refused')
expect(mockOnClose).not.toHaveBeenCalled()
})
})
it('calls onClose when Cancel button is clicked', () => {
renderDialog()
const cancelBtn = screen.getByRole('button', { name: /cancel/i })
fireEvent.click(cancelBtn)
expect(mockOnClose).toHaveBeenCalled()
})
})
@@ -0,0 +1,106 @@
import { useState, useEffect } from 'react'
import { useMutation } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { Loader2, Send } from 'lucide-react'
import { toast } from 'sonner'
import { m } from '@/ui/paraglide/messages.js'
export interface TestEmailDialogProps {
isOpen: boolean
onClose: () => void
teamId: string
defaultFrom?: string
}
export function TestEmailDialog({
isOpen,
onClose,
teamId,
defaultFrom = '',
}: TestEmailDialogProps) {
const [fromAddress, setFromAddress] = useState(defaultFrom)
useEffect(() => {
if (isOpen) {
setFromAddress(defaultFrom)
}
}, [defaultFrom, isOpen])
const { mutateAsync: sendTestEmail, isPending: isSending } = useMutation({
mutationFn: async (from: string) => {
const res = await client.api.teams[':teamId'].notifications.email.test.$post({
param: { teamId },
json: { from },
})
if (!res.ok) {
const err = (await res.json().catch(() => null)) as { message?: string } | null
throw new Error(err?.message || m.failed_to_send_test_email())
}
return await res.json()
},
})
const handleSend = async () => {
if (!fromAddress.trim()) {
toast.error(m.from_address_required())
return
}
try {
await sendTestEmail(fromAddress.trim())
toast.success(m.test_email_sent_successfully())
onClose()
} catch (err) {
toast.error(err instanceof Error ? err.message : m.failed_to_send_test_email())
}
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
<Send className="w-5 h-5 text-primary" />
<DialogTitle>{m.send_test_email()}</DialogTitle>
</div>
<DialogDescription>{m.send_test_email_dialog_description()}</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<label htmlFor="test-dialog-from-input" className="text-sm font-medium text-foreground">
{m.sender_from()}
</label>
<Input
id="test-dialog-from-input"
value={fromAddress}
onChange={(e) => setFromAddress(e.target.value)}
placeholder="Shumai <noreply@example.com>"
disabled={isSending}
autoFocus
/>
</div>
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={onClose} disabled={isSending}>
{m.cancel()}
</Button>
<Button onClick={handleSend} disabled={isSending}>
{isSending && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
{m.send_test_email()}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+33
View File
@@ -295,6 +295,39 @@
"kanban_comments": "Kanban Comments",
"when_kanban_task_commented": "When someone comments on a task",
"email_notifications": "Email Notifications",
"email_notifications_description": "Configure SMTP settings for sending email notifications to team members.",
"enable_email_notifications": "Enable Email Notifications",
"enable_email_notifications_description": "Send email notifications for comments, mentions, uploads, and other team activity.",
"smtp_settings": "SMTP Server Settings",
"smtp_host": "SMTP Host",
"smtp_host_placeholder": "e.g. smtp.example.com",
"smtp_port": "SMTP Port",
"smtp_username": "Username",
"smtp_username_placeholder": "e.g. user@example.com",
"smtp_password": "Password",
"smtp_password_placeholder": "Enter SMTP password",
"smtp_password_keep_placeholder": "•••••••• (Leave blank to keep current)",
"smtp_secure": "SSL / TLS (SMTPS)",
"smtp_secure_description": "Connect directly over SSL/TLS (commonly used with port 465).",
"smtp_ignore_cert": "Ignore Certificate Errors",
"smtp_ignore_cert_description": "Allow self-signed or unverified SSL/TLS certificates.",
"sender_settings": "Sender Information",
"sender_from": "From Address",
"sender_from_description": "Sender email address, for example: \"Shumai <noreply@example.com>\". Make sure to use an address you're allowed to send emails from.",
"sender_reply_to": "Reply-To Address",
"sender_reply_to_description": "Optional address where replies to notifications should be directed.",
"save_and_send_test_email": "Save & Send Test Email",
"send_test_email": "Send Test Email",
"send_test_email_dialog_description": "Sender email address, for example: \"Shumai <noreply@example.com>\". Make sure to use an address you're allowed to send emails from.",
"test_email_sent_successfully": "Test email sent successfully",
"failed_to_send_test_email": "Failed to send test email",
"email_settings_saved": "Email settings saved successfully",
"failed_to_save_email_settings": "Failed to save email settings",
"failed_to_load_email_settings": "Failed to load email settings",
"smtp_host_required": "SMTP Host is required",
"from_address_required": "From address is required",
"api_tokens": "API Tokens",
"api_tokens_description": "Generate and manage API tokens. These tokens allow you or your agents to run terminal commands via shumai-cli.",
"developer_settings": "Developer Settings",
+33
View File
@@ -295,6 +295,39 @@
"kanban_comments": "看板评论",
"when_kanban_task_commented": "当有人在任务中发表评论时",
"email_notifications": "邮件通知",
"email_notifications_description": "配置用于向团队成员发送邮件通知的 SMTP 设置。",
"enable_email_notifications": "启用邮件通知",
"enable_email_notifications_description": "当有评论、提及、上传及其他团队活动时发送邮件通知。",
"smtp_settings": "SMTP 服务器设置",
"smtp_host": "SMTP 主机",
"smtp_host_placeholder": "例如 smtp.example.com",
"smtp_port": "SMTP 端口",
"smtp_username": "用户名",
"smtp_username_placeholder": "例如 user@example.com",
"smtp_password": "密码",
"smtp_password_placeholder": "输入 SMTP 密码",
"smtp_password_keep_placeholder": "••••••••(留空以保持当前密码)",
"smtp_secure": "SSL / TLS (SMTPS)",
"smtp_secure_description": "直接使用 SSL/TLS 连接(通常用于 465 端口)。",
"smtp_ignore_cert": "忽略证书错误",
"smtp_ignore_cert_description": "允许自签名或未验证的 SSL/TLS 证书。",
"sender_settings": "发件人信息",
"sender_from": "发件人地址",
"sender_from_description": "发件人邮箱地址,例如:“Shumai <noreply@example.com>”。请确保使用您有权使用的邮箱地址进行发送。",
"sender_reply_to": "回复地址",
"sender_reply_to_description": "通知邮件回复时指向的可选邮箱地址。",
"save_and_send_test_email": "保存并发送测试邮件",
"send_test_email": "发送测试邮件",
"send_test_email_dialog_description": "发件人邮箱地址,例如:“Shumai <noreply@example.com>”。请确保使用您有权使用的邮箱地址进行发送。",
"test_email_sent_successfully": "测试邮件发送成功",
"failed_to_send_test_email": "发送测试邮件失败",
"email_settings_saved": "邮件设置已保存",
"failed_to_save_email_settings": "保存邮件设置失败",
"failed_to_load_email_settings": "加载邮件设置失败",
"smtp_host_required": "必须提供 SMTP 主机",
"from_address_required": "必须提供发件人地址",
"api_tokens": "API 令牌",
"api_tokens_description": "生成和管理 API 令牌。这些令牌允许您或您的智能体通过 shumai-cli 运行终端命令。",
"developer_settings": "开发者设置",
@@ -15,6 +15,7 @@ import { NotificationSettings } from '@/ui/components/settings/NotificationSetti
import { DeveloperSettings } from '@/ui/components/settings/DeveloperSettings'
import { QuotasSettings } from '@/ui/components/settings/QuotasSettings'
import { AppearanceSettings } from '@/ui/components/settings/AppearanceSettings'
import { EmailNotificationSettings } from '@/ui/components/settings/EmailNotificationSettings'
import { ImageVideoGenerationSettings } from '@/ui/components/settings/ImageVideoGenerationSettings'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Slider } from '@/ui/components/ui/slider'
@@ -25,6 +26,7 @@ import {
Cpu,
Film,
Loader2,
Mail,
Puzzle,
Server,
Shield,
@@ -57,6 +59,7 @@ type SettingsTab =
| 'transcode'
| 'quotas'
| 'appearance'
| 'email'
| 'skills'
| 'mcp'
| 'providers'
@@ -71,6 +74,7 @@ const VALID_SETTINGS_TABS: readonly SettingsTab[] = [
'transcode',
'quotas',
'appearance',
'email',
'skills',
'mcp',
'providers',
@@ -173,6 +177,7 @@ function TeamSettingsPage() {
'transcode',
'quotas',
'appearance',
'email',
'providers',
'image-video',
'skills',
@@ -468,6 +473,22 @@ function TeamSettingsPage() {
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
<button
onClick={() => handleTabChange('email')}
className={cn(
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
activeTab === 'email'
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
)}
>
<Mail className="w-5 h-5" />
{m.email_notifications()}
{activeTab === 'email' && (
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
)}
</button>
</>
)}
@@ -588,6 +609,7 @@ function TeamSettingsPage() {
{activeTab === 'transcode' && m.media_processing()}
{activeTab === 'quotas' && m.resource_quotas()}
{activeTab === 'appearance' && m.appearance_settings()}
{activeTab === 'email' && m.email_notifications()}
{activeTab === 'skills' && m.skills_management()}
{activeTab === 'mcp' && m.mcp_servers()}
{activeTab === 'providers' && m.ai_providers()}
@@ -602,6 +624,7 @@ function TeamSettingsPage() {
{activeTab === 'transcode' && m.transcode_description()}
{activeTab === 'quotas' && m.resource_quotas_description()}
{activeTab === 'appearance' && m.appearance_settings_description()}
{activeTab === 'email' && m.email_notifications_description()}
{activeTab === 'skills' && m.skills_description()}
{activeTab === 'mcp' && m.mcp_servers_description()}
{activeTab === 'providers' && m.providers_description()}
@@ -908,6 +931,8 @@ function TeamSettingsPage() {
{activeTab === 'quotas' && <QuotasSettings teamId={teamId} />}
{activeTab === 'appearance' && <AppearanceSettings teamId={teamId} />}
{activeTab === 'email' && <EmailNotificationSettings teamId={teamId} />}
</div>
</div>
</main>