feat: formatted text, a list view, ticket details, public proposals and votes
Formatted text
- Descriptions, comments, replies and release notes render Markdown,
sanitised with DOMPurify (tested against scripts, handlers and
javascript: links). A pasted image is uploaded and written as
; the web fetches it with the reader's session,
so it works on private projects. Every text box has a preview. The
attachment upload now answers its attachmentId.
List view
- /p/:key/list: every ticket as rows, sortable by any column, filtered by
text, open/closed, type, priority and assignee; status, priority and
assignee change in place; bulk edit (the backlog's bar, now shared).
Ticket details
- Reactions on comments (GitHub's eight), for members and viewers.
- Duplicate a ticket: what it says, not where it stands.
- blockedBy: open tickets it waits for (BLOCKS / DEPENDS_ON), worked out
when reading with one query per board or page; shown on cards, list
rows and the ticket.
Public proposals
- A public project can take bug reports and ideas from anyone
(acceptsProposals): POST /api/explore/projects/{project}/proposals and
the form at /p/:key/proponer. They become tickets labelled «propuesta»,
opened by TaskStream; a honeypot field and 5 per address every 15
minutes keep spam out. No e-mail is asked: it would be public.
Votes
- Anyone signed in votes on a public project's tickets, members on a
private one (voteIssue, PUT/DELETE /api/issues/{issue}/vote): votes and
voted on each ticket, buttons on the ticket and the roadmap, a column
in the list. The showcase carries votes and the open proposals.
MCP: vote_issue, duplicate_issue, react_to_comment; listings show
blockers and votes. Docs, Word and PDF updated; chat notifications
(Discord, Slack, Telegram) noted for later.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ export * from './lib/comments.service';
|
||||
export * from './lib/releases.service';
|
||||
export * from './lib/changes.service';
|
||||
export * from './lib/workflows.service';
|
||||
export * from './lib/blockers.service';
|
||||
export * from './lib/notifications.service';
|
||||
export * from './lib/notifications';
|
||||
export * from './lib/saved-filters.service';
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import {
|
||||
IssueLinkType,
|
||||
IssueReadModel,
|
||||
StatusCategory,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { BlockersService } from './blockers.service';
|
||||
import { FindIssuesRepository } from './ports/find-issues.repository';
|
||||
|
||||
const issue = (
|
||||
id: string,
|
||||
statusCategory = StatusCategory.TODO,
|
||||
links: IssueReadModel['links'] = [],
|
||||
) =>
|
||||
({
|
||||
id,
|
||||
key: `WEB-${id}`,
|
||||
title: `Ticket ${id}`,
|
||||
statusCategory,
|
||||
trashedAt: null,
|
||||
links,
|
||||
}) as unknown as IssueReadModel;
|
||||
|
||||
describe('BlockersService', () => {
|
||||
const store = new Map(
|
||||
[
|
||||
issue('2'),
|
||||
issue('3', StatusCategory.DONE),
|
||||
issue('4', StatusCategory.IN_PROGRESS),
|
||||
issue('5'),
|
||||
].map((i) => [i.id, i]),
|
||||
);
|
||||
const queries: string[][] = [];
|
||||
const service = new BlockersService({
|
||||
findByIds: async (ids: string[]) => {
|
||||
queries.push(ids);
|
||||
return ids.map((id) => store.get(id)).filter(Boolean);
|
||||
},
|
||||
} as unknown as FindIssuesRepository);
|
||||
const link = (
|
||||
type: IssueLinkType,
|
||||
direction: 'INWARD' | 'OUTWARD',
|
||||
id: string,
|
||||
) => ({ type, direction, issueId: id, issueKey: `WEB-${id}` });
|
||||
|
||||
beforeEach(() => (queries.length = 0));
|
||||
|
||||
it('is waiting on what blocks it and what it depends on, while open', async () => {
|
||||
const one = issue('1', StatusCategory.TODO, [
|
||||
link(IssueLinkType.BLOCKS, 'INWARD', '2'), // 2 blocks 1
|
||||
link(IssueLinkType.DEPENDS_ON, 'OUTWARD', '3'), // 1 depends on 3 (done)
|
||||
link(IssueLinkType.DEPENDS_ON, 'OUTWARD', '4'), // 1 depends on 4
|
||||
link(IssueLinkType.BLOCKS, 'OUTWARD', '5'), // 1 blocks 5: not a blocker
|
||||
link(IssueLinkType.RELATES_TO, 'OUTWARD', '2'),
|
||||
]);
|
||||
expect((await service.blockedBy(one)).map((b) => b.key)).toEqual([
|
||||
'WEB-2',
|
||||
'WEB-4',
|
||||
]);
|
||||
});
|
||||
|
||||
it('asks once for the tickets of one moment (a board)', async () => {
|
||||
const card = (id: string, blocker: string) =>
|
||||
issue(id, StatusCategory.TODO, [
|
||||
link(IssueLinkType.DEPENDS_ON, 'OUTWARD', blocker),
|
||||
]);
|
||||
const results = await Promise.all([
|
||||
service.blockedBy(card('10', '2')),
|
||||
service.blockedBy(card('11', '4')),
|
||||
service.blockedBy(issue('12')),
|
||||
]);
|
||||
expect(results.map((r) => r.map((b) => b.key))).toEqual([
|
||||
['WEB-2'],
|
||||
['WEB-4'],
|
||||
[],
|
||||
]);
|
||||
expect(queries).toEqual([['2', '4']]);
|
||||
});
|
||||
});
|
||||
86
libs/api/tracker/application/src/lib/blockers.service.ts
Normal file
86
libs/api/tracker/application/src/lib/blockers.service.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
IssueLinkType,
|
||||
IssueReadModel,
|
||||
StatusCategory,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { FindIssuesRepository } from './ports/find-issues.repository';
|
||||
|
||||
/** A ticket another one waits for. */
|
||||
export interface Blocker {
|
||||
id: string;
|
||||
key: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
const FINISHED = new Set<StatusCategory>([
|
||||
StatusCategory.DONE,
|
||||
StatusCategory.CANCELLED,
|
||||
]);
|
||||
|
||||
/**
|
||||
* What a ticket waits for: the tickets that block it and the ones it
|
||||
* depends on, while they are open. Links keep no status, so it is worked
|
||||
* out when reading; the lookups of one moment (a board, a page of a list)
|
||||
* go to the read model as one query, not one per ticket.
|
||||
*/
|
||||
@Injectable()
|
||||
export class BlockersService {
|
||||
private batch: {
|
||||
ids: Set<string>;
|
||||
result: Promise<Map<string, IssueReadModel>>;
|
||||
} | null = null;
|
||||
|
||||
constructor(private readonly findIssues: FindIssuesRepository) {}
|
||||
|
||||
async blockedBy(issue: IssueReadModel): Promise<Blocker[]> {
|
||||
const ids = blockerIdsOf(issue);
|
||||
if (!ids.length) return [];
|
||||
const found = await this.load(ids);
|
||||
return ids
|
||||
.map((id) => found.get(id))
|
||||
.filter(
|
||||
(blocker): blocker is IssueReadModel =>
|
||||
!!blocker &&
|
||||
!blocker.trashedAt &&
|
||||
!FINISHED.has(blocker.statusCategory),
|
||||
)
|
||||
.map(({ id, key, title }) => ({ id, key, title }));
|
||||
}
|
||||
|
||||
private load(ids: string[]): Promise<Map<string, IssueReadModel>> {
|
||||
if (!this.batch) {
|
||||
const pending = new Set<string>();
|
||||
const result = new Promise<Map<string, IssueReadModel>>(
|
||||
(resolve, reject) =>
|
||||
setImmediate(() => {
|
||||
this.batch = null;
|
||||
this.findIssues
|
||||
.findByIds([...pending])
|
||||
.then((issues) => resolve(new Map(issues.map((i) => [i.id, i]))))
|
||||
.catch(reject);
|
||||
}),
|
||||
);
|
||||
this.batch = { ids: pending, result };
|
||||
}
|
||||
for (const id of ids) this.batch.ids.add(id);
|
||||
return this.batch.result;
|
||||
}
|
||||
}
|
||||
|
||||
/** "X blocks this" and "this depends on X": X is what it waits for. */
|
||||
export function blockerIdsOf(issue: IssueReadModel): string[] {
|
||||
return [
|
||||
...new Set(
|
||||
(issue.links ?? [])
|
||||
.filter(
|
||||
(link) =>
|
||||
(link.type === IssueLinkType.BLOCKS &&
|
||||
link.direction === 'INWARD') ||
|
||||
(link.type === IssueLinkType.DEPENDS_ON &&
|
||||
link.direction === 'OUTWARD'),
|
||||
)
|
||||
.map((link) => link.issueId),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto';
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { BusinessRuleError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
|
||||
import { AttachFileCommand } from './attach-file.command';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { AttachFileCommand, AttachmentResult } from './attach-file.command';
|
||||
import { ack } from './command-result';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/**
|
||||
@@ -19,7 +19,7 @@ export class AttachFileCommandHandler
|
||||
private readonly storage: AttachmentStorage,
|
||||
) {}
|
||||
|
||||
async execute(command: AttachFileCommand): Promise<CommandResult> {
|
||||
async execute(command: AttachFileCommand): Promise<AttachmentResult> {
|
||||
const { issue } = await this.access.issueForContributor(
|
||||
command.issueId,
|
||||
command.actorId,
|
||||
@@ -52,6 +52,7 @@ export class AttachFileCommandHandler
|
||||
await this.storage.remove(key);
|
||||
throw error;
|
||||
}
|
||||
return ack(issue);
|
||||
// The id lets a client point at the file, e.g. an image inside a comment.
|
||||
return { ...ack(issue), attachmentId: id };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,12 @@ export interface IncomingFile {
|
||||
content: Buffer;
|
||||
}
|
||||
|
||||
export class AttachFileCommand extends Command<CommandResult> {
|
||||
/** The ticket's acknowledgement, and the id of the file now on it. */
|
||||
export interface AttachmentResult extends CommandResult {
|
||||
attachmentId: string;
|
||||
}
|
||||
|
||||
export class AttachFileCommand extends Command<AttachmentResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly issueId: string,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { DuplicateIssueCommandHandler } from './duplicate-issue.command-handler';
|
||||
import { ReactToCommentCommandHandler } from './react-to-comment.command-handler';
|
||||
import { VoteIssueCommandHandler } from './vote-issue.command-handler';
|
||||
import { SubmitProposalCommandHandler } from './submit-proposal.command-handler';
|
||||
import { CreateProjectCommandHandler } from './create-project.command-handler';
|
||||
import { UpdateProjectCommandHandler } from './update-project.command-handler';
|
||||
import { UpdateProjectSettingsCommandHandler } from './update-project-settings.command-handler';
|
||||
@@ -42,6 +46,10 @@ import {
|
||||
} from './change-checklist.command-handler';
|
||||
|
||||
export const COMMAND_HANDLERS = [
|
||||
SubmitProposalCommandHandler,
|
||||
VoteIssueCommandHandler,
|
||||
ReactToCommentCommandHandler,
|
||||
DuplicateIssueCommandHandler,
|
||||
CreateProjectCommandHandler,
|
||||
UpdateProjectCommandHandler,
|
||||
UpdateProjectSettingsCommandHandler,
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
Issue,
|
||||
IssueStatus,
|
||||
Project,
|
||||
IssuePriority,
|
||||
IssueType,
|
||||
ProjectRole,
|
||||
TRACKER_FACTORIES,
|
||||
@@ -74,6 +75,11 @@ import { ReleaseNamesRepository } from '../ports/release-names.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { AttachmentStorage } from '../ports/attachment-storage';
|
||||
import { AddCommentCommand } from './add-comment.command';
|
||||
import { DuplicateIssueCommand } from './duplicate-issue.command';
|
||||
import { ReactToCommentCommand } from './react-to-comment.command';
|
||||
import { UpdateProjectCommand } from './update-project.command';
|
||||
import { SubmitProposalCommand } from './submit-proposal.command';
|
||||
import { VoteIssueCommand } from './vote-issue.command';
|
||||
import { AddProjectMemberCommand } from './add-project-member.command';
|
||||
import { AssignIssueCommand } from './assign-issue.command';
|
||||
import { AttachFileCommand } from './attach-file.command';
|
||||
@@ -97,6 +103,10 @@ import { FindProjectsRepository } from '../ports/find-projects.repository';
|
||||
|
||||
async function setup() {
|
||||
const store = new InMemoryEventStore();
|
||||
const projectViews = new Map<
|
||||
string,
|
||||
{ id: string; key: string; isPublic: boolean; acceptsProposals: boolean }
|
||||
>();
|
||||
// The project's Git repositories, as Mongo would keep them.
|
||||
const gitRepositories = new Map<string, GitRepositoryConfig[]>();
|
||||
const git: GitIntegrationsRepository = {
|
||||
@@ -129,7 +139,13 @@ async function setup() {
|
||||
ReadAccess,
|
||||
{
|
||||
provide: FindProjectsRepository,
|
||||
useValue: { findRole: async () => null, findById: async () => null },
|
||||
// Read-model lookups: projects are added by the tests that need them.
|
||||
useValue: {
|
||||
findRole: async () => null,
|
||||
findById: async (id: string) => projectViews.get(id) ?? null,
|
||||
findByKey: async (key: string) =>
|
||||
[...projectViews.values()].find((p) => p.key === key) ?? null,
|
||||
},
|
||||
},
|
||||
{ provide: GitIntegrationsRepository, useValue: git },
|
||||
AggregateRehydrator,
|
||||
@@ -177,6 +193,7 @@ async function setup() {
|
||||
sprints,
|
||||
keys,
|
||||
git,
|
||||
projectViews,
|
||||
run,
|
||||
rehydrator: moduleRef.get(AggregateRehydrator),
|
||||
};
|
||||
@@ -832,6 +849,133 @@ describe('tracker commands (event sourced)', () => {
|
||||
expect(rebuilt.deleted).toBe(true);
|
||||
});
|
||||
|
||||
it('duplicates what a ticket says, not where it stands', async () => {
|
||||
const { run, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const original = await run(
|
||||
new CreateIssueCommand(
|
||||
'dev',
|
||||
projectId,
|
||||
IssueType.BUG,
|
||||
'Pago roto',
|
||||
{
|
||||
description: 'Falla en Safari',
|
||||
priority: IssuePriority.HIGH,
|
||||
labels: ['pagos'],
|
||||
storyPoints: 3,
|
||||
},
|
||||
'qa',
|
||||
),
|
||||
);
|
||||
await run(new AddChecklistItemCommand('dev', original.id, 'Reproducir'));
|
||||
|
||||
const copy = await run(new DuplicateIssueCommand('qa', original.id));
|
||||
expect(copy.key).not.toBe(original.key);
|
||||
const issue = await rehydrator.rehydrate(copy.id, Issue);
|
||||
expect(issue).toMatchObject({
|
||||
title: 'Pago roto (copia)',
|
||||
description: 'Falla en Safari',
|
||||
priority: IssuePriority.HIGH,
|
||||
labels: ['pagos'],
|
||||
storyPoints: 3,
|
||||
assigneeId: null,
|
||||
reporterId: 'qa',
|
||||
});
|
||||
expect(issue.checklist.map((s) => [s.text, s.done])).toEqual([
|
||||
['Reproducir', false],
|
||||
]);
|
||||
await expect(
|
||||
run(new DuplicateIssueCommand('pm', original.id)),
|
||||
).rejects.toThrow(ForbiddenError);
|
||||
});
|
||||
|
||||
it('takes reactions from members, once each, viewers included', async () => {
|
||||
const { run, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand('dev', projectId, IssueType.TASK, 'Spike', {}),
|
||||
);
|
||||
const comment = await run(new AddCommentCommand('dev', issue.id, 'Redis'));
|
||||
await run(new ReactToCommentCommand('qa', comment.id, '👍', true));
|
||||
await run(new ReactToCommentCommand('pm', comment.id, '👍', true));
|
||||
await run(new ReactToCommentCommand('pm', comment.id, '👍', true));
|
||||
await run(new ReactToCommentCommand('dev', comment.id, '🎉', true));
|
||||
await run(new ReactToCommentCommand('dev', comment.id, '🎉', false));
|
||||
expect((await rehydrator.rehydrate(comment.id, Comment)).reactions).toEqual(
|
||||
{ '👍': ['qa', 'pm'] },
|
||||
);
|
||||
await expect(
|
||||
run(new ReactToCommentCommand('qa', comment.id, '💩', true)),
|
||||
).rejects.toThrow(ValidationError);
|
||||
await expect(
|
||||
run(new ReactToCommentCommand('stranger', comment.id, '👍', true)),
|
||||
).rejects.toThrow(ForbiddenError);
|
||||
});
|
||||
|
||||
it('takes votes from members, and from anyone once it is public', async () => {
|
||||
const { run, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand(
|
||||
'dev',
|
||||
projectId,
|
||||
IssueType.FEATURE,
|
||||
'Modo oscuro',
|
||||
{},
|
||||
),
|
||||
);
|
||||
await run(new VoteIssueCommand('pm', issue.id, true));
|
||||
await run(new VoteIssueCommand('pm', issue.id, true));
|
||||
await expect(
|
||||
run(new VoteIssueCommand('stranger', issue.id, true)),
|
||||
).rejects.toThrow(ForbiddenError);
|
||||
|
||||
await run(new UpdateProjectCommand('owner', projectId, { isPublic: true }));
|
||||
await run(new VoteIssueCommand('stranger', issue.id, true));
|
||||
await run(new VoteIssueCommand('pm', issue.id, false));
|
||||
expect((await rehydrator.rehydrate(issue.id, Issue)).voterIds).toEqual([
|
||||
'stranger',
|
||||
]);
|
||||
});
|
||||
|
||||
it('turns a proposal into a ticket, only where the project takes them', async () => {
|
||||
const { run, rehydrator, projectViews } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const view = {
|
||||
id: projectId,
|
||||
key: 'TS',
|
||||
isPublic: true,
|
||||
acceptsProposals: false,
|
||||
};
|
||||
projectViews.set(projectId, view);
|
||||
const propose = () =>
|
||||
run(
|
||||
new SubmitProposalCommand(
|
||||
'ts',
|
||||
'BUG',
|
||||
'No carga en Firefox',
|
||||
'Pantalla en blanco',
|
||||
'Lucía',
|
||||
),
|
||||
);
|
||||
await expect(propose()).rejects.toThrow(ForbiddenError);
|
||||
|
||||
view.acceptsProposals = true;
|
||||
const result = await propose();
|
||||
const issue = await rehydrator.rehydrate(result.id, Issue);
|
||||
expect(issue).toMatchObject({
|
||||
title: 'No carga en Firefox',
|
||||
type: IssueType.BUG,
|
||||
labels: ['propuesta'],
|
||||
reporterId: 'system',
|
||||
});
|
||||
expect(issue.description).toContain('Pantalla en blanco');
|
||||
expect(issue.description).toContain('por Lucía');
|
||||
|
||||
view.isPublic = false;
|
||||
await expect(propose()).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('answers comments one level deep, on the same ticket', async () => {
|
||||
const { run, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { CommandHandler, EventPublisher, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { IssueFactory, assertCanNest } from '@task-stream/api/tracker/domain';
|
||||
import {
|
||||
IssueFactory,
|
||||
SYSTEM_ACTOR_ID,
|
||||
assertCanNest,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { IssueNumbersRepository } from '../ports/issue-numbers.repository';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { CreateIssueCommand } from './create-issue.command';
|
||||
@@ -21,7 +25,10 @@ export class CreateIssueCommandHandler
|
||||
|
||||
async execute(command: CreateIssueCommand): Promise<CommandResult> {
|
||||
const project = await this.access.project(command.projectId);
|
||||
project.assertCanContribute(command.actorId);
|
||||
// TaskStream itself (proposals from the public form) is no member; only
|
||||
// internal commands act as it, never a request from outside.
|
||||
if (command.actorId !== SYSTEM_ACTOR_ID)
|
||||
project.assertCanContribute(command.actorId);
|
||||
// Before taking a number: an invalid type or area must not burn one.
|
||||
const workflow = project.workflow;
|
||||
workflow.assertActiveType(command.type);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CommandBus, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { AddChecklistItemCommand } from './change-checklist.command';
|
||||
import { CommandResult } from './command-result';
|
||||
import { CreateIssueCommand } from './create-issue.command';
|
||||
import { DuplicateIssueCommand } from './duplicate-issue.command';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/**
|
||||
* Copies what a ticket says (type, title, description, area, priority,
|
||||
* labels, Figma, estimate, dates, parent and checklist steps, unticked),
|
||||
* not where it stands: the copy starts in the first status, unassigned,
|
||||
* out of sprints and releases, without comments or files. Created through
|
||||
* the usual command, so the same rules and events apply.
|
||||
*/
|
||||
@CommandHandler(DuplicateIssueCommand)
|
||||
export class DuplicateIssueCommandHandler
|
||||
implements ICommandHandler<DuplicateIssueCommand>
|
||||
{
|
||||
constructor(
|
||||
private readonly access: WriteAccess,
|
||||
private readonly commandBus: CommandBus,
|
||||
) {}
|
||||
|
||||
async execute(command: DuplicateIssueCommand): Promise<CommandResult> {
|
||||
const { issue } = await this.access.issueForContributor(
|
||||
command.issueId,
|
||||
command.actorId,
|
||||
);
|
||||
const copy: CommandResult = await this.commandBus.execute(
|
||||
new CreateIssueCommand(
|
||||
command.actorId,
|
||||
issue.projectId,
|
||||
issue.type,
|
||||
`${issue.title} (copia)`.slice(0, 255),
|
||||
{
|
||||
description: issue.description,
|
||||
area: issue.area,
|
||||
priority: issue.priority,
|
||||
labels: issue.labels,
|
||||
figmaUrl: issue.figmaUrl,
|
||||
storyPoints: issue.storyPoints,
|
||||
startDate: issue.startDate,
|
||||
dueDate: issue.dueDate,
|
||||
},
|
||||
null,
|
||||
null,
|
||||
issue.parentId,
|
||||
null,
|
||||
// The original's text is the content, not the type's template.
|
||||
false,
|
||||
),
|
||||
);
|
||||
let result = copy;
|
||||
for (const step of issue.checklist) {
|
||||
result = await this.commandBus.execute(
|
||||
new AddChecklistItemCommand(command.actorId, copy.id, step.text),
|
||||
);
|
||||
}
|
||||
return { ...result, key: copy.key };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
/** A new ticket like this one, to start from: the copy's key in the result. */
|
||||
export class DuplicateIssueCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly issueId: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,11 @@ export * from './assign-issue.command';
|
||||
export * from './change-issue-status.command';
|
||||
export * from './change-project-member-role.command';
|
||||
export * from './create-issue.command';
|
||||
export * from './duplicate-issue.command';
|
||||
export * from './react-to-comment.command';
|
||||
export * from './vote-issue.command';
|
||||
export * from './submit-proposal.command';
|
||||
export { PROPOSAL_LABEL } from './submit-proposal.command-handler';
|
||||
export * from './create-project.command';
|
||||
export * from './create-release.command';
|
||||
export * from './delete-comment.command';
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { ForbiddenError } from '@task-stream/api/shared/domain';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { ReactToCommentCommand } from './react-to-comment.command';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/** Reacting is for members, viewers included: reading is enough to agree. */
|
||||
@CommandHandler(ReactToCommentCommand)
|
||||
export class ReactToCommentCommandHandler
|
||||
implements ICommandHandler<ReactToCommentCommand>
|
||||
{
|
||||
constructor(private readonly access: WriteAccess) {}
|
||||
|
||||
async execute(command: ReactToCommentCommand): Promise<CommandResult> {
|
||||
const comment = await this.access.comment(command.commentId);
|
||||
const project = await this.access.project(comment.projectId);
|
||||
if (!project.isMember(command.actorId))
|
||||
throw new ForbiddenError(
|
||||
`You are not a member of project ${project.key}`,
|
||||
);
|
||||
comment.react(command.actorId, command.emoji, command.on);
|
||||
await comment.commitAndWait();
|
||||
return ack(comment);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
/** Adds (`on`) or takes back one's reaction (👍…) on a comment. */
|
||||
export class ReactToCommentCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly commentId: string,
|
||||
public readonly emoji: string,
|
||||
public readonly on: boolean,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { CommandBus, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import {
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
assertThat,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import {
|
||||
IssuePriority,
|
||||
SYSTEM_ACTOR_ID,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { FindProjectsRepository } from '../ports/find-projects.repository';
|
||||
import { CommandResult } from './command-result';
|
||||
import { CreateIssueCommand } from './create-issue.command';
|
||||
import { ProposalKind, SubmitProposalCommand } from './submit-proposal.command';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/** The label every proposal carries, for the team to find and sort them. */
|
||||
export const PROPOSAL_LABEL = 'propuesta';
|
||||
|
||||
/** Preferred ticket type of each kind, when the project has it active. */
|
||||
const TYPE_OF: Record<ProposalKind, string> = { BUG: 'BUG', IDEA: 'FEATURE' };
|
||||
|
||||
/**
|
||||
* Only a public project that takes proposals accepts one. It is opened by
|
||||
* TaskStream (nobody signed in), in the first status, as a Bug or a Feature
|
||||
* (or the first active type if the project has neither), and signed with
|
||||
* the name they gave, if any.
|
||||
*/
|
||||
@CommandHandler(SubmitProposalCommand)
|
||||
export class SubmitProposalCommandHandler
|
||||
implements ICommandHandler<SubmitProposalCommand>
|
||||
{
|
||||
constructor(
|
||||
private readonly findProjects: FindProjectsRepository,
|
||||
private readonly access: WriteAccess,
|
||||
private readonly commandBus: CommandBus,
|
||||
) {}
|
||||
|
||||
async execute(command: SubmitProposalCommand): Promise<CommandResult> {
|
||||
const found =
|
||||
(await this.findProjects.findById(command.project)) ??
|
||||
(await this.findProjects.findByKey(command.project.toUpperCase()));
|
||||
if (!found?.isPublic) throw new NotFoundError('Project', command.project);
|
||||
if (!found.acceptsProposals)
|
||||
throw new ForbiddenError(`${found.key} does not take proposals`);
|
||||
|
||||
const title = command.title.trim();
|
||||
assertThat(
|
||||
title.length >= 3 && title.length <= 150,
|
||||
'A proposal needs a title of 3 to 150 characters',
|
||||
);
|
||||
const text = command.description.trim();
|
||||
assertThat(text.length <= 5000, 'A proposal is 5000 characters at most');
|
||||
|
||||
const project = await this.access.project(found.id);
|
||||
const active = project.settings.issueTypes.filter((t) => !t.archived);
|
||||
const type =
|
||||
active.find((t) => t.id === TYPE_OF[command.kind])?.id ?? active[0]?.id;
|
||||
const author = command.author?.trim().slice(0, 80);
|
||||
const signature = `_Propuesta enviada desde el formulario público${author ? ` por ${author}` : ''}._`;
|
||||
|
||||
return this.commandBus.execute(
|
||||
new CreateIssueCommand(
|
||||
SYSTEM_ACTOR_ID,
|
||||
project.id,
|
||||
type,
|
||||
title,
|
||||
{
|
||||
description: text ? `${text}\n\n${signature}` : signature,
|
||||
labels: [PROPOSAL_LABEL],
|
||||
priority: IssuePriority.MEDIUM,
|
||||
},
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
// What they wrote is the content, not the type's template.
|
||||
false,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
export type ProposalKind = 'BUG' | 'IDEA';
|
||||
|
||||
/**
|
||||
* A bug report or an idea from anyone, through a public project's form:
|
||||
* it becomes a ticket labelled `propuesta`, for the team to look at.
|
||||
*/
|
||||
export class SubmitProposalCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
/** Project id or key. */
|
||||
public readonly project: string,
|
||||
public readonly kind: ProposalKind,
|
||||
public readonly title: string,
|
||||
public readonly description: string,
|
||||
/** How they sign it, if they want to: shown in the ticket. */
|
||||
public readonly author: string | null,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export class UpdateProjectCommand extends Command<CommandResult> {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
isPublic?: boolean;
|
||||
acceptsProposals?: boolean;
|
||||
},
|
||||
) {
|
||||
super();
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import {
|
||||
BusinessRuleError,
|
||||
ForbiddenError,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { VoteIssueCommand } from './vote-issue.command';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/**
|
||||
* Anyone signed in votes on a public project's tickets (that is the point:
|
||||
* the people it is for say what they want); on a private one, its members.
|
||||
*/
|
||||
@CommandHandler(VoteIssueCommand)
|
||||
export class VoteIssueCommandHandler
|
||||
implements ICommandHandler<VoteIssueCommand>
|
||||
{
|
||||
constructor(private readonly access: WriteAccess) {}
|
||||
|
||||
async execute(command: VoteIssueCommand): Promise<CommandResult> {
|
||||
const issue = await this.access.issue(command.issueId);
|
||||
const project = await this.access.project(issue.projectId);
|
||||
if (!project.isPublic && !project.isMember(command.actorId))
|
||||
throw new ForbiddenError(
|
||||
`You are not a member of project ${project.key}`,
|
||||
);
|
||||
if (issue.trashedAt)
|
||||
throw new BusinessRuleError(`${issue.key} is in the trash`);
|
||||
issue.vote(command.actorId, command.on);
|
||||
await issue.commitAndWait();
|
||||
return ack(issue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
/** The actor votes for a ticket (`on`) or takes the vote back. */
|
||||
export class VoteIssueCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly issueId: string,
|
||||
public readonly on: boolean,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { AddCommentCommand } from './commands/add-comment.command';
|
||||
import { CommandResult } from './commands/command-result';
|
||||
import { DeleteCommentCommand } from './commands/delete-comment.command';
|
||||
import { EditCommentCommand } from './commands/edit-comment.command';
|
||||
import { ReactToCommentCommand } from './commands/react-to-comment.command';
|
||||
import { Page } from './ports/find-issues.repository';
|
||||
import { GetCommentsQuery } from './queries/get-comments.query';
|
||||
|
||||
@@ -36,6 +37,18 @@ export class CommentsService {
|
||||
);
|
||||
}
|
||||
|
||||
/** Adds (`on`) or takes back one's reaction (👍…). */
|
||||
react(
|
||||
actorId: string,
|
||||
commentId: string,
|
||||
emoji: string,
|
||||
on: boolean,
|
||||
): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new ReactToCommentCommand(actorId, commentId, emoji, on),
|
||||
);
|
||||
}
|
||||
|
||||
delete(actorId: string, commentId: string): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new DeleteCommentCommand(actorId, commentId),
|
||||
|
||||
@@ -29,6 +29,7 @@ export class CommentAddedEventHandler
|
||||
body: comment.body,
|
||||
replyTo: comment.replyTo ?? null,
|
||||
deleted: false,
|
||||
reactions: [],
|
||||
createdAt: comment.createdAt,
|
||||
editedAt: null,
|
||||
version: versionOf(event),
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import {
|
||||
CommentReactedEvent,
|
||||
REACTIONS,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { UpsertMaterializedCommentRepository } from '../ports/upsert-materialized-comment.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { ReadModelNotifier, versionOf } from './read-model-notifier';
|
||||
|
||||
@EventsHandler(CommentReactedEvent)
|
||||
export class CommentReactedEventHandler
|
||||
implements IEventHandler<CommentReactedEvent>
|
||||
{
|
||||
constructor(
|
||||
private readonly upsertMaterializedCommentRepository: UpsertMaterializedCommentRepository,
|
||||
private readonly users: UserDirectory,
|
||||
private readonly notifier: ReadModelNotifier,
|
||||
) {}
|
||||
|
||||
async handle(event: CommentReactedEvent) {
|
||||
const refs = await this.users.refs(Object.values(event.reactions).flat());
|
||||
await this.upsertMaterializedCommentRepository.upsert({
|
||||
id: event.aggregateId,
|
||||
reactions: REACTIONS.filter(
|
||||
(emoji) => event.reactions[emoji]?.length,
|
||||
).map((emoji) => ({
|
||||
emoji,
|
||||
users: event.reactions[emoji].map((id) => refs.of(id)),
|
||||
})),
|
||||
version: versionOf(event),
|
||||
});
|
||||
await this.notifier.comment(event.aggregateId, event.issueId, event);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { ActivityEventHandler } from './activity.event-handler';
|
||||
import { CommentAddedEventHandler } from './comment-added.event-handler';
|
||||
import { CommentDeletedEventHandler } from './comment-deleted.event-handler';
|
||||
import { CommentEditedEventHandler } from './comment-edited.event-handler';
|
||||
import { CommentReactedEventHandler } from './comment-reacted.event-handler';
|
||||
import { IssueVotedEventHandler } from './issue-voted.event-handler';
|
||||
import { IssueAssignedEventHandler } from './issue-assigned.event-handler';
|
||||
import { IssueCreatedEventHandler } from './issue-created.event-handler';
|
||||
import { IssueLinkedEventHandler } from './issue-linked.event-handler';
|
||||
@@ -46,6 +48,8 @@ export const EVENT_HANDLERS = [
|
||||
CommentAddedEventHandler,
|
||||
CommentDeletedEventHandler,
|
||||
CommentEditedEventHandler,
|
||||
CommentReactedEventHandler,
|
||||
IssueVotedEventHandler,
|
||||
IssueAssignedEventHandler,
|
||||
IssueCreatedEventHandler,
|
||||
IssueLinkedEventHandler,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import { IssueVotedEvent } from '@task-stream/api/tracker/domain';
|
||||
import { UpsertMaterializedIssueRepository } from '../ports/upsert-materialized-issue.repository';
|
||||
import { ReadModelNotifier, versionOf } from './read-model-notifier';
|
||||
|
||||
@EventsHandler(IssueVotedEvent)
|
||||
export class IssueVotedEventHandler implements IEventHandler<IssueVotedEvent> {
|
||||
constructor(
|
||||
private readonly upsertMaterializedIssueRepository: UpsertMaterializedIssueRepository,
|
||||
private readonly notifier: ReadModelNotifier,
|
||||
) {}
|
||||
|
||||
async handle(event: IssueVotedEvent) {
|
||||
// A vote is not a change to the ticket: `updatedAt` stays.
|
||||
await this.upsertMaterializedIssueRepository.upsert({
|
||||
id: event.aggregateId,
|
||||
votes: event.voterIds.length,
|
||||
voterIds: event.voterIds,
|
||||
version: versionOf(event),
|
||||
});
|
||||
await this.notifier.issue(event.aggregateId, event);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ export class ProjectCreatedEventHandler
|
||||
name: project.name,
|
||||
description: project.description,
|
||||
isPublic: project.isPublic ?? false,
|
||||
acceptsProposals: project.acceptsProposals ?? false,
|
||||
owner: users.of(project.ownerId),
|
||||
members: project.members.map((m) => ({
|
||||
user: users.of(m.userId),
|
||||
|
||||
@@ -8,8 +8,11 @@ import {
|
||||
IssueReadModel,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { AssignIssueCommand } from './commands/assign-issue.command';
|
||||
import { DuplicateIssueCommand } from './commands/duplicate-issue.command';
|
||||
import { VoteIssueCommand } from './commands/vote-issue.command';
|
||||
import {
|
||||
AttachFileCommand,
|
||||
AttachmentResult,
|
||||
IncomingFile,
|
||||
} from './commands/attach-file.command';
|
||||
import { DetachFileCommand } from './commands/detach-file.command';
|
||||
@@ -169,7 +172,7 @@ export class IssuesService {
|
||||
issueId: string,
|
||||
file: IncomingFile,
|
||||
commentId: string | null = null,
|
||||
): Promise<CommandResult> {
|
||||
): Promise<AttachmentResult> {
|
||||
return this.commandBus.execute(
|
||||
new AttachFileCommand(actorId, issueId, file, commentId),
|
||||
);
|
||||
@@ -258,6 +261,16 @@ export class IssuesService {
|
||||
return this.commandBus.execute(new RestoreIssueCommand(actorId, issueId));
|
||||
}
|
||||
|
||||
/** Votes for the ticket (`on`) or takes the vote back. */
|
||||
vote(actorId: string, issueId: string, on: boolean): Promise<CommandResult> {
|
||||
return this.commandBus.execute(new VoteIssueCommand(actorId, issueId, on));
|
||||
}
|
||||
|
||||
/** A new ticket like this one (what it says, not where it stands). */
|
||||
duplicate(actorId: string, issueId: string): Promise<CommandResult> {
|
||||
return this.commandBus.execute(new DuplicateIssueCommand(actorId, issueId));
|
||||
}
|
||||
|
||||
trashed(
|
||||
viewerId: string | null,
|
||||
projectId: string,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
ProposalKind,
|
||||
SubmitProposalCommand,
|
||||
} from './commands/submit-proposal.command';
|
||||
import { GetShowcaseQuery, Showcase } from './queries/get-showcase.query';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { CommandBus, QueryBus } from '@nestjs/cqrs';
|
||||
@@ -34,6 +38,19 @@ export class ProjectsService {
|
||||
) {}
|
||||
|
||||
/** A public project's roadmap, releases, sprint and good first tickets (no token). */
|
||||
/** A bug report or an idea from anyone, for a public project that takes them. */
|
||||
propose(
|
||||
project: string,
|
||||
kind: ProposalKind,
|
||||
title: string,
|
||||
description: string,
|
||||
author: string | null,
|
||||
): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new SubmitProposalCommand(project, kind, title, description, author),
|
||||
);
|
||||
}
|
||||
|
||||
showcase(project: string): Promise<Showcase> {
|
||||
return this.queryBus.execute(new GetShowcaseQuery(project));
|
||||
}
|
||||
@@ -61,7 +78,12 @@ export class ProjectsService {
|
||||
update(
|
||||
actorId: string,
|
||||
projectId: string,
|
||||
changes: { name?: string; description?: string | null; isPublic?: boolean },
|
||||
changes: {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
isPublic?: boolean;
|
||||
acceptsProposals?: boolean;
|
||||
},
|
||||
): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new UpdateProjectCommand(actorId, projectId, changes),
|
||||
|
||||
@@ -6,6 +6,8 @@ import { FindProjectsRepository } from '../ports/find-projects.repository';
|
||||
import { FindReleasesRepository } from '../ports/find-releases.repository';
|
||||
import { FindSprintsRepository } from '../ports/find-sprints.repository';
|
||||
|
||||
import { PROPOSAL_LABEL } from '../commands/submit-proposal.command-handler';
|
||||
|
||||
/** Tickets with this label are offered to newcomers on public pages. */
|
||||
export const GOOD_FIRST_LABEL = 'good-first-issue';
|
||||
|
||||
@@ -35,6 +37,8 @@ export interface Showcase {
|
||||
dueDate: string | null;
|
||||
percent: number;
|
||||
done: boolean;
|
||||
/** How many want it. */
|
||||
votes: number;
|
||||
path: string;
|
||||
}[];
|
||||
releases: {
|
||||
@@ -46,6 +50,20 @@ export interface Showcase {
|
||||
notes: string | null;
|
||||
}[];
|
||||
goodFirst: { key: string; title: string; type: string; path: string }[];
|
||||
/** Bug reports and ideas from the public: whether it takes them, where, and the open ones. */
|
||||
proposals: {
|
||||
open: boolean;
|
||||
/** The form in the web app, while it takes them. */
|
||||
path: string | null;
|
||||
/** Open proposals, most voted first. */
|
||||
top: {
|
||||
key: string;
|
||||
title: string;
|
||||
type: string;
|
||||
votes: number;
|
||||
path: string;
|
||||
}[];
|
||||
};
|
||||
}
|
||||
|
||||
export class GetShowcaseQuery extends Query<Showcase> {
|
||||
@@ -55,6 +73,11 @@ export class GetShowcaseQuery extends Query<Showcase> {
|
||||
}
|
||||
|
||||
const FINISHED = [StatusCategory.DONE, StatusCategory.CANCELLED];
|
||||
const OPEN = [
|
||||
StatusCategory.TODO,
|
||||
StatusCategory.IN_PROGRESS,
|
||||
StatusCategory.QA,
|
||||
];
|
||||
|
||||
@QueryHandler(GetShowcaseQuery)
|
||||
export class GetShowcaseQueryHandler
|
||||
@@ -74,7 +97,7 @@ export class GetShowcaseQueryHandler
|
||||
(await this.findProjects.findByKey(query.project.toUpperCase()));
|
||||
if (!project?.isPublic) throw new NotFoundError('Project', query.project);
|
||||
const path = (key: string) => `/p/${project.key}/issues/${key}`;
|
||||
const [epics, releases, sprint, goodFirst] = await Promise.all([
|
||||
const [epics, releases, sprint, goodFirst, proposals] = await Promise.all([
|
||||
this.findIssues.epics(project.id),
|
||||
this.findReleases.findByProject(project.id),
|
||||
this.findSprints.findActive(project.id),
|
||||
@@ -85,6 +108,13 @@ export class GetShowcaseQueryHandler
|
||||
limit: 20,
|
||||
offset: 0,
|
||||
}),
|
||||
this.findIssues.search({
|
||||
projectId: project.id,
|
||||
labels: [PROPOSAL_LABEL],
|
||||
categories: OPEN,
|
||||
limit: 100,
|
||||
offset: 0,
|
||||
}),
|
||||
]);
|
||||
const visible = releases
|
||||
.filter((r) => r.status !== ReleaseStatus.ARCHIVED)
|
||||
@@ -120,6 +150,7 @@ export class GetShowcaseQueryHandler
|
||||
dueDate: issue.dueDate,
|
||||
percent: p.percent,
|
||||
done: FINISHED.includes(issue.statusCategory),
|
||||
votes: issue.votes,
|
||||
path: path(issue.key),
|
||||
})),
|
||||
releases: visible.map((r, i) => ({
|
||||
@@ -136,6 +167,20 @@ export class GetShowcaseQueryHandler
|
||||
type: i.type,
|
||||
path: path(i.key),
|
||||
})),
|
||||
proposals: {
|
||||
open: project.acceptsProposals,
|
||||
path: project.acceptsProposals ? `/p/${project.key}/proponer` : null,
|
||||
top: [...proposals.items]
|
||||
.sort((a, b) => b.votes - a.votes)
|
||||
.slice(0, 10)
|
||||
.map((i) => ({
|
||||
key: i.key,
|
||||
title: i.title,
|
||||
type: i.type,
|
||||
votes: i.votes,
|
||||
path: path(i.key),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
StartSprintCommand,
|
||||
} from '../commands/sprint.commands';
|
||||
import { FindSprintsRepository } from '../ports/find-sprints.repository';
|
||||
import { FindProjectsRepository } from '../ports/find-projects.repository';
|
||||
import { SprintCarryOverSaga } from './sprint-carry-over.saga';
|
||||
import { FindIssuesRepository } from '../ports/find-issues.repository';
|
||||
import { IssueNumbersRepository } from '../ports/issue-numbers.repository';
|
||||
@@ -87,6 +88,8 @@ async function setup() {
|
||||
IssueTree,
|
||||
AggregateRehydrator,
|
||||
{ provide: EventStore, useValue: store },
|
||||
// Proposals look projects up in the read model; no saga sends one.
|
||||
{ provide: FindProjectsRepository, useValue: {} },
|
||||
{ provide: AttachmentStorage, useValue: files },
|
||||
{ provide: UserDirectory, useValue: users },
|
||||
{ provide: ProjectKeysRepository, useClass: InMemoryProjectKeys },
|
||||
|
||||
@@ -17,6 +17,7 @@ import { ReadAccess } from './queries/read-access';
|
||||
import { ReleasesService } from './releases.service';
|
||||
import { SAGAS } from './sagas/sagas';
|
||||
import { WorkflowsService } from './workflows.service';
|
||||
import { BlockersService } from './blockers.service';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { Notifier } from './notifications/notifier';
|
||||
import { NotificationsEventHandler } from './notifications/notifications.event-handler';
|
||||
@@ -60,6 +61,7 @@ const SERVICES = [
|
||||
ReleasesService,
|
||||
ChangesService,
|
||||
WorkflowsService,
|
||||
BlockersService,
|
||||
NotificationsService,
|
||||
SavedFiltersService,
|
||||
SprintsService,
|
||||
|
||||
@@ -7,6 +7,10 @@ import {
|
||||
import { CommentAddedEvent } from '../events/comment-added.event';
|
||||
import { CommentDeletedEvent } from '../events/comment-deleted.event';
|
||||
import { CommentEditedEvent } from '../events/comment-edited.event';
|
||||
import { CommentReactedEvent } from '../events/comment-reacted.event';
|
||||
|
||||
/** The reactions a comment takes, in the order they are shown (GitHub's). */
|
||||
export const REACTIONS = ['👍', '👎', '😄', '🎉', '😕', '❤️', '🚀', '👀'];
|
||||
|
||||
/** Data of a comment (what CommentAddedEvent carries). */
|
||||
export interface CommentProps {
|
||||
@@ -35,6 +39,8 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
|
||||
public authorId!: string;
|
||||
public body!: string;
|
||||
public replyTo: string | null = null;
|
||||
/** Who chose each emoji (only the ones somebody chose). */
|
||||
public reactions: Record<string, string[]> = {};
|
||||
public deleted = false;
|
||||
public createdAt!: string;
|
||||
public editedAt: string | null = null;
|
||||
@@ -62,6 +68,31 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
|
||||
);
|
||||
}
|
||||
|
||||
/** Adds (`on`) or takes back the actor's reaction; repeating it changes nothing. */
|
||||
react(actorId: string, emoji: string, on: boolean): void {
|
||||
this.assertAlive();
|
||||
assertThat(
|
||||
REACTIONS.includes(emoji),
|
||||
`Reactions are one of ${REACTIONS.join(' ')}`,
|
||||
);
|
||||
const users = this.reactions[emoji] ?? [];
|
||||
if (on === users.includes(actorId)) return;
|
||||
const next = {
|
||||
...this.reactions,
|
||||
[emoji]: on ? [...users, actorId] : users.filter((u) => u !== actorId),
|
||||
};
|
||||
if (!next[emoji].length) delete next[emoji];
|
||||
this.apply(
|
||||
new CommentReactedEvent(
|
||||
actorId,
|
||||
this.id,
|
||||
this.projectId,
|
||||
this.issueId,
|
||||
next,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** @param canModerate whether the actor manages the project (may delete others' comments). */
|
||||
delete(actorId: string, canModerate: boolean): void {
|
||||
this.assertAlive();
|
||||
@@ -86,6 +117,10 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
|
||||
this.editedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onCommentReactedEvent(event: CommentReactedEvent): void {
|
||||
this.reactions = event.reactions;
|
||||
}
|
||||
|
||||
onCommentDeletedEvent(): void {
|
||||
this.deleted = true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { AutowiredEvent } from '@task-stream/api/shared/domain';
|
||||
import { TrackerEvent } from './tracker.event';
|
||||
|
||||
/** Someone added or took back a reaction (👍…) on a comment. */
|
||||
@AutowiredEvent
|
||||
export class CommentReactedEvent extends TrackerEvent {
|
||||
constructor(
|
||||
actorId: string,
|
||||
commentId: string,
|
||||
projectId: string,
|
||||
readonly issueId: string,
|
||||
/** Every reaction after the change: who chose each emoji. */
|
||||
readonly reactions: Record<string, string[]>,
|
||||
) {
|
||||
super(actorId, commentId, projectId);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export * from './issue-unlinked.event';
|
||||
export * from './issue-release-changed.event';
|
||||
export * from './comment-added.event';
|
||||
export * from './comment-edited.event';
|
||||
export * from './comment-reacted.event';
|
||||
export * from './comment-deleted.event';
|
||||
export * from './release-created.event';
|
||||
export * from './release-updated.event';
|
||||
@@ -25,6 +26,7 @@ export * from './release-deleted.event';
|
||||
export * from './issue-attachment-added.event';
|
||||
export * from './issue-attachment-removed.event';
|
||||
export * from './issue-watched.event';
|
||||
export * from './issue-voted.event';
|
||||
export * from './issue-unwatched.event';
|
||||
export * from './issue-parent-changed.event';
|
||||
export * from './issue-checklist-item-added.event';
|
||||
|
||||
16
libs/api/tracker/domain/src/lib/events/issue-voted.event.ts
Normal file
16
libs/api/tracker/domain/src/lib/events/issue-voted.event.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { AutowiredEvent } from '@task-stream/api/shared/domain';
|
||||
import { TrackerEvent } from './tracker.event';
|
||||
|
||||
/** Someone voted for a ticket, or took the vote back. */
|
||||
@AutowiredEvent
|
||||
export class IssueVotedEvent extends TrackerEvent {
|
||||
constructor(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
projectId: string,
|
||||
/** Everyone who wants it, after the change. */
|
||||
readonly voterIds: string[],
|
||||
) {
|
||||
super(actorId, issueId, projectId);
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,17 @@ import { AutowiredEvent } from '@task-stream/api/shared/domain';
|
||||
import type { ProjectProps } from '../project/project';
|
||||
import { TrackerEvent } from './tracker.event';
|
||||
|
||||
/** Name, description or visibility changed. */
|
||||
/** Name, description, visibility or whether it takes public proposals changed. */
|
||||
@AutowiredEvent
|
||||
export class ProjectUpdatedEvent extends TrackerEvent {
|
||||
constructor(
|
||||
actorId: string,
|
||||
projectId: string,
|
||||
readonly changes: Partial<
|
||||
Pick<ProjectProps, 'name' | 'description' | 'isPublic'>
|
||||
Pick<
|
||||
ProjectProps,
|
||||
'name' | 'description' | 'isPublic' | 'acceptsProposals'
|
||||
>
|
||||
>,
|
||||
) {
|
||||
super(actorId, projectId, projectId);
|
||||
|
||||
@@ -25,6 +25,7 @@ import { IssueUnlinkedEvent } from '../events/issue-unlinked.event';
|
||||
import { IssueUpdatedEvent } from '../events/issue-updated.event';
|
||||
import { IssueUnwatchedEvent } from '../events/issue-unwatched.event';
|
||||
import { IssueWatchedEvent } from '../events/issue-watched.event';
|
||||
import { IssueVotedEvent } from '../events/issue-voted.event';
|
||||
import { ProjectWorkflow } from '../project/project-settings';
|
||||
import {
|
||||
IssueAttachment,
|
||||
@@ -116,6 +117,8 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
public attachments: IssueAttachment[] = [];
|
||||
/** People who asked to be told about this ticket. */
|
||||
public watchers: string[] = [];
|
||||
/** People who want it done (a public roadmap's way to prioritise). */
|
||||
public voterIds: string[] = [];
|
||||
/** The epic or ticket this one breaks down. */
|
||||
public parentId: string | null = null;
|
||||
public checklist: ChecklistItem[] = [];
|
||||
@@ -337,6 +340,21 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
);
|
||||
}
|
||||
|
||||
/** The actor votes for it (`on`) or takes the vote back. Idempotent. */
|
||||
vote(actorId: string, on: boolean): void {
|
||||
if (on === this.voterIds.includes(actorId)) return;
|
||||
this.apply(
|
||||
new IssueVotedEvent(
|
||||
actorId,
|
||||
this.id,
|
||||
this.projectId,
|
||||
on
|
||||
? [...this.voterIds, actorId]
|
||||
: this.voterIds.filter((id) => id !== actorId),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** `userId` starts following the ticket. Idempotent. */
|
||||
watch(actorId: string, userId: string): void {
|
||||
if (this.watchers.includes(userId)) return;
|
||||
@@ -553,6 +571,10 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
this.updatedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onIssueVotedEvent(event: IssueVotedEvent): void {
|
||||
this.voterIds = event.voterIds;
|
||||
}
|
||||
|
||||
onIssueWatchedEvent(event: IssueWatchedEvent): void {
|
||||
this.watchers = [...this.watchers, event.userId];
|
||||
}
|
||||
|
||||
@@ -32,6 +32,11 @@ export interface ProjectProps {
|
||||
description: string | null;
|
||||
/** Anyone (even without signing in) can read it. Absent in old projects: private. */
|
||||
isPublic?: boolean;
|
||||
/**
|
||||
* Takes bug reports and ideas from anyone, through a public form (only
|
||||
* while it is public). Absent in old projects: no.
|
||||
*/
|
||||
acceptsProposals?: boolean;
|
||||
ownerId: string;
|
||||
members: ProjectMember[];
|
||||
/** Absent in projects created before settings existed: defaults apply. */
|
||||
@@ -49,6 +54,7 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
|
||||
public name!: string;
|
||||
public description: string | null = null;
|
||||
public isPublic = false;
|
||||
public acceptsProposals = false;
|
||||
public ownerId!: string;
|
||||
public members: ProjectMember[] = [];
|
||||
public settings: ProjectSettings = defaultProjectSettings();
|
||||
@@ -104,13 +110,19 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
|
||||
|
||||
updateDetails(
|
||||
actorId: string,
|
||||
changes: { name?: string; description?: string | null; isPublic?: boolean },
|
||||
changes: {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
isPublic?: boolean;
|
||||
acceptsProposals?: boolean;
|
||||
},
|
||||
): void {
|
||||
this.assertCanManage(actorId);
|
||||
const patch: {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
isPublic?: boolean;
|
||||
acceptsProposals?: boolean;
|
||||
} = {};
|
||||
if (changes.name !== undefined) {
|
||||
const name = changes.name.trim();
|
||||
@@ -123,6 +135,11 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
|
||||
}
|
||||
if (changes.isPublic !== undefined && changes.isPublic !== this.isPublic)
|
||||
patch.isPublic = changes.isPublic;
|
||||
if (
|
||||
changes.acceptsProposals !== undefined &&
|
||||
changes.acceptsProposals !== this.acceptsProposals
|
||||
)
|
||||
patch.acceptsProposals = changes.acceptsProposals;
|
||||
if (Object.keys(patch).length === 0) return;
|
||||
this.apply(new ProjectUpdatedEvent(actorId, this.id, patch));
|
||||
}
|
||||
@@ -213,6 +230,7 @@ export class Project extends VersionedAggregateRoot implements ProjectProps {
|
||||
this.name = project.name;
|
||||
this.description = project.description;
|
||||
this.isPublic = project.isPublic ?? false;
|
||||
this.acceptsProposals = project.acceptsProposals ?? false;
|
||||
this.ownerId = project.ownerId;
|
||||
this.members = project.members.map((m) => ({ ...m }));
|
||||
this.settings = structuredClone(
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { UserRefReadModel } from './user-ref.read-model';
|
||||
|
||||
/** One emoji on a comment and who chose it. */
|
||||
export class CommentReactionReadModel {
|
||||
emoji!: string;
|
||||
users!: UserRefReadModel[];
|
||||
}
|
||||
|
||||
export class CommentReadModel {
|
||||
id!: string;
|
||||
issueId!: string;
|
||||
@@ -13,6 +19,8 @@ export class CommentReadModel {
|
||||
* conversation under it still makes sense. Gone with its last reply.
|
||||
*/
|
||||
deleted!: boolean;
|
||||
/** In the order they are offered; only the ones somebody chose. */
|
||||
reactions!: CommentReactionReadModel[];
|
||||
createdAt!: string;
|
||||
editedAt!: string | null;
|
||||
version!: number;
|
||||
|
||||
@@ -81,6 +81,10 @@ export class IssueReadModel {
|
||||
attachments!: AttachmentReadModel[];
|
||||
/** People following the ticket. */
|
||||
watchers!: UserRefReadModel[];
|
||||
/** How many want it done. */
|
||||
votes!: number;
|
||||
/** Who voted: to tell someone whether they did; never shown as a list. */
|
||||
voterIds!: string[];
|
||||
parent!: IssueParentReadModel | null;
|
||||
/** Place in the backlog (and in each board column): ascending. */
|
||||
rank!: string;
|
||||
|
||||
@@ -14,6 +14,8 @@ export class ProjectReadModel {
|
||||
description!: string | null;
|
||||
/** Readable by anyone, also without signing in. */
|
||||
isPublic!: boolean;
|
||||
/** Takes bug reports and ideas from anyone (only while public). */
|
||||
acceptsProposals!: boolean;
|
||||
owner!: UserRefReadModel;
|
||||
members!: ProjectMemberReadModel[];
|
||||
/** Statuses, transitions, ticket types and areas. */
|
||||
|
||||
@@ -50,6 +50,7 @@ const commentFromDoc = (doc: CommentDoc): CommentReadModel => ({
|
||||
...fromDoc(doc),
|
||||
replyTo: doc.replyTo ?? null,
|
||||
deleted: doc.deleted ?? false,
|
||||
reactions: doc.reactions ?? [],
|
||||
});
|
||||
|
||||
const escapeRegex = (text: string) =>
|
||||
@@ -63,6 +64,7 @@ function toProject(doc: ProjectDoc): ProjectReadModel {
|
||||
return {
|
||||
...fromDoc(rest),
|
||||
isPublic: rest.isPublic ?? false,
|
||||
acceptsProposals: rest.acceptsProposals ?? false,
|
||||
settings: rest.settings ?? defaultProjectSettings(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -293,6 +293,8 @@ export function issueFromDoc(doc: IssueDoc): IssueReadModel {
|
||||
// Tickets projected before attachments existed have none.
|
||||
attachments: rest.attachments ?? [],
|
||||
watchers: rest.watchers ?? [],
|
||||
votes: rest.votes ?? 0,
|
||||
voterIds: rest.voterIds ?? [],
|
||||
parent: rest.parent?.id ? rest.parent : null,
|
||||
rank: rest.rank ?? implicitRank(rest.number),
|
||||
startDate: rest.startDate ?? null,
|
||||
|
||||
@@ -31,6 +31,18 @@ export class CommentResolver {
|
||||
return this.comments.edit(me.id, commentId, body);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, {
|
||||
description: 'React (👍 👎 😄 🎉 😕 ❤️ 🚀 👀) or take it back (on: false)',
|
||||
})
|
||||
reactToComment(
|
||||
@CurrentUser() me: User,
|
||||
@Args('commentId', { type: () => ID }) commentId: string,
|
||||
@Args('emoji') emoji: string,
|
||||
@Args('on') on: boolean,
|
||||
) {
|
||||
return this.comments.react(me.id, commentId, emoji, on);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, { description: 'Author or project admin' })
|
||||
deleteComment(
|
||||
@CurrentUser() me: User,
|
||||
|
||||
@@ -74,6 +74,14 @@ export class UpdateProjectInput {
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isPublic?: boolean;
|
||||
@Field({
|
||||
nullable: true,
|
||||
description:
|
||||
'Take bug reports and ideas from anyone through the public form (while public)',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
acceptsProposals?: boolean;
|
||||
}
|
||||
|
||||
@InputType()
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
OptionalAuth,
|
||||
} from '@task-stream/api/identity/presenters';
|
||||
import {
|
||||
BlockersService,
|
||||
CommentsService,
|
||||
IssuesService,
|
||||
WorkflowsService,
|
||||
@@ -44,6 +45,7 @@ import {
|
||||
EpicGql,
|
||||
IssueGql,
|
||||
IssuePageGql,
|
||||
IssueParentGql,
|
||||
} from './types';
|
||||
|
||||
@Resolver(() => IssueGql)
|
||||
@@ -52,6 +54,7 @@ export class IssueResolver {
|
||||
private readonly issuesService: IssuesService,
|
||||
private readonly commentsService: CommentsService,
|
||||
private readonly workflows: WorkflowsService,
|
||||
private readonly blockers: BlockersService,
|
||||
) {}
|
||||
|
||||
@OptionalAuth()
|
||||
@@ -154,6 +157,22 @@ export class IssueResolver {
|
||||
return this.workflows.allowedTransitions(issue);
|
||||
}
|
||||
|
||||
@ResolveField(() => [IssueParentGql], {
|
||||
description:
|
||||
'Open tickets it waits for: the ones that block it and the ones it depends on',
|
||||
})
|
||||
blockedBy(@Parent() issue: IssueReadModel) {
|
||||
return this.blockers.blockedBy(issue);
|
||||
}
|
||||
|
||||
@ResolveField(() => Boolean, { description: 'Whether I voted for it' })
|
||||
voted(
|
||||
@CurrentUser() me: User | undefined,
|
||||
@Parent() issue: IssueReadModel,
|
||||
): boolean {
|
||||
return !!me && issue.voterIds.includes(me.id);
|
||||
}
|
||||
|
||||
@ResolveField(() => [IssueGql], { description: 'Linked tickets I can see' })
|
||||
linkedIssues(
|
||||
@CurrentUser() me: User | undefined,
|
||||
@@ -307,6 +326,29 @@ export class IssueResolver {
|
||||
return this.issuesService.trash(me.id, issueId);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, {
|
||||
description:
|
||||
'A new ticket like this one: what it says, not where it stands (the key comes in the result)',
|
||||
})
|
||||
duplicateIssue(
|
||||
@CurrentUser() me: User,
|
||||
@Args('issueId', { type: () => ID }) issueId: string,
|
||||
) {
|
||||
return this.issuesService.duplicate(me.id, issueId);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, {
|
||||
description:
|
||||
'Vote for a ticket (on) or take the vote back: anyone signed in on a public project, members on a private one',
|
||||
})
|
||||
voteIssue(
|
||||
@CurrentUser() me: User,
|
||||
@Args('issueId', { type: () => ID }) issueId: string,
|
||||
@Args('on') on: boolean,
|
||||
) {
|
||||
return this.issuesService.vote(me.id, issueId, on);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, { description: 'Back from the trash' })
|
||||
restoreIssue(
|
||||
@CurrentUser() me: User,
|
||||
|
||||
@@ -102,6 +102,10 @@ export class ProjectGql {
|
||||
@Field(() => String, { nullable: true }) description!: string | null;
|
||||
@Field({ description: 'Anyone can read it, also without signing in' })
|
||||
isPublic!: boolean;
|
||||
@Field({
|
||||
description: 'Takes bug reports and ideas from anyone (while public)',
|
||||
})
|
||||
acceptsProposals!: boolean;
|
||||
@Field(() => UserRefGql) owner!: UserRefGql;
|
||||
@Field(() => [ProjectMemberGql]) members!: ProjectMemberGql[];
|
||||
@Field() createdAt!: string;
|
||||
@@ -374,6 +378,8 @@ export class IssueGql {
|
||||
})
|
||||
devLinks!: DevLinkGql[];
|
||||
@Field(() => Int) commentCount!: number;
|
||||
@Field(() => Int, { description: 'How many want it done' })
|
||||
votes!: number;
|
||||
@Field() createdAt!: string;
|
||||
@Field() updatedAt!: string;
|
||||
@Field(() => Int) version!: number;
|
||||
@@ -440,6 +446,13 @@ export class BoardColumnGql {
|
||||
@Field(() => Int) total!: number;
|
||||
}
|
||||
|
||||
@ObjectType('CommentReaction', { description: 'One emoji on a comment' })
|
||||
export class CommentReactionGql {
|
||||
@Field() emoji!: string;
|
||||
@Field(() => [UserRefGql], { description: 'Who chose it' })
|
||||
users!: UserRefGql[];
|
||||
}
|
||||
|
||||
@ObjectType('Comment')
|
||||
export class CommentGql {
|
||||
@Field(() => ID) id!: string;
|
||||
@@ -456,6 +469,10 @@ export class CommentGql {
|
||||
description: 'Deleted, but kept (without its text) while it has replies',
|
||||
})
|
||||
deleted!: boolean;
|
||||
@Field(() => [CommentReactionGql], {
|
||||
description: 'In the order they are offered; only the ones somebody chose',
|
||||
})
|
||||
reactions!: CommentReactionGql[];
|
||||
@Field() createdAt!: string;
|
||||
@Field(() => String, { nullable: true }) editedAt!: string | null;
|
||||
@Field(() => Int) version!: number;
|
||||
|
||||
@@ -36,7 +36,7 @@ import { IssuesService } from '@task-stream/api/tracker/application';
|
||||
import type { Response } from 'express';
|
||||
import { viewerOf } from '../common/viewer';
|
||||
import { AttachFileDto } from './dto/requests.dto';
|
||||
import { CommandResultDto } from './dto/responses.dto';
|
||||
import { AttachmentResultDto, CommandResultDto } from './dto/responses.dto';
|
||||
import { Refs } from './refs';
|
||||
|
||||
const ISSUE = ApiParam({
|
||||
@@ -80,7 +80,7 @@ export class AttachmentsController {
|
||||
'Multipart with the file as `file` and, optionally, `commentId` to place it under a comment. ' +
|
||||
'Up to ATTACHMENTS_MAX_MB megabytes (25 by default) and 50 files per ticket.',
|
||||
})
|
||||
@ApiCreatedResponse({ type: CommandResultDto })
|
||||
@ApiCreatedResponse({ type: AttachmentResultDto })
|
||||
@ApiCommandErrors()
|
||||
async attach(
|
||||
@CurrentUser() me: User,
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { Body, Controller, Delete, Param, Patch } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
HttpCode,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { User } from '@task-stream/api/identity/domain';
|
||||
import {
|
||||
@@ -7,7 +15,8 @@ import {
|
||||
} from '@task-stream/api/identity/presenters';
|
||||
import { ApiCommandErrors } from '@task-stream/api/shared/presenters';
|
||||
import { CommentsService } from '@task-stream/api/tracker/application';
|
||||
import { CommentBodyDto } from './dto/requests.dto';
|
||||
import { REACTIONS } from '@task-stream/api/tracker/domain';
|
||||
import { CommentBodyDto, ReactToCommentDto } from './dto/requests.dto';
|
||||
import { CommandResultDto } from './dto/responses.dto';
|
||||
|
||||
/** REST adapter of the comment use cases (listing and adding live under /issues). */
|
||||
@@ -29,6 +38,22 @@ export class CommentsController {
|
||||
return this.comments.edit(me.id, commentId, body.body);
|
||||
}
|
||||
|
||||
@Post(':commentId/reactions')
|
||||
@HttpCode(200)
|
||||
@ApiOperation({
|
||||
summary: 'React to a comment, or take the reaction back (members)',
|
||||
description: `One of ${REACTIONS.join(' ')}; repeating it changes nothing.`,
|
||||
})
|
||||
@ApiOkResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
react(
|
||||
@CurrentUser() me: User,
|
||||
@Param('commentId') commentId: string,
|
||||
@Body() body: ReactToCommentDto,
|
||||
) {
|
||||
return this.comments.react(me.id, commentId, body.emoji, body.on);
|
||||
}
|
||||
|
||||
@Delete(':commentId')
|
||||
@ApiOperation({ summary: 'Delete a comment (author or project admin)' })
|
||||
@ApiOkResponse({ type: CommandResultDto })
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
IssueLinkType,
|
||||
IssuePriority,
|
||||
ProjectRole,
|
||||
REACTIONS,
|
||||
SETTING_COLORS,
|
||||
StatusCategory,
|
||||
TYPE_ICONS,
|
||||
@@ -88,7 +89,15 @@ export class CreateProjectDto {
|
||||
|
||||
export class UpdateProjectDto extends PartialType(
|
||||
OmitType(CreateProjectDto, ['key'] as const),
|
||||
) {}
|
||||
) {
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
'Take bug reports and ideas from anyone through the public form (while public)',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
acceptsProposals?: boolean;
|
||||
}
|
||||
|
||||
export class DeleteProjectQueryDto {
|
||||
@ApiProperty({
|
||||
@@ -985,6 +994,59 @@ export class AddCommentDto extends CommentBodyDto {
|
||||
replyTo?: string;
|
||||
}
|
||||
|
||||
export class ReactToCommentDto {
|
||||
@ApiProperty({ enum: REACTIONS, example: '👍' })
|
||||
@IsIn(REACTIONS)
|
||||
emoji!: string;
|
||||
|
||||
@ApiProperty({ description: 'true adds the reaction, false takes it back' })
|
||||
@IsBoolean()
|
||||
on!: boolean;
|
||||
}
|
||||
|
||||
// ---- Public proposals -------------------------------------------------------
|
||||
|
||||
export class ProposalDto {
|
||||
@ApiProperty({
|
||||
enum: ['BUG', 'IDEA'],
|
||||
description: 'A bug report or an idea',
|
||||
})
|
||||
@IsIn(['BUG', 'IDEA'])
|
||||
kind!: 'BUG' | 'IDEA';
|
||||
|
||||
@ApiProperty({ minLength: 3, maxLength: 150 })
|
||||
@IsString()
|
||||
@MinLength(3)
|
||||
@MaxLength(150)
|
||||
title!: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
maxLength: 5000,
|
||||
description: 'What happens, or what they would like (Markdown)',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(5000)
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
maxLength: 80,
|
||||
description:
|
||||
'How they sign it; shown in the ticket (no e-mail: it would be public)',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(80)
|
||||
author?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Leave empty: a field only bots fill in',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
website?: string;
|
||||
}
|
||||
|
||||
// ---- Releases ---------------------------------------------------------------
|
||||
|
||||
export class CreateReleaseDto {
|
||||
|
||||
@@ -96,6 +96,11 @@ export class ProjectDto {
|
||||
@ApiProperty({ type: String, nullable: true }) description!: string | null;
|
||||
@ApiProperty({ description: 'Readable by anyone, also without a token' })
|
||||
isPublic!: boolean;
|
||||
@ApiProperty({
|
||||
description:
|
||||
'Takes bug reports and ideas from anyone (POST /api/explore/projects/{project}/proposals) while public',
|
||||
})
|
||||
acceptsProposals!: boolean;
|
||||
@ApiProperty({ type: UserRefDto }) owner!: UserRefDto;
|
||||
@ApiProperty({ type: [ProjectMemberDto] }) members!: ProjectMemberDto[];
|
||||
@ApiProperty({ type: ProjectSettingsDto })
|
||||
@@ -279,6 +284,7 @@ class ShowcaseEpicDto {
|
||||
dueDate!: string | null;
|
||||
@ApiProperty() percent!: number;
|
||||
@ApiProperty() done!: boolean;
|
||||
@ApiProperty({ description: 'How many want it' }) votes!: number;
|
||||
@ApiProperty({
|
||||
example: '/p/WEB/issues/WEB-3',
|
||||
description: 'In the web app',
|
||||
@@ -308,6 +314,27 @@ class ShowcaseIssueDto {
|
||||
@ApiProperty({ example: '/p/WEB/issues/WEB-9' }) path!: string;
|
||||
}
|
||||
|
||||
class ShowcaseProposalDto extends ShowcaseIssueDto {
|
||||
@ApiProperty({ description: 'How many want it' }) votes!: number;
|
||||
}
|
||||
|
||||
class ShowcaseProposalsDto {
|
||||
@ApiProperty({ description: 'Whether it takes bug reports and ideas now' })
|
||||
open!: boolean;
|
||||
@ApiProperty({
|
||||
type: String,
|
||||
nullable: true,
|
||||
example: '/p/WEB/proponer',
|
||||
description: 'The form in the web app, while it takes them',
|
||||
})
|
||||
path!: string | null;
|
||||
@ApiProperty({
|
||||
type: [ShowcaseProposalDto],
|
||||
description: 'Open proposals, most voted first',
|
||||
})
|
||||
top!: ShowcaseProposalDto[];
|
||||
}
|
||||
|
||||
export class ShowcaseDto {
|
||||
@ApiProperty({ type: ShowcaseProjectDto }) project!: ShowcaseProjectDto;
|
||||
@ApiProperty({ type: ShowcaseSprintDto, nullable: true })
|
||||
@@ -319,6 +346,25 @@ export class ShowcaseDto {
|
||||
description: 'Open tickets labelled good-first-issue',
|
||||
})
|
||||
goodFirst!: ShowcaseIssueDto[];
|
||||
@ApiProperty({ type: ShowcaseProposalsDto })
|
||||
proposals!: ShowcaseProposalsDto;
|
||||
}
|
||||
|
||||
export class ProposalResultDto {
|
||||
@ApiProperty({
|
||||
type: String,
|
||||
nullable: true,
|
||||
example: 'WEB-42',
|
||||
description: 'The ticket it became',
|
||||
})
|
||||
key!: string | null;
|
||||
@ApiProperty({
|
||||
type: String,
|
||||
nullable: true,
|
||||
example: '/p/WEB/issues/WEB-42',
|
||||
description: 'Where to see it in the web app',
|
||||
})
|
||||
path!: string | null;
|
||||
}
|
||||
|
||||
export class GitDeliveryResultDto {
|
||||
@@ -390,6 +436,13 @@ export class IssueDto {
|
||||
description: 'The epic or ticket this one breaks down',
|
||||
})
|
||||
parent!: IssueParentDto | null;
|
||||
@ApiProperty({
|
||||
type: [IssueParentDto],
|
||||
description:
|
||||
'Open tickets it waits for: the ones that block it and the ones it depends on',
|
||||
})
|
||||
blockedBy!: IssueParentDto[];
|
||||
@ApiProperty({ description: 'How many want it done' }) votes!: number;
|
||||
@ApiProperty({
|
||||
description:
|
||||
'Place in the backlog and its board column (ascending, as text)',
|
||||
@@ -462,6 +515,11 @@ export class BoardColumnDto {
|
||||
total!: number;
|
||||
}
|
||||
|
||||
export class CommentReactionDto {
|
||||
@ApiProperty({ example: '👍' }) emoji!: string;
|
||||
@ApiProperty({ type: [UserRefDto] }) users!: UserRefDto[];
|
||||
}
|
||||
|
||||
export class CommentDto {
|
||||
@ApiProperty({ format: 'uuid' }) id!: string;
|
||||
@ApiProperty({ format: 'uuid' }) issueId!: string;
|
||||
@@ -481,6 +539,11 @@ export class CommentDto {
|
||||
description: 'Deleted, but kept (without its text) while it has replies',
|
||||
})
|
||||
deleted!: boolean;
|
||||
@ApiProperty({
|
||||
type: [CommentReactionDto],
|
||||
description: 'In the order they are offered; only the ones somebody chose',
|
||||
})
|
||||
reactions!: CommentReactionDto[];
|
||||
@ApiProperty({ format: 'date-time' }) createdAt!: string;
|
||||
@ApiProperty({ type: String, nullable: true, format: 'date-time' })
|
||||
editedAt!: string | null;
|
||||
@@ -649,6 +712,15 @@ export class CommandResultDto {
|
||||
version!: number;
|
||||
}
|
||||
|
||||
export class AttachmentResultDto extends CommandResultDto {
|
||||
@ApiProperty({
|
||||
format: 'uuid',
|
||||
description:
|
||||
'The new file; `` shows an image inside a description or comment',
|
||||
})
|
||||
attachmentId!: string;
|
||||
}
|
||||
|
||||
// ---- Statistics ---------------------------------------------------------------
|
||||
|
||||
export class CreatedResolvedDto {
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import { Controller, Get, Header, Param } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Header,
|
||||
Param,
|
||||
Post,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiCreatedResponse,
|
||||
ApiForbiddenResponse,
|
||||
ApiNotFoundResponse,
|
||||
ApiTooManyRequestsResponse,
|
||||
ApiOkResponse,
|
||||
ApiOperation,
|
||||
ApiParam,
|
||||
@@ -8,14 +19,24 @@ import {
|
||||
} from '@nestjs/swagger';
|
||||
import { Public } from '@task-stream/api/identity/presenters';
|
||||
import { ProjectsService } from '@task-stream/api/tracker/application';
|
||||
import { ProjectDto, ShowcaseDto } from './dto/responses.dto';
|
||||
import { Request } from 'express';
|
||||
import { ProposalDto } from './dto/requests.dto';
|
||||
import {
|
||||
ProjectDto,
|
||||
ProposalResultDto,
|
||||
ShowcaseDto,
|
||||
} from './dto/responses.dto';
|
||||
import { ProposalLimiter } from './proposal-limiter';
|
||||
import { toProjectDto } from './refs';
|
||||
|
||||
/** What anyone can read without signing in. */
|
||||
@ApiTags('Explore')
|
||||
@Controller('explore')
|
||||
export class ExploreController {
|
||||
constructor(private readonly projects: ProjectsService) {}
|
||||
constructor(
|
||||
private readonly projects: ProjectsService,
|
||||
private readonly limiter: ProposalLimiter,
|
||||
) {}
|
||||
|
||||
@Get('projects')
|
||||
@Public()
|
||||
@@ -47,4 +68,51 @@ export class ExploreController {
|
||||
showcase(@Param('project') project: string) {
|
||||
return this.projects.showcase(project);
|
||||
}
|
||||
|
||||
@Post('projects/:project/proposals')
|
||||
@Public()
|
||||
@ApiParam({
|
||||
name: 'project',
|
||||
description: 'Project id or key',
|
||||
example: 'WEB',
|
||||
})
|
||||
@ApiOperation({
|
||||
summary: 'Report a bug or propose an idea (no token needed)',
|
||||
description:
|
||||
'For public projects that take proposals. It becomes a ticket labelled `propuesta`, opened by TaskStream in the first status (Bug or Feature), signed with `author` if given. Five per address every 15 minutes.',
|
||||
})
|
||||
@ApiCreatedResponse({ type: ProposalResultDto })
|
||||
@ApiNotFoundResponse({ description: 'Not a public project' })
|
||||
@ApiForbiddenResponse({ description: 'It does not take proposals' })
|
||||
@ApiTooManyRequestsResponse({ description: 'Too many from this address' })
|
||||
async propose(
|
||||
@Param('project') project: string,
|
||||
@Body() body: ProposalDto,
|
||||
@Req() req: Request,
|
||||
): Promise<ProposalResultDto> {
|
||||
// Bots fill in every field: pretend it worked, and keep nothing.
|
||||
if (body.website?.trim()) return { key: null, path: null };
|
||||
this.limiter.take(addressOf(req));
|
||||
const result = await this.projects.propose(
|
||||
project,
|
||||
body.kind,
|
||||
body.title,
|
||||
body.description ?? '',
|
||||
body.author ?? null,
|
||||
);
|
||||
const key = result.key ?? null;
|
||||
return {
|
||||
key,
|
||||
path: key ? `/p/${key.split('-')[0]}/issues/${key}` : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Behind a proxy (Traefik, nginx), who asked comes in X-Forwarded-For. */
|
||||
function addressOf(req: Request): string {
|
||||
const forwarded = req.headers['x-forwarded-for'];
|
||||
const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)
|
||||
?.split(',')[0]
|
||||
?.trim();
|
||||
return first || req.ip || 'unknown';
|
||||
}
|
||||
|
||||
@@ -338,6 +338,45 @@ export class IssuesController {
|
||||
return this.issues.restore(me.id, await this.refs.issueId(me.id, issue));
|
||||
}
|
||||
|
||||
@Put('issues/:issue/vote')
|
||||
@ISSUE
|
||||
@ApiOperation({
|
||||
summary: 'Vote for the ticket',
|
||||
description:
|
||||
'Anyone signed in, on a public project (that is the point: the people it is for say what they want); members on a private one. Voting twice changes nothing.',
|
||||
})
|
||||
@ApiOkResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
async vote(@CurrentUser() me: User, @Param('issue') issue: string) {
|
||||
return this.issues.vote(me.id, await this.refs.issueId(me.id, issue), true);
|
||||
}
|
||||
|
||||
@Delete('issues/:issue/vote')
|
||||
@ISSUE
|
||||
@ApiOperation({ summary: 'Take back my vote for the ticket' })
|
||||
@ApiOkResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
async unvote(@CurrentUser() me: User, @Param('issue') issue: string) {
|
||||
return this.issues.vote(
|
||||
me.id,
|
||||
await this.refs.issueId(me.id, issue),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
@Post('issues/:issue/duplicate')
|
||||
@ISSUE
|
||||
@ApiOperation({
|
||||
summary: 'Duplicate the ticket',
|
||||
description:
|
||||
'Copies what it says (type, title, description, area, priority, labels, Figma, estimate, dates, parent and checklist steps, unticked), not where it stands: the copy starts in the first status, unassigned, out of sprints and releases, without comments or files. The result carries its key.',
|
||||
})
|
||||
@ApiCreatedResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
async duplicate(@CurrentUser() me: User, @Param('issue') issue: string) {
|
||||
return this.issues.duplicate(me.id, await this.refs.issueId(me.id, issue));
|
||||
}
|
||||
|
||||
@Get('projects/:project/trash')
|
||||
@ApiOptionalPireonAuth()
|
||||
@PROJECT
|
||||
|
||||
33
libs/api/tracker/presenters/src/lib/http/proposal-limiter.ts
Normal file
33
libs/api/tracker/presenters/src/lib/http/proposal-limiter.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
|
||||
/** Proposals from one address within the window. */
|
||||
const LIMIT = 5;
|
||||
const WINDOW_MS = 15 * 60_000;
|
||||
|
||||
/**
|
||||
* Keeps one address from flooding a project with proposals. In memory:
|
||||
* enough for one instance, and an approximation with several (each counts
|
||||
* its own), which is fine for what it guards against.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ProposalLimiter {
|
||||
private readonly sent = new Map<string, number[]>();
|
||||
|
||||
take(address: string): void {
|
||||
const now = Date.now();
|
||||
const recent = (this.sent.get(address) ?? []).filter(
|
||||
(at) => now - at < WINDOW_MS,
|
||||
);
|
||||
if (recent.length >= LIMIT)
|
||||
throw new HttpException(
|
||||
'Too many proposals from here; try again in a few minutes',
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
recent.push(now);
|
||||
this.sent.set(address, recent);
|
||||
// Forget quiet addresses now and then, so the map does not grow forever.
|
||||
if (this.sent.size > 10_000)
|
||||
for (const [key, times] of this.sent)
|
||||
if (times.every((at) => now - at >= WINDOW_MS)) this.sent.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
BlockersService,
|
||||
IssuesService,
|
||||
ProjectsService,
|
||||
WorkflowsService,
|
||||
@@ -23,6 +24,7 @@ export class Refs {
|
||||
private readonly projects: ProjectsService,
|
||||
private readonly issues: IssuesService,
|
||||
private readonly workflows: WorkflowsService,
|
||||
private readonly blockers: BlockersService,
|
||||
) {}
|
||||
|
||||
async projectId(viewerId: string | null, ref: string): Promise<string> {
|
||||
@@ -35,12 +37,15 @@ export class Refs {
|
||||
return (await this.issues.findOne(viewerId, ref)).id;
|
||||
}
|
||||
|
||||
/** The ticket as the REST API returns it: read model + allowed transitions. */
|
||||
/** The ticket as the REST API returns it: read model, allowed transitions and what blocks it. */
|
||||
async issueDto(issue: IssueReadModel) {
|
||||
return {
|
||||
...issue,
|
||||
allowedTransitions: await this.workflows.allowedTransitions(issue),
|
||||
};
|
||||
const [allowedTransitions, blockedBy] = await Promise.all([
|
||||
this.workflows.allowedTransitions(issue),
|
||||
this.blockers.blockedBy(issue),
|
||||
]);
|
||||
// Who voted is only for telling someone whether they did.
|
||||
const { voterIds: _voters, ...shown } = issue;
|
||||
return { ...shown, allowedTransitions, blockedBy };
|
||||
}
|
||||
|
||||
issueDtos(issues: IssueReadModel[]) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { AttachmentsController } from './http/attachments.controller';
|
||||
import { CommentsController } from './http/comments.controller';
|
||||
import { IssuesController } from './http/issues.controller';
|
||||
import { ExploreController } from './http/explore.controller';
|
||||
import { ProposalLimiter } from './http/proposal-limiter';
|
||||
import { ProjectsController } from './http/projects.controller';
|
||||
import { Refs } from './http/refs';
|
||||
import { ReleasesController } from './http/releases.controller';
|
||||
@@ -63,6 +64,7 @@ import { AutomationResolver } from './graphql/automation.resolver';
|
||||
],
|
||||
providers: [
|
||||
Refs,
|
||||
ProposalLimiter,
|
||||
ProjectResolver,
|
||||
IssueResolver,
|
||||
CommentResolver,
|
||||
|
||||
Reference in New Issue
Block a user