mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
feat(agentic kanban): phase 1 not-agentic kanban board (#330)
* feat(kanban): implement AI-native kanban database models, services, and REST APIs * feat(webui): implement team kanban board and task management * style(webui): increase kanban dialog widths and form container * fix(webui): ensure kanban dialogs override sm:max-w-lg base class * style(webui): set edit task dialog max width to 5xl * chore: untrack kanban plan markdown files * feat(webui): update kanban page layout to 2 columns and refine task activity UI * fix(webui): constrain kanban column and board heights for vertical scrolling * feat(kanban): unify task status transition into updateTask API and allow unconstrained human task transitions * fix(webui): add optimistic updates to kanban drag-and-drop to eliminate flash * refactor(webui): remove client-side search box from kanban header * feat(kanban): redesign task dialog comments area and add attachment support * refactor(webui): remove top status action bar from task info dialog * fix(webui): narrow query cache predicate and add defensive guards for kanban drag optimistic update * feat(kanban): add drag-and-drop task reordering with fractional indexing (#331) * feat(kanban): add drag-and-drop task reordering with fractional indexing * fix(kanban): improve card drop zones, snap indicators, and column highlight * fix(kanban): enable card droppables only during active drag * fix(kanban): refine hover styles and drop indicators for column boundaries * fix(kanban): unify bottom drop indicator and fix top indicator clipping * fix(kanban): ensure full column highlight and full coverage drop target * minor change * feat(kanban): allow agent tasks free drag-and-drop and enforce status change permissions (#332) * refactor(kanban): rename task_type_agentic translation keys to task_type_agent * feat(kanban): refactor task type enum to isAgentTask boolean (#333) * refactor(kanban): remove phase 2 agent execution logic and streamline phase 1 kanban * feat(kanban): add notifications and audit logging for kanban (#334) * feat(kanban): redesign config area layout and add parent tasks multi-selector (#335) * feat(webui): redesign kanban task dialog config area * feat(kanban): simplify task dependencies with parent tasks multi-selector * refactor(kanban): remove unused links routes and legacy dependency methods * feat(kanban): connect assets and kanban tasks with many-to-many relationship (#336) * feat(kanban): connect assets and kanban tasks with many-to-many relationship * feat(kanban): improve asset picker layout, infinite scrolling, and breadcrumb icon styling * fix(kanban): ensure asset picker scrollarea is scrollable with min-h-0 and shrink-0 flex styling * fix(kanban): hide recently deleted in folder tree picker and adjust header padding * fix(kanban): use lucide files icon instead of paperclip for linked assets * feat(kanban): improve task deletion, goal sidebar interaction, and card styling (#337) * feat(kanban): improve task deletion, goal sidebar interaction, and card styling * feat(kanban): move agent task badge after priority and update to orange style * feat(kanban): add status Compare-And-Swap (CAS) to prevent drag-and-drop race conditions (#338) * feat(kanban): add status Compare-And-Swap (CAS) to prevent drag-and-drop race conditions * style(kanban): rotate kanban icon 180 degrees in sidebar and top nav * style(kanban): remove rotate-180 from SquareKanban icons * feat(kanban): add unassigned goal record and fix all tasks count (#339) * feat(kanban): add unassigned goal record and fix all tasks count * feat(kanban): toggle task count with three-dot action button on goal card hover * fix(ci): pin bun version to 1.3.14 across CI and Docker (#340) * fix(webui): truncate goal name to max 2 lines in kanban sidebar (#341)
This commit is contained in:
@@ -84,4 +84,36 @@ describe('AuditLogService', () => {
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('records kanban actions accurately', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Kanban User', email: 'kanban_user@example.com', password: 'password' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Kanban Audit Team' },
|
||||
})
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_task_create,
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
itemId: 'task-123',
|
||||
})
|
||||
|
||||
await auditLogService.logAction({
|
||||
action: AuditAction.kanban_goal_create,
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
itemId: 'goal-123',
|
||||
})
|
||||
|
||||
const result = await auditLogService.listAuditLogs({
|
||||
teamId: team.id,
|
||||
actions: [AuditAction.kanban_task_create, AuditAction.kanban_goal_create],
|
||||
})
|
||||
|
||||
expect(result.total).toBe(2)
|
||||
expect(result.nodes.map((n) => n.action)).toContain(AuditAction.kanban_task_create)
|
||||
expect(result.nodes.map((n) => n.action)).toContain(AuditAction.kanban_goal_create)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -25,6 +25,8 @@ export enum ResourceType {
|
||||
Comment = 'comment',
|
||||
AgentSession = 'agentSession',
|
||||
QuotaRule = 'quotaRule',
|
||||
KanbanGoal = 'kanbanGoal',
|
||||
KanbanTask = 'kanbanTask',
|
||||
}
|
||||
|
||||
export interface AuthzRequest {
|
||||
@@ -269,6 +271,24 @@ export class AuthzService {
|
||||
return { teamId: rule.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.KanbanGoal: {
|
||||
const goal = await prisma.kanbanGoal.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!goal) throw new HTTPException(404, { message: 'Kanban goal not found' })
|
||||
return { teamId: goal.teamId }
|
||||
}
|
||||
|
||||
case ResourceType.KanbanTask: {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!task) throw new HTTPException(404, { message: 'Kanban task not found' })
|
||||
return { teamId: task.teamId, projectId: task.projectId ?? undefined }
|
||||
}
|
||||
|
||||
default:
|
||||
throw new HTTPException(403, { message: `Unsupported resource type: ${type}` })
|
||||
}
|
||||
|
||||
@@ -27,3 +27,4 @@ export * from './watermark/watermark'
|
||||
export * from './gotenberg/gotenberg'
|
||||
export * from './mcp/mcp-service'
|
||||
export * from './quota/quota-service'
|
||||
export * from './kanban/kanban'
|
||||
|
||||
@@ -0,0 +1,878 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums'
|
||||
import { UNASSIGNED_GOAL_ID } from '@shumai/dtos'
|
||||
import { kanbanService } from './kanban'
|
||||
|
||||
describe('KanbanService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
async function setupTeamAndUsers() {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Team Owner', email: 'owner@example.com' },
|
||||
})
|
||||
const editor = await prisma.user.create({
|
||||
data: { name: 'Team Editor', email: 'editor@example.com' },
|
||||
})
|
||||
const reviewer = await prisma.user.create({
|
||||
data: { name: 'Team Reviewer', email: 'reviewer@example.com' },
|
||||
})
|
||||
|
||||
const team = await prisma.team.create({
|
||||
data: {
|
||||
name: 'Kanban Core Team',
|
||||
settings: {
|
||||
transcode: { videoStrategy: 'best_match' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.createMany({
|
||||
data: [
|
||||
{ teamId: team.id, userId: owner.id, role: 'owner', scope: 'team' },
|
||||
{ teamId: team.id, userId: editor.id, role: 'editor', scope: 'team' },
|
||||
{ teamId: team.id, userId: reviewer.id, role: 'reviewer', scope: 'team' },
|
||||
],
|
||||
})
|
||||
|
||||
return { team, owner, editor, reviewer }
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Goals
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Goals', () => {
|
||||
it('creates, lists, updates, and deletes goals including unassigned record', async () => {
|
||||
const { team, owner, editor } = await setupTeamAndUsers()
|
||||
|
||||
// When no custom goals exist, listGoals returns only the unassigned goal record with taskCount 0
|
||||
const initialGoals = await kanbanService.listGoals(team.id)
|
||||
expect(initialGoals.length).toBe(1)
|
||||
expect(initialGoals[0].id).toBe(UNASSIGNED_GOAL_ID)
|
||||
expect(initialGoals[0].taskCount).toBe(0)
|
||||
|
||||
// Create an unassigned task (no goalId)
|
||||
const unassignedTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Unassigned Task' },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
|
||||
const goalsWithUnassignedTask = await kanbanService.listGoals(team.id)
|
||||
expect(goalsWithUnassignedTask.length).toBe(1)
|
||||
expect(goalsWithUnassignedTask[0].id).toBe(UNASSIGNED_GOAL_ID)
|
||||
expect(goalsWithUnassignedTask[0].taskCount).toBe(1)
|
||||
|
||||
const goal = await kanbanService.createGoal(
|
||||
team.id,
|
||||
{
|
||||
title: 'Q3 Launch Release',
|
||||
description: 'Ship all core kanban features',
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
expect(goal).toBeDefined()
|
||||
expect(goal.title).toBe('Q3 Launch Release')
|
||||
expect(goal.taskCount).toBe(0)
|
||||
|
||||
// Create a task under this goal
|
||||
const assignedTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Design Wireframes',
|
||||
goalId: goal.id,
|
||||
},
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
|
||||
// Get goals: should return [unassignedGoal, customGoal]
|
||||
const listedGoals = await kanbanService.listGoals(team.id)
|
||||
expect(listedGoals.length).toBe(2)
|
||||
expect(listedGoals[0].id).toBe(UNASSIGNED_GOAL_ID)
|
||||
expect(listedGoals[0].taskCount).toBe(1)
|
||||
expect(listedGoals[1].id).toBe(goal.id)
|
||||
expect(listedGoals[1].taskCount).toBe(1)
|
||||
|
||||
// Filtering tasks with goalId = UNASSIGNED_GOAL_ID
|
||||
const unassignedTasksList = await kanbanService.listTasks(team.id, {
|
||||
goalId: UNASSIGNED_GOAL_ID,
|
||||
})
|
||||
expect(unassignedTasksList.data.length).toBe(1)
|
||||
expect(unassignedTasksList.data[0].id).toBe(unassignedTask.id)
|
||||
|
||||
// Filtering tasks with custom goalId
|
||||
const assignedTasksList = await kanbanService.listTasks(team.id, {
|
||||
goalId: goal.id,
|
||||
})
|
||||
expect(assignedTasksList.data.length).toBe(1)
|
||||
expect(assignedTasksList.data[0].id).toBe(assignedTask.id)
|
||||
|
||||
// Update goal
|
||||
const updated = await kanbanService.updateGoal(
|
||||
goal.id,
|
||||
{ title: 'Q3 Launch Release Updated' },
|
||||
'owner',
|
||||
)
|
||||
expect(updated.title).toBe('Q3 Launch Release Updated')
|
||||
|
||||
// Should reject updating unassigned goal
|
||||
await expect(
|
||||
kanbanService.updateGoal(UNASSIGNED_GOAL_ID, { title: 'Illegal' }, 'owner'),
|
||||
).rejects.toThrow('Cannot edit or delete the unassigned goal')
|
||||
|
||||
// Should reject deleting unassigned goal
|
||||
await expect(kanbanService.deleteGoal(UNASSIGNED_GOAL_ID, 'owner')).rejects.toThrow(
|
||||
'Cannot edit or delete the unassigned goal',
|
||||
)
|
||||
|
||||
// Delete custom goal
|
||||
await kanbanService.deleteGoal(goal.id, 'owner')
|
||||
const afterDelete = await kanbanService.listGoals(team.id)
|
||||
// Only unassigned record remains, now with 2 unassigned tasks (since assignedTask's goal was set to null on delete)
|
||||
expect(afterDelete.length).toBe(1)
|
||||
expect(afterDelete[0].id).toBe(UNASSIGNED_GOAL_ID)
|
||||
expect(afterDelete[0].taskCount).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Tasks CRUD & Status
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Tasks CRUD & Permissions', () => {
|
||||
it('allows owners and editors to create tasks and starts in TODO', async () => {
|
||||
const { team, owner, editor } = await setupTeamAndUsers()
|
||||
|
||||
// Owner can create Agent Task
|
||||
const agentTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'AI Task 1',
|
||||
isAgentTask: true,
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
expect(agentTask.isAgentTask).toBe(true)
|
||||
expect(agentTask.status).toBe(KanbanTaskStatus.TODO)
|
||||
|
||||
// Editor can create Agent Task
|
||||
const editorAgentTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Editor AI Task',
|
||||
isAgentTask: true,
|
||||
},
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
expect(editorAgentTask.isAgentTask).toBe(true)
|
||||
expect(editorAgentTask.status).toBe(KanbanTaskStatus.TODO)
|
||||
|
||||
// Editor can create Standard Task
|
||||
const manualTask = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Manual Task 1',
|
||||
isAgentTask: false,
|
||||
},
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
expect(manualTask.isAgentTask).toBe(false)
|
||||
expect(manualTask.status).toBe(KanbanTaskStatus.TODO)
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// DAG Cycles & Dependencies
|
||||
// --------------------------------------------------------------------------
|
||||
describe('DAG Cycle Detection', () => {
|
||||
it('prevents self dependency and circular dependency chains', async () => {
|
||||
const { team, editor } = await setupTeamAndUsers()
|
||||
|
||||
const taskA = await kanbanService.createTask(team.id, { title: 'A' }, editor.id, 'editor')
|
||||
const taskB = await kanbanService.createTask(team.id, { title: 'B' }, editor.id, 'editor')
|
||||
const taskC = await kanbanService.createTask(team.id, { title: 'C' }, editor.id, 'editor')
|
||||
|
||||
// Self dependency
|
||||
await expect(kanbanService.setDependencies(taskA.id, [taskA.id], editor.id)).rejects.toThrow()
|
||||
|
||||
// Chain: A -> B -> C (B depends on A, C depends on B)
|
||||
await kanbanService.setDependencies(taskB.id, [taskA.id], editor.id)
|
||||
await kanbanService.setDependencies(taskC.id, [taskB.id], editor.id)
|
||||
|
||||
// Attempt cycle: A depends on C (would create A -> B -> C -> A)
|
||||
await expect(kanbanService.setDependencies(taskA.id, [taskC.id], editor.id)).rejects.toThrow(
|
||||
/Circular dependency detected/,
|
||||
)
|
||||
|
||||
// Remove dependency of C on B
|
||||
await kanbanService.setDependencies(taskC.id, [], editor.id)
|
||||
|
||||
// Now A can depend on C since chain is broken
|
||||
await kanbanService.setDependencies(taskA.id, [taskC.id], editor.id)
|
||||
})
|
||||
|
||||
it('syncs parent dependencies via setDependencies and updateTask', async () => {
|
||||
const { team, editor } = await setupTeamAndUsers()
|
||||
|
||||
const task1 = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Parent 1' },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
const task2 = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Parent 2' },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
const task3 = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Parent 3' },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
const child = await kanbanService.createTask(team.id, { title: 'Child' }, editor.id, 'editor')
|
||||
|
||||
// Set initial parents [task1, task2]
|
||||
await kanbanService.setDependencies(child.id, [task1.id, task2.id], editor.id)
|
||||
let detail = await kanbanService.getTask(child.id)
|
||||
expect(detail.dependencies.map((d) => d.id).sort()).toEqual([task1.id, task2.id].sort())
|
||||
|
||||
// Update parents to [task2, task3] via updateTask (removes task1, adds task3)
|
||||
await kanbanService.updateTask(
|
||||
child.id,
|
||||
{ parentIds: [task2.id, task3.id] },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
detail = await kanbanService.getTask(child.id)
|
||||
expect(detail.dependencies.map((d) => d.id).sort()).toEqual([task2.id, task3.id].sort())
|
||||
|
||||
// Clear parents
|
||||
await kanbanService.updateTask(child.id, { parentIds: [] }, editor.id, 'editor')
|
||||
detail = await kanbanService.getTask(child.id)
|
||||
expect(detail.dependencies.length).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Task Listing with Status Event
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Task Listing and Status Event Details', () => {
|
||||
it('attaches latestStatusEvent and filters by isAgentTask, status, goal', async () => {
|
||||
const { team, owner, editor } = await setupTeamAndUsers()
|
||||
|
||||
const goal = await kanbanService.createGoal(team.id, { title: 'Q3 Goal' }, owner.id, 'owner')
|
||||
|
||||
const task1 = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Manual 1',
|
||||
isAgentTask: false,
|
||||
goalId: goal.id,
|
||||
priority: KanbanTaskPriority.HIGH,
|
||||
},
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
const task2 = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Agent 1', isAgentTask: true },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
// Filter by isAgentTask: false
|
||||
const manualList = await kanbanService.listTasks(team.id, { isAgentTask: false })
|
||||
expect(manualList.data.length).toBe(1)
|
||||
expect(manualList.data[0].id).toBe(task1.id)
|
||||
expect(manualList.data[0].latestStatusEvent).toBeDefined()
|
||||
|
||||
// Filter by goalId
|
||||
const goalList = await kanbanService.listTasks(team.id, { goalId: goal.id })
|
||||
expect(goalList.data.length).toBe(1)
|
||||
expect(goalList.data[0].id).toBe(task1.id)
|
||||
|
||||
// Filter by isAgentTask: true
|
||||
const agentList = await kanbanService.listTasks(team.id, { isAgentTask: true })
|
||||
expect(agentList.data.length).toBe(1)
|
||||
expect(agentList.data[0].id).toBe(task2.id)
|
||||
})
|
||||
|
||||
it('deletes tasks properly with permissions', async () => {
|
||||
const { team, editor, reviewer } = await setupTeamAndUsers()
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Task to Delete', isAgentTask: false },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
|
||||
// Reviewer (not creator, not owner, not reporter) cannot delete
|
||||
await expect(kanbanService.deleteTask(task.id, reviewer.id, 'reviewer')).rejects.toThrow()
|
||||
|
||||
// Creator (editor) can delete
|
||||
const deleted = await kanbanService.deleteTask(task.id, editor.id, 'editor')
|
||||
expect(deleted.id).toBe(task.id)
|
||||
|
||||
// Confirm deleted from db
|
||||
const fromDb = await prisma.kanbanTask.findUnique({ where: { id: task.id } })
|
||||
expect(fromDb).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Unified Status Transitions & Permissions
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Unified Status Transitions & Task Status Permissions', () => {
|
||||
it('allows tasks to transition between any states via updateTask', async () => {
|
||||
const { team, editor } = await setupTeamAndUsers()
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Flexible Human Task', isAgentTask: false },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
expect(task.status).toBe(KanbanTaskStatus.TODO)
|
||||
|
||||
// Direct transition: TODO -> IN_PROGRESS
|
||||
const inProgress = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.IN_PROGRESS },
|
||||
editor.id,
|
||||
)
|
||||
expect(inProgress.status).toBe(KanbanTaskStatus.IN_PROGRESS)
|
||||
expect(inProgress.startedAt).toBeDefined()
|
||||
|
||||
// Direct transition: IN_PROGRESS -> BLOCKED
|
||||
const blocked = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.BLOCKED, reason: 'Waiting for design' },
|
||||
editor.id,
|
||||
)
|
||||
expect(blocked.status).toBe(KanbanTaskStatus.BLOCKED)
|
||||
|
||||
// Direct transition: BLOCKED -> DONE
|
||||
const done = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.DONE },
|
||||
editor.id,
|
||||
)
|
||||
expect(done.status).toBe(KanbanTaskStatus.DONE)
|
||||
expect(done.completedAt).toBeDefined()
|
||||
|
||||
// Direct transition: DONE -> IN_PROGRESS (re-open directly into progress)
|
||||
const reopened = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.IN_PROGRESS },
|
||||
editor.id,
|
||||
)
|
||||
expect(reopened.status).toBe(KanbanTaskStatus.IN_PROGRESS)
|
||||
expect(reopened.completedAt).toBeNull()
|
||||
|
||||
// Direct transition: IN_PROGRESS -> IN_REVIEW
|
||||
const inReview = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.IN_REVIEW },
|
||||
editor.id,
|
||||
)
|
||||
expect(inReview.status).toBe(KanbanTaskStatus.IN_REVIEW)
|
||||
|
||||
// Direct transition: IN_REVIEW -> TODO
|
||||
const todo = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.TODO },
|
||||
editor.id,
|
||||
)
|
||||
expect(todo.status).toBe(KanbanTaskStatus.TODO)
|
||||
})
|
||||
|
||||
it('enforces status change permissions (only owner, reporter, or assignee can change status)', async () => {
|
||||
const { team, owner, editor, reviewer } = await setupTeamAndUsers()
|
||||
|
||||
// Create another editor in team who is NOT reporter and NOT assignee
|
||||
const otherEditor = await prisma.user.create({
|
||||
data: { name: 'Other Editor', email: 'other-editor@example.com' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: otherEditor.id, role: 'editor', scope: 'team' },
|
||||
})
|
||||
|
||||
// Create a task: reporter is editor, assignee is reviewer
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Guarded Task',
|
||||
reporterId: editor.id,
|
||||
assigneeId: reviewer.id,
|
||||
},
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
|
||||
// Other editor tries to change status -> rejected with 403
|
||||
await expect(
|
||||
kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.IN_PROGRESS },
|
||||
otherEditor.id,
|
||||
'editor',
|
||||
),
|
||||
).rejects.toThrow(/Only team owners, task reporters, or assignees can change task status/)
|
||||
|
||||
// Other editor CAN update non-status fields (e.g. description)
|
||||
const descUpdated = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ description: 'Updated by other editor' },
|
||||
otherEditor.id,
|
||||
'editor',
|
||||
)
|
||||
expect(descUpdated.description).toBe('Updated by other editor')
|
||||
|
||||
// Reporter (editor) CAN change status -> succeeds
|
||||
const reporterUpdated = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.IN_PROGRESS },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
expect(reporterUpdated.status).toBe(KanbanTaskStatus.IN_PROGRESS)
|
||||
|
||||
// Assignee (reviewer) CAN change status -> succeeds
|
||||
const assigneeUpdated = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.IN_REVIEW },
|
||||
reviewer.id,
|
||||
'reviewer',
|
||||
)
|
||||
expect(assigneeUpdated.status).toBe(KanbanTaskStatus.IN_REVIEW)
|
||||
|
||||
// Owner CAN change status -> succeeds
|
||||
const ownerUpdated = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ status: KanbanTaskStatus.DONE },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
expect(ownerUpdated.status).toBe(KanbanTaskStatus.DONE)
|
||||
})
|
||||
|
||||
it('handles status CAS (Compare-And-Swap) with fromStatus validation', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'CAS Task', isAgentTask: false },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
expect(task.status).toBe(KanbanTaskStatus.TODO)
|
||||
|
||||
// 1. Matching fromStatus succeeds
|
||||
const inProgress = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{ fromStatus: KanbanTaskStatus.TODO, status: KanbanTaskStatus.IN_PROGRESS },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
expect(inProgress.status).toBe(KanbanTaskStatus.IN_PROGRESS)
|
||||
|
||||
// 2. Mismatched fromStatus throws 409 Conflict
|
||||
await expect(
|
||||
kanbanService.updateTask(
|
||||
task.id,
|
||||
{ fromStatus: KanbanTaskStatus.TODO, status: KanbanTaskStatus.DONE },
|
||||
owner.id,
|
||||
'owner',
|
||||
),
|
||||
).rejects.toThrow(/Task status has been modified by another user/)
|
||||
|
||||
// 3. Status is still IN_PROGRESS
|
||||
const current = await kanbanService.getTask(task.id)
|
||||
expect(current.status).toBe(KanbanTaskStatus.IN_PROGRESS)
|
||||
})
|
||||
|
||||
it('prevents race conditions when two users update status concurrently', async () => {
|
||||
const { team, owner, editor } = await setupTeamAndUsers()
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Race Condition Task',
|
||||
reporterId: editor.id,
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
expect(task.status).toBe(KanbanTaskStatus.TODO)
|
||||
|
||||
// User 1 drags to IN_PROGRESS (from TODO)
|
||||
const u1Promise = kanbanService.updateTask(
|
||||
task.id,
|
||||
{ fromStatus: KanbanTaskStatus.TODO, status: KanbanTaskStatus.IN_PROGRESS },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
// User 2 drags to DONE (from TODO)
|
||||
const u2Promise = kanbanService.updateTask(
|
||||
task.id,
|
||||
{ fromStatus: KanbanTaskStatus.TODO, status: KanbanTaskStatus.DONE },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
|
||||
const results = await Promise.allSettled([u1Promise, u2Promise])
|
||||
const fulfilled = results.filter((r) => r.status === 'fulfilled')
|
||||
const rejected = results.filter((r) => r.status === 'rejected')
|
||||
|
||||
// Exactly one should succeed, and one should fail with 409 Conflict
|
||||
expect(fulfilled).toHaveLength(1)
|
||||
expect(rejected).toHaveLength(1)
|
||||
expect((rejected[0] as PromiseRejectedResult).reason.message).toMatch(
|
||||
/Task status has been modified by another user/,
|
||||
)
|
||||
|
||||
// Verify the task event log is consistent
|
||||
const detail = await kanbanService.getTask(task.id)
|
||||
const statusEvents = detail.events.filter(
|
||||
(e) => e.type === 'STATUS_CHANGED' && e.toStatus !== null,
|
||||
)
|
||||
// Only the winning transition was recorded
|
||||
expect(statusEvents.length).toBe(1)
|
||||
expect(statusEvents[0].fromStatus).toBe(KanbanTaskStatus.TODO)
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Comments and Attachments
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Comments and Attachments', () => {
|
||||
it('creates attachments, adds comment with attachments, and deletes comment', async () => {
|
||||
const { team, owner, editor, reviewer } = await setupTeamAndUsers()
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{ title: 'Task with Attachments' },
|
||||
editor.id,
|
||||
'editor',
|
||||
)
|
||||
|
||||
// Create attachment
|
||||
const att = await kanbanService.createAttachment(team.id, {
|
||||
fileName: 'design.png',
|
||||
size: 1024,
|
||||
contentType: 'image/png',
|
||||
})
|
||||
expect(att.id).toBeDefined()
|
||||
expect(att.uploadUrl).toBeDefined()
|
||||
expect(att.proxyType).toBe('image')
|
||||
|
||||
// Add comment with attachment
|
||||
const comment = await kanbanService.addComment(task.id, editor.id, 'Here is the design', [
|
||||
{
|
||||
id: att.id,
|
||||
name: att.name,
|
||||
key: att.key,
|
||||
sizeByte: att.sizeByte,
|
||||
contentType: att.contentType,
|
||||
proxyType: att.proxyType,
|
||||
},
|
||||
])
|
||||
expect(comment.id).toBeDefined()
|
||||
expect(comment.attachments.length).toBe(1)
|
||||
expect(comment.attachments[0].name).toBe('design.png')
|
||||
expect(comment.attachments[0].url).toBeDefined()
|
||||
|
||||
// List comments
|
||||
const list = await kanbanService.listComments(task.id)
|
||||
expect(list.length).toBe(1)
|
||||
expect(list[0].attachments.length).toBe(1)
|
||||
|
||||
// Non-author reviewer cannot delete comment
|
||||
await expect(
|
||||
kanbanService.deleteComment(task.id, comment.id, reviewer.id, 'reviewer'),
|
||||
).rejects.toThrow(/Not authorized/)
|
||||
|
||||
// Team owner can delete comment
|
||||
await kanbanService.deleteComment(task.id, comment.id, owner.id, 'owner')
|
||||
const afterDelete = await kanbanService.listComments(task.id)
|
||||
expect(afterDelete.length).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Task Ordering & Fractional Indexing
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Task Ordering & Fractional Indexing', () => {
|
||||
it('appends newly created tasks to the bottom of the column', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
|
||||
const task1 = await kanbanService.createTask(team.id, { title: 'Task 1' }, owner.id, 'owner')
|
||||
const task2 = await kanbanService.createTask(team.id, { title: 'Task 2' }, owner.id, 'owner')
|
||||
const task3 = await kanbanService.createTask(team.id, { title: 'Task 3' }, owner.id, 'owner')
|
||||
|
||||
expect(task1.sortIndex).toBeDefined()
|
||||
expect(task2.sortIndex).toBeDefined()
|
||||
expect(task3.sortIndex).toBeDefined()
|
||||
expect(task1.sortIndex! < task2.sortIndex!).toBe(true)
|
||||
expect(task2.sortIndex! < task3.sortIndex!).toBe(true)
|
||||
|
||||
const list = await kanbanService.listTasks(team.id, { status: KanbanTaskStatus.TODO })
|
||||
expect(list.data.map((t) => t.id)).toEqual([task1.id, task2.id, task3.id])
|
||||
})
|
||||
|
||||
it('reorders tasks within the same column using beforeIndex and afterIndex', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
|
||||
const taskA = await kanbanService.createTask(team.id, { title: 'Task A' }, owner.id, 'owner')
|
||||
const taskB = await kanbanService.createTask(team.id, { title: 'Task B' }, owner.id, 'owner')
|
||||
const taskC = await kanbanService.createTask(team.id, { title: 'Task C' }, owner.id, 'owner')
|
||||
|
||||
// Move task C before task A
|
||||
const updatedC = await kanbanService.updateTask(
|
||||
taskC.id,
|
||||
{ beforeIndex: taskA.sortIndex! },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
expect(updatedC.sortIndex! < taskA.sortIndex!).toBe(true)
|
||||
|
||||
let list = await kanbanService.listTasks(team.id, { status: KanbanTaskStatus.TODO })
|
||||
expect(list.data.map((t) => t.id)).toEqual([taskC.id, taskA.id, taskB.id])
|
||||
|
||||
// Move task C after task A (between A and B)
|
||||
const reorderedTaskC = await kanbanService.updateTask(
|
||||
taskC.id,
|
||||
{ afterIndex: taskA.sortIndex! },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
expect(reorderedTaskC.sortIndex! > taskA.sortIndex!).toBe(true)
|
||||
expect(reorderedTaskC.sortIndex! < taskB.sortIndex!).toBe(true)
|
||||
|
||||
list = await kanbanService.listTasks(team.id, { status: KanbanTaskStatus.TODO })
|
||||
expect(list.data.map((t) => t.id)).toEqual([taskA.id, taskC.id, taskB.id])
|
||||
})
|
||||
|
||||
it('moves tasks across columns with custom position', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
|
||||
const task1 = await kanbanService.createTask(team.id, { title: 'Task 1' }, owner.id, 'owner')
|
||||
const task2 = await kanbanService.createTask(team.id, { title: 'Task 2' }, owner.id, 'owner')
|
||||
|
||||
// Start task1 so it's in IN_PROGRESS
|
||||
const inProgressTask1 = await kanbanService.updateTask(
|
||||
task1.id,
|
||||
{ status: KanbanTaskStatus.IN_PROGRESS },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
// Now move task2 to IN_PROGRESS before task1
|
||||
const updatedTask2 = await kanbanService.updateTask(
|
||||
task2.id,
|
||||
{
|
||||
status: KanbanTaskStatus.IN_PROGRESS,
|
||||
beforeIndex: inProgressTask1.sortIndex!,
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
expect(updatedTask2.status).toBe(KanbanTaskStatus.IN_PROGRESS)
|
||||
expect(updatedTask2.sortIndex! < inProgressTask1.sortIndex!).toBe(true)
|
||||
|
||||
const inProgressList = await kanbanService.listTasks(team.id, {
|
||||
status: KanbanTaskStatus.IN_PROGRESS,
|
||||
})
|
||||
expect(inProgressList.data.map((t) => t.id)).toEqual([task2.id, task1.id])
|
||||
})
|
||||
|
||||
it('moves tasks across columns without explicit position placing at bottom', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
|
||||
const task1 = await kanbanService.createTask(team.id, { title: 'Task 1' }, owner.id, 'owner')
|
||||
const task2 = await kanbanService.createTask(team.id, { title: 'Task 2' }, owner.id, 'owner')
|
||||
|
||||
// Move task1 to DONE
|
||||
const doneTask1 = await kanbanService.updateTask(
|
||||
task1.id,
|
||||
{ status: KanbanTaskStatus.DONE },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
// Move task2 to DONE without position
|
||||
const updatedTask2 = await kanbanService.updateTask(
|
||||
task2.id,
|
||||
{ status: KanbanTaskStatus.DONE },
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
expect(updatedTask2.status).toBe(KanbanTaskStatus.DONE)
|
||||
expect(updatedTask2.sortIndex! > doneTask1.sortIndex!).toBe(true)
|
||||
|
||||
const doneList = await kanbanService.listTasks(team.id, { status: KanbanTaskStatus.DONE })
|
||||
expect(doneList.data.map((t) => t.id)).toEqual([task1.id, task2.id])
|
||||
})
|
||||
})
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Asset Associations
|
||||
// --------------------------------------------------------------------------
|
||||
describe('Asset Associations', () => {
|
||||
async function setupProjectAndAssets(teamId: string, userId: string) {
|
||||
const project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'Media Project',
|
||||
teamId,
|
||||
},
|
||||
})
|
||||
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Video Folder',
|
||||
type: 'folder',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
creatorId: userId,
|
||||
},
|
||||
})
|
||||
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Video.mp4',
|
||||
type: 'file',
|
||||
mediaType: 'video/mp4',
|
||||
status: 'processed',
|
||||
parentId: folder.id,
|
||||
projectId: project.id,
|
||||
creatorId: userId,
|
||||
},
|
||||
})
|
||||
|
||||
return { project, folder, file }
|
||||
}
|
||||
|
||||
it('creates a task with linked assets and retrieves them in getTask', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
const { file, folder } = await setupProjectAndAssets(team.id, owner.id)
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Review Video',
|
||||
assetIds: [file.id, folder.id],
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
expect(task.assetCount).toBe(2)
|
||||
|
||||
const detail = await kanbanService.getTask(task.id)
|
||||
expect(detail.assets).toHaveLength(2)
|
||||
const assetNames = detail.assets.map((a) => a.name)
|
||||
expect(assetNames).toContain('Video.mp4')
|
||||
expect(assetNames).toContain('Video Folder')
|
||||
|
||||
// Check listTasks includes assetCount
|
||||
const list = await kanbanService.listTasks(team.id, {})
|
||||
const listed = list.data.find((t) => t.id === task.id)
|
||||
expect(listed?.assetCount).toBe(2)
|
||||
})
|
||||
|
||||
it('updates task assets when assetIds are passed in updateTask', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
const { file, folder } = await setupProjectAndAssets(team.id, owner.id)
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Initial Task',
|
||||
assetIds: [file.id],
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
expect(task.assetCount).toBe(1)
|
||||
|
||||
// Replace file with folder
|
||||
const updated = await kanbanService.updateTask(
|
||||
task.id,
|
||||
{
|
||||
assetIds: [folder.id],
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
expect(updated.assetCount).toBe(1)
|
||||
const detail = await kanbanService.getTask(task.id)
|
||||
expect(detail.assets).toHaveLength(1)
|
||||
expect(detail.assets[0].id).toBe(folder.id)
|
||||
})
|
||||
|
||||
it('supports linkAsset, linkAssets, unlinkAsset, and listTasksForAsset', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
const { file, folder } = await setupProjectAndAssets(team.id, owner.id)
|
||||
|
||||
const task1 = await kanbanService.createTask(team.id, { title: 'Task 1' }, owner.id, 'owner')
|
||||
const task2 = await kanbanService.createTask(team.id, { title: 'Task 2' }, owner.id, 'owner')
|
||||
|
||||
// Link single asset
|
||||
await kanbanService.linkAsset(team.id, task1.id, file.id)
|
||||
// Link multiple assets
|
||||
await kanbanService.linkAssets(team.id, task2.id, [file.id, folder.id])
|
||||
|
||||
// Check count and list for file
|
||||
const fileTaskCount = await kanbanService.getAssetTaskCount(file.id)
|
||||
expect(fileTaskCount).toBe(2)
|
||||
|
||||
const fileTasks = await kanbanService.listTasksForAsset(team.id, file.id)
|
||||
expect(fileTasks).toHaveLength(2)
|
||||
expect(fileTasks.map((t) => t.id)).toContain(task1.id)
|
||||
expect(fileTasks.map((t) => t.id)).toContain(task2.id)
|
||||
|
||||
// Unlink asset from task1
|
||||
await kanbanService.unlinkAsset(team.id, task1.id, file.id)
|
||||
const afterUnlink = await kanbanService.listTasksForAsset(team.id, file.id)
|
||||
expect(afterUnlink).toHaveLength(1)
|
||||
expect(afterUnlink[0].id).toBe(task2.id)
|
||||
})
|
||||
|
||||
it('cascade deletes links when asset or task is deleted', async () => {
|
||||
const { team, owner } = await setupTeamAndUsers()
|
||||
const { file } = await setupProjectAndAssets(team.id, owner.id)
|
||||
|
||||
const task = await kanbanService.createTask(
|
||||
team.id,
|
||||
{
|
||||
title: 'Task to be deleted',
|
||||
assetIds: [file.id],
|
||||
},
|
||||
owner.id,
|
||||
'owner',
|
||||
)
|
||||
|
||||
expect(await kanbanService.getAssetTaskCount(file.id)).toBe(1)
|
||||
|
||||
// Delete task
|
||||
await kanbanService.deleteTask(task.id, owner.id, 'owner')
|
||||
expect(await kanbanService.getAssetTaskCount(file.id)).toBe(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -419,7 +419,14 @@ describe('NotificationService', () => {
|
||||
const info = await svc['toNotificationInfo'](
|
||||
await prisma.notification.findUniqueOrThrow({
|
||||
where: { id: n.id },
|
||||
include: { creator: true, team: true, project: true, asset: true, user: true },
|
||||
include: {
|
||||
creator: true,
|
||||
team: true,
|
||||
project: true,
|
||||
asset: true,
|
||||
user: true,
|
||||
kanbanTask: true,
|
||||
},
|
||||
}),
|
||||
null,
|
||||
)
|
||||
@@ -430,4 +437,103 @@ describe('NotificationService', () => {
|
||||
expect(info.asset?.originalWidth).toBe(1280)
|
||||
expect(info.asset?.originalHeight).toBe(720)
|
||||
})
|
||||
|
||||
it('notifyKanbanTaskEvent broadcasts to stakeholders excluding actor and parses mentions', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team Kanban' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'Actor', email: `actor-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const u2 = await prisma.user.create({
|
||||
data: { name: 'Assignee', email: `assignee-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const u3 = await prisma.user.create({
|
||||
data: { name: 'Mentioned', email: `mentioned-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
const task = await prisma.kanbanTask.create({
|
||||
data: {
|
||||
teamId: tm.id,
|
||||
creatorId: u1.id,
|
||||
title: 'Important task',
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
await svc.notifyKanbanTaskEvent({
|
||||
type: NotificationType.kanban_task_comment_created,
|
||||
teamId: tm.id,
|
||||
creatorId: u1.id,
|
||||
kanbanTaskId: task.id,
|
||||
stakeholderIds: [u1.id, u2.id],
|
||||
commentMessage: `Hey <@${u3.id}> please check this`,
|
||||
})
|
||||
|
||||
const notifications = await prisma.notification.findMany({
|
||||
where: { kanbanTaskId: task.id },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
|
||||
// u1 is actor, should not get notification.
|
||||
// u2 is stakeholder, gets kanban_task_comment_created.
|
||||
// u3 is mentioned, gets mention.
|
||||
expect(notifications).toHaveLength(2)
|
||||
|
||||
const commentNotif = notifications.find(
|
||||
(n) => n.type === NotificationType.kanban_task_comment_created,
|
||||
)
|
||||
expect(commentNotif?.userId).toBe(u2.id)
|
||||
|
||||
const mentionNotif = notifications.find((n) => n.type === NotificationType.mention)
|
||||
expect(mentionNotif?.userId).toBe(u3.id)
|
||||
})
|
||||
|
||||
it('filters kanban notifications based on user preferences', async () => {
|
||||
const tm = await prisma.team.create({ data: { name: 'Team Settings' } })
|
||||
const u1 = await prisma.user.create({
|
||||
data: { name: 'U1', email: `u1-set-${Date.now()}@example.com`, password: 'p' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: tm.id, userId: u1.id, role: 'owner' },
|
||||
})
|
||||
const task = await prisma.kanbanTask.create({
|
||||
data: { teamId: tm.id, creatorId: u1.id, title: 'Task' },
|
||||
})
|
||||
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
teamId: tm.id,
|
||||
type: NotificationType.kanban_task_created,
|
||||
userId: u1.id,
|
||||
kanbanTaskId: task.id,
|
||||
},
|
||||
})
|
||||
await prisma.notification.create({
|
||||
data: {
|
||||
teamId: tm.id,
|
||||
type: NotificationType.kanban_task_comment_created,
|
||||
userId: u1.id,
|
||||
kanbanTaskId: task.id,
|
||||
},
|
||||
})
|
||||
|
||||
const svc = notificationService
|
||||
// By default both are enabled
|
||||
const listDefault = await svc.list(tm.id, u1.id, {})
|
||||
expect(listDefault.data).toHaveLength(2)
|
||||
|
||||
// Disable kanbanTasks
|
||||
await userMetadataService.upsertMetadata(u1.id, tm.id, 'notification_settings', {
|
||||
comments: true,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: false,
|
||||
kanbanComments: true,
|
||||
})
|
||||
|
||||
const listWithoutTasks = await svc.list(tm.id, u1.id, {})
|
||||
expect(listWithoutTasks.data).toHaveLength(1)
|
||||
expect(listWithoutTasks.data[0].type).toBe(NotificationType.kanban_task_comment_created)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -15,6 +15,74 @@ import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadat
|
||||
const mentionRegex = /<@([^>]+)>/g
|
||||
|
||||
export class NotificationService {
|
||||
async notifyKanbanTaskEvent(params: {
|
||||
type: NotificationType
|
||||
teamId: string
|
||||
projectId?: string | null
|
||||
creatorId: string
|
||||
kanbanTaskId?: string
|
||||
stakeholderIds?: (string | null | undefined)[]
|
||||
targetUserId?: string
|
||||
commentMessage?: string
|
||||
}) {
|
||||
const recipients = new Set<string>()
|
||||
if (params.targetUserId) {
|
||||
recipients.add(params.targetUserId)
|
||||
}
|
||||
if (params.stakeholderIds) {
|
||||
for (const id of params.stakeholderIds) {
|
||||
if (id) recipients.add(id)
|
||||
}
|
||||
}
|
||||
recipients.delete(params.creatorId)
|
||||
|
||||
const promises: Promise<void>[] = []
|
||||
for (const recipientId of recipients) {
|
||||
promises.push(
|
||||
this.createAsync({
|
||||
type: params.type,
|
||||
teamId: params.teamId,
|
||||
projectId: params.projectId ?? undefined,
|
||||
creatorId: params.creatorId,
|
||||
kanbanTaskId: params.kanbanTaskId,
|
||||
userId: recipientId,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
if (params.commentMessage) {
|
||||
const matches = [...params.commentMessage.matchAll(mentionRegex)]
|
||||
const mentionedIds = new Set<string>()
|
||||
|
||||
for (const match of matches) {
|
||||
if (match.length > 1) {
|
||||
const userId = match[1]
|
||||
if (mentionedIds.has(userId)) {
|
||||
continue
|
||||
}
|
||||
mentionedIds.add(userId)
|
||||
|
||||
if (params.creatorId === userId) {
|
||||
continue
|
||||
}
|
||||
|
||||
promises.push(
|
||||
this.createAsync({
|
||||
type: NotificationType.mention,
|
||||
teamId: params.teamId,
|
||||
projectId: params.projectId ?? undefined,
|
||||
creatorId: params.creatorId,
|
||||
kanbanTaskId: params.kanbanTaskId,
|
||||
userId: userId,
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(promises)
|
||||
}
|
||||
|
||||
async create(req: CreateNotificationRequest) {
|
||||
// Note: Do not await this, we fire and forget similarly to Go
|
||||
this.createAsync(req).catch((err) => {
|
||||
@@ -36,6 +104,16 @@ export class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve ProjectID from KanbanTaskId if missing
|
||||
if (!projectId && req.kanbanTaskId) {
|
||||
const task = await prisma.kanbanTask.findUnique({
|
||||
where: { id: req.kanbanTaskId },
|
||||
})
|
||||
if (task?.projectId) {
|
||||
projectId = task.projectId
|
||||
}
|
||||
}
|
||||
|
||||
// Check project notification settings
|
||||
if (projectId) {
|
||||
const project = await prisma.project.findUnique({
|
||||
@@ -57,6 +135,7 @@ export class NotificationService {
|
||||
creatorId: req.creatorId,
|
||||
assetId: req.assetId,
|
||||
taskId: req.taskId,
|
||||
kanbanTaskId: req.kanbanTaskId,
|
||||
userId: targetUserId,
|
||||
},
|
||||
})
|
||||
@@ -71,7 +150,8 @@ export class NotificationService {
|
||||
// 2. Handle Mentions for Comment/Reply types
|
||||
if (
|
||||
(req.type === NotificationType.comment_created ||
|
||||
req.type === NotificationType.reply_created) &&
|
||||
req.type === NotificationType.reply_created ||
|
||||
req.type === NotificationType.kanban_task_comment_created) &&
|
||||
req.commentMessage
|
||||
) {
|
||||
const matches = [...req.commentMessage.matchAll(mentionRegex)]
|
||||
@@ -128,23 +208,25 @@ export class NotificationService {
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
kanbanTasks: true,
|
||||
kanbanComments: true,
|
||||
}
|
||||
|
||||
const typeConditions: Prisma.NotificationWhereInput[] = []
|
||||
|
||||
// 1. Comments
|
||||
if (settings.comments) {
|
||||
if (settings.comments ?? true) {
|
||||
typeConditions.push({ type: NotificationType.comment_created, userId: null })
|
||||
}
|
||||
|
||||
// 2. Replies
|
||||
if (settings.replies) {
|
||||
if (settings.replies ?? true) {
|
||||
typeConditions.push({ type: NotificationType.reply_created, userId: userId })
|
||||
typeConditions.push({ type: NotificationType.reply_created, userId: null })
|
||||
}
|
||||
|
||||
// 3. Mentions
|
||||
if (settings.mentions) {
|
||||
if (settings.mentions ?? true) {
|
||||
typeConditions.push({ type: NotificationType.mention, userId: userId })
|
||||
}
|
||||
|
||||
@@ -161,11 +243,35 @@ export class NotificationService {
|
||||
}
|
||||
|
||||
// 5. Status Updates
|
||||
if (settings.statusUpdates) {
|
||||
if (settings.statusUpdates ?? true) {
|
||||
typeConditions.push({ type: NotificationType.metadata_field_updated_status })
|
||||
}
|
||||
|
||||
// 6. Always include team/project join notifications
|
||||
// 6. Kanban Tasks
|
||||
if (settings.kanbanTasks ?? true) {
|
||||
typeConditions.push({
|
||||
type: {
|
||||
in: [
|
||||
NotificationType.kanban_task_created,
|
||||
NotificationType.kanban_task_assigned,
|
||||
NotificationType.kanban_task_status_updated,
|
||||
NotificationType.kanban_task_updated,
|
||||
NotificationType.kanban_task_deleted,
|
||||
],
|
||||
},
|
||||
userId: userId,
|
||||
})
|
||||
}
|
||||
|
||||
// 7. Kanban Comments
|
||||
if (settings.kanbanComments ?? true) {
|
||||
typeConditions.push({
|
||||
type: NotificationType.kanban_task_comment_created,
|
||||
userId: userId,
|
||||
})
|
||||
}
|
||||
|
||||
// 8. Always include team/project join notifications
|
||||
typeConditions.push({ type: NotificationType.new_user_join_team })
|
||||
typeConditions.push({ type: NotificationType.new_user_join_project })
|
||||
|
||||
@@ -193,6 +299,7 @@ export class NotificationService {
|
||||
{
|
||||
OR: [
|
||||
{ type: NotificationType.mention }, // Always allow mentions (targeted)
|
||||
{ userId: userId }, // Direct targeted notifications (e.g. assigned, stakeholder)
|
||||
{ projectId: { in: projectFilter } }, // Only show notifications for projects user is member of
|
||||
],
|
||||
},
|
||||
@@ -270,6 +377,7 @@ export class NotificationService {
|
||||
project: true,
|
||||
asset: true,
|
||||
user: true,
|
||||
kanbanTask: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -329,7 +437,14 @@ export class NotificationService {
|
||||
|
||||
private async toNotificationInfo(
|
||||
n: Prisma.NotificationGetPayload<{
|
||||
include: { creator: true; team: true; project: true; asset: true; user: true }
|
||||
include: {
|
||||
creator: true
|
||||
team: true
|
||||
project: true
|
||||
asset: true
|
||||
user: true
|
||||
kanbanTask: true
|
||||
}
|
||||
}>,
|
||||
lastRead: Prisma.NotificationGetPayload<Record<string, never>> | null,
|
||||
): Promise<NotificationInfo> {
|
||||
@@ -368,6 +483,14 @@ export class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
if (n.kanbanTask) {
|
||||
info.kanbanTask = {
|
||||
id: n.kanbanTask.id,
|
||||
title: n.kanbanTask.title,
|
||||
status: n.kanbanTask.status,
|
||||
}
|
||||
}
|
||||
|
||||
if (n.asset) {
|
||||
const a = n.asset
|
||||
let previewUrl = ''
|
||||
|
||||
Reference in New Issue
Block a user