Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion apps/api/src/modules/documents/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { and, asc, eq } from 'drizzle-orm';
import { documentVisibleTo } from './access';
import { HttpError } from '#shared/lib';
import { issueSources } from '#modules/issues/sources';

export interface DocumentIssueLinkRow {
issueId: number;
Expand All @@ -17,6 +18,7 @@ export interface DocumentIssueLinkRow {
title: string;
archived: boolean;
createdAt: string;
source: string | null;
}

export interface DocumentInitiativeLinkRow {
Expand Down Expand Up @@ -99,13 +101,15 @@ export async function listDocumentIssueLinks(
.innerJoin(issue, eq(issue.id, projectDocumentIssue.issueId))
.where(and(eq(projectDocumentIssue.documentId, documentId), eq(issue.projectId, projectId)))
.orderBy(asc(issue.sequenceNumber));
const sources = await issueSources(rows.map((row) => row.issueId));
return rows.map((row) => ({
issueId: row.issueId,
sequenceNumber: row.sequenceNumber,
identifier: `${projectKey}-${row.sequenceNumber}`,
title: row.title,
archived: row.archivedAt !== null,
createdAt: row.createdAt.toISOString(),
source: sources.get(row.issueId) ?? null,
}));
}

Expand Down Expand Up @@ -150,7 +154,7 @@ export async function addDocumentIssueLink(input: {
issueId: number;
userId: string;
}): Promise<DocumentIssueLinkRow> {
return db.transaction(async (tx) => {
const link = await db.transaction(async (tx) => {
const document = await visibleDocument(input.projectId, input.documentId, input.userId, tx);
if (!document) throw new HttpError(404, 'Document not found');
if (document.archivedAt !== null)
Expand Down Expand Up @@ -188,6 +192,7 @@ export async function addDocumentIssueLink(input: {
createdAt: created.createdAt.toISOString(),
};
});
return { ...link, source: (await issueSources([link.issueId])).get(link.issueId) ?? null };
}

export async function removeDocumentIssueLink(input: {
Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/modules/documents/model.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { t } from 'elysia';
import { AttachmentContent, ViewAttachmentsResponse } from '#modules/attachments/model';
import { IssueSource } from '#modules/issues/model';

export const documentParams = t.Object({
projectKey: t.String(),
Expand Down Expand Up @@ -189,6 +190,7 @@ export const DocumentIssueLinkResponse = t.Object({
title: t.String(),
archived: t.Boolean(),
createdAt: t.String(),
source: IssueSource,
});

export const DocumentIssueLinkListResponse = t.Array(DocumentIssueLinkResponse);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createHmac } from 'node:crypto';
import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import { app } from '../../../../app';
import { authedApi, type Api, createProject } from '#tests/helpers/app';
import { api, authedApi, type Api, createProject } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
import { createAgent } from '#tests/helpers/agents';
Expand Down Expand Up @@ -350,6 +350,34 @@ describe('Repository issue sync', () => {
);
});

it('names the host of a linked issue on the board and on the issue, not on a public link', async () => {
const s = await setup(fake);
await repository(s).patch({ issueSync: 'one_way' });
await deliver(s, 'issues', issueEvent('opened', opened));
const project = s.asOwner.projects({ projectKey: 'MKT' });
const plain = (await project.issues.post({ columnId: s.columns[0]!.id, title: 'Plain' })).data!;

const board = (await project.issues.board.get()).data!.issues;
const linked = board.find((issue) => issue.id !== plain.id)!;
expect(linked.source).toBe('github');
expect(board.find((issue) => issue.id === plain.id)!.source).toBeNull();
const detail = (await s.asOwner.issues({ issueId: linked.id }).get()).data!;
expect(detail.source).toBe('github');

const view = (await project.views.post({ name: 'Board', filters: {} })).data!;
const viewToken = (await s.asOwner.views({ viewId: view.id }).share.post({ extended: true }))
.data!.token;
const issueToken = (
await s.asOwner.issues({ issueId: linked.id }).share.post({ extended: true })
).data!.token;
const sharedBoard = (await api.share.view({ token: viewToken }).get()).data! as {
issues: { id: number; source: string | null }[];
};
expect(sharedBoard.issues.find((issue) => issue.id === linked.id)!.source).toBeNull();
const sharedIssue = (await api.share.issue({ token: issueToken }).get()).data!;
expect(sharedIssue.issue.source).toBeNull();
});

it('notifies nobody a repository issue mentions', async () => {
const s = await setup(fake);
const member = await signUpTestUser();
Expand Down Expand Up @@ -1119,7 +1147,11 @@ describe('Repository issue sync', () => {
expect(await deliver(s, 'issue_comment', comment)).toMatchObject({ handled: 'ignored' });
expect(fake.stateChanges).toEqual([]);
const detail = (await s.asOwner.issues({ issueId: created!.id }).get()).data!;
expect(detail).toMatchObject({ title: opened.title, repositoryIssue: null });
expect(detail).toMatchObject({
title: opened.title,
repositoryIssue: null,
source: null,
});
});

it('adds a repository issue to a column at its hard WIP limit', async () => {
Expand Down
19 changes: 18 additions & 1 deletion apps/api/src/modules/git/issue-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
issue,
issueActivity,
} from '@repo/db';
import { and, asc, eq, inArray, isNull, lt, ne, sql } from 'drizzle-orm';
import { and, asc, eq, inArray, isNull, lt, ne, sql, type SQLWrapper } from 'drizzle-orm';
import { HttpError } from '#shared/lib';
import {
createIssue,
Expand Down Expand Up @@ -558,6 +558,23 @@ export async function pushLinkedIssueState(issueId: number, columnId: number): P
}
}

// The host of the repository issue each of these issues is synced with: the source of an
// issue that came from a repository.
export async function repositoryHosts(
ids: number[] | SQLWrapper,
): Promise<{ issueId: number; source: string }[]> {
return db
.select({ issueId: issue.id, source: gitProviderConnection.provider })
.from(gitIssueLink)
.innerJoin(issue, eq(gitIssueLink.issueId, issue.id))
.innerJoin(gitManagedRepository, eq(gitIssueLink.repositoryId, gitManagedRepository.id))
.innerJoin(
gitProviderConnection,
eq(gitManagedRepository.connectionId, gitProviderConnection.id),
)
.where(and(inArray(gitIssueLink.issueId, ids), sameProject));
}

export async function getLinkedRepositoryIssue(
issueId: number,
): Promise<LinkedRepositoryIssue | null> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import { inArray } from 'drizzle-orm';
import { db, issue } from '@repo/db';
import { api as anonymous, authedApi, createProject } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
import { setIssueSources } from '../../sources';

// Where an issue came from, beside a repository host (git-issue-sync.test.ts): the source an
// extension of the api names for its own issues through setIssueSources.

describe('Issue sources an extension adds', () => {
beforeEach(resetDb);
afterEach(() => setIssueSources());

it('names the source of the issues an extension resolves, and none of the others', async () => {
const owner = await signUpTestUser();
const api = authedApi(owner.cookie);
await createProject(api, { key: 'MKT', name: 'Marketing' });
const project = api.projects({ projectKey: 'MKT' });
const columnId = (await project.get()).data!.columns[0]!.id;
const filed = (await project.issues.post({ columnId, title: 'From a form' })).data!;
const plain = (await project.issues.post({ columnId, title: 'Made here' })).data!;

setIssueSources(async (ids) => {
const rows = await db.select({ id: issue.id }).from(issue).where(inArray(issue.id, ids));
return rows
.filter((row) => row.id === filed.id)
.map((row) => ({ issueId: row.id, source: 'portal' }));
});

const board = (await project.issues.board.get()).data!.issues;
expect(board.find((one) => one.id === filed.id)!.source).toBe('portal');
expect(board.find((one) => one.id === plain.id)!.source).toBeNull();
expect((await api.issues({ issueId: filed.id }).get()).data!.source).toBe('portal');

setIssueSources();
expect((await api.issues({ issueId: filed.id }).get()).data!.source).toBeNull();
});

it('names it where another issue, a search or a page lists the issue, and not on a public link', async () => {
const owner = await signUpTestUser();
const api = authedApi(owner.cookie);
await createProject(api, { key: 'MKT', name: 'Marketing' });
const project = api.projects({ projectKey: 'MKT' });
const columnId = (await project.get()).data!.columns[0]!.id;
const parent = (await project.issues.post({ columnId, title: 'Launch' })).data!;
const filed = (
await project.issues.post({ columnId, title: 'Zephyr request', parentId: parent.id })
).data!;
setIssueSources(async (ids) => {
const rows = await db.select({ id: issue.id }).from(issue).where(inArray(issue.id, ids));
return rows
.filter((row) => row.id === filed.id)
.map((row) => ({ issueId: row.id, source: 'portal' }));
});

const link = await api
.issues({ issueId: parent.id })
.links.post({ targetIssueId: filed.id, kind: 'relates' });
expect(link.data!.issue.source).toBe('portal');
const detail = (await api.issues({ issueId: parent.id }).get()).data!;
expect(detail.subtasks.map((one) => one.source)).toEqual(['portal']);
expect(detail.links.map((one) => one.issue.source)).toEqual(['portal']);

const hit = (await project.issues.search.get({ query: { q: 'zephyr' } })).data!;
expect(hit.map((one) => one.source)).toEqual(['portal']);
const everywhere = (await api.issues.search.get({ query: { q: 'zephyr' } })).data!;
expect(everywhere.map((one) => one.source)).toEqual(['portal']);

const page = (await project.documents.post({ title: 'Notes', content: '' })).data!;
const linked = await project
.documents({ documentId: page.id })
.issues.post({ issueId: filed.id });
expect(linked.data!.source).toBe('portal');
const pageIssues = (await project.documents({ documentId: page.id }).issues.get()).data!;
expect(pageIssues.map((one) => one.source)).toEqual(['portal']);

const token = (await api.issues({ issueId: parent.id }).share.post()).data!.token;
// The public route's response schema is t.Any().
const shared = (await anonymous.share.issue({ token }).get()).data!.issue as {
subtasks: { source: string | null }[];
links: { issue: { source: string | null } }[];
};
expect(shared.subtasks.map((one) => one.source)).toEqual([null]);
expect(shared.links.map((one) => one.issue.source)).toEqual([null]);
});
});
23 changes: 21 additions & 2 deletions apps/api/src/modules/issues/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import {
} from './worklogs';
import { listIssueCycles } from './cycle-history';
import { moveIssue } from './move';
import { attachIssueSources } from './sources';
import {
createAndLinkPullRequest,
linkExistingPullRequest,
Expand Down Expand Up @@ -555,8 +556,14 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
// and move confirmations can show what the action takes along. Web-only.
.get(
'/projects/:projectKey/issues/subtree',
async ({ project, query }) =>
listSubtree(project.id, query.ids.split(',').map(Number).filter(Number.isInteger)),
async ({ project, query }) => {
const subtree = await listSubtree(
project.id,
query.ids.split(',').map(Number).filter(Number.isInteger),
);
await attachIssueSources(subtree);
return subtree;
},
{
params: projectKeyParams,
query: subtreeQuery,
Expand Down Expand Up @@ -599,6 +606,12 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
const parent = await getParentRef(issue.parentId);
const subtasks = await listSubtasks(issue.id);
const ancestors = await listAncestors(issue.id);
await attachIssueSources([
...links.map((link) => link.issue),
...subtasks,
...ancestors,
...(parent ? [parent] : []),
]);
const checklists = await listChecklists(issue.id);
const development = await listIssueDevelopmentLinks(issue.id);
const repositoryIssue = await getLinkedRepositoryIssue(issue.id);
Expand Down Expand Up @@ -741,6 +754,12 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
const parent = await getParentRef(issue.parentId);
const subtasks = await listSubtasks(issue.id);
const ancestors = await listAncestors(issue.id);
await attachIssueSources([
...links.map((link) => link.issue),
...subtasks,
...ancestors,
...(parent ? [parent] : []),
]);
const checklists = await listChecklists(issue.id);
const development = await listIssueDevelopmentLinks(issue.id);
const repositoryIssue = await getLinkedRepositoryIssue(issue.id);
Expand Down
14 changes: 5 additions & 9 deletions apps/api/src/modules/issues/links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { HttpError } from '#shared/lib';
import { recordActivityEntries, rowSide, textSide, type ActivityInput } from './activity';
import { emitIssueEvents } from './webhook-payload';
import { getIssues } from './service';
import { issueSources } from './sources';
import type { IssueRef } from './subtasks';

// Relations between issues of one project. A relation is one row (issue_link);
// which side of it an issue sits on decides how the relation reads for that
Expand All @@ -29,15 +31,7 @@ export interface IssueLinkRow {
kind: IssueLinkKind;
direction: IssueLinkDirection;
// The issue on the other end of the relation.
issue: {
id: number;
sequenceNumber: number;
identifier: string;
title: string;
columnId: number;
typeId: number | null;
archived: boolean;
};
issue: IssueRef;
}

// How a relation reads from the other end, used as the activity feed's subject so
Expand Down Expand Up @@ -108,6 +102,7 @@ export async function listIssueLinks(issueId: number): Promise<IssueLinkRow[]> {
columnId: row.columnId,
typeId: row.typeId,
archived: row.archivedAt !== null,
source: null,
},
}));
}
Expand Down Expand Up @@ -297,6 +292,7 @@ export async function addIssueLink(
columnId: target.columnId,
typeId: target.typeId,
archived: target.archived,
source: (await issueSources([target.id])).get(target.id) ?? null,
},
};
}
Expand Down
11 changes: 11 additions & 0 deletions apps/api/src/modules/issues/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ export const IssueFieldValueEntry = t.Object({
optionIds: t.Array(t.Number()),
});

// Where an issue came from (attachIssueSources in sources.ts).
export const IssueSource = t.Nullable(
t.String({
description:
'Where the issue came from: the repository host of the repository issue it is synced with, such as github, or a source an extension adds. Null for an issue made here.',
}),
);

// IssueRow from the service.
export const IssueResponse = t.Object({
id: t.Number(),
Expand Down Expand Up @@ -121,6 +129,7 @@ export const IssueResponse = t.Object({
shareExpiresAt: t.Nullable(t.String()),
labelIds: t.Array(t.Number()),
fieldValues: t.Array(IssueFieldValueEntry),
source: IssueSource,
});

// IssueFieldValueRow from the service: one applicable custom field with its value on
Expand All @@ -144,6 +153,7 @@ export const IssueRefResponse = t.Object({
columnId: t.Number(),
typeId: t.Nullable(t.Number()),
archived: t.Boolean(),
source: IssueSource,
});

export const SubtreeIssueResponse = t.Composite([
Expand Down Expand Up @@ -351,6 +361,7 @@ export const IssueSearchHitResponse = t.Object({
updatedAt: t.String(),
statusSince: t.String(),
completedAt: t.Nullable(t.String()),
source: IssueSource,
});

export const CrossProjectIssueHitResponse = t.Composite([
Expand Down
Loading
Loading