diff --git a/api/project-tickets.test.ts b/api/project-tickets.test.ts index 5a532fc..b1b7785 100644 --- a/api/project-tickets.test.ts +++ b/api/project-tickets.test.ts @@ -5,10 +5,13 @@ import { createGithubProvider } from './github-provider.ts' import { createJiraProvider } from './jira-provider.ts' import { filterTickets, + getProjectTicket, listProjectTickets, + toTicketDetailRow, toTicketRow, } from './project-tickets.ts' import { + type Comment, groupIntoTickets, type Person, type ProjectScope, @@ -214,3 +217,130 @@ describe('toTicketRow', () => { assertEquals('discussion' in row, false) }) }) + +const threadProvider = ( + id: Provider['id'], + items: WorkItem[], + thread: (item: WorkItem) => Comment[], +) => { + const asked: string[] = [] + const provider: Provider = { + id, + list: () => Promise.resolve(items), + comments: (item) => { + asked.push(item.externalId) + return Promise.resolve(thread(item)) + }, + } + return { provider, asked } +} + +describe('getProjectTicket', () => { + const jiraSide = threadProvider( + 'jira', + [jira('TNT-1'), jira('TNT-2')], + (item) => [ + { + source: 'jira', + author: 'ada@example.com', + body: `description of ${item.externalId}`, + createdAt: 100, + }, + { + source: 'jira', + author: 'ada@example.com', + body: 'jira comment', + createdAt: 400, + }, + ], + ) + const githubSide = threadProvider( + 'github', + [pr('TNT-1 Fix it'), pr('TNT-1 Follow-up', { externalId: 'gh-2' })], + (item) => [ + { + source: 'github', + author: 'grace', + body: `review on ${item.externalId}`, + createdAt: item.externalId === 'gh-2' ? 300 : 200, + }, + { source: 'github', author: 'stranger', body: 'undated' }, + ], + ) + const load = (key: string) => + getProjectTicket( + { jiraProjectKey: 'TNT' }, + key, + [jiraSide.provider, githubSide.provider], + () => Promise.resolve(directory), + ) + + it('merges the comments of every linked item, oldest first', async () => { + jiraSide.asked.length = 0 + githubSide.asked.length = 0 + const ticket = await load('TNT1') + + assertEquals(ticket?.key, 'TNT1') + assertEquals(jiraSide.asked, ['jira-TNT-1']) + assertEquals(githubSide.asked.sort(), ['gh-2', 'gh-TNT-1 Fix it']) + assertEquals(ticket?.discussion.map((comment) => comment.body), [ + 'description of jira-TNT-1', + 'review on gh-TNT-1 Fix it', + 'review on gh-2', + 'jira comment', + 'undated', + 'undated', + ]) + }) + + it('resolves comment authors against the team directory', async () => { + const ticket = await load('TNT1') + const authors = ticket?.discussion.map((comment) => comment.author?.id) + assertEquals(authors, ['p1', 'p2', 'p2', 'p1', undefined, undefined]) + }) + + it('finds a ticket from any key notation', async () => { + assertEquals((await load('tnt-2'))?.key, 'TNT2') + }) + + it('finds an unkeyed ticket by its exact key', async () => { + const side = threadProvider('github', [pr('Bump deps')], () => []) + const ticket = await getProjectTicket( + {}, + 'github:gh-Bump deps', + [side.provider], + () => Promise.resolve([]), + ) + assertEquals(ticket?.title, 'Bump deps') + assertEquals(ticket?.discussion, []) + }) + + it('returns undefined for an unknown key', async () => { + assertEquals(await load('TNT-999'), undefined) + assertEquals(await load('nonsense'), undefined) + }) +}) + +describe('toTicketDetailRow', () => { + it('only exposes resolved authors, never the raw source identity', async () => { + const side = threadProvider('jira', [jira('TNT-1')], () => [ + { source: 'jira', author: 'ada@example.com', body: 'hi', createdAt: 1 }, + { source: 'jira', author: 'nobody@example.com', body: 'yo' }, + ]) + const ticket = await getProjectTicket( + {}, + 'TNT-1', + [side.provider], + () => Promise.resolve(directory), + ) + + const row = toTicketDetailRow(ticket!) + + assertEquals(row.discussion.map((comment) => comment.author), [ + { id: 'p1', name: 'Ada Lovelace' }, + undefined, + ]) + assertEquals(JSON.stringify(row).includes('@example.com'), false) + assertEquals(row.items.every((item) => !('raw' in item)), true) + }) +}) diff --git a/api/project-tickets.ts b/api/project-tickets.ts index b67c9d9..54f782c 100644 --- a/api/project-tickets.ts +++ b/api/project-tickets.ts @@ -3,10 +3,14 @@ import { githubProvider } from './github-provider.ts' import { jiraProvider } from './jira-provider.ts' import { buildTeamDirectory } from './team-directory.ts' import { + type Comment, groupIntoTickets, + normalizeKey, type Person, + type PersonRef, type ProjectScope, type Provider, + resolvePerson, type Source, type Ticket, type TicketStatus, @@ -35,17 +39,85 @@ const ticketUpdatedAt = (ticket: Ticket): number => const byLatestActivity = (a: Ticket, b: Ticket): number => ticketUpdatedAt(b) - ticketUpdatedAt(a) || a.key.localeCompare(b.key) +const loadTickets = async ( + scope: ProjectScope, + providers: Provider[], + loadDirectory: () => Promise, +) => { + const [directory, ...results] = await Promise.all([ + loadDirectory(), + ...providers.map((provider) => provider.list(scope)), + ]) + return { directory, tickets: groupIntoTickets(results.flat(), directory) } +} + // each provider returns [] by itself when its scope field is missing export const listProjectTickets = async ( scope: ProjectScope, providers: Provider[] = ticketProviders, loadDirectory: () => Promise = buildTeamDirectory, ): Promise => { - const [directory, ...results] = await Promise.all([ - loadDirectory(), - ...providers.map((provider) => provider.list(scope)), - ]) - return groupIntoTickets(results.flat(), directory).sort(byLatestActivity) + const { tickets } = await loadTickets(scope, providers, loadDirectory) + return tickets.sort(byLatestActivity) +} + +// comments without a date go last, ties keep the provider order +const byCreatedAt = (a: Comment, b: Comment): number => { + if (a.createdAt === undefined) return b.createdAt === undefined ? 0 : 1 + if (b.createdAt === undefined) return -1 + return a.createdAt - b.createdAt +} + +// what a comment author is, per source (see each provider's toComment) +const authorRef = ({ source, author }: Comment): PersonRef | undefined => { + if (!author) return undefined + switch (source) { + case 'jira': + return { email: author } + case 'github': + return { login: author } + case 'discord': + return { discordId: author } + } +} + +export type TicketComment = Omit & { author?: Person } +export type TicketDetail = Omit & { + discussion: TicketComment[] +} + +// "tnt-393" finds TNT393, unkeyed tickets are found by their exact key +export const getProjectTicket = async ( + scope: ProjectScope, + key: string, + providers: Provider[] = ticketProviders, + loadDirectory: () => Promise = buildTeamDirectory, +): Promise => { + const { directory, tickets } = await loadTickets( + scope, + providers, + loadDirectory, + ) + const wanted = key.trim() + const normalized = normalizeKey(wanted) + const ticket = tickets.find((ticket) => ticket.key === wanted) ?? + (normalized + ? tickets.find((ticket) => ticket.key === normalized) + : undefined) + if (!ticket) return undefined + + const bySource = new Map(providers.map((provider) => [provider.id, provider])) + const threads = await Promise.all( + ticket.items.map((item) => + bySource.get(item.source)?.comments(item) ?? Promise.resolve([]) + ), + ) + const discussion = threads.flat().sort(byCreatedAt).map((comment) => { + const ref = authorRef(comment) + const author = ref ? resolvePerson(directory, ref) : undefined + return { ...comment, author } + }) + return { ...ticket, discussion } } const hasPerson = (persons: Person[], id: string): boolean => @@ -90,3 +162,15 @@ export const toTicketRow = (ticket: Ticket) => ({ assignees: ticket.assignees.map(toPersonRow), reviewers: ticket.reviewers.map(toPersonRow), }) + +// the author is only ever exposed as a resolved directory person +export const toTicketDetailRow = (ticket: TicketDetail) => ({ + ...toTicketRow({ ...ticket, discussion: [] }), + discussion: ticket.discussion.map((comment) => ({ + source: comment.source, + author: comment.author && toPersonRow(comment.author), + body: comment.body, + url: comment.url, + createdAt: comment.createdAt, + })), +}) diff --git a/api/routes.ts b/api/routes.ts index e2e83ba..ebfc1fb 100644 --- a/api/routes.ts +++ b/api/routes.ts @@ -46,7 +46,9 @@ import { analyzeQueryWithAI } from '/api/fix-query.ts' import { PERSON_LINK_PATH, type PersonLink } from './team-directory.ts' import { filterTickets, + getProjectTicket, listProjectTickets, + toTicketDetailRow, toTicketRow, } from './project-tickets.ts' @@ -148,6 +150,25 @@ const userInTeam = async (teamId: string, userId?: string) => { return !!matches } +const withProjectAccess = async ( + ctx: RequestContext & { session: User }, + projectId: string, + resource: string, +) => { + const project = ProjectsCollection.get(projectId) + if (!project) { + throw new respond.NotFoundError({ message: 'Project not found' }) + } + if (!project.isPublic && !ctx.session.isAdmin) { + if (!(await userInTeam(project.teamId, ctx.session.id))) { + throw new respond.ForbiddenError({ + message: `Access to project ${resource} denied`, + }) + } + } + return project +} + const withDeploymentTableAccess = async ( ctx: RequestContext & { session: User }, deployment: string, @@ -161,17 +182,7 @@ const withDeploymentTableAccess = async ( }) } - const project = ProjectsCollection.get(dep.projectId) - if (!project) { - throw new respond.NotFoundError({ message: 'Project not found' }) - } - if (!project.isPublic && !ctx.session.isAdmin) { - if (!(await userInTeam(project.teamId, ctx.session.id))) { - throw new respond.ForbiddenError({ - message: 'Access to project tables denied', - }) - } - } + await withProjectAccess(ctx, dep.projectId, 'tables') return dep } @@ -229,6 +240,29 @@ const ticketOutput = OBJ({ reviewers: ARR(ticketPersonOutput, 'The resolved reviewers'), }) +const ticketOutputFields = ticketOutput.properties +const ticketDetailOutput = OBJ({ + ...ticketOutputFields, + discussion: ARR( + OBJ({ + source: LIST(TICKET_SOURCES, 'The source system of the comment'), + author: optional(ticketPersonOutput), + body: STR('The comment text'), + url: optional(STR('The link to the comment in the source system')), + createdAt: optional(NUM('The comment creation date, in ms')), + }), + 'Every comment of every linked source, oldest first', + ), +}) + +const toTicketScope = ( + project: NonNullable>, +) => ({ + repositoryUrl: project.repositoryUrl ?? undefined, + jiraProjectKey: project.jiraProjectKey ?? undefined, + discordChannelId: project.discordChannelId ?? undefined, +}) + // GET params always arrive as strings, NUM would reject them const toCount = (value: string | null | undefined, fallback: number) => { if (value == null) return fallback @@ -535,29 +569,14 @@ const defs = { 'GET/api/project/tickets': route({ authorize: withUserSession, fn: async (ctx, { project: slug, limit, offset, ...filters }) => { - const project = ProjectsCollection.get(slug) - if (!project) { - throw new respond.NotFoundError({ message: 'Project not found' }) - } - if (!project.isPublic && !ctx.session.isAdmin) { - if (!(await userInTeam(project.teamId, ctx.session.id))) { - throw new respond.ForbiddenError({ - message: 'Access to project tickets denied', - }) - } - } - + const project = await withProjectAccess(ctx, slug, 'tickets') const start = toCount(offset, 0) const size = Math.min( toCount(limit, DEFAULT_TICKET_LIMIT), MAX_TICKET_LIMIT, ) const tickets = filterTickets( - await listProjectTickets({ - repositoryUrl: project.repositoryUrl ?? undefined, - jiraProjectKey: project.jiraProjectKey ?? undefined, - discordChannelId: project.discordChannelId ?? undefined, - }), + await listProjectTickets(toTicketScope(project)), filters, ) return { @@ -590,6 +609,24 @@ const defs = { description: 'List the tickets of a project, aggregated from Jira, GitHub and Discord, latest activity first', }), + 'GET/api/project/ticket': route({ + authorize: withUserSession, + fn: async (ctx, { project: slug, key }) => { + const project = await withProjectAccess(ctx, slug, 'tickets') + const ticket = await getProjectTicket(toTicketScope(project), key) + if (!ticket) { + throw new respond.NotFoundError({ message: 'Ticket not found' }) + } + return toTicketDetailRow(ticket) + }, + input: OBJ({ + project: STR('The slug of the project'), + key: STR('The ticket key, as returned by GET /api/project/tickets'), + }), + output: ticketDetailOutput, + description: + 'Get one ticket of a project with its discussion merged from all of its linked sources', + }), 'GET/api/deployment': route({ authorize: withUserSession, fn: async ({ session }, { url }) => { @@ -749,17 +786,7 @@ const defs = { message: 'Logging not enabled for deployment', }) } - const project = ProjectsCollection.get(deployment.projectId) - if (!project) { - throw new respond.NotFoundError({ message: 'Project not found' }) - } - if (!project.isPublic && !ctx.session.isAdmin) { - if (!(await userInTeam(project.teamId, ctx.session.id))) { - throw new respond.ForbiddenError({ - message: 'Access to project logs denied', - }) - } - } + await withProjectAccess(ctx, deployment.projectId, 'logs') return getLogs(deployment.url, params) },