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
  ![name](attachment:<id>); 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:
2026-10-09 21:36:11 +02:00
parent 298766ad1a
commit f2001aca88
116 changed files with 17997 additions and 650 deletions

View File

@@ -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';

View File

@@ -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']]);
});
});

View 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),
),
];
}

View File

@@ -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 };
}
}

View File

@@ -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,

View File

@@ -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,

View File

@@ -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);

View File

@@ -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);

View File

@@ -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 };
}
}

View File

@@ -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();
}
}

View File

@@ -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';

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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,
),
);
}
}

View File

@@ -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();
}
}

View File

@@ -9,6 +9,7 @@ export class UpdateProjectCommand extends Command<CommandResult> {
name?: string;
description?: string | null;
isPublic?: boolean;
acceptsProposals?: boolean;
},
) {
super();

View File

@@ -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);
}
}

View File

@@ -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();
}
}

View File

@@ -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),

View File

@@ -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),

View File

@@ -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);
}
}

View File

@@ -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,

View File

@@ -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);
}
}

View File

@@ -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),

View File

@@ -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,

View File

@@ -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),

View File

@@ -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),
})),
},
};
}
}

View File

@@ -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 },

View File

@@ -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,