Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

19.0 KB
Raw Blame
import { describe, it, expect, beforeEach } from 'bun:test';
import { db, notificationDelivery } from '@repo/db';
import { asc } from 'drizzle-orm';
import { authedApi, type Api, createProject } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';

// Notifications are fanned out when an issue changes and read back through the
// session user's inbox. The actor is never notified about their own action, and
// only project members receive notifications. New members join through invites, so
// a second member is added by creating and accepting an invite.

interface Member {
  api: Api;
  userId: string;
  username: string;
}

async function setup() {
  const u = await signUpTestUser();
  const api = authedApi(u.cookie);
  await createProject(api, { key: 'MKT', name: 'Marketing' });
  const view = await api.projects({ projectKey: 'MKT' }).get();
  const columns = view.data!.columns;
  const done = columns.find((c) => c.stateType === 'completed') ?? columns[columns.length - 1];
  return {
    owner: { api, userId: u.userId, username: u.username },
    project: view.data!.project,
    columnId: columns[0].id,
    doneColumnId: done.id,
  };
}

async function addMember(owner: Member): Promise<Member> {
  const u = await signUpTestUser();
  const invite = await owner.api
    .projects({ projectKey: 'MKT' })
    .invites.post({ email: u.email, role: 'member' });
  const api = authedApi(u.cookie);
  await api.invites({ token: invite.data!.token }).accept.post();
  return { api, userId: u.userId, username: u.username };
}

function createIssue(client: Api, columnId: number, patch: Record<string, unknown> = {}) {
  return client.projects({ projectKey: 'MKT' }).issues.post({ columnId, title: 'Task', ...patch });
}

