Files
task-stream/libs/api/tracker/domain/src/lib/issue/issue.ts
Josep Piguillem 0e301ad545 feat: per-project workflow settings, statistics and "my work" home
Per-project settings (owners/admins, «Configuración» tab):
- Statuses with category (TODO, IN_PROGRESS, QA, DONE, CANCELLED), colour and
  "requires reason"; configurable transitions; ticket types (icon, colour) and
  areas. Defaults are the previous fixed values; projects created before keep
  them without migration.
- Values are archived, never deleted: tickets, history and statistics keep
  referring to them. Validated in the domain (ProjectSettingsChangedEvent).
- Releases, board, tracking and "my work" use categories, so custom statuses
  keep working. Status changes carry name/category metadata for history.
- GraphQL: status/type/area are strings (breaking for clients sending enum
  literals); Project.settings, updateProjectSettings, statusCategory,
  myIssues(categories). REST: PUT /projects/{project}/settings, category filters.
- Read model: statusCategory on issues (backfilled at startup).

Statistics («Estadísticas» tab):
- New issue_timeline projection; pure functions compute created vs resolved,
  cumulative flow, cycle/lead time (avg + p85), throughput per person, QA
  pass/fail and release burnup. GraphQL Project.analytics(days),
  Release.burnup; REST /projects/{project}/analytics, /releases/{id}/burnup.
- Web: SVG charts with validated light/dark palette, crosshair tooltip,
  keyboard navigation, legend and data table.

Home "Mi trabajo": my open tickets across projects grouped by category (QA
failures first), tickets waiting for QA, upcoming releases and "Ir a…".

Tests: domain/application specs, e2e scenario for settings and analytics,
facade tests. Docs, READMEs, schema.gql/openapi.json and Word/PDF updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 20:53:45 +02:00

301 lines
8.9 KiB
TypeScript