describe('notifications', () => {
  it('bulk read and delete keep notifications outside the active type filter', async () => {
    const { owner, columnId, doneColumnId } = await setup();
    const member = await addMember(owner);
    const issue = (await createIssue(owner.api, columnId, { assigneeUserId: member.userId })).data!;
    const client = owner.api.issues({ issueId: issue.id });
    await client.comments.post({ body: 'Please review' } as never);
    await client.patch({ description: `@${member.username} review this` });
    await client.patch({ columnId: doneColumnId });

    const before = (await member.api.notifications.get({ query: {} })).data!.items;
    expect(before.map((item) => item.type).sort()).toEqual([
      'assigned',
      'commented',
      'mentioned',
      'state_changed',
    ]);
    const read = await member.api.notifications['read-all'].post({
      types: ['state_changed'],
      includeSnoozed: false,
    });
    expect(read.status).toBe(200);
    expect(read.data!.count).toBe(1);
    const afterRead = (await member.api.notifications.get({ query: {} })).data!.items;
    expect(afterRead.filter((item) => item.readAt != null).map((item) => item.type)).toEqual([
      'state_changed',
    ]);
    expect((await member.api.notifications['read-all'].post()).data!.count).toBe(3);
    const deleted = await member.api.notifications.delete(undefined, {
      query: { scope: 'read-completed', types: 'state_changed', includeSnoozed: 'false' },
    });
    expect(deleted.data!.count).toBe(1);
    const remaining = (await member.api.notifications.get({ query: {} })).data!.items;
    expect(remaining.map((item) => item.type).sort()).toEqual([
      'assigned',
      'commented',
      'mentioned',
    ]);
    expect(remaining.every((item) => item.readAt != null)).toBe(true);
  });

  it('completed deletes unread and read notifications, and leaves active issues alone', async () => {
    const { owner, columnId, doneColumnId } = await setup();
    const member = await addMember(owner);
    const active = (await createIssue(owner.api, columnId, { assigneeUserId: member.userId }))
      .data!;
    const completed = (
      await createIssue(owner.api, doneColumnId, { assigneeUserId: member.userId })
    ).data!;
    await owner.api.issues({ issueId: completed.id }).comments.post({ body: 'Done' } as never);

    const before = (await member.api.notifications.get({ query: {} })).data!.items;
    expect(before).toHaveLength(3);
    expect(
      before
        .filter((item) => item.issueId === completed.id)
        .map((item) => item.type)
        .sort(),
    ).toEqual(['assigned', 'commented']);
    expect(before.find((item) => item.issueId === active.id)!.type).toBe('assigned');
    expect(before.every((item) => item.readAt == null)).toBe(true);
    await member.api.notifications['read-all'].post({ types: ['commented'] });

    const assigned = await member.api.notifications.delete(undefined, {
      query: {
        scope: 'completed',
        types: 'assigned',
        includeRead: 'false',
        includeSnoozed: 'false',
      },
    });
    expect(assigned.data!.count).toBe(1);
    const afterAssigned = (await member.api.notifications.get({ query: {} })).data!.items;
    expect(afterAssigned.map((item) => item.issueId!).sort((a, b) => a - b)).toEqual(
      [active.id, completed.id].sort((a, b) => a - b),
    );
    expect(afterAssigned.find((item) => item.issueId === completed.id)!.readAt).not.toBeNull();
    expect(afterAssigned.find((item) => item.issueId === active.id)!.readAt).toBeNull();

    const all = await member.api.notifications.delete(undefined, {
      query: { scope: 'completed', includeRead: 'false', includeSnoozed: 'false' },
    });
    expect(all.data!.count).toBe(1);
    const remaining = (await member.api.notifications.get({ query: {} })).data!.items;
    expect(remaining).toHaveLength(1);
    expect(remaining[0].issueId).toBe(active.id);
    expect(remaining[0].readAt).toBeNull();
  });

  it('bulk actions respect actor and snooze filters', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    const other = await addMember(owner);
    const issue = (await createIssue(owner.api, columnId, { assigneeUserId: member.userId })).data!;
    await other.api.issues({ issueId: issue.id }).comments.post({ body: 'Other actor' } as never);
    await owner.api.issues({ issueId: issue.id }).comments.post({ body: 'Owner actor' } as never);
    const items = (await member.api.notifications.get({ query: {} })).data!.items;
    const snoozed = items.find((item) => item.type === 'assigned')!;
    await member.api.notifications({ id: snoozed.id }).snooze.post({
      until: new Date(Date.now() + 86_400_000).toISOString(),
    });
    const read = await member.api.notifications['read-all'].post({
      from: owner.userId,
      includeSnoozed: false,
    });
    expect(read.data!.count).toBe(1);
    const deleted = await member.api.notifications.delete(undefined, {
      query: { scope: 'all', from: owner.userId, includeSnoozed: 'false' },
    });
    expect(deleted.data!.count).toBe(1);
    const remaining = (await member.api.notifications.get({ query: { includeSnoozed: 'true' } }))
      .data!.items;
    expect(remaining).toHaveLength(2);
    expect(remaining.every((item) => item.readAt == null)).toBe(true);
    expect(remaining.some((item) => item.id === snoozed.id)).toBe(true);
  });

  it('rejects an unknown bulk delete type without deleting notifications', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    await createIssue(owner.api, columnId, { assigneeUserId: member.userId });
    const deleted = await member.api.notifications.delete(undefined, {
      query: { scope: 'all', types: 'unknown' },
    });
    expect(deleted.status).toBe(400);
    expect((await member.api.notifications.get({ query: {} })).data!.items).toHaveLength(1);
  });

  beforeEach(async () => {
    await resetDb();
  });

  it('notifies a member mentioned in the description', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    const issue = (await createIssue(owner.api, columnId)).data!;

    await owner.api.issues({ issueId: issue.id }).patch({
      description: `@${member.username} please size this`,
    });

    const inbox = await member.api.notifications.get({ query: { types: 'mentioned' } });
    expect(inbox.data!.items).toHaveLength(1);
    expect(inbox.data!.items[0]).toMatchObject({
      type: 'mentioned',
      actorUserId: owner.userId,
      issueCommentId: null,
    });
  });

  it('notifies a member mentioned in a markdown custom field', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    const field = (
      await owner.api
        .projects({ projectKey: 'MKT' })
        ['custom-fields'].post({ name: 'Notes', fieldType: 'markdown' })
    ).data!;
    const issue = (await createIssue(owner.api, columnId)).data!;

    await owner.api
      .issues({ issueId: issue.id })
      .fields({ fieldId: field.id })
      .put({ value: `@${member.username} take the copy` });

    const inbox = await member.api.notifications.get({ query: { types: 'mentioned' } });
    expect(inbox.data!.items).toHaveLength(1);
  });

  it('does not notify again for a mention the description already carried', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    const issue = (await createIssue(owner.api, columnId)).data!;
    const client = owner.api.issues({ issueId: issue.id });
    await client.patch({ description: `@${member.username} please size this` });

    await client.patch({ description: `@${member.username} please size this today` });

    const inbox = await member.api.notifications.get({ query: { types: 'mentioned' } });
    expect(inbox.data!.items).toHaveLength(1);
  });

  it('notifies the new assignee, not the actor', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);

    await createIssue(owner.api, columnId, {
      title: 'Ship it',
      assigneeUserId: member.userId,
    });

    const inbox = await member.api.notifications.get({ query: {} });
    expect(inbox.status).toBe(200);
    expect(inbox.data!.items).toHaveLength(1);
    expect(inbox.data!.items[0]).toMatchObject({
      type: 'assigned',
      actorUserId: owner.userId,
      issueTitle: 'Ship it',
      projectKey: 'MKT',
      readAt: null,
    });

    // The actor is not notified about their own action.
    const ownerInbox = await owner.api.notifications.get({ query: {} });
    expect(ownerInbox.data!.items).toHaveLength(0);
  });

  it('notifies the member put into a member custom field', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    const field = (
      await owner.api
        .projects({ projectKey: 'MKT' })
        ['custom-fields'].post({ name: 'Reviewer', fieldType: 'member', memberScope: 'humans' })
    ).data!;
    const issue = (await createIssue(owner.api, columnId, { title: 'Ship it' })).data!;

    await owner.api
      .issues({ issueId: issue.id })
      .fields({ fieldId: field.id })
      .put({ value: member.userId });

    const inbox = await member.api.notifications.get({ query: {} });
    expect(inbox.data!.items).toHaveLength(1);
    expect(inbox.data!.items[0]).toMatchObject({
      type: 'assigned',
      actorUserId: owner.userId,
      issueTitle: 'Ship it',
    });
  });

  it('notifies watchers on a comment', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);

    // Owner creates the issue assigned to member, which subscribes both: the owner
    // as its author, the member through the assignment.
    const issue = await createIssue(owner.api, columnId, { assigneeUserId: member.userId });
    const issueId = issue.data!.id;

    // Member comments -> owner (a watcher) gets a 'commented' notification.
    await owner.api.issues({ issueId }).comments.post({ body: 'looking into it' } as never);
    const comment = (await member.api.issues({ issueId }).comments.post({ body: 'done' })).data!;

    const ownerInbox = await owner.api.notifications.get({ query: { types: 'commented' } });
    expect(ownerInbox.data!.items).toHaveLength(1);
    expect(ownerInbox.data!.items[0]).toMatchObject({
      type: 'commented',
      actorUserId: member.userId,
      issueCommentId: comment.id,
    });
  });

  it('keeps the notification of a deleted comment, pointing at the issue only', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    const issue = (await createIssue(owner.api, columnId)).data!;
    const comment = (
      await owner.api
        .issues({ issueId: issue.id })
        .comments.post({ body: `@${member.username} look` })
    ).data!;

    await owner.api.comments({ commentId: comment.id }).delete();

    const inbox = await member.api.notifications.get({ query: {} });
    expect(inbox.data!.items).toHaveLength(1);
    expect(inbox.data!.items[0]).toMatchObject({
      type: 'mentioned',
      issueId: issue.id,
      issueCommentId: null,
    });
  });

  it('links the email about a comment to the comment, and about a description to the issue', async () => {
    const { owner, project, columnId } = await setup();
    const member = await addMember(owner);
    await owner.api.teams({ teamId: project.teamId })['notification-settings'].put({
      smtp: {
        enabled: true,
        host: 'smtp.example.com',
        port: 587,
        encryption: 'none',
        username: '[email protected]',
        password: 'secret',
        timeout: null,
      },
    });
    const events = { assigned: true, mentioned: true, commented: true, state_changed: true };
    await member.api.projects({ projectKey: 'MKT' })['notification-preferences'].put({
      emailEvents: events,
      telegramEvents: events,
    });
    const issue = (await createIssue(owner.api, columnId)).data!;
    const client = owner.api.issues({ issueId: issue.id });
    const comment = (await client.comments.post({ body: `@${member.username} have a look` })).data!;
    await client.patch({ description: `@${member.username} size this` });

    // No route reads the outbox, and its rows are what the worker sends.
    const queued = await db
      .select({ payload: notificationDelivery.payload })
      .from(notificationDelivery)
      .orderBy(asc(notificationDelivery.id));
    const issueLink = `${process.env.APP_URL}/${project.teamRef}/issue/${issue.identifier}`;
    expect(queued.map((row) => row.payload.url)).toEqual([
      `${issueLink}#comment-${comment.id}`,
      issueLink,
    ]);
  });

  it('sends each recipient the email in their language, with what god changed', async () => {
    const { owner, project, columnId, doneColumnId } = await setup();
    const member = await addMember(owner);
    await owner.api.teams({ teamId: project.teamId })['notification-settings'].put({
      smtp: {
        enabled: true,
        host: 'smtp.example.com',
        port: 587,
        encryption: 'none',
        username: '[email protected]',
        password: 'secret',
        timeout: null,
      },
    });
    const events = { assigned: true, mentioned: true, commented: true, state_changed: true };
    await member.api.projects({ projectKey: 'MKT' })['notification-preferences'].put({
      emailEvents: events,
      telegramEvents: events,
    });
    await member.api.account.preferences.patch({ locale: 'ru' });
    await owner.api.god['email-templates'].put({
      edits: {
        stateChanged: {
          ru: {
            subject: 'Статус {ref}: {to}',
            body: '**{title}** {from} → {to}',
            button: 'Открыть',
          },
        },
      },
      layout: null,
    });
    const issue = (
      await createIssue(owner.api, columnId, {
        title: '<b>Loud</b> title',
        assigneeUserId: member.userId,
      })
    ).data!;
    await db.delete(notificationDelivery);

    await owner.api.issues({ issueId: issue.id }).patch({ columnId: doneColumnId });

    const [queued] = await db
      .select({ payload: notificationDelivery.payload })
      .from(notificationDelivery);
    expect(queued!.payload.subject).toStartWith(`Статус ${issue.identifier}:`);
    expect(queued!.payload.text).toContain('<b>Loud</b> title');
    expect(queued!.payload.html).toContain('&lt;b&gt;Loud&lt;/b&gt; title');
    expect(queued!.payload.html).toContain('class="button"');
  });

  it('a status change notification names the states it moved between', async () => {
    const { owner, columnId, doneColumnId } = await setup();
    const member = await addMember(owner);
    const issue = await createIssue(owner.api, columnId, { assigneeUserId: member.userId });

    await owner.api.issues({ issueId: issue.data!.id }).patch({ columnId: doneColumnId });

    const view = await owner.api.projects({ projectKey: 'MKT' }).get();
    const names = new Map(view.data!.columns.map((c) => [c.id, c.name]));
    const inbox = await member.api.notifications.get({ query: { types: 'state_changed' } });
    expect(inbox.data!.items).toHaveLength(1);
    expect(inbox.data!.items[0]).toMatchObject({
      type: 'state_changed',
      fromState: names.get(columnId),
      toState: names.get(doneColumnId),
    });
  });

  it('unread count tracks reads', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    await createIssue(owner.api, columnId, { assigneeUserId: member.userId });

    const first = await member.api.notifications.unread.get({ query: {} });
    expect(first.data!.unread).toBe(1);

    const inbox = await member.api.notifications.get({ query: {} });
    const id = inbox.data!.items[0].id;
    const read = await member.api.notifications({ id }).read.post({ read: true } as never);
    expect(read.status).toBe(204);

    expect((await member.api.notifications.unread.get({ query: {} })).data!.unread).toBe(0);

    // includeRead=false hides the now-read notification.
    const unreadOnly = await member.api.notifications.get({ query: { includeRead: 'false' } });
    expect(unreadOnly.data!.items).toHaveLength(0);
  });

  it('drops the notifications of a project the user was removed from', async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    await createIssue(owner.api, columnId, { assigneeUserId: member.userId });
    expect((await member.api.notifications.get({ query: {} })).data!.items).toHaveLength(1);

    await owner.api.projects({ projectKey: 'MKT' }).members({ userId: member.userId }).delete();

    expect((await member.api.notifications.get({ query: {} })).data!.items).toHaveLength(0);
    expect((await member.api.notifications.unread.get({ query: {} })).data!.unread).toBe(0);
  });

  it("a member cannot read or mutate another user's notification", async () => {
    const { owner, columnId } = await setup();
    const member = await addMember(owner);
    await createIssue(owner.api, columnId, { assigneeUserId: member.userId });
    const inbox = await member.api.notifications.get({ query: {} });
    const id = inbox.data!.items[0].id;

    // The owner does not own this notification: mutating it is a 404.
    const res = await owner.api.notifications({ id }).read.post({ read: true } as never);
    expect(res.status).toBe(404);
  });
});