import {
BusinessRuleError,
VersionedAggregateRoot,
assertThat,
} from '@task-stream/api/shared/domain';
import { IssueAssignedEvent } from '../events/issue-assigned.event';
import { IssueCreatedEvent } from '../events/issue-created.event';
import { IssueLinkedEvent } from '../events/issue-linked.event';
import { IssueReleaseChangedEvent } from '../events/issue-release-changed.event';
import { IssueStatusChangedEvent } from '../events/issue-status-changed.event';
import { IssueUnlinkedEvent } from '../events/issue-unlinked.event';
import { IssueUpdatedEvent } from '../events/issue-updated.event';
import { ProjectWorkflow } from '../project/project-settings';
import { IssueLinkType, IssuePriority } from './issue.enums';
export interface IssueLink {
type: IssueLinkType;
targetIssueId: string;
targetKey: string;
}
/** Fields editable after creation. */
export interface IssueDetails {
title?: string;
description?: string | null;
/** Id of one of the project's ticket types. */
type?: string;
/** Id of one of the project's areas. */
area?: string | null;
priority?: IssuePriority;
labels?: string[];
figmaUrl?: string | null;
storyPoints?: number | null;
dueDate?: string | null;
}
/** Data of a ticket (what IssueCreatedEvent carries). */
export interface IssueProps {
id: string;
projectId: string;
number: number;
key: string;
type: string;
area: string | null;
title: string;
description: string | null;
/** Id of a status of the project's workflow. */
status: string;
priority: IssuePriority;
reporterId: string;
assigneeId: string | null;
releaseId: string | null;
labels: string[];
figmaUrl: string | null;
storyPoints: number | null;
dueDate: string | null;
links: IssueLink[];
createdAt: string;
updatedAt: string;
}
/**
* A ticket: bug, feature, UI change, task or QA. Event-sourced: create it
* with IssueFactory, load it with the AggregateRehydrator.
*/
export class Issue extends VersionedAggregateRoot implements IssueProps {
public projectId!: string;
public number!: number;
public key!: string;
public type!: string;
public area: string | null = null;
public title!: string;
public description: string | null = null;
public status!: string;
public priority: IssuePriority = IssuePriority.MEDIUM;
public reporterId!: string;
public assigneeId: string | null = null;
public releaseId: string | null = null;
public labels: string[] = [];
public figmaUrl: string | null = null;
public storyPoints: number | null = null;
public dueDate: string | null = null;
public links: IssueLink[] = [];
public createdAt!: string;
public updatedAt!: string;
constructor(id: string) {
super();
this.id = id;
}
/** `workflow` (the project's) validates a new type or area. */
updateDetails(
actorId: string,
changes: IssueDetails,
workflow: ProjectWorkflow = ProjectWorkflow.default(),
): void {
const next = normalizeIssueDetails(changes);
const patch: IssueDetails = {};
for (const field of Object.keys(next) as (keyof IssueDetails)[]) {
const value = next[field];
if (value === undefined) continue;
if (JSON.stringify(value) === JSON.stringify(this[field])) continue;
(patch as Record<string, unknown>)[field] = value;
}
if (patch.title !== undefined)
assertThat(patch.title.length > 0, 'Issue title is required');
if (patch.type !== undefined) workflow.assertActiveType(patch.type);
if (patch.area !== undefined) workflow.assertActiveArea(patch.area);
if (Object.keys(patch).length === 0) return;
this.apply(new IssueUpdatedEvent(actorId, this.id, this.projectId, patch));
}
/** Moves the ticket along its project's workflow. */
changeStatus(
actorId: string,
to: string,
reason?: string | null,
workflow: ProjectWorkflow = ProjectWorkflow.default(),
): void {
const from = this.status;
if (from === to) return;
if (!workflow.canTransition(from, to)) {
throw new BusinessRuleError(
`Cannot move ${this.key} from ${workflow.statusName(from)} to ${workflow.statusName(to)}. ` +
`Allowed: ${
workflow
.allowedFrom(from)
.map((s) => workflow.statusName(s))
.join(', ') || 'none'
}`,
);
}
const trimmedReason = reason?.trim() || null;
if (workflow.requiresReason(to) && !trimmedReason) {
throw new BusinessRuleError(
`A reason is required to move ${this.key} to ${workflow.statusName(to)}`,
);
}
this.apply(
new IssueStatusChangedEvent(
actorId,
this.id,
this.projectId,
from,
to,
trimmedReason,
{
fromName: workflow.statusName(from),
toName: workflow.statusName(to),
fromCategory: workflow.categoryOf(from),
toCategory: workflow.categoryOf(to),
},
),
);
}
/** @param assigneeId null to unassign */
assign(actorId: string, assigneeId: string | null): void {
if (this.assigneeId === assigneeId) return;
this.apply(
new IssueAssignedEvent(
actorId,
this.id,
this.projectId,
assigneeId,
this.assigneeId,
),
);
}
linkTo(
actorId: string,
type: IssueLinkType,
target: { id: string; key: string },
): void {
if (target.id === this.id)
throw new BusinessRuleError('An issue cannot be linked to itself');
if (
this.links.some((l) => l.type === type && l.targetIssueId === target.id)
) {
throw new BusinessRuleError(`${this.key} already ${type} ${target.key}`);
}
this.apply(
new IssueLinkedEvent(actorId, this.id, this.projectId, {
type,
targetIssueId: target.id,
targetKey: target.key,
}),
);
}
unlink(actorId: string, type: IssueLinkType, targetIssueId: string): void {
const link = this.links.find(
(l) => l.type === type && l.targetIssueId === targetIssueId,
);
if (!link) throw new BusinessRuleError('Link not found');
this.apply(
new IssueUnlinkedEvent(actorId, this.id, this.projectId, { ...link }),
);
}
/** Moves the ticket in or out of a release (null removes it). */
setRelease(actorId: string, releaseId: string | null): void {
if (this.releaseId === releaseId) return;
this.apply(
new IssueReleaseChangedEvent(
actorId,
this.id,
this.projectId,
releaseId,
this.releaseId,
),
);
}
/* ---- State transitions (also replayed by loadFromHistory) ---- */
onIssueCreatedEvent({ issue }: IssueCreatedEvent): void {
Object.assign(this, {
...issue,
labels: [...issue.labels],
links: issue.links.map((l) => ({ ...l })),
});
}
onIssueUpdatedEvent(event: IssueUpdatedEvent): void {
Object.assign(this, event.changes);
this.updatedAt = event.occurredAt;
}
onIssueStatusChangedEvent(event: IssueStatusChangedEvent): void {
this.status = event.to;
this.updatedAt = event.occurredAt;
}
onIssueAssignedEvent(event: IssueAssignedEvent): void {
this.assigneeId = event.assigneeId;
this.updatedAt = event.occurredAt;
}
onIssueLinkedEvent(event: IssueLinkedEvent): void {
this.links = [...this.links, { ...event.link }];
this.updatedAt = event.occurredAt;
}
onIssueUnlinkedEvent(event: IssueUnlinkedEvent): void {
this.links = this.links.filter(
(l) =>
!(
l.type === event.link.type &&
l.targetIssueId === event.link.targetIssueId
),
);
this.updatedAt = event.occurredAt;
}
onIssueReleaseChangedEvent(event: IssueReleaseChangedEvent): void {
this.releaseId = event.releaseId;
this.updatedAt = event.occurredAt;
}
}
/** Trims, deduplicates and validates editable issue fields. */
export function normalizeIssueDetails(details: IssueDetails): IssueDetails {
const out: IssueDetails = { ...details };
if (details.title !== undefined) out.title = details.title.trim();
if (details.description !== undefined)
out.description = details.description?.trim() || null;
if (details.labels !== undefined) {
out.labels = [
...new Set(
details.labels.map((l) => l.trim().toLowerCase()).filter(Boolean),
),
];
}
if (details.figmaUrl !== undefined && details.figmaUrl !== null) {
const url = details.figmaUrl.trim();
assertThat(
/^https:\/\/([\w-]+\.)?figma\.com\//.test(url),
'figmaUrl must be a figma.com link',
);
out.figmaUrl = url;
}
if (details.storyPoints !== undefined && details.storyPoints !== null) {
assertThat(
Number.isInteger(details.storyPoints) &&
details.storyPoints >= 0 &&
details.storyPoints <= 100,
'storyPoints must be an integer between 0 and 100',
);
}
if (details.dueDate !== undefined && details.dueDate !== null) {
assertThat(
!Number.isNaN(Date.parse(details.dueDate)),
'dueDate must be an ISO date',
);
}
return out;
}