Compare commits

..

31 Commits

Author SHA1 Message Date
41f81cd2b0 fix(web): a poll asks its own question instead of a stock one
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:45:07 +02:00
f36c31e66d fix(web): a poll says how it is published, and needs no text of its own
With a poll open the button reads «Publicar encuesta» and two options are
enough. The «Más» menu keeps the page's gutter on a phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:20:00 +02:00
425db24eea fix(web): the ticket's header fits, with «Más» for the less frequent actions
The reminder and what is new are pi-notes; the poll editor's buttons align.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:17:24 +02:00
285bd5c454 feat: what is new since my last visit, and turning a comment into a ticket
Opening a ticket notes the visit and answers the one before (issue_visits),
so the page marks others' comments and changes since. A comment can become
a ticket of its own, as a subtask or linked; it remembers where it went.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:05:44 +02:00
429b52e6f5 fix(web): polls, recordings, reviews and reminders use @pi/ui's fields and buttons
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:24:37 +02:00
3c211f0e56 test(web): the routes spec knows the public release notes page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:24:37 +02:00
909edc9f4d feat(web): record the screen or the voice from a comment, and play it there
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 06:58:18 +02:00
c27aa4b1d7 feat(web): the roadmap shows dependencies on other projects
Tickets of other projects that block a dated epic, or that it depends
on, now show under «De otros proyectos» with a dashed bar, their arrows,
and the same warning when the dates clash («EPI-1 empieza el 25 oct,
pero BACK-1 (otro proyecto), que la bloquea, acaba el 5 nov»). Both
halves of a relation are read, since one recorded from the other project
only leaves its inward half here. The ones without dates, or out of
reach, are named under the chart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 21:12:37 +02:00
79b8094011 feat(web): project health as a traffic light, with its causes
The project dashboard opens with «Salud del proyecto»: good, attention or
at risk, the worst of its signals, each with the cause and the tickets
behind it: stuck work, overdue and blocked tickets, critical or several
high bugs, QA sending back 30 % or more (with enough verdicts), releases
late or at risk by the forecast, columns over their WIP limit. Worked
out in the web from the insights it already reads (projectHealth). The
portfolio shows each project's light too, with its causes on hover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 21:08:21 +02:00
8ed16f133e feat: a public notes page per release, for clients
On the releases page, «Página pública» (owners and admins) opens a
secret link to a page with the release's notes, readable without an
account, also for private projects: the notes written, or the draft
from its finished tickets while there are none (without repeating the
title the page already shows). The link can be copied, renewed (the old
one stops working) or withdrawn. Stored in Mongo (`release_note_shares`).

API: shareReleaseNotes / unshareReleaseNotes / releaseNotesShare,
publicReleaseNotes(token); GET/PUT/DELETE /api/releases/{id}/public-notes,
GET /api/shared/release-notes/{token}. Web: /notes/:token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:57:40 +02:00
3a46a236e4 feat: quick polls in comments that end in a decision
«📊 Añadir una encuesta» adds 2 to 6 options to a new comment. Members,
viewers too, vote by clicking an option (one vote each, which they can
change or take back) and see each option's votes as a bar. Whoever
started it, or an admin, closes it with «Cerrar y decidir»: the most
voted wins (none on a tie) and a «Decidido: …» reply marked as a
decision shows above the ticket. Events of the comment (voted, closed).

API: addComment(…, poll), votePoll, closePoll, Comment.poll;
POST /api/comments/{id}/poll/vote and …/poll/close. MCP: add_comment
poll, vote_poll, close_poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:48:12 +02:00
93d028e870 feat: ask a teammate to review a ticket
«Pedir revisión» on a ticket asks a member (with an optional note): they
are notified and see it under «Te piden revisión» in my work until they
answer «Todo bien» or «Pedir cambios» (with what to change) from the
ticket's Revisiones box; whoever asked hears the answer and can withdraw
an open request. Events of the ticket (requested, answered, cancelled),
so they show in its history and the activity feed. Viewers can be asked
and answer; not oneself, nor twice the same person with one pending.

API: requestReview / answerReview / cancelReview, Issue.reviews,
myIssues(reviewing); POST /api/issues/{issue}/reviews,
POST …/reviews/{id}/answer, DELETE …/reviews/{id}. MCP: request_review,
answer_review, my_issues reviewing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:38:30 +02:00
172c53d21d feat(web): the board works from the keyboard
With a card focused (Tab reaches them): arrows move between cards, also
across swimlanes' columns; Shift+←/→ moves the card to the next column
with the same rules as dragging it (allowed transitions, WIP warning,
reason when the status asks for one) and keeps the focus on it; p, e
and a open its priority, estimate or assignee; Enter opens it. The «?»
help lists them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:20:30 +02:00
dfb5f973f4 feat: «Mi día», the few tickets I pick for today
A home panel with the tickets picked for today (10 at most), crossed out
as they get done and counted («1 de 3 terminados»), my open tickets to
add with one click, and what was left unfinished on my last day to carry
over. «☀ Mi día» on a ticket adds it or takes it out. The day is the
person's own (YYYY-MM-DD from the browser); private, no history (Mongo
`my_days`).

API: myDay(day), addToMyDay, removeFromMyDay; GET /api/me/day,
PUT/DELETE /api/me/day/{issue}. MCP: my_day.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:18:10 +02:00
b88296c22b feat: «Recordármelo», a reminder of a ticket only for me
On a ticket, «Recordármelo» offers in an hour, this evening, tomorrow or
next Monday at 9, in a week, or any date and time, with an optional note.
The ticket shows the waiting one («Te lo recordaré el mié 21 a las 9:00»)
to change or drop. Every minute a scheduler tells the ones whose time
came as a REMINDER notification (bell, push, e-mail), once, and forgets
those whose ticket went to the trash or out of reach. One per person and
ticket, private, no history (Mongo `issue_reminders`).

API: setReminder / clearReminder, Issue.myReminder, myReminders;
PUT/DELETE /api/issues/{issue}/reminder, GET /api/me/reminders. MCP:
remind_me.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:08:50 +02:00
d79ef418d3 feat: follow an epic with everything under it
«Seguir todo» on a ticket with subtasks (and on each epic of the Epics
page) tells you of it and of every ticket hanging from it, at any depth,
also the ones added later: their moves, assignments, comments and plan
changes, as a follower of each, plus when a ticket is placed under it.
Guests of a private project are left out. Personal, no history (Mongo
`tree_follows`).

API: followTree / unfollowTree, Issue.followingTree, PUT/DELETE
/api/issues/{issue}/follow-tree. MCP: watch_issue with tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:59:04 +02:00
179d6a5e94 fix(web): bulk changes of more than 100 tickets go in batches
The list shows up to 200 tickets and «select all» picks them all, but
the API takes 100 per bulk change: above that the whole change failed
(«At most 100 tickets at once») and nothing changed. The gateway now
sends batches of 100 one after another and adds up the results, for the
list and the backlog alike.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:34:09 +02:00
199b60e4ce feat: conversations on a ticket are settled, and you see who is typing
A top-level comment and its replies can be resolved by whoever can
change the ticket (CommentThreadResolvedEvent), with an optional
conclusion added as a reply marked as a decision, so it shows above the
ticket. A settled conversation folds to one line (topic, who settled it
and the conclusion) and can be unfolded or reopened; the header counts
the open ones, and finishing the ticket with one open asks first.

«Ana está escribiendo…» shows in the conversation being answered, at
once: a `typing` mutation publishes to a Redis channel per ticket
(`typing` subscription), never stored. In replies, Enter sends and
Shift+Enter breaks the line, except inside lists and code.

API: resolveThread / PUT-DELETE /api/comments/{id}/resolution, Comment
.resolved/resolvedBy/resolvedAt, typing mutation and subscription. MCP:
resolve_thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 22:35:46 +02:00
c0b0417b6d fix(api): automations without conditions list and run again
Mongo leaves empty objects out, so a rule saved with no conditions came
back without them: the automations list failed («Cannot return null for
non-nullable field Automation.conditions») and the rules engine threw
on it, so those rules never ran. The repository now gives them an empty
object, as the views of «my work» already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 19:53:56 +02:00
33c593521e feat: statuses and ticket types take any colour from a colour picker
Settings shows a native colour picker (the palette as suggestions)
instead of the list of eleven names. The API takes a palette name, as
before, or any #rrggbb; picking a palette colour still saves its name,
so it keeps its hand-made dark version. A free colour gets one variant
per theme, computed with the `color` library (moved towards white or
black until it contrasts 3:1 with the surface) and applied with
light-dark(): a pale yellow darkens on white, a navy lightens on dark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 16:08:47 +02:00
034704e46f feat: alerts open bugs, and repeats of the same problem go to that bug
Owners and admins turn on a secret URL per project (Settings →
Integrations), POST /api/webhooks/alerts/{project}/{token}, that Sentry,
Uptime Kuma, Prometheus Alertmanager, Grafana or any tool sending JSON
with a title can call. A new problem opens a bug as TaskStream (label
«alerta», chosen type and priority); while that bug is open, the same
fingerprint goes to it (a comment at most every 30 minutes) and
«resolved» is said on it; once it is closed, a new bug names the old
one. Alerts of a project are handled one at a time, so two at once open
one bug, and a bug not yet projected still counts as open. Unknown
project, alerts off or a bad token all answer 403.

TaskStream may now comment as the system actor, like it already opened
tickets for public proposals. Stored in Mongo (alert_integrations,
alert_traces), not in the event store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:36:55 +02:00
42a21412d9 feat(web): «Deshacer» after moving, reassigning or trashing a ticket
A toast offers to undo for seven seconds (or Ctrl/⌘ Z outside a field)
by running the opposite command: the card back to its column or the
ticket to its status (the workflow may refuse it), the previous
assignee, or the ticket back from the trash. The undo itself only says
«Deshecho». On the board, from the card's assignee; on the ticket page,
status, assignee and trash, which no longer asks for confirmation.

The toast is the app's own (UndoToastComponent): pi-snack-bar cannot
tell its button from the timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:43:54 +02:00
70e4fbd399 feat: comments marked as decisions, on top of the ticket and searchable
Whoever can change the ticket flags a comment as a decision (new event
CommentDecisionMarkedEvent on the comment). The ticket page lists its
decisions above the description, with a link to the comment in the
conversation (`?comment=<id>` scrolls to it and points at it), and the
search palette finds them by their text across my projects.

API: markDecision / PUT-DELETE /api/comments/{id}/decision; Issue.decisions
and GET /api/issues/{issue}/decisions; decisions(projectId?, search) and
GET /api/projects/{project}/decisions, GET /api/me/decisions. MCP:
mark_decision, search_decisions, and get_issue includes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:32:07 +02:00
8f83fdefb6 fix(web): the ticket page fits a phone again
Its main column was a grid without columns, so it grew to the width of
its widest form field (650 px on a 390 px screen) and cut the text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:23:27 +02:00
dfa42a8a1a feat: pinned tickets, at hand on the home page and in search
Each person pins up to 20 tickets from the ticket's page («Fijar»). They
show as a strip under the projects on the home page and in the search
palette before typing. Private and without history, like the views of
«my work» (Mongo `pinned_issues`); tickets in the trash or out of reach
are left out, and when the list is full the unreadable ones are dropped
first.

API: GET /api/me/pins, PUT/DELETE /api/issues/{issue}/pin; GraphQL
myPins, pinIssue, unpinIssue and Issue.pinned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 10:15:28 +02:00
423f82c1a3 feat(web): priority, estimate and assignee change right on the board card
The card's title is now the link (stretched over the card), and the three
chips carry an invisible native select each, so they work by keyboard,
on a phone and with a screen reader without opening the ticket. Dragging
still works from anywhere on the card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 09:41:23 +02:00
a32c937765 fix(api): a read-side failure waits for its event instead of losing it
The Redis consumer used to leave a failed event pending and go on to the
next ones, retrying it only at the next start. With Mongo down for a
while, a later change of the same ticket was then projected first, and
the version check dropped the earlier one for good (a status change
could vanish from the read model), besides the read side lagging until
a restart.

Now a failed event is retried in place, waiting longer each time (up to
30 s), and the next one waits for it. Failures of the infrastructure
(Mongo, Redis, the network: isTransientError) wait as long as it takes,
so the read side catches up by itself; an event that keeps failing on
its own goes, after 5 attempts, to <stream>:dead with its error, so it
does not hold up the rest.

GET /api/health reports the way from write to read (events waiting in
the outbox, pending to be projected, set aside) and says `degraded`,
still with 200, when something is stuck.

Tried for real: with Mongo stopped, two status changes went in; the
first failed to project with ECONNREFUSED, and once Mongo was back the
ticket's history had both steps, in order, without restarting the API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:24:19 +02:00
d66b1f3ece feat: a day of the activity map opens what happened, ticket by ticket
On the project dashboard, a day with activity can be picked on the map:
a side panel lists that day's moves grouped by ticket (each key opens
it), with the time of each, and the project's own (sprints, releases,
members) apart.

The activity feed takes an `after` date (GraphQL, REST), so with
`before` it reads a window such as a day; the MCP's
get_project_activity takes a `day`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:42:30 +02:00
de9c8a7780 fix(web): «Desde tu última visita» keeps its four numbers in line
Each number sat under its label, and in a narrow panel «Vueltos de QA»
takes two lines, so its number fell lower than the others. The numbers
go on top now (the markup stays label then value).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:42:27 +02:00
4969fb3f6d fix(web): settings and bell use accessible checkboxes, not slide toggles
@pi/ui's slide toggle hides its input with display: none and gives it
no name: neither the Tab key nor a screen reader could reach the
switches in settings (visibility, the public's proposals, the
definition of done, the link for clients) or the bell's (e-mail copy,
notices on this device). They are pi-checkbox now, each with a name
saying what it turns on: reachable by keyboard, toggled with the space
bar and announced.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:20:06 +02:00
e10c9b84bf refactor(web): settings switches are @pi/ui's slide toggle
Visibility, the public's proposals, the definition of done and the link
for clients each had a hand-made switch; they use pi-slide-toggle now,
like the bell's, with their state written beside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:12:13 +02:00
225 changed files with 26735 additions and 716 deletions

View File

@@ -1425,6 +1425,26 @@ describe('task-stream (e2e)', () => {
expect(insights.body['journey']).toMatchObject({ samples: 0, steps: [] }); expect(insights.body['journey']).toMatchObject({ samples: 0, steps: [] });
expect(insights.body['proposals']).toBeNull(); expect(insights.body['proposals']).toBeNull();
// A day of it: only what happened between after and before.
const tomorrow = new Date(Date.parse(`${today}T00:00:00Z`) + 86_400_000);
const ofToday = await rest(
'token-ana',
'GET',
`/projects/${key}/activity?after=${today}T00:00:00.000Z&before=${tomorrow.toISOString()}&limit=200`,
);
expect(ofToday.body.length).toBeGreaterThan(0);
expect(
ofToday.body.every((a: { occurredAt: string }) =>
a.occurredAt.startsWith(today),
),
).toBe(true);
const ofYesterday = await rest(
'token-ana',
'GET',
`/projects/${key}/activity?after=2020-01-01T00:00:00.000Z&before=2020-01-02T00:00:00.000Z`,
);
expect(ofYesterday.body).toEqual([]);
// What changed since a moment, and what the backlog lacks. // What changed since a moment, and what the backlog lacks.
const since = new Date(Date.now() - 60_000).toISOString(); const since = new Date(Date.now() - 60_000).toISOString();
const later = await rest( const later = await rest(

File diff suppressed because it is too large Load Diff

View File

@@ -45,6 +45,27 @@ type Aging {
thresholdDays: Float thresholdDays: Float
} }
"""Alerts → bugs: the secret URL monitoring tools call to open bugs"""
type AlertIntegration {
enabled: Boolean!
priority: IssuePriority!
"""Ticket type it opens; null: the project's first bug type"""
typeId: ID
"""
Path of the URL on this API, secret token included; only owners and admins see it
"""
webhookPath: String
}
input AlertSettingsInput {
priority: IssuePriority
"""Ticket type to open; null: the project's first bug type"""
typeId: ID
}
type AreaOption { type AreaOption {
archived: Boolean! archived: Boolean!
id: String! id: String!
@@ -270,18 +291,36 @@ type Comment {
"""Empty on a deleted comment kept for its replies""" """Empty on a deleted comment kept for its replies"""
body: String! body: String!
createdAt: String! createdAt: String!
decidedAt: String
"""Who marked it as a decision"""
decidedBy: UserRef
"""Marked as a decision of the ticket (shown above it)"""
decision: Boolean!
"""Deleted, but kept (without its text) while it has replies""" """Deleted, but kept (without its text) while it has replies"""
deleted: Boolean! deleted: Boolean!
editedAt: String editedAt: String
id: ID! id: ID!
issueId: ID! issueId: ID!
poll: CommentPoll
"""In the order they are offered; only the ones somebody chose""" """In the order they are offered; only the ones somebody chose"""
reactions: [CommentReaction!]! reactions: [CommentReaction!]!
"""The top-level comment it answers; null for a top-level one""" """The top-level comment it answers; null for a top-level one"""
replyTo: ID replyTo: ID
"""A conversation (top-level comment and its replies) that was settled"""
resolved: Boolean!
resolvedAt: String
"""Who settled it"""
resolvedBy: UserRef
"""Tickets made from it («Convertir en ticket»), oldest first"""
spawned: [CommentSpawn!]!
version: Int! version: Int!
} }
@@ -301,6 +340,15 @@ type CommentPage {
total: Int! total: Int!
} }
"""A quick poll in a comment"""
type CommentPoll {
closed: Boolean!
options: [PollOption!]!
"""Index of the winning option once closed (null on a tie)"""
winner: Int
}
"""One emoji on a comment""" """One emoji on a comment"""
type CommentReaction { type CommentReaction {
emoji: String! emoji: String!
@@ -309,6 +357,12 @@ type CommentReaction {
users: [UserRef!]! users: [UserRef!]!
} }
"""A ticket made from a comment"""
type CommentSpawn {
id: ID!
key: String!
}
type CountByAssignee { type CountByAssignee {
count: Int! count: Int!
@@ -475,6 +529,12 @@ type DashboardShare {
token: String! token: String!
} }
"""A comment marked as a decision, with its ticket"""
type Decision {
comment: Comment!
issue: IssueParent!
}
"""A commit, branch or pull request that mentions the ticket""" """A commit, branch or pull request that mentions the ticket"""
type DevLink { type DevLink {
at: String! at: String!
@@ -640,6 +700,9 @@ type Issue {
"""Values of the project's custom fields (only those set)""" """Values of the project's custom fields (only those set)"""
customFields: [CustomFieldValue!]! customFields: [CustomFieldValue!]!
"""Its comments marked as decisions, oldest first"""
decisions: [Comment!]!
description: String description: String
"""Commits, branches and pull requests that mention it""" """Commits, branches and pull requests that mention it"""
@@ -647,6 +710,9 @@ type Issue {
dueDate: String dueDate: String
figmaUrl: String figmaUrl: String
"""Whether I follow it with everything under it (false without a token)"""
followingTree: Boolean!
"""History of this ticket""" """History of this ticket"""
history(limit: Int! = 50): [Activity!]! history(limit: Int! = 50): [Activity!]!
id: ID! id: ID!
@@ -658,10 +724,16 @@ type Issue {
"""Linked tickets I can see""" """Linked tickets I can see"""
linkedIssues: [Issue!]! linkedIssues: [Issue!]!
links: [IssueLink!]! links: [IssueLink!]!
"""My waiting reminder on it (null without one or a token)"""
myReminder: IssueReminder
number: Int! number: Int!
"""The epic or ticket this one breaks down""" """The epic or ticket this one breaks down"""
parent: IssueParent parent: IssueParent
"""Whether I pinned it (false without a token)"""
pinned: Boolean!
priority: IssuePriority! priority: IssuePriority!
projectId: ID! projectId: ID!
projectKey: String! projectKey: String!
@@ -672,6 +744,9 @@ type Issue {
rank: String! rank: String!
release: ReleaseRef release: ReleaseRef
reporter: UserRef! reporter: UserRef!
"""Reviews asked, open and answered, oldest first"""
reviews: [IssueReview!]!
sprint: SprintRef sprint: SprintRef
"""When work should start (roadmap)""" """When work should start (roadmap)"""
@@ -795,6 +870,27 @@ enum IssuePriority {
MEDIUM MEDIUM
} }
"""My own reminder on a ticket («remind me on Thursday»)"""
type IssueReminder {
"""When it tells me (ISO, UTC)"""
at: String!
note: String
}
"""A review someone asked on the ticket"""
type IssueReview {
answer: String
answeredAt: String
id: ID!
note: String
requestedAt: String!
requester: UserRef!
reviewer: UserRef!
"""Null while waiting for an answer"""
verdict: ReviewVerdict
}
"""RECENT: last updated first. RANK: backlog order.""" """RECENT: last updated first. RANK: backlog order."""
enum IssueSort { enum IssueSort {
RANK RANK
@@ -826,6 +922,8 @@ type IssueTypeOption {
input IssueTypeOptionInput { input IssueTypeOptionInput {
archived: Boolean! = false archived: Boolean! = false
"""A palette colour (follows the theme) or #rrggbb"""
color: String! color: String!
icon: String! icon: String!
id: String! id: String!
@@ -885,7 +983,14 @@ type Mutation {
""" """
Comment on a ticket, or answer a comment (replyTo; one level of replies) Comment on a ticket, or answer a comment (replyTo; one level of replies)
""" """
addComment(body: String!, issueId: ID!, replyTo: ID): CommandResult! addComment(
body: String!
issueId: ID!
"""A quick poll: 2 to 6 options"""
poll: [String!]
replyTo: ID
): CommandResult!
""" """
Add a repository with its own secret (the first turns the integration on) Add a repository with its own secret (the first turns the integration on)
@@ -895,6 +1000,12 @@ type Mutation {
"""Add a Pireon user to the project""" """Add a Pireon user to the project"""
addProjectMember(input: ProjectMemberInput!): CommandResult! addProjectMember(input: ProjectMemberInput!): CommandResult!
"""Add tickets to «Mi día» (10 at most)"""
addToMyDay(day: String!, issueIds: [ID!]!): Boolean!
"""Answer a review I was asked for: all good, or changes"""
answerReview(answer: String, issueId: ID!, reviewId: ID!, verdict: ReviewVerdict!): CommandResult!
""" """
Archive the project (owner only): everything stays readable, nothing changes until it is unarchived Archive the project (owner only): everything stays readable, nothing changes until it is unarchived
""" """
@@ -915,10 +1026,21 @@ type Mutation {
""" """
bulkUpdateIssues(input: BulkUpdateIssuesInput!): BulkResult! bulkUpdateIssues(input: BulkUpdateIssuesInput!): BulkResult!
"""Withdraw a review request I made (or, as admin, any)"""
cancelReview(issueId: ID!, reviewId: ID!): CommandResult!
"""Move a ticket through the workflow (incl. QA)""" """Move a ticket through the workflow (incl. QA)"""
changeIssueStatus(input: ChangeIssueStatusInput!): CommandResult! changeIssueStatus(input: ChangeIssueStatusInput!): CommandResult!
changeProjectMemberRole(input: ProjectMemberInput!): CommandResult! changeProjectMemberRole(input: ProjectMemberInput!): CommandResult!
"""Drop my reminder on a ticket"""
clearReminder(issueId: ID!): Boolean!
"""
Close a poll (whoever started it, or an admin); with decide, the winner stays as a decision of the ticket
"""
closePoll(commentId: ID!, decide: Boolean! = true): CommandResult!
""" """
Close the sprint under way. Unfinished tickets move to carryOverToSprintId, or back to the backlog when it is null. Close the sprint under way. Unfinished tickets move to carryOverToSprintId, or back to the backlog when it is null.
""" """
@@ -958,21 +1080,39 @@ type Mutation {
deleteSprint(sprintId: ID!): CommandResult! deleteSprint(sprintId: ID!): CommandResult!
deleteWebhook(webhookId: ID!): Boolean! deleteWebhook(webhookId: ID!): Boolean!
"""Turn it off; the bugs it opened stay"""
disableAlertIntegration(projectId: ID!): Boolean!
""" """
A new ticket like this one: what it says, not where it stands (the key comes in the result) A new ticket like this one: what it says, not where it stands (the key comes in the result)
""" """
duplicateIssue(issueId: ID!): CommandResult! duplicateIssue(issueId: ID!): CommandResult!
editComment(body: String!, commentId: ID!): CommandResult! editComment(body: String!, commentId: ID!): CommandResult!
"""
Follow a ticket with everything under it (an epic): its changes and those of every ticket hanging from it, also future ones
"""
followTree(issueId: ID!): Boolean!
"""I left this ticket's page""" """I left this ticket's page"""
leavePresence(issueId: ID!): Boolean! leavePresence(issueId: ID!): Boolean!
"""Relate tickets, e.g. FE DEPENDS_ON BE, QA TESTS FE""" """Relate tickets, e.g. FE DEPENDS_ON BE, QA TESTS FE"""
linkIssues(input: LinkIssuesInput!): CommandResult! linkIssues(input: LinkIssuesInput!): CommandResult!
"""
Mark a comment as a decision of its ticket, or unmark it (on: false). Whoever can change the ticket
"""
markDecision(commentId: ID!, on: Boolean! = true): CommandResult!
"""Mark these as read, or all of them when `ids` is omitted""" """Mark these as read, or all of them when `ids` is omitted"""
markNotificationsRead(ids: [ID!]): Boolean! markNotificationsRead(ids: [ID!]): Boolean!
"""
Pin a ticket: keep it at hand on my home page and in search (private, at most 20)
"""
pinIssue(issueId: ID!): Boolean!
""" """
Ship the release. Fails while it has unfinished tickets unless force = true. Ship the release. Fails while it has unfinished tickets unless force = true.
""" """
@@ -990,19 +1130,40 @@ type Mutation {
removeAttachment(attachmentId: ID!, issueId: ID!): CommandResult! removeAttachment(attachmentId: ID!, issueId: ID!): CommandResult!
removeChecklistItem(issueId: ID!, itemId: ID!): CommandResult! removeChecklistItem(issueId: ID!, itemId: ID!): CommandResult!
"""Take a ticket out of «Mi día»"""
removeFromMyDay(day: String!, issueId: ID!): Boolean!
"""Remove a repository; what it linked stays on the tickets""" """Remove a repository; what it linked stays on the tickets"""
removeGitRepository(projectId: ID!, repositoryId: ID!): Boolean! removeGitRepository(projectId: ID!, repositoryId: ID!): Boolean!
removeProjectMember(projectId: ID!, userId: ID!): CommandResult! removeProjectMember(projectId: ID!, userId: ID!): CommandResult!
"""
Ask a member to review a ticket (with an optional note): they are told and see it in their work
"""
requestReview(issueId: ID!, note: String, reviewerId: ID!): CommandResult!
"""
Settle a conversation (a top-level comment and its replies) or reopen it (resolved: false). A conclusion is added as a reply marked as a decision. Whoever can change the ticket
"""
resolveThread(commentId: ID!, conclusion: String, resolved: Boolean! = true): CommandResult!
"""Back from the trash""" """Back from the trash"""
restoreIssue(issueId: ID!): CommandResult! restoreIssue(issueId: ID!): CommandResult!
"""My calendar URL stops working""" """My calendar URL stops working"""
revokeCalendarFeed: Boolean! revokeCalendarFeed: Boolean!
"""A new secret URL; the old one stops working at once"""
rotateAlertToken(projectId: ID!): AlertIntegration!
"""A new secret for a repository; the old one stops working""" """A new secret for a repository; the old one stops working"""
rotateGitRepositorySecret(projectId: ID!, repositoryId: ID!): GitRepository! rotateGitRepositorySecret(projectId: ID!, repositoryId: ID!): GitRepository!
"""
Turn alerts → bugs on, or change the type and priority it opens (the URL stays)
"""
saveAlertIntegration(input: AlertSettingsInput!, projectId: ID!): AlertIntegration!
"""Save the current board filters under a name (members of the project)""" """Save the current board filters under a name (members of the project)"""
saveFilter(input: SaveFilterInput!): ID! saveFilter(input: SaveFilterInput!): ID!
@@ -1020,9 +1181,24 @@ type Mutation {
"""Put a ticket in a sprint (null: back to the backlog)""" """Put a ticket in a sprint (null: back to the backlog)"""
setIssueSprint(issueId: ID!, sprintId: ID): CommandResult! setIssueSprint(issueId: ID!, sprintId: ID): CommandResult!
"""
Remind me of a ticket at a date and time (a notification), with an optional note. One per ticket: it replaces the waiting one
"""
setReminder(
"""ISO date-time, in the future"""
at: String!
issueId: ID!
note: String
): IssueReminder!
"""Turn the link on or change its blocks; renew for a new secret""" """Turn the link on or change its blocks; renew for a new secret"""
shareDashboard(input: ShareDashboardInput!): DashboardShare! shareDashboard(input: ShareDashboardInput!): DashboardShare!
"""
Turn a release's public notes page on; renew makes a new link (the old one stops working)
"""
shareReleaseNotes(releaseId: ID!, renew: Boolean! = false): ReleaseNotesShare!
"""Start a planned sprint (only one under way per project)""" """Start a planned sprint (only one under way per project)"""
startSprint(sprintId: ID!): CommandResult! startSprint(sprintId: ID!): CommandResult!
@@ -1042,13 +1218,44 @@ type Mutation {
""" """
trashIssue(issueId: ID!): CommandResult! trashIssue(issueId: ID!): CommandResult!
"""
Make a ticket of a comment: its text becomes the description, as a subtask of its ticket or linked to it (RELATES_TO). Answers the new ticket. Whoever can change tickets
"""
turnCommentIntoIssue(
asSubtask: Boolean! = false
commentId: ID!
title: String!
"""One of the project's ticket type ids"""
type: String!
): CommandResult!
"""
I am writing on this ticket (send every few seconds while typing): those with it open see it at once via `typing`
"""
typing(
issueId: ID!
"""The conversation being answered; null: a new comment"""
threadId: ID
): Boolean!
"""Bring an archived project back (owner only)""" """Bring an archived project back (owner only)"""
unarchiveProject(projectId: ID!): CommandResult! unarchiveProject(projectId: ID!): CommandResult!
"""Stop following a ticket with everything under it"""
unfollowTree(issueId: ID!): Boolean!
unlinkIssues(input: LinkIssuesInput!): CommandResult! unlinkIssues(input: LinkIssuesInput!): CommandResult!
"""Unpin a ticket"""
unpinIssue(issueId: ID!): Boolean!
"""The link stops working""" """The link stops working"""
unshareDashboard(projectId: ID!): Boolean! unshareDashboard(projectId: ID!): Boolean!
"""A release's public notes link stops working"""
unshareReleaseNotes(releaseId: ID!): Boolean!
"""Push off on this device""" """Push off on this device"""
unsubscribePush(endpoint: String!): Boolean! unsubscribePush(endpoint: String!): Boolean!
@@ -1072,11 +1279,21 @@ type Mutation {
updateSprint(input: UpdateSprintInput!): CommandResult! updateSprint(input: UpdateSprintInput!): CommandResult!
updateWebhook(input: UpdateWebhookInput!): Webhook! updateWebhook(input: UpdateWebhookInput!): Webhook!
"""
I opened this ticket now: answers when I had opened it before (null: never), to show what is new since
"""
visitIssue(issueId: ID!): String
""" """
Vote for a ticket (on) or take the vote back: anyone signed in on a public project, members on a private one Vote for a ticket (on) or take the vote back: anyone signed in on a public project, members on a private one
""" """
voteIssue(issueId: ID!, on: Boolean!): CommandResult! voteIssue(issueId: ID!, on: Boolean!): CommandResult!
"""
Vote in a comment's poll (option index), or take the vote back (null). Members, viewers too
"""
votePoll(commentId: ID!, option: Int): CommandResult!
""" """
Follow a ticket: be told when it moves, is reassigned or gets a comment Follow a ticket: be told when it moves, is reassigned or gets a comment
""" """
@@ -1088,6 +1305,22 @@ type Mutation {
writeReleaseNotes(notes: String, releaseId: ID!): CommandResult! writeReleaseNotes(notes: String, releaseId: ID!): CommandResult!
} }
"""«Mi día»: the tickets I picked for today"""
type MyDay {
"""YYYY-MM-DD, in my time zone"""
day: String!
"""In order, done ones included"""
issues: [Issue!]!
leftover: MyDayLeftover
}
"""What was left unfinished on the latest earlier day"""
type MyDayLeftover {
day: String!
issues: [Issue!]!
}
type MyNotifications { type MyNotifications {
items: [Notification!]! items: [Notification!]!
@@ -1167,6 +1400,8 @@ enum NotificationKind {
QA_FAILED QA_FAILED
REMINDER REMINDER
REPLIED REPLIED
REVIEW_ANSWERED
REVIEW_REQUESTED
STATUS_CHANGED STATUS_CHANGED
WATCHED WATCHED
} }
@@ -1199,6 +1434,11 @@ type OptionCount {
value: String! value: String!
} }
type PollOption {
text: String!
voters: [UserRef!]!
}
""" """
One of my active projects at a glance: open work, risks, sprint, releases and epics One of my active projects at a glance: open work, risks, sprint, releases and epics
""" """
@@ -1431,6 +1671,23 @@ type ProposalsFunnel {
waiting: Int! waiting: Int!
} }
"""A release's notes, for anyone with its link"""
type PublicReleaseNotes {
description: String
"""Markdown"""
notes: String!
projectKey: String!
projectName: String!
releaseName: String!
releasedAt: String
status: ReleaseStatus!
targetDate: String
"""False: drawn from its finished tickets (none written yet)"""
written: Boolean!
}
"""A browser's Web Push subscription (PushSubscription.toJSON())""" """A browser's Web Push subscription (PushSubscription.toJSON())"""
input PushSubscriptionInput { input PushSubscriptionInput {
auth: String! auth: String!
@@ -1464,17 +1721,28 @@ type Quality {
type Query { type Query {
"""Project activity feed (newest first)""" """Project activity feed (newest first)"""
activity( activity(
"""
ISO date: only activity at or after it (with before, a window such as a day)
"""
after: String
"""ISO date cursor""" """ISO date cursor"""
before: String before: String
issueId: ID issueId: ID
limit: Int! = 50 limit: Int! = 50
projectId: ID! projectId: ID!
): [Activity!]! ): [Activity!]!
alertIntegration(projectId: ID!): AlertIntegration!
automations(projectId: ID!): [Automation!]! automations(projectId: ID!): [Automation!]!
"""The project's link for clients, if any (owners and admins)""" """The project's link for clients, if any (owners and admins)"""
dashboardShare(projectId: ID!): DashboardShare dashboardShare(projectId: ID!): DashboardShare
"""
Decisions by their text, most recent first: of a project, or of all my projects without one
"""
decisions(limit: Int! = 20, projectId: ID, search: String): [Decision!]!
""" """
A project's epics: top-level tickets that group others, with the progress of those A project's epics: top-level tickets that group others, with the progress of those
""" """
@@ -1492,6 +1760,14 @@ type Query {
"""My calendar URL, if I made one""" """My calendar URL, if I made one"""
myCalendarFeed: CalendarFeed myCalendarFeed: CalendarFeed
"""
«Mi día»: the tickets I picked for today, and what was left on my last day
"""
myDay(
"""Today, YYYY-MM-DD in my time zone"""
day: String!
): MyDay!
""" """
The home page beyond my work: agenda of the week, activity of my projects, the week in numbers, sprints, project cards, suggestions, first steps and who is on what now The home page beyond my work: agenda of the week, activity of my projects, the week in numbers, sprints, project cards, suggestions, first steps and who is on what now
""" """
@@ -1516,6 +1792,9 @@ type Query {
"""Only these of my projects""" """Only these of my projects"""
projectIds: [ID!] projectIds: [ID!]
"""Only the tickets I was asked to review (unanswered)"""
reviewing: Boolean! = false
"""Matches key, title or description (global search)""" """Matches key, title or description (global search)"""
search: String search: String
statuses: [String!] statuses: [String!]
@@ -1527,9 +1806,17 @@ type Query {
"""My notifications, newest first, and how many are unread""" """My notifications, newest first, and how many are unread"""
myNotifications(limit: Int! = 30, unreadOnly: Boolean! = false): MyNotifications! myNotifications(limit: Int! = 30, unreadOnly: Boolean! = false): MyNotifications!
"""
My pinned tickets, most recently pinned first (trashed or out of reach left out)
"""
myPins: [Issue!]!
"""Projects where I am a member""" """Projects where I am a member"""
myProjects: [Project!]! myProjects: [Project!]!
"""My waiting reminders on tickets, soonest first"""
myReminders: [ReminderOnIssue!]!
"""My saved views of my work, across my projects""" """My saved views of my work, across my projects"""
myViews: [MyView!]! myViews: [MyView!]!
notificationSettings: NotificationSettings! notificationSettings: NotificationSettings!
@@ -1547,8 +1834,14 @@ type Query {
"""Projects anyone can read, also without signing in""" """Projects anyone can read, also without signing in"""
publicProjects: [Project!]! publicProjects: [Project!]!
"""A release's notes, for anyone with its link"""
publicReleaseNotes(token: String!): PublicReleaseNotes
release(id: ID!): Release! release(id: ID!): Release!
"""A release's public notes link, if any (owners and admins)"""
releaseNotesShare(releaseId: ID!): ReleaseNotesShare
"""My views of the project's board, then the shared ones""" """My views of the project's board, then the shared ones"""
savedFilters(projectId: ID!): [SavedFilter!]! savedFilters(projectId: ID!): [SavedFilter!]!
@@ -1646,6 +1939,15 @@ type ReleaseForecast {
verdict: String! verdict: String!
} }
"""A release's public notes link (owners and admins)"""
type ReleaseNotesShare {
createdAt: String!
releaseId: ID!
"""The secret of the link: /notes/{token}"""
token: String!
}
type ReleaseProgress { type ReleaseProgress {
byStatus: [CountByStatus!]! byStatus: [CountByStatus!]!
finished: Int! finished: Int!
@@ -1664,6 +1966,18 @@ enum ReleaseStatus {
RELEASED RELEASED
} }
"""One of my waiting reminders, with its ticket"""
type ReminderOnIssue {
issue: Issue!
reminder: IssueReminder!
}
"""APPROVED: all good. CHANGES: something to change"""
enum ReviewVerdict {
APPROVED
CHANGES
}
"""Tickets to look at now (worst first)""" """Tickets to look at now (worst first)"""
type Risks { type Risks {
blocked: [InsightIssue!]! blocked: [InsightIssue!]!
@@ -1906,6 +2220,11 @@ type Subscription {
projectChanged(projectId: ID!): ProjectChange! projectChanged(projectId: ID!): ProjectChange!
releaseChanged(projectId: ID!): ReleaseChange! releaseChanged(projectId: ID!): ReleaseChange!
sprintChanged(projectId: ID!): SprintChange! sprintChanged(projectId: ID!): SprintChange!
"""
Who is writing on a ticket, as they type (one's own come too: leave them out)
"""
typing(issueId: ID!): Typing!
} }
type Suggestion { type Suggestion {
@@ -1956,6 +2275,16 @@ type Throughput {
week: String! week: String!
} }
"""Someone writing on a ticket right now (not stored)"""
type Typing {
at: String!
issueId: ID!
"""The conversation being answered; null: a new comment"""
threadId: ID
user: UserRef!
}
input UpdateChecklistItemInput { input UpdateChecklistItemInput {
done: Boolean done: Boolean
issueId: ID! issueId: ID!
@@ -2081,7 +2410,7 @@ type WorkflowStatus {
archived: Boolean! archived: Boolean!
category: StatusCategory! category: StatusCategory!
"""Colour token: slate, violet, green…""" """A palette colour (slate, violet, green…, follows the theme) or #rrggbb"""
color: String! color: String!
"""Stable id stored on tickets, e.g. IN_REVIEW""" """Stable id stored on tickets, e.g. IN_REVIEW"""
@@ -2100,6 +2429,8 @@ type WorkflowStatus {
input WorkflowStatusInput { input WorkflowStatusInput {
archived: Boolean! = false archived: Boolean! = false
category: StatusCategory! category: StatusCategory!
"""A palette colour (follows the theme) or #rrggbb"""
color: String! color: String!
id: String! id: String!
name: String! name: String!

View File

@@ -12,7 +12,11 @@ import {
ApiTags, ApiTags,
} from '@nestjs/swagger'; } from '@nestjs/swagger';
import { Public } from '@task-stream/api/identity/presenters'; import { Public } from '@task-stream/api/identity/presenters';
import { REDIS_CLIENT } from '@task-stream/api/shared/infrastructure'; import {
EventPipelineReading,
EventPipelineStatus,
REDIS_CLIENT,
} from '@task-stream/api/shared/infrastructure';
import Redis from 'ioredis'; import Redis from 'ioredis';
import { Connection } from 'mongoose'; import { Connection } from 'mongoose';
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
@@ -24,14 +28,31 @@ export class HealthController {
private readonly postgres: DataSource, private readonly postgres: DataSource,
@InjectConnection() private readonly mongo: Connection, @InjectConnection() private readonly mongo: Connection,
@Inject(REDIS_CLIENT) private readonly redis: Redis, @Inject(REDIS_CLIENT) private readonly redis: Redis,
private readonly events: EventPipelineStatus,
) {} ) {}
@Public() @Public()
@Get() @Get()
@ApiOperation({ summary: 'API and databases status' }) @ApiOperation({
summary: 'API, databases and the way from write to read',
description:
'503 when a database is down. With the databases up, `status` is `degraded` (still 200, so a lagging read side does not get the container restarted) when events wait in the outbox over a minute, 500 or more wait to be projected, or some were set aside after failing again and again (`task-stream:events:dead`); `events.problems` says which.',
})
@ApiOkResponse({ @ApiOkResponse({
schema: { schema: {
example: { status: 'ok', postgres: 'up', mongo: 'up', redis: 'up' }, example: {
status: 'ok',
postgres: 'up',
mongo: 'up',
redis: 'up',
events: {
unpublished: 0,
oldestUnpublishedSeconds: null,
pending: 0,
dead: 0,
problems: [],
},
},
}, },
}) })
@ApiServiceUnavailableResponse({ description: 'A database is down' }) @ApiServiceUnavailableResponse({ description: 'A database is down' })
@@ -44,10 +65,38 @@ export class HealthController {
const [postgres, mongo, redis] = checks.map((c) => const [postgres, mongo, redis] = checks.map((c) =>
c.status === 'fulfilled' ? 'up' : 'down', c.status === 'fulfilled' ? 'up' : 'down',
); );
const result = { status: 'ok', postgres, mongo, redis }; const events = await this.events.read().then(
(reading) => ({ ...reading, problems: problemsOf(reading) }),
() => null,
);
const result = {
status: events?.problems.length ? 'degraded' : 'ok',
postgres,
mongo,
redis,
events,
};
if (checks.some((c) => c.status === 'rejected')) { if (checks.some((c) => c.status === 'rejected')) {
throw new ServiceUnavailableException({ ...result, status: 'degraded' }); throw new ServiceUnavailableException({ ...result, status: 'degraded' });
} }
return result; return result;
} }
} }
/** What is wrong on the way from write to read, if anything. */
function problemsOf(reading: EventPipelineReading): string[] {
const problems: string[] = [];
if ((reading.oldestUnpublishedSeconds ?? 0) > 60)
problems.push(
`${reading.unpublished} events wait in the outbox (the oldest, ${reading.oldestUnpublishedSeconds} s): is Redis reachable?`,
);
if (reading.pending >= 500)
problems.push(
`${reading.pending} events wait to be projected: is Mongo reachable?`,
);
if (reading.dead > 0)
problems.push(
`${reading.dead} events were set aside after failing again and again (task-stream:events:dead)`,
);
return problems;
}

File diff suppressed because it is too large Load Diff

View File

@@ -89,6 +89,12 @@ export class IssuesResolver {
.describe( .describe(
'Only the tickets the user follows (use with assignedToMe false)', 'Only the tickets the user follows (use with assignedToMe false)',
), ),
reviewing: z
.boolean()
.default(false)
.describe(
'Only the tickets the user was asked to review and has not answered (use with assignedToMe false)',
),
categories: z categories: z
.array(CATEGORY) .array(CATEGORY)
.optional() .optional()
@@ -110,6 +116,7 @@ export class IssuesResolver {
params: { params: {
assignedToMe: boolean; assignedToMe: boolean;
watching: boolean; watching: boolean;
reviewing: boolean;
categories?: z.infer<typeof CATEGORY>[]; categories?: z.infer<typeof CATEGORY>[];
priorities?: z.infer<typeof PRIORITY>[]; priorities?: z.infer<typeof PRIORITY>[];
bugsOnly?: boolean; bugsOnly?: boolean;
@@ -125,6 +132,7 @@ export class IssuesResolver {
query: { query: {
assignedToMe: params.assignedToMe, assignedToMe: params.assignedToMe,
watching: params.watching, watching: params.watching,
reviewing: params.reviewing,
category: params.categories ?? ['TODO', 'IN_PROGRESS', 'QA'], category: params.categories ?? ['TODO', 'IN_PROGRESS', 'QA'],
priority: params.priorities, priority: params.priorities,
bugsOnly: params.bugsOnly, bugsOnly: params.bugsOnly,
@@ -254,7 +262,7 @@ export class IssuesResolver {
@Tool({ @Tool({
name: 'get_issue', name: 'get_issue',
description: description:
'A ticket in full: description, parent, checklist (with item ids), links, commits and pull requests, followers, allowed next statuses, and optionally its comments and history.', 'A ticket in full: description, parent, checklist (with item ids), links, commits and pull requests, followers, allowed next statuses, the comments marked as decisions, and optionally its comments and history.',
paramsSchema: z.object({ paramsSchema: z.object({
issue: issueRef, issue: issueRef,
withComments: z.boolean().default(true), withComments: z.boolean().default(true),
@@ -289,8 +297,32 @@ export class IssuesResolver {
emoji: r.emoji, emoji: r.emoji,
by: r.users.map((u) => u.name), by: r.users.map((u) => u.name),
})), })),
decision: c.decision || undefined,
resolved: c.resolved || undefined,
poll: c.poll
? {
options: c.poll.options.map((o, index) => ({
index,
text: o.text,
votes: o.voters.length,
})),
closed: c.poll.closed,
winner: c.poll.winner,
}
: undefined,
})) }))
: undefined; : undefined;
const decisions = (
await this.api.data(
client.GET('/api/issues/{issue}/decisions', { params: { path } }),
)
).map((c) => ({
commentId: c.id,
by: c.author.name,
at: c.createdAt,
markedBy: c.decidedBy?.name ?? null,
body: c.body,
}));
const history = params.withHistory const history = params.withHistory
? ( ? (
await this.api.data( await this.api.data(
@@ -319,9 +351,18 @@ export class IssuesResolver {
url: d.url, url: d.url,
})), })),
watchers: issue.watchers.map((w) => w.name), watchers: issue.watchers.map((w) => w.name),
reviews: issue.reviews.map((r) => ({
id: r.id,
requester: r.requester.name,
reviewer: r.reviewer.name,
note: r.note,
verdict: r.verdict,
answer: r.answer,
})),
attachments: issue.attachments.length, attachments: issue.attachments.length,
trashedAt: issue.trashedAt, trashedAt: issue.trashedAt,
createdAt: issue.createdAt, createdAt: issue.createdAt,
decisions,
comments, comments,
history, history,
}; };
@@ -482,18 +523,108 @@ export class IssuesResolver {
.string() .string()
.optional() .optional()
.describe('Id of the comment it answers (see get_issue)'), .describe('Id of the comment it answers (see get_issue)'),
poll: z
.array(z.string().min(1).max(80))
.min(2)
.max(6)
.optional()
.describe('A quick poll in the comment: 2 to 6 options'),
}), }),
annotations: WRITE, annotations: WRITE,
}) })
comment( comment(
{ issue, body, replyTo }: { issue: string; body: string; replyTo?: string }, {
issue,
body,
replyTo,
poll,
}: { issue: string; body: string; replyTo?: string; poll?: string[] },
ctx: McpContext, ctx: McpContext,
) { ) {
return toolResult(() => return toolResult(() =>
this.api.data( this.api.data(
this.api.as(ctx).POST('/api/issues/{issue}/comments', { this.api.as(ctx).POST('/api/issues/{issue}/comments', {
params: { path: { issue } }, params: { path: { issue } },
body: { body, replyTo }, body: { body, replyTo, poll },
}),
),
);
}
@Tool({
name: 'vote_poll',
description:
"Vote in a comment's poll (option index from get_issue), or take the vote back (option null).",
paramsSchema: z.object({
commentId: z.string().min(1),
option: z.number().int().min(0).nullable(),
}),
annotations: { ...WRITE, idempotentHint: true },
})
votePoll(
{ commentId, option }: { commentId: string; option: number | null },
ctx: McpContext,
) {
return toolResult(() =>
this.api.data(
this.api.as(ctx).POST('/api/comments/{commentId}/poll/vote', {
params: { path: { commentId } },
body: { option },
}),
),
);
}
@Tool({
name: 'close_poll',
description:
'Close a poll the user started (or as admin); with decide (default), the winner stays as a decision of the ticket.',
paramsSchema: z.object({
commentId: z.string().min(1),
decide: z.boolean().default(true),
}),
annotations: WRITE,
})
closePoll(
{ commentId, decide }: { commentId: string; decide: boolean },
ctx: McpContext,
) {
return toolResult(() =>
this.api.data(
this.api.as(ctx).POST('/api/comments/{commentId}/poll/close', {
params: { path: { commentId } },
body: { decide },
}),
),
);
}
@Tool({
name: 'turn_comment_into_issue',
description:
"Make a ticket of a comment that turned out to be work of its own: its text becomes the description, as a subtask of the comment's ticket (asSubtask) or linked to it. Read type ids with get_project. Answers the new ticket's key.",
paramsSchema: z.object({
commentId: z.string().min(1),
title: z.string().min(1).max(200),
type: z.string().min(1).describe("One of the project's ticket type ids"),
asSubtask: z.boolean().default(false),
}),
annotations: WRITE,
})
turnCommentIntoIssue(
{
commentId,
title,
type,
asSubtask,
}: { commentId: string; title: string; type: string; asSubtask: boolean },
ctx: McpContext,
) {
return toolResult(() =>
this.api.data(
this.api.as(ctx).POST('/api/comments/{commentId}/issue', {
params: { path: { commentId } },
body: { title, type, asSubtask },
}), }),
), ),
); );
@@ -551,19 +682,29 @@ export class IssuesResolver {
@Tool({ @Tool({
name: 'watch_issue', name: 'watch_issue',
description: description:
'Follow a ticket (notifications of its changes and comments) or stop following it.', 'Follow a ticket (notifications of its changes and comments) or stop following it. With tree: true, an epic (or any ticket with subtasks) with everything under it, also tickets added later.',
paramsSchema: z.object({ paramsSchema: z.object({
issue: issueRef, issue: issueRef,
follow: z.boolean().default(true), follow: z.boolean().default(true),
tree: z.boolean().default(false),
}), }),
annotations: { ...WRITE, idempotentHint: true }, annotations: { ...WRITE, idempotentHint: true },
}) })
watch( watch(
{ issue, follow }: { issue: string; follow: boolean }, { issue, follow, tree }: { issue: string; follow: boolean; tree: boolean },
ctx: McpContext, ctx: McpContext,
) { ) {
const client = this.api.as(ctx); const client = this.api.as(ctx);
const options = { params: { path: { issue } } }; const options = { params: { path: { issue } } };
if (tree)
return toolResult(async () => {
await this.api.data(
follow
? client.PUT('/api/issues/{issue}/follow-tree', options)
: client.DELETE('/api/issues/{issue}/follow-tree', options),
);
return { issue, followingTree: follow };
});
return toolResult(() => return toolResult(() =>
this.api.data( this.api.data(
follow follow
@@ -734,6 +875,233 @@ export class IssuesResolver {
); );
} }
@Tool({
name: 'mark_decision',
description:
'Mark a comment as a decision of its ticket (what was agreed), or unmark it (on: false). Whoever can change the ticket. Comment ids come with get_issue.',
paramsSchema: z.object({
commentId: z.string().min(1),
on: z.boolean().default(true),
}),
annotations: { ...WRITE, idempotentHint: true },
})
markDecision(
{ commentId, on }: { commentId: string; on: boolean },
ctx: McpContext,
) {
const client = this.api.as(ctx);
const options = { params: { path: { commentId } } };
return toolResult(() =>
this.api.data(
on
? client.PUT('/api/comments/{commentId}/decision', options)
: client.DELETE('/api/comments/{commentId}/decision', options),
),
);
}
@Tool({
name: 'request_review',
description:
'Ask a member of the project to review a ticket (with an optional note): they are told and see it in my_issues with reviewing. reviewer is a user id (get_project lists members).',
paramsSchema: z.object({
issue: issueRef,
reviewer: z.string().min(1),
note: z.string().max(1000).optional(),
}),
annotations: WRITE,
})
requestReview(
params: { issue: string; reviewer: string; note?: string },
ctx: McpContext,
) {
return toolResult(() =>
this.api.data(
this.api.as(ctx).POST('/api/issues/{issue}/reviews', {
params: { path: { issue: params.issue } },
body: { reviewer: params.reviewer, note: params.note },
}),
),
);
}
@Tool({
name: 'answer_review',
description:
'Answer a review the user was asked for: APPROVED (all good) or CHANGES, with an optional answer. Review ids come with get_issue.',
paramsSchema: z.object({
issue: issueRef,
reviewId: z.string().min(1),
verdict: z.enum(['APPROVED', 'CHANGES']),
answer: z.string().max(1000).optional(),
}),
annotations: WRITE,
})
answerReview(
params: {
issue: string;
reviewId: string;
verdict: 'APPROVED' | 'CHANGES';
answer?: string;
},
ctx: McpContext,
) {
return toolResult(() =>
this.api.data(
this.api.as(ctx).POST('/api/issues/{issue}/reviews/{review}/answer', {
params: { path: { issue: params.issue, review: params.reviewId } },
body: { verdict: params.verdict, answer: params.answer },
}),
),
);
}
@Tool({
name: 'my_day',
description:
'«Mi día»: the tickets I picked for today (done ones marked), and what was left unfinished on my last day. Optionally add or remove one first. day is today in my time zone, YYYY-MM-DD.',
paramsSchema: z.object({
day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
add: issueRef.optional(),
remove: issueRef.optional(),
}),
annotations: WRITE,
})
myDay(
params: { day: string; add?: string; remove?: string },
ctx: McpContext,
) {
const client = this.api.as(ctx);
const query = { day: params.day };
return toolResult(async () => {
if (params.add)
await this.api.data(
client.PUT('/api/me/day/{issue}', {
params: { path: { issue: params.add }, query },
}),
);
if (params.remove)
await this.api.data(
client.DELETE('/api/me/day/{issue}', {
params: { path: { issue: params.remove }, query },
}),
);
const myDay = await this.api.data(
client.GET('/api/me/day', { params: { query } }),
);
return {
day: myDay.day,
issues: myDay.issues.map(issueLine),
leftover: myDay.leftover && {
day: myDay.leftover.day,
issues: myDay.leftover.issues.map(issueLine),
},
};
});
}
@Tool({
name: 'remind_me',
description:
'Remind me of a ticket at a date and time (a notification), with an optional note; one per ticket, it replaces the waiting one. clear: true drops it. Times are ISO with offset, e.g. 2026-10-23T09:00:00+02:00.',
paramsSchema: z.object({
issue: issueRef,
at: z.string().optional(),
note: z.string().max(280).optional(),
clear: z.boolean().default(false),
}),
annotations: { ...WRITE, idempotentHint: true },
})
remindMe(
params: { issue: string; at?: string; note?: string; clear: boolean },
ctx: McpContext,
) {
const client = this.api.as(ctx);
const path = { issue: params.issue };
return toolResult(async () => {
if (params.clear) {
await this.api.data(
client.DELETE('/api/issues/{issue}/reminder', { params: { path } }),
);
return { issue: params.issue, reminder: null };
}
if (!params.at) throw new Error('at is required unless clear is true');
return this.api.data(
client.PUT('/api/issues/{issue}/reminder', {
params: { path },
body: { at: params.at, note: params.note },
}),
);
});
}
@Tool({
name: 'resolve_thread',
description:
'Settle a conversation (a top-level comment and its replies), optionally with a conclusion that is added as a reply marked as a decision; or reopen it (resolved: false). Whoever can change the ticket. Comment ids come with get_issue.',
paramsSchema: z.object({
commentId: z.string().min(1),
resolved: z.boolean().default(true),
conclusion: z.string().max(20000).optional(),
}),
annotations: { ...WRITE, idempotentHint: true },
})
resolveThread(
params: { commentId: string; resolved: boolean; conclusion?: string },
ctx: McpContext,
) {
const client = this.api.as(ctx);
const path = { commentId: params.commentId };
return toolResult(() =>
this.api.data(
params.resolved
? client.PUT('/api/comments/{commentId}/resolution', {
params: { path },
body: { conclusion: params.conclusion },
})
: client.DELETE('/api/comments/{commentId}/resolution', {
params: { path },
}),
),
);
}
@Tool({
name: 'search_decisions',
description:
'What was decided, by words in the decision: comments marked as decisions, most recent first, with their ticket. Of one project, or of all my projects without one.',
paramsSchema: z.object({
project: projectRef.optional(),
search: z.string().max(200).optional(),
limit: limit(100, 20),
}),
annotations: READ,
})
searchDecisions(
params: { project?: string; search?: string; limit: number },
ctx: McpContext,
) {
return toolResult(async () => {
const client = this.api.as(ctx);
const query = { search: params.search, limit: params.limit };
const found = await this.api.data(
params.project
? client.GET('/api/projects/{project}/decisions', {
params: { path: { project: params.project }, query },
})
: client.GET('/api/me/decisions', { params: { query } }),
);
return found.map((d) => ({
issue: d.issue.key,
title: d.issue.title,
commentId: d.comment.id,
by: d.comment.author.name,
at: d.comment.createdAt,
body: d.comment.body,
}));
});
}
@Tool({ @Tool({
name: 'vote_issue', name: 'vote_issue',
description: description:

View File

@@ -280,19 +280,36 @@ export class ProjectsResolver {
@Tool({ @Tool({
name: 'get_project_activity', name: 'get_project_activity',
description: 'Latest activity of a project (newest first).', description:
paramsSchema: z.object({ project: projectRef, limit: limit(200, 30) }), 'Latest activity of a project (newest first), or that of one day (UTC) with day.',
paramsSchema: z.object({
project: projectRef,
limit: limit(200, 30),
day: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.optional()
.describe('YYYY-MM-DD: only what happened that day (UTC)'),
}),
annotations: READ, annotations: READ,
}) })
activity( activity(
{ project, limit }: { project: string; limit: number }, { project, limit, day }: { project: string; limit: number; day?: string },
ctx: McpContext, ctx: McpContext,
) { ) {
const window = day
? {
after: `${day}T00:00:00.000Z`,
before: new Date(
Date.parse(`${day}T00:00:00Z`) + 86_400_000,
).toISOString(),
}
: {};
return toolResult(async () => return toolResult(async () =>
( (
await this.api.data( await this.api.data(
this.api.as(ctx).GET('/api/projects/{project}/activity', { this.api.as(ctx).GET('/api/projects/{project}/activity', {
params: { path: { project }, query: { limit } }, params: { path: { project }, query: { limit, ...window } },
}), }),
) )
).map((a) => ({ ).map((a) => ({

View File

@@ -25,6 +25,7 @@ describe('appRoutes', () => {
'portfolio', 'portfolio',
'explore', 'explore',
'share/:token', 'share/:token',
'notes/:token',
'cartera', 'cartera',
'explorar', 'explorar',
'p/:key', 'p/:key',
@@ -32,12 +33,13 @@ describe('appRoutes', () => {
expect(children[0].canActivate).toContain(authGuard); expect(children[0].canActivate).toContain(authGuard);
expect(children[1].canActivate).toContain(authGuard); expect(children[1].canActivate).toContain(authGuard);
expect(children[2].canActivate).toBeUndefined(); expect(children[2].canActivate).toBeUndefined();
// The page for clients needs no session: its link is the key. // The pages for clients need no session: their link is the key.
expect(children[3].canActivate).toBeUndefined(); expect(children[3].canActivate).toBeUndefined();
expect(children[6].canActivate).toBeUndefined(); expect(children[4].canActivate).toBeUndefined();
expect(children[7].canActivate).toBeUndefined();
// The Spanish paths of shared links lead to the English ones. // The Spanish paths of shared links lead to the English ones.
expect(children[4].redirectTo).toBe('portfolio'); expect(children[5].redirectTo).toBe('portfolio');
expect(children[5].redirectTo).toBe('explore'); expect(children[6].redirectTo).toBe('explore');
}); });
it('gives each page its own state, not the root', async () => { it('gives each page its own state, not the root', async () => {

View File

@@ -409,7 +409,8 @@ h3 {
// A field's label floats above its box; other fields leave room for it // A field's label floats above its box; other fields leave room for it
// below them (their hint line), a segmented control does not. // below them (their hint line), a segmented control does not.
> pi-segmented-control { > pi-segmented-control,
> p:has(+ pi-text-field, + pi-textarea, + pi-select-field, + pi-date-field) {
margin-bottom: 0.75rem; margin-bottom: 0.75rem;
} }
} }

View File

@@ -3,7 +3,7 @@
## Qué resuelve ## Qué resuelve
| Necesidad | Cómo se resuelve | | Necesidad | Cómo se resuelve |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 🐛 Bugs | Tickets de tipo `BUG` con prioridad, área y etiquetas | | 🐛 Bugs | Tickets de tipo `BUG` con prioridad, área y etiquetas |
| 🌍 Públicos | Un proyecto público se puede leer sin iniciar sesión (web, GraphQL y REST): tablero, tickets, comentarios, releases, actividad y estadísticas; «Explorar» los lista | | 🌍 Públicos | Un proyecto público se puede leer sin iniciar sesión (web, GraphQL y REST): tablero, tickets, comentarios, releases, actividad y estadísticas; «Explorar» los lista |
| 🗑️ Borrar | El propietario borra un proyecto confirmando su clave; tickets, comentarios, releases y enlaces desde otros proyectos se borran en cascada (sagas) y la clave queda libre | | 🗑️ Borrar | El propietario borra un proyecto confirmando su clave; tickets, comentarios, releases y enlaces desde otros proyectos se borran en cascada (sagas) y la clave queda libre |
@@ -12,11 +12,14 @@
| ⚙️ Features | Tipo `FEATURE` siguiendo el workflow completo | | ⚙️ Features | Tipo `FEATURE` siguiendo el workflow completo |
| 🧪 QA | Por defecto, `READY_FOR_QA → IN_QA → DONE / QA_FAILED`; fallar QA exige un motivo | | 🧪 QA | Por defecto, `READY_FOR_QA → IN_QA → DONE / QA_FAILED`; fallar QA exige un motivo |
| 🚀 Releases | Versiones a las que se asignan tickets; no se publican con tickets sin terminar (salvo forzando) | | 🚀 Releases | Versiones a las que se asignan tickets; no se publican con tickets sin terminar (salvo forzando) |
| 📝 Notas de versión | Borrador en Markdown con los tickets terminados por tipo, editable y copiable, también tras publicar | | 📝 Notas de versión | Borrador en Markdown con los tickets terminados por tipo, editable y copiable, también tras publicar; y una página pública por release para los clientes, con enlace secreto |
| 👥 Asignaciones | Solo a miembros del proyecto; panel de carga por persona | | 👥 Asignaciones | Solo a miembros del proyecto; panel de carga por persona |
| 💬 Comentarios | Decisiones y explicaciones dentro del ticket, con formato (editor visual, guardado en Markdown), capturas pegadas, respuestas, reacciones (👍 🎉…) y `@menciones`; el autor edita, el admin modera | | 💬 Comentarios | Decisiones y explicaciones dentro del ticket, con formato (editor visual, guardado en Markdown), capturas pegadas, respuestas, reacciones (👍 🎉…), decisiones (un comentario marcado sale encima del ticket y se encuentra al buscar), conversaciones que se resuelven con su conclusión, convertir un comentario en ticket, lo nuevo desde tu última visita marcado, encuestas rápidas que acaban en decisión, «está escribiendo…» en vivo y `@menciones`; el autor edita, el admin modera |
| 🔎 Vistas | El tablero se filtra por texto, persona (o sin asignar), tipo, prioridad, área y release; los filtros se guardan como vistas propias o compartidas con el proyecto | | 🔎 Vistas | El tablero se filtra por texto, persona (o sin asignar), tipo, prioridad, área y release; los filtros se guardan como vistas propias o compartidas con el proyecto |
| 📋 Lista | Todos los tickets en filas: ordenar por cualquier columna, filtrar, cambiar estado, prioridad o persona sin abrirlos, editar en bloque y duplicar | | 📋 Lista | Todos los tickets en filas: ordenar por cualquier columna, filtrar, cambiar estado, prioridad o persona sin abrirlos, editar en bloque y duplicar |
| ↩️ Deshacer | Mover, reasignar o mandar a la papelera ofrece «Deshacer» unos segundos (también Ctrl/⌘ Z), con la orden contraria |
| ☀ Mi día | Cada mañana eliges los tickets de hoy; se tachan al terminar y lo que quede se pasa al día siguiente; y «Recordármelo» en cualquier ticket |
| 🚦 Salud | Un semáforo por proyecto (en su panel y en la cartera) que dice qué va mal y por qué: atascados, vencidos, bugs urgentes, QA, releases tarde |
| 🚦 WIP y carriles | Límite de trabajo en curso por estado (la columna se marca al pasarse) y tablero agrupable por persona, épica, prioridad o tipo | | 🚦 WIP y carriles | Límite de trabajo en curso por estado (la columna se marca al pasarse) y tablero agrupable por persona, épica, prioridad o tipo |
| 🎲 Estimación | Puntos por ticket (escala 0-1-2-3-5-8-13-21) en la ficha, las tarjetas, las columnas y el backlog; velocidad por sprint y aviso si un sprint planificado supera la media | | 🎲 Estimación | Puntos por ticket (escala 0-1-2-3-5-8-13-21) en la ficha, las tarjetas, las columnas y el backlog; velocidad por sprint y aviso si un sprint planificado supera la media |
| 🏃 Sprints | Iteraciones con fechas y objetivo, una en curso por proyecto, con burndown (tickets o puntos) y traspaso de lo pendiente al cerrar | | 🏃 Sprints | Iteraciones con fechas y objetivo, una en curso por proyecto, con burndown (tickets o puntos) y traspaso de lo pendiente al cerrar |
@@ -24,7 +27,7 @@
| 📋 Backlog | Lo pendiente de empezar, en el orden en que se va a coger; se reordena arrastrando y el tablero sigue ese orden | | 📋 Backlog | Lo pendiente de empezar, en el orden en que se va a coger; se reordena arrastrando y el tablero sigue ese orden |
| 🗑️ Papelera | Borrar un ticket lo manda a la papelera (quien lo abrió o un admin); se recupera durante 30 días y luego se borra del todo | | 🗑️ Papelera | Borrar un ticket lo manda a la papelera (quien lo abrió o un admin); se recupera durante 30 días y luego se borra del todo |
| ☑️ En bloque | Selecciona varios tickets del backlog y cámbiales a la vez estado, persona, sprint, prioridad o etiqueta | | ☑️ En bloque | Selecciona varios tickets del backlog y cámbiales a la vez estado, persona, sprint, prioridad o etiqueta |
| ⌨️ Atajos y búsqueda | Ctrl/⌘ K o / busca tickets y proyectos de todos tus proyectos; `g b`, `g k`, `g s`, `g r` navegan, `c` crea, `e` edita, `?` los lista | | ⌨️ Atajos y búsqueda | Ctrl/⌘ K o / busca tickets, decisiones y proyectos de todos tus proyectos (antes de escribir, tus tickets fijados); `g b`, `g k`, `g s`, `g r` navegan, `c` crea, en el tablero las flechas recorren las tarjetas y Shift+←/→ las cambia de columna, `e` edita, `?` los lista |
| 🗺️ Hoja de ruta | Las épicas en el tiempo (fecha de inicio y límite), con los sprints y las releases como referencias y flechas entre las que dependen unas de otras | | 🗺️ Hoja de ruta | Las épicas en el tiempo (fecha de inicio y límite), con los sprints y las releases como referencias y flechas entre las que dependen unas de otras |
| 🗳️ Propuestas y votos | Un proyecto público puede abrir un formulario para que cualquiera, sin cuenta, reporte un error o proponga una idea; quien tenga sesión vota lo que quiere | | 🗳️ Propuestas y votos | Un proyecto público puede abrir un formulario para que cualquiera, sin cuenta, reporte un error o proponga una idea; quien tenga sesión vota lo que quiere |
| 🌐 Web del colectivo | La página de cada proyecto en pireon.dev enseña su hoja de ruta, versiones, sprint y tickets para recién llegados (`good-first-issue`) | | 🌐 Web del colectivo | La página de cada proyecto en pireon.dev enseña su hoja de ruta, versiones, sprint y tickets para recién llegados (`good-first-issue`) |
@@ -32,9 +35,10 @@
| 👀 Seguir | Cualquier miembro sigue los tickets que le interesan y los ve juntos en «Que sigo»; quien lo abre, lo tiene asignado o comenta, lo sigue solo | | 👀 Seguir | Cualquier miembro sigue los tickets que le interesan y los ve juntos en «Que sigo»; quien lo abre, lo tiene asignado o comenta, lo sigue solo |
| 🔔 Avisos | Campana con lo que te concierne (asignaciones, cambios de estado, QA fallido, comentarios, respuestas), en vivo y opcionalmente por correo | | 🔔 Avisos | Campana con lo que te concierne (asignaciones, cambios de estado, QA fallido, comentarios, respuestas), en vivo y opcionalmente por correo |
| ⏰ Recordatorios | Aviso (y correo, si se quiere) el día antes, el mismo día y al vencer la fecha límite, a quien lo tiene y a quien lo sigue; las tarjetas marcan lo que vence | | ⏰ Recordatorios | Aviso (y correo, si se quiere) el día antes, el mismo día y al vencer la fecha límite, a quien lo tiene y a quien lo sigue; las tarjetas marcan lo que vence |
| 📎 Adjuntos | Capturas, logs y vídeos en el ticket o bajo un comentario; arrastrar, elegir o pegar con Ctrl+V; miniaturas de las imágenes | | 📎 Adjuntos | Capturas, logs y vídeos en el ticket o bajo un comentario; arrastrar, elegir o pegar con Ctrl+V; miniaturas de las imágenes; grabar la pantalla o la voz desde el comentario y verlo ahí mismo |
| 🔗 Relaciones | `BLOCKS`, `DEPENDS_ON`, `TESTS`, `DUPLICATES`, `RELATES_TO`, también entre proyectos (FE ↔ BE ↔ QA); lo que espera a otro ticket abierto sale marcado como «Bloqueado» | | 🔗 Relaciones | `BLOCKS`, `DEPENDS_ON`, `TESTS`, `DUPLICATES`, `RELATES_TO`, también entre proyectos (FE ↔ BE ↔ QA); lo que espera a otro ticket abierto sale marcado como «Bloqueado» |
| 🌿 Git | Webhook para GitHub, Gitea o GitLab: commits, ramas y pull requests que nombran un ticket (WEB-12) aparecen en su ficha | | 🌿 Git | Webhook para GitHub, Gitea o GitLab: commits, ramas y pull requests que nombran un ticket (WEB-12) aparecen en su ficha |
| 🚨 Alertas → bugs | Sentry, Uptime Kuma, Grafana o cualquier herramienta abren bugs por una URL secreta; el mismo problema repetido va al bug abierto, y «resuelta» se dice en él |
| 🧾 Plantillas | Cada tipo de ticket puede traer una descripción inicial y una checklist que se aplican al crearlo | | 🧾 Plantillas | Cada tipo de ticket puede traer una descripción inicial y una checklist que se aplican al crearlo |
| 🤖 Automatizaciones | Reglas «cuando… si… entonces…»: al crear, mover, asignar, comentar o fusionar una PR, mover, asignar, etiquetar, priorizar, comentar o meter en el sprint | | 🤖 Automatizaciones | Reglas «cuando… si… entonces…»: al crear, mover, asignar, comentar o fusionar una PR, mover, asignar, etiquetar, priorizar, comentar o meter en el sprint |
| 📡 Webhooks | Un POST firmado (HMAC-SHA256) a otro sistema cuando pasa algo: tickets, comentarios, releases, sprints; con prueba y último envío | | 📡 Webhooks | Un POST firmado (HMAC-SHA256) a otro sistema cuando pasa algo: tickets, comentarios, releases, sprints; con prueba y último envío |

View File

@@ -125,12 +125,26 @@ sequenceDiagram
### De escritura a lectura: Redis ### De escritura a lectura: Redis
- La tabla `events` es la **bandeja de salida (outbox)**: cada evento entra en la misma transacción que la escritura,
con `published_at` vacío. Si Postgres falla, la escritura falla entera y no queda nada a medias.
- El **`EventStoreRelay`** copia los eventos nuevos (`published_at IS NULL`) al Redis Stream `task-stream:events`, - El **`EventStoreRelay`** copia los eventos nuevos (`published_at IS NULL`) al Redis Stream `task-stream:events`,
en orden y con `FOR UPDATE SKIP LOCKED` (varias instancias no duplican). La entrega es _at-least-once_. en orden y con `FOR UPDATE SKIP LOCKED` (varias instancias no duplican). La entrega es _at-least-once_. Si Redis
falla, los eventos esperan en la tabla y salen al volver.
- El **`EventsBridge`** consume el stream con un _consumer group_, deserializa cada evento (`EventClsRegistry` + - El **`EventsBridge`** consume el stream con un _consumer group_, deserializa cada evento (`EventClsRegistry` +
`@AutowiredEvent`) y lo entrega a los `@EventsHandler` registrados para su clase. A diferencia de `@AutowiredEvent`) y lo entrega a los `@EventsHandler` registrados para su clase. A diferencia de
`eventBus.subject$.next()`, **espera** a cada handler y procesa los eventos en orden; solo hace `XACK` cuando todos `eventBus.subject$.next()`, **espera** a cada handler y procesa los eventos en orden; solo hace `XACK` cuando todos
terminan. Si uno falla, el evento queda pendiente y se reintenta (y `XAUTOCLAIM` recupera los de instancias caídas). terminan. El grupo de consumidores hace de **bandeja de entrada (inbox)**, y la idempotencia la ponen las
proyecciones (versión, abajo).
- **Si un evento falla, se reintenta en su sitio** (`EventStreamConsumer`), esperando cada vez más (hasta 30 s), y el
siguiente espera: saltárselo aplicaría antes un cambio posterior y la comprobación de versión descartaría después el
anterior para siempre. Si el fallo es de la infraestructura (Mongo, Redis o la red caídos, ver `isTransientError`),
espera lo que haga falta y se pone al día solo al volver, sin reiniciar. Si es del propio evento (un fallo del
código), tras 5 intentos va al stream `task-stream:events:dead` con el error, para no bloquear el resto. Lo que
queda pendiente al parar se reintenta al arrancar (y `XAUTOCLAIM` recupera lo de instancias caídas).
- `GET /api/health` dice en `events` cuántos eventos esperan en la bandeja de salida, cuántos están pendientes de
proyectar y cuántos se apartaron; con alguno de más, `status: degraded` (pero 200: un retraso de la lectura no
reinicia el contenedor). El stream se recorta a `EVENT_STREAM_MAX_LENGTH` (un millón): solo un corte larguísimo
podría recortar algo pendiente, y Postgres siempre permite reconstruir la lectura.
- Después de los handlers, el bridge ejecuta también las **sagas** (ver abajo). - Después de los handlers, el bridge ejecuta también las **sagas** (ver abajo).
### Lectura: MongoDB ### Lectura: MongoDB

View File

@@ -124,7 +124,8 @@ Reglas:
- Hace falta al menos un estado activo de categoría `TODO` (los tickets nuevos entran en el primero), uno `DONE` y un - Hace falta al menos un estado activo de categoría `TODO` (los tickets nuevos entran en el primero), uno `DONE` y un
tipo activo. tipo activo.
- Las transiciones solo pueden apuntar a estados que existen y nunca de un estado a sí mismo. - Las transiciones solo pueden apuntar a estados que existen y nunca de un estado a sí mismo.
- Colores: `slate`, `stone`, `violet`, `blue`, `sky`, `teal`, `green`, `amber`, `orange`, `red`, `pink`. Iconos: - Colores: uno de la paleta (`slate`, `stone`, `violet`, `blue`, `sky`, `teal`, `green`, `amber`, `orange`, `red`,
`pink`), que tiene su versión para modo oscuro, o cualquier `#rrggbb`. Iconos:
`bug`, `feature`, `palette`, `task`, `qa`, `flag`, `star-fill`, `rocket`, `document`, `light-bulb`, `key`, `support`. `bug`, `feature`, `palette`, `task`, `qa`, `flag`, `star-fill`, `rocket`, `document`, `light-bulb`, `key`, `support`.
Un proyecto nuevo puede **empezar con la configuración de otro** que administres: `templateProjectId` en Un proyecto nuevo puede **empezar con la configuración de otro** que administres: `templateProjectId` en
@@ -238,6 +239,30 @@ stateDiagram-v2
- **Reacciones**: 👍 👎 😄 🎉 😕 ❤️ 🚀 👀 en los comentarios (`reactToComment(commentId, emoji, on)`, - **Reacciones**: 👍 👎 😄 🎉 😕 ❤️ 🚀 👀 en los comentarios (`reactToComment(commentId, emoji, on)`,
`POST /api/comments/{id}/reactions`); los miembros, también los lectores. Cada comentario da `reactions` con quién `POST /api/comments/{id}/reactions`); los miembros, también los lectores. Cada comentario da `reactions` con quién
eligió cada una. No generan actividad ni avisos. eligió cada una. No generan actividad ni avisos.
- **Encuestas**: un comentario puede llevar una encuesta de 2 a 6 opciones (`addComment(…, poll)`, `poll` en
`POST …/comments`). Los miembros, también los lectores, votan una opción y pueden cambiarla o retirarla
(`votePoll(commentId, option)`, `POST /api/comments/{id}/poll/vote`; `CommentPollVotedEvent`). Quien la abrió, o un
admin, la cierra (`closePoll(commentId, decide)`, `POST …/poll/close`; `CommentPollClosedEvent`): gana la más votada
(con empate, ninguna) y, con `decide`, se añade una respuesta «Decidido: …» marcada como decisión. El comentario da
`poll { options { text voters } closed winner }`.
- **Convertir en ticket**: un comentario que resulta ser trabajo propio se convierte en ticket
(`turnCommentIntoIssue(commentId, title, type, asSubtask)`, `POST /api/comments/{id}/issue`), como subtarea del ticket
del comentario o enlazado a él (`RELATES_TO`), por quien puede cambiar tickets. El texto del comentario es la
descripción (sin la plantilla del tipo), con una línea de dónde sale; el comentario lo recuerda
(`CommentTurnedIntoIssueEvent`) y da `spawned { id key }`. Devuelve el ticket nuevo.
- **Conversaciones**: un comentario raíz y sus respuestas se resuelven (`resolveThread(commentId, resolved, conclusion)`,
`PUT/DELETE /api/comments/{id}/resolution`; evento `CommentThreadResolvedEvent`) por quien puede cambiar el ticket;
una respuesta no se resuelve sola. Si trae `conclusion`, antes de cerrarla se añade como respuesta marcada como
decisión. El comentario da `resolved`, `resolvedBy` y `resolvedAt`. **Escribiendo**: `typing(issueId, threadId)`
(mutation, cada pocos segundos mientras se escribe) avisa al momento por la subscription `typing(issueId)` a quien
tenga el ticket abierto; no se guarda (canal de Redis `tracker.typing.<ticket>`), y cada cliente descarta sus propios
avisos.
- **Decisiones**: quien puede cambiar el ticket marca un comentario como decisión (`markDecision(commentId, on)`,
`PUT/DELETE /api/comments/{id}/decision`; evento `CommentDecisionMarkedEvent`). El comentario da `decision`,
`decidedBy` y `decidedAt`; el ticket, `decisions` (más antiguas primero, `GET /api/issues/{issue}/decisions`), que la
web muestra encima de la descripción. Se buscan por su texto: `decisions(projectId?, search, limit)`,
`GET /api/projects/{project}/decisions` y, de todos mis proyectos, `GET /api/me/decisions` (más recientes primero; sin
las de la papelera y, para un invitado, solo las de sus tickets).
- **Bloqueos**: un ticket espera a otro si ese otro lo bloquea (`BLOCKS`) o si él depende de ese otro (`DEPENDS_ON`), - **Bloqueos**: un ticket espera a otro si ese otro lo bloquea (`BLOCKS`) o si él depende de ese otro (`DEPENDS_ON`),
mientras el otro no esté hecho ni cancelado. `blockedBy` lo calcula al leer (los enlaces no guardan el estado del mientras el otro no esté hecho ni cancelado. `blockedBy` lo calcula al leer (los enlaces no guardan el estado del
otro ticket), con una sola consulta por tablero o página. otro ticket), con una sola consulta por tablero o página.
@@ -249,7 +274,9 @@ stateDiagram-v2
- **Adjuntos**: los suben los miembros (no los lectores), hasta `ATTACHMENTS_MAX_MB` (25 MB) por archivo y 50 por - **Adjuntos**: los suben los miembros (no los lectores), hasta `ATTACHMENTS_MAX_MB` (25 MB) por archivo y 50 por
ticket; pueden ir en el ticket o bajo uno de sus comentarios (`commentId`). Quita uno quien lo subió o un admin. ticket; pueden ir en el ticket o bajo uno de sus comentarios (`commentId`). Quita uno quien lo subió o un admin.
Los bytes se guardan primero y el evento después, así que nunca queda un adjunto apuntando a un archivo que no Los bytes se guardan primero y el evento después, así que nunca queda un adjunto apuntando a un archivo que no
existe; si el evento no se guarda, el archivo se borra. Al borrar un ticket se borran sus archivos. existe; si el evento no se guarda, el archivo se borra. Al borrar un ticket se borran sus archivos. Las imágenes,
los PDF, el texto y el vídeo o audio que reproduce el navegador (mp4, webm, mp3, ogg, wav) se sirven para verse en
la página; el resto, como descarga.
- **Épicas y subtareas**: un ticket puede colgar de otro del mismo proyecto (`parent`), hasta tres niveles - **Épicas y subtareas**: un ticket puede colgar de otro del mismo proyecto (`parent`), hasta tres niveles
(épica → ticket → subtarea) y sin bucles; se comprueba sobre el event store, no sobre el read model. Una «épica» es (épica → ticket → subtarea) y sin bucles; se comprueba sobre el event store, no sobre el read model. Una «épica» es
cualquier ticket de primer nivel del que cuelgan otros (`epics(projectId)` da su progreso: terminados = hechos o cualquier ticket de primer nivel del que cuelgan otros (`epics(projectId)` da su progreso: terminados = hechos o
@@ -259,6 +286,20 @@ stateDiagram-v2
encima y el de quien queda debajo, leídos del event store; si entretanto el orden cambió, la API lo rechaza y la web encima y el de quien queda debajo, leídos del event store; si entretanto el orden cambió, la API lo rechaza y la web
recarga. Un ticket que nunca se movió ocupa su orden de creación (`IssueRankedEvent` no existe para él). Las recarga. Un ticket que nunca se movió ocupa su orden de creación (`IssueRankedEvent` no existe para él). Las
columnas del tablero y `issues(filter: { sort: RANK })` siguen este orden. columnas del tablero y `issues(filter: { sort: RANK })` siguen este orden.
- **Alertas → bugs**: un owner o admin activa en Integraciones una URL secreta por proyecto,
`POST /api/webhooks/alerts/{proyecto}/{token}` (el token es el secreto: Sentry o Uptime Kuma solo dejan pegar una
URL). Entiende Sentry (integración interna, cabecera `sentry-hook-resource`, o el plugin de webhooks), Uptime Kuma,
Prometheus Alertmanager y Grafana; cualquier otra herramienta manda JSON con `title` y, si quiere, `fingerprint`,
`description`, `url` y `resolved`. Cada aviso tiene una huella (el id del problema en Sentry, el monitor en Uptime
Kuma, el `groupKey` en Alertmanager o `fingerprint`): la primera vez TaskStream abre un bug (actor `system`, etiqueta
`alerta`, el tipo y la prioridad elegidos; sin tipo, el primero con icono de bug); mientras ese bug siga abierto, las
repeticiones van a él (un comentario como mucho cada 30 minutos, con cuántas van) y «resuelta» se dice en él; si ya
está cerrado, abre otro que nombra el anterior. Responde `{ action: created | repeated | resolved | ignored, issueKey
}`; proyecto desconocido, alertas apagadas o token malo responden igual: 403. Las alertas de un proyecto se atienden
de una en una, así que dos iguales a la vez abren un solo bug. Configuración: `alertIntegration`,
`saveAlertIntegration(input: { typeId, priority })`, `rotateAlertToken`, `disableAlertIntegration`;
`GET/PUT/DELETE /api/projects/{project}/alert-integration` y `POST …/token`. Vive en MongoDB (`alert_integrations`,
y `alert_traces` con qué bug abrió cada huella), no en el event store.
- **Integración con Git**: un owner o admin añade en la configuración del proyecto sus repositorios (`api`, `web`, - **Integración con Git**: un owner o admin añade en la configuración del proyecto sus repositorios (`api`, `web`,
`admin`…), cada uno con su propio secreto. Todos llaman a la misma URL, `POST /api/webhooks/git/{proyecto}`, con los `admin`…), cada uno con su propio secreto. Todos llaman a la misma URL, `POST /api/webhooks/git/{proyecto}`, con los
eventos _push_ y _pull/merge request_; GitHub y Gitea firman el cuerpo con el secreto (HMAC-SHA256) y GitLab lo envía eventos _push_ y _pull/merge request_; GitHub y Gitea firman el cuerpo con el secreto (HMAC-SHA256) y GitLab lo envía
@@ -281,7 +322,14 @@ stateDiagram-v2
- **Edición en bloque**: `bulkUpdateIssues` / `POST /api/issues/bulk` aplica el mismo cambio (estado, persona o - **Edición en bloque**: `bulkUpdateIssues` / `POST /api/issues/bulk` aplica el mismo cambio (estado, persona o
`unassign`, sprint o `noSprint`, release o `noRelease`, prioridad, etiquetas que añadir) a hasta 100 tickets. Cada `unassign`, sprint o `noSprint`, release o `noRelease`, prioridad, etiquetas que añadir) a hasta 100 tickets. Cada
uno pasa por los comandos normales (permisos, flujo, sprints y releases abiertos) y puede negarse sin parar al resto; uno pasa por los comandos normales (permisos, flujo, sprints y releases abiertos) y puede negarse sin parar al resto;
la respuesta dice cuáles. la respuesta dice cuáles. La web parte selecciones mayores (la Lista enseña hasta 200) en tandas de 100, una tras
otra, y suma el resultado.
- **Notas públicas de una release**: quien gestiona el proyecto abre un enlace secreto con las notas de una release,
para clientes y sin cuenta (también en proyectos privados): `shareReleaseNotes(releaseId, renew)`,
`unshareReleaseNotes`, `releaseNotesShare`; `GET/PUT/DELETE /api/releases/{id}/public-notes`. La página
(`publicReleaseNotes(token)`, `GET /api/shared/release-notes/{token}`, la web en `/notes/{token}`) enseña las notas
escritas o, mientras no las haya, el borrador de sus tickets terminados (`written: false`). Renovar hace un enlace
nuevo; retirarlo, o borrar la release, lo deja sin efecto. Vive en MongoDB (`release_note_shares`).
- **Archivar una release**: `archiveRelease(releaseId, moveTo)` / `POST /api/releases/{id}/archive` (`{ moveTo }`). - **Archivar una release**: `archiveRelease(releaseId, moveTo)` / `POST /api/releases/{id}/archive` (`{ moveTo }`).
Sus tickets sin terminar pasan a `moveTo` (otra release abierta del mismo proyecto) o, sin él, se quedan sin release; Sus tickets sin terminar pasan a `moveTo` (otra release abierta del mismo proyecto) o, sin él, se quedan sin release;
los terminados se quedan, como registro de lo que salió. Igual que al cerrar un sprint con `carryOverTo`. los terminados se quedan, como registro de lo que salió. Igual que al cerrar un sprint con `carryOverTo`.
@@ -396,7 +444,33 @@ eventos `IssueWatchedEvent`/`IssueUnwatchedEvent`), y quien lo abre, quien lo ti
sigue un ticket (`WATCHED`) sabe cuándo cambia de estado, se asigna, se comenta, cambia su prioridad o su fecha límite, sigue un ticket (`WATCHED`) sabe cuándo cambia de estado, se asigna, se comenta, cambia su prioridad o su fecha límite,
o entra o sale de un sprint; las ediciones menores (título, etiquetas…) no avisan. «Los que sigo»: `watching` en o entra o sale de un sprint; las ediciones menores (título, etiquetas…) no avisan. «Los que sigo»: `watching` en
`myIssues` / `GET /api/me/issues` y en la búsqueda de un proyecto (`issues(filter: { watching: true })`, `myIssues` / `GET /api/me/issues` y en la búsqueda de un proyecto (`issues(filter: { watching: true })`,
`?watching=true`; sin sesión, ninguno). El id es `?watching=true`; sin sesión, ninguno). **Revisiones**: quien puede cambiar un ticket pide a un miembro que lo revise, con nota opcional
(`requestReview(issueId, reviewerId, note)`, `POST /api/issues/{issue}/reviews`; evento `IssueReviewRequestedEvent`).
Esa persona, aunque sea lectora, responde «todo bien» o «cambios» con su respuesta (`answerReview`, `POST
…/reviews/{id}/answer`, `IssueReviewAnsweredEvent`); quien la pidió (o un admin) puede retirarla (`cancelReview`, `DELETE
…/reviews/{id}`, `IssueReviewCancelledEvent`). No a uno mismo ni dos veces a la misma persona con una pendiente. Avisos
`REVIEW_REQUESTED` y `REVIEW_ANSWERED`; `Issue.reviews`; «Te piden revisión» es `myIssues(reviewing: true)` /
`GET /api/me/issues?reviewing=true`. **Mi día**: los tickets que cada persona elige para hoy (`myDay(day)`, `addToMyDay(day, issueIds)`,
`removeFromMyDay(day, issueId)`; `GET /api/me/day?day=`, `PUT/DELETE /api/me/day/{issue}?day=`), hasta 10. `day` es
hoy en la zona horaria de quien pregunta (`YYYY-MM-DD`, a dos días como mucho de la del servidor). La respuesta trae
también lo que quedó sin terminar el último día anterior (si fue en la última semana), para pasarlo a hoy. Privado y sin
historial (`my_days`). **Recordármelo**: cada persona pone en un ticket un recordatorio con fecha y hora y nota opcional
(`setReminder(issueId, at, note)`, `clearReminder`, `Issue.myReminder`, `myReminders`; `PUT/DELETE
/api/issues/{issue}/reminder`, `GET /api/me/reminders`): uno por ticket, en el futuro y como mucho a un año. Cada minuto
`IssueReminderScheduler` avisa de los que tocan (`REMINDER`, por la campana, el navegador y el correo; una vez, por su
id) y olvida los de tickets en la papelera o fuera de alcance. Privados y sin historial (`issue_reminders`);
`REMINDERS_ENABLED=false` los apaga junto con los de fecha límite. **Lo nuevo desde tu última visita**: al abrir un
ticket, `visitIssue(issueId)` (`PUT /api/issues/{issue}/visit`) apunta la visita y devuelve la anterior (null la
primera vez); con ella el cliente marca lo que otros han hecho desde entonces. Personal y sin historial (colección
`issue_visits`). **Seguir todo**: seguir un ticket con todo lo que cuelga de él (una épica, un ticket con subtareas):
`followTree`/`unfollowTree`, `Issue.followingTree`; `PUT/DELETE /api/issues/{issue}/follow-tree`. Quien lo hace oye lo
mismo que un seguidor de cada ticket de debajo, a cualquier profundidad, también de los que se añadan, y además cuándo
uno entra (`IssueParentChangedEvent`). Personal y sin historial (colección `tree_follows`); los invitados de un proyecto
privado no oyen los tickets que no son suyos. **Fijar**: cada persona fija hasta 20 tickets para tenerlos a mano en el
inicio y en la búsqueda (`pinIssue`/`unpinIssue`, `myPins`, `Issue.pinned`; `GET /api/me/pins`,
`PUT/DELETE /api/issues/{issue}/pin`). Son privados y sin historial (colección `pinned_issues`, como las vistas de «Mi
trabajo»); los que están en la papelera o fuera de su alcance no se listan, y al llegar a 20 se olvidan primero los
que ya no puede leer. El id es
`<agregado>:<versión>:<persona>`, así que reentregar un evento no duplica avisos. Llegan en vivo por la subscription `<agregado>:<versión>:<persona>`, así que reentregar un evento no duplica avisos. Llegan en vivo por la subscription
`notificationAdded` y, si la instalación tiene `SMTP_URL`, también por correo a quien lo active (`email`, desactivado `notificationAdded` y, si la instalación tiene `SMTP_URL`, también por correo a quien lo active (`email`, desactivado
por defecto); un correo que falla se registra y no bloquea el stream. por defecto); un correo que falla se registra y no bloquea el stream.
@@ -501,17 +575,17 @@ que funcionan también sin token.
| `epics(projectId)` | Épicas del proyecto (tickets de primer nivel de los que cuelgan otros) con el progreso de sus hijos | | `epics(projectId)` | Épicas del proyecto (tickets de primer nivel de los que cuelgan otros) con el progreso de sus hijos |
| `issue(idOrKey)` | Un ticket. Campos calculados: `allowedTransitions`, `linkedIssues`, `comments`, `history` | | `issue(idOrKey)` | Un ticket. Campos calculados: `allowedTransitions`, `linkedIssues`, `comments`, `history` |
| `release(id)` | Una release. Campos calculados: `progress`, `burnup`, `issues` | | `release(id)` | Una release. Campos calculados: `progress`, `burnup`, `issues` |
| `activity(projectId, issueId?, limit, before?)` | Feed de actividad, del más reciente al más antiguo | | `activity(projectId, issueId?, limit, before?, after?)` | Feed de actividad, del más reciente al más antiguo; con `after` y `before`, una ventana (un día, por ejemplo). Por REST, los mismos parámetros en `…/activity` |
### Mutations ### Mutations
Todas devuelven `CommandResult { id, key, version }`. Todas devuelven `CommandResult { id, key, version }`.
| Ámbito | Mutations | | Ámbito | Mutations |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Proyectos | `createProject`, `updateProject`, `updateProjectSettings`, `deleteProject(confirmKey)`, `addProjectMember`, `changeProjectMemberRole`, `removeProjectMember` | | Proyectos | `createProject`, `updateProject`, `updateProjectSettings`, `deleteProject(confirmKey)`, `addProjectMember`, `changeProjectMemberRole`, `removeProjectMember` |
| Tickets | `createIssue`, `updateIssue`, `changeIssueStatus`, `assignIssue`, `linkIssues`, `unlinkIssues`, `setIssueRelease`, `setIssueParent`, `rankIssue`, `addChecklistItem`, `updateChecklistItem`, `removeChecklistItem`, `watchIssue`, `unwatchIssue`, `removeAttachment` (subir: por REST), `duplicateIssue`, `voteIssue` | | Tickets | `createIssue`, `updateIssue`, `changeIssueStatus`, `assignIssue`, `linkIssues`, `unlinkIssues`, `setIssueRelease`, `setIssueParent`, `rankIssue`, `addChecklistItem`, `updateChecklistItem`, `removeChecklistItem`, `watchIssue`, `unwatchIssue`, `requestReview`, `answerReview`, `cancelReview`, `pinIssue`, `unpinIssue`, `followTree`, `unfollowTree`, `visitIssue`, `clearReminder`, `addToMyDay`, `removeFromMyDay` (devuelven `true`), `setReminder`, `removeAttachment` (subir: por REST), `duplicateIssue`, `voteIssue` |
| Comentarios | `addComment(replyTo)`, `editComment`, `deleteComment`, `reactToComment` | | Comentarios | `addComment(replyTo, poll)`, `votePoll`, `closePoll`, `editComment`, `deleteComment`, `reactToComment`, `markDecision(commentId, on)`, `resolveThread(commentId, resolved, conclusion)`, `turnCommentIntoIssue(commentId, title, type, asSubtask)`, `typing(issueId, threadId)`; consulta `decisions(projectId, search)` |
| Webhooks | `createWebhook` (devuelve el secreto), `updateWebhook`, `deleteWebhook`, `testWebhook` | | Webhooks | `createWebhook` (devuelve el secreto), `updateWebhook`, `deleteWebhook`, `testWebhook` |
| Git | `addGitRepository` (devuelve su secreto), `rotateGitRepositorySecret`, `removeGitRepository` | | Git | `addGitRepository` (devuelve su secreto), `rotateGitRepositorySecret`, `removeGitRepository` |
| Sprints | `createSprint`, `updateSprint`, `startSprint`, `closeSprint(carryOverToSprintId)`, `deleteSprint`, `setIssueSprint` | | Sprints | `createSprint`, `updateSprint`, `startSprint`, `closeSprint(carryOverToSprintId)`, `deleteSprint`, `setIssueSprint` |
@@ -522,9 +596,10 @@ Todas devuelven `CommandResult { id, key, version }`.
### Subscriptions ### Subscriptions
| Subscription | Se emite cuando | | Subscription | Se emite cuando |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------- | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `issueChanged(projectId)` | Se crea o cambia cualquier ticket del proyecto (incluye el ticket completo y `action` = nombre del evento) | | `issueChanged(projectId)` | Se crea o cambia cualquier ticket del proyecto (incluye el ticket completo y `action` = nombre del evento) |
| `commentChanged(issueId)` | Se añade, edita o borra un comentario (`comment` es `null` al borrar, o el que queda sin texto si tenía respuestas) | | `commentChanged(issueId)` | Se añade, edita o borra un comentario (`comment` es `null` al borrar, o el que queda sin texto si tenía respuestas) |
| `typing(issueId)` | Alguien escribe en el ticket (`threadId`: la conversación que responde; `null`, un comentario nuevo). Llegan también los propios |
| `activityAdded(projectId)` | Hay una nueva entrada en el feed | | `activityAdded(projectId)` | Hay una nueva entrada en el feed |
| `releaseChanged(projectId)` | Cambia una release | | `releaseChanged(projectId)` | Cambia una release |
| `sprintChanged(projectId)` | Se planifica, cambia, empieza, cierra o borra un sprint (`sprint` es `null` al borrar) | | `sprintChanged(projectId)` | Se planifica, cambia, empieza, cierra o borra un sprint (`sprint` es `null` al borrar) |
@@ -715,11 +790,11 @@ Lo que cada usuario puede ver o cambiar depende de su rol en cada proyecto, como
Proyectos y tickets se pueden indicar por **id o por clave** (`WEB`, `WEB-12`). Proyectos y tickets se pueden indicar por **id o por clave** (`WEB`, `WEB-12`).
| Recurso | Rutas | | Recurso | Rutas |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Usuarios | `GET /api/users/me`, `GET /api/users?search=`, `GET /api/users/{id}` | | Usuarios | `GET /api/users/me`, `GET /api/users?search=`, `GET /api/users/{id}` |
| Proyectos | `GET/POST /api/projects`, `GET/PATCH/DELETE /api/projects/{project}` (`DELETE …?confirm=CLAVE`), `POST …/archive`, `POST …/unarchive`, `PUT …/settings`, `…/board`, `…/epics`, `…/stats`, `…/analytics?days=`, `…/insights`, `…/activity`, `…/members` (POST, PATCH, DELETE) | | Proyectos | `GET/POST /api/projects`, `GET/PATCH/DELETE /api/projects/{project}` (`DELETE …?confirm=CLAVE`), `POST …/archive`, `POST …/unarchive`, `PUT …/settings`, `…/board`, `…/epics`, `…/stats`, `…/analytics?days=`, `…/insights`, `…/activity`, `…/members` (POST, PATCH, DELETE) |
| Tickets | `GET /api/me/home` (portada), `GET /api/me/portfolio` (cartera), `GET /api/me/issues` (mi trabajo; filtros `project`, `priority`, `bugsOnly`, `overdue`), `GET/POST /api/projects/{project}/issues`, `GET/PATCH /api/issues/{issue}`, `PUT …/status`, `PUT …/assignee`, `PUT …/release`, `PUT/DELETE …/watch`, `PUT/DELETE …/presence`, `PUT …/parent`, `PUT …/rank`, `POST …/checklist`, `PATCH/DELETE …/checklist/{item}`, `POST/DELETE …/links`, `GET/POST …/comments`, `GET …/history`, `POST /api/issues/{issue}/duplicate`, `PUT/DELETE …/vote` | | Tickets | `GET /api/me/home` (portada), `GET /api/me/portfolio` (cartera), `GET /api/me/issues` (mi trabajo; filtros `project`, `priority`, `bugsOnly`, `overdue`), `GET/POST /api/projects/{project}/issues`, `GET/PATCH /api/issues/{issue}`, `PUT …/status`, `PUT …/assignee`, `PUT …/release`, `PUT/DELETE …/watch`, `POST …/reviews`, `POST …/reviews/{id}/answer`, `DELETE …/reviews/{id}`, `PUT/DELETE …/follow-tree`, `PUT/DELETE …/reminder`, `GET /api/me/reminders`, `GET /api/me/day`, `PUT/DELETE /api/me/day/{issue}`, `GET /api/me/pins` y `PUT/DELETE …/pin` (fijados), `PUT/DELETE …/presence`, `PUT …/parent`, `PUT …/rank`, `POST …/checklist`, `PATCH/DELETE …/checklist/{item}`, `POST/DELETE …/links`, `GET/POST …/comments`, `GET …/history`, `POST /api/issues/{issue}/duplicate`, `PUT/DELETE …/vote` |
| Comentarios | `PATCH/DELETE /api/comments/{commentId}`, `POST …/reactions` | | Comentarios | `PATCH/DELETE /api/comments/{commentId}`, `POST …/reactions`, `PUT/DELETE …/decision`, `PUT/DELETE …/resolution`, `POST …/poll/vote`, `POST …/poll/close`, `POST …/issue` (convertir en ticket); `GET /api/issues/{issue}/decisions`, `GET /api/projects/{project}/decisions`, `GET /api/me/decisions` |
| Sprints | `GET/POST /api/projects/{project}/sprints`, `GET/PATCH/DELETE /api/sprints/{sprint}`, `POST …/start`, `POST …/close`, `GET …/progress`, `…/burndown`, `…/issues`, `PUT /api/issues/{issue}/sprint` | | Sprints | `GET/POST /api/projects/{project}/sprints`, `GET/PATCH/DELETE /api/sprints/{sprint}`, `POST …/start`, `POST …/close`, `GET …/progress`, `…/burndown`, `…/issues`, `PUT /api/issues/{issue}/sprint` |
| Vistas | `GET/POST /api/projects/{project}/filters`, `DELETE /api/filters/{id}` | | Vistas | `GET/POST /api/projects/{project}/filters`, `DELETE /api/filters/{id}` |
| Avisos | `GET /api/me/notifications`, `POST /api/me/notifications/read`, `GET/PUT /api/me/notification-settings` | | Avisos | `GET /api/me/notifications`, `POST /api/me/notifications/read`, `GET/PUT /api/me/notification-settings` |
@@ -730,6 +805,7 @@ Proyectos y tickets se pueden indicar por **id o por clave** (`WEB`, `WEB-12`).
| Importar | `GET /api/projects/{project}/export.csv`, `POST /api/projects/{project}/import?dryRun=` (multipart `file`) | | Importar | `GET /api/projects/{project}/export.csv`, `POST /api/projects/{project}/import?dryRun=` (multipart `file`) |
| Webhooks | `GET /api/webhook-events`, `GET/POST /api/projects/{project}/webhooks`, `PATCH/DELETE /api/outgoing-webhooks/{id}`, `POST …/test` | | Webhooks | `GET /api/webhook-events`, `GET/POST /api/projects/{project}/webhooks`, `PATCH/DELETE /api/outgoing-webhooks/{id}`, `POST …/test` |
| Git | `GET /api/projects/{project}/git-integration`, `POST …/git-integration/repositories`, `POST …/repositories/{id}/secret`, `DELETE …/repositories/{id}`, `POST /api/webhooks/git/{project}` (lo llama el host de Git) | | Git | `GET /api/projects/{project}/git-integration`, `POST …/git-integration/repositories`, `POST …/repositories/{id}/secret`, `DELETE …/repositories/{id}`, `POST /api/webhooks/git/{project}` (lo llama el host de Git) |
| Alertas | `GET/PUT/DELETE /api/projects/{project}/alert-integration`, `POST …/alert-integration/token`, `POST /api/webhooks/alerts/{project}/{token}` |
| Explorar | `GET /api/explore/projects/{project}/showcase` (sin token, proyectos públicos): hoja de ruta con votos, versiones, sprint en curso, tickets `good-first-issue` y propuestas abiertas; `POST …/proposals` (sin token) | | Explorar | `GET /api/explore/projects/{project}/showcase` (sin token, proyectos públicos): hoja de ruta con votos, versiones, sprint en curso, tickets `good-first-issue` y propuestas abiertas; `POST …/proposals` (sin token) |
| Sistema | `GET /api/health`, `GET /api/auth/config`, `POST /api/auth/token`, `POST /api/webhooks/pireon` | | Sistema | `GET /api/health`, `GET /api/auth/config`, `POST /api/auth/token`, `POST /api/webhooks/pireon` |

View File

@@ -8,7 +8,7 @@ API repartida en `libs/web/*`.
| Librería | Contenido | | Librería | Contenido |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `web/shared/infrastructure` | Cliente Apollo (`provideGraphql`: HTTP + `graphql-ws`), `API_CONFIG`, puerto `AccessTokenSource` | | `web/shared/infrastructure` | Cliente Apollo (`provideGraphql`: HTTP + `graphql-ws`), `API_CONFIG`, puerto `AccessTokenSource` |
| `web/shared/ui` | Integración de `@pi/ui` (`providePiUi`), modo oscuro, iconos, `ToastService`, `DrawerService`, `AppShellComponent` | | `web/shared/ui` | Integración de `@pi/ui` (`providePiUi`), modo oscuro, iconos, `ToastService` (con `undoable`: aviso con «Deshacer», `UndoToastComponent`), `DrawerService`, `AppShellComponent` |
| `web/identity/domain` | `Session`, `CurrentUser`, `AuthConfig` y puertos `AuthGateway`, `ProfileGateway`, `SessionStorage`, `AuthorizationFlow` | | `web/identity/domain` | `Session`, `CurrentUser`, `AuthConfig` y puertos `AuthGateway`, `ProfileGateway`, `SessionStorage`, `AuthorizationFlow` |
| `web/identity/application` | `AuthFacade` (pública); por dentro `AuthStore` y eventos `authPageEvents`, `authApiEvents`, `sessionEvents` | | `web/identity/application` | `AuthFacade` (pública); por dentro `AuthStore` y eventos `authPageEvents`, `authApiEvents`, `sessionEvents` |
| `web/identity/infrastructure` | `/api/auth/*` (HTTP), `me` (GraphQL), `localStorage`, PKCE con Web Crypto; enlaza `AccessTokenSource` con la `AuthFacade` | | `web/identity/infrastructure` | `/api/auth/*` (HTTP), `me` (GraphQL), `localStorage`, PKCE con Web Crypto; enlaza `AccessTokenSource` con la `AuthFacade` |
@@ -118,7 +118,7 @@ Qué gana la página:
| `MyViewsFacade` | `MyViewsStore` | ruta `/` (portada) | Mis vistas guardadas de «Mi trabajo» (entre proyectos: proyectos, asignados a mí, que sigo, estados, prioridades, solo bugs, vencidos, texto) y los tickets de la elegida | | `MyViewsFacade` | `MyViewsStore` | ruta `/` (portada) | Mis vistas guardadas de «Mi trabajo» (entre proyectos: proyectos, asignados a mí, que sigo, estados, prioridades, solo bugs, vencidos, texto) y los tickets de la elegida |
| `ExploreFacade` | `ExploreStore` | ruta `explore` | Proyectos públicos («Explorar»), también sin sesión | | `ExploreFacade` | `ExploreStore` | ruta `explore` | Proyectos públicos («Explorar»), también sin sesión |
| `ProjectFacade` | `ProjectStore` | ruta `/p/:key` | Proyecto, miembros, stats, releases, actividad en vivo, búsqueda de usuarios, configuración (`workflow`, `saveSettings`) y estadísticas (`loadAnalytics`, `loadBurnup`) | | `ProjectFacade` | `ProjectStore` | ruta `/p/:key` | Proyecto, miembros, stats, releases, actividad en vivo, búsqueda de usuarios, configuración (`workflow`, `saveSettings`) y estadísticas (`loadAnalytics`, `loadBurnup`) |
| `BoardFacade` | `BoardStore` | ruta `board` | Tablero kanban, filtros, movimiento optimista, nuevo ticket, cambios en vivo | | `BoardFacade` | `BoardStore` | ruta `board` | Tablero kanban, filtros, movimiento optimista (con «Deshacer»), prioridad, estimación y persona cambiadas desde la tarjeta, nuevo ticket, cambios en vivo |
| `ListFacade` | `ListStore` | ruta `list` | Todos los tickets del proyecto en filas: filtros (enviados a la API), cambios de estado, prioridad y persona en la fila, edición en bloque; se recarga tras cada cambio propio y con los de otros | | `ListFacade` | `ListStore` | ruta `list` | Todos los tickets del proyecto en filas: filtros (enviados a la API), cambios de estado, prioridad y persona en la fila, edición en bloque; se recarga tras cada cambio propio y con los de otros |
| `IssueFacade` | `IssueStore` | ruta `issues/:issueKey` | Ticket, comentarios en vivo, historial y todas sus acciones | | `IssueFacade` | `IssueStore` | ruta `issues/:issueKey` | Ticket, comentarios en vivo, historial y todas sus acciones |
@@ -255,8 +255,11 @@ globales como `.ts-pill` o `.ts-key` leen esa variable. Las animaciones se desac
Estados, tipos y áreas son de cada proyecto, así que la UI nunca los tiene fijos: `ProjectFacade.workflow()` envuelve Estados, tipos y áreas son de cada proyecto, así que la UI nunca los tiene fijos: `ProjectFacade.workflow()` envuelve
`project.settings` (`Workflow` en el dominio web) y da nombre, color, icono, categoría, transiciones permitidas y si un `project.settings` (`Workflow` en el dominio web) y da nombre, color, icono, categoría, transiciones permitidas y si un
estado pide motivo. `statusLook`/`typeLook` de `ui/copy.ts` lo convierten en etiqueta y tono (`--ts-c-<color>`, con su estado pide motivo. `statusLook`/`typeLook` de `ui/copy.ts` lo convierten en etiqueta y tono: `--ts-c-<color>` para
versión oscura). Un id que ya no está configurado sigue mostrándose (`IN_REVIEW` → «In review»). «Mi trabajo» mezcla la paleta, con su versión oscura hecha a mano, y para un `#rrggbb` propio, `light-dark()` con una variante por tema
que `ui/colors.ts` calcula con la librería `color` (se acerca al blanco o al negro hasta contrastar 3:1 con la
superficie). En Configuración, cada estado y tipo elige su color con el selector nativo (`<input type="color">`), con
la paleta como sugerencias; si se elige un color de la paleta, se guarda su nombre. Un id que ya no está configurado sigue mostrándose (`IN_REVIEW` → «In review»). «Mi trabajo» mezcla
proyectos: cada fila usa el workflow de su proyecto y los grupos son por categoría. proyectos: cada fila usa el workflow de su proyecto y los grupos son por categoría.
En el tablero, un ticket solo se puede soltar en las columnas a las que su workflow le deja pasar, y los tipos En el tablero, un ticket solo se puede soltar en las columnas a las que su workflow le deja pasar, y los tipos
@@ -291,30 +294,31 @@ visualización de la plataforma:
lectura, y en uno privado (o inexistente), el enlace para iniciar sesión volviendo a esa página (`returnUrl`). lectura, y en uno privado (o inexistente), el enlace para iniciar sesión volviendo a esa página (`returnUrl`).
- El tiempo real necesita sesión: `GraphqlRealtimeGateway` no abre subscriptions sin token (si lo hiciera, la API - El tiempo real necesita sesión: `GraphqlRealtimeGateway` no abre subscriptions sin token (si lo hiciera, la API
cerraría el WebSocket y el cliente reintentaría sin fin). Los visitantes anónimos ven los datos al cargar la página. cerraría el WebSocket y el cliente reintentaría sin fin). Los visitantes anónimos ven los datos al cargar la página.
- Configuración tiene en General el interruptor «Público» (propietario y admins) y, en Zona peligrosa y solo para el propietario, «Eliminar el - Configuración tiene en General la casilla «Proyecto público» (propietario y admins) y, en Zona peligrosa y solo para el propietario, «Eliminar el
proyecto», que exige escribir la clave. Al borrarlo se vuelve a la portada; si otro lo borra mientras lo tienes proyecto», que exige escribir la clave. Al borrarlo se vuelve a la portada; si otro lo borra mientras lo tienes
abierto, la subscription avisa (`ProjectChanged.deleted`) y también se vuelve a la portada. abierto, la subscription avisa (`ProjectChanged.deleted`) y también se vuelve a la portada.
## 4.6 Rutas ## 4.6 Rutas
| Ruta | Página | | Ruta | Página |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `/login` | Inicio de sesión (solo sin sesión) | | `/login` | Inicio de sesión (solo sin sesión) |
| `/auth/callback` | Retorno de Pireon (PKCE) | | `/auth/callback` | Retorno de Pireon (PKCE) |
| `/` | Inicio: saludo según la hora con el resumen del día, «Ir a…» (`WEB-12`), primeros pasos, mis proyectos con su actividad (lo primero, para llegar antes), cuatro cifras (`ts-home-kpis`: abiertos míos, esperando QA, terminados por mí y por el equipo esta semana), la semana (`ts-week-agenda`), mis vistas guardadas y dos columnas: mis tickets y lo último en mis proyectos; sprints en curso, esperando QA, que sigo, próximas releases, quién está ahora y «Retomar» | | `/` | Inicio: saludo según la hora con el resumen del día, «Ir a…» (`WEB-12`), primeros pasos, mis proyectos con su actividad (lo primero, para llegar antes), «Mi día» (`ts-my-day`: los tickets que elijo para hoy, tachados al terminar, mis abiertos para añadir y lo que quedó del último día), mis fijados (`ts-pinned`, una franja que se quita con ×; solo si hay), cuatro cifras (`ts-home-kpis`: abiertos míos, esperando QA, terminados por mí y por el equipo esta semana), la semana (`ts-week-agenda`), mis vistas guardadas y dos columnas: mis tickets y lo último en mis proyectos; sprints en curso, esperando QA, que sigo, próximas releases, quién está ahora y «Retomar» |
| `/portfolio` | Cartera (con sesión): una tarjeta por proyecto activo con lo abierto y en riesgo, el sprint en curso (¿llega?), las próximas releases con su previsión y las épicas abiertas; en directo: se vuelve a leer sola cuando cambia un ticket, sprint o release de esos proyectos | | `/portfolio` | Cartera (con sesión): una tarjeta por proyecto activo con lo abierto y en riesgo, el sprint en curso (¿llega?), las próximas releases con su previsión y las épicas abiertas; en directo: se vuelve a leer sola cuando cambia un ticket, sprint o release de esos proyectos. Cada proyecto lleva su semáforo de salud (`portfolioHealth`), con las causas al pasar por encima |
| `/explore` | Proyectos públicos (sin sesión) | | `/explore` | Proyectos públicos (sin sesión) |
| `/p/:key/board` | Tablero kanban (`?release=` y `?assignee=` preseleccionan los filtros) | | `/p/:key/board` | Tablero kanban (`?release=` y `?assignee=` preseleccionan los filtros). Quien puede contribuir cambia prioridad, estimación y persona desde la propia tarjeta (selectores nativos sobre sus distintivos; el título es el enlace). Mover una tarjeta o cambiar su persona ofrece «Deshacer» unos segundos (o Ctrl/⌘ Z): la orden contraria, que el flujo puede rechazar. Con el teclado: Tab entra en las tarjetas, las flechas se mueven entre ellas, Shift+←/→ pasa la tarjeta de columna (mismas reglas que arrastrar), `p`/`e`/`a` abren su prioridad, estimación o persona y Enter la abre |
| `/p/:key/issues/:issueKey` | Ticket. Encima del título, quién más lo está viendo o editando ahora (`PresenceFacade`: late cada 10 s; editar es tener abierto el formulario del ticket o de un comentario, o estar escribiendo uno) | | `/p/:key/issues/:issueKey` | Ticket. Encima del título, quién más lo está viendo o editando ahora (`PresenceFacade`: late cada 10 s; editar es tener abierto el formulario del ticket o de un comentario, o estar escribiendo uno). A la vista, «Votar», «Seguir» y «Editar»; el resto (pedir revisión, mi día, recordármelo, seguir todo, fijar y duplicar) está en el menú «Más» (menú del CDK: se recorre con las flechas y Escape lo cierra). «Fijar» lo deja a mano en el inicio y en la paleta de búsqueda. Arriba, sus decisiones (comentarios marcados con la bandera por quien puede cambiar el ticket); `?comment=<id>` lleva a un comentario y lo señala. Cambiar el estado o la persona y mandarlo a la papelera (sin confirmación) ofrecen «Deshacer». Cada conversación con respuestas se resuelve («✓ Resolver», con una conclusión opcional que queda como decisión) y se pliega en una línea; la cabecera cuenta las abiertas y terminar el ticket con alguna pregunta antes. Se ve quién está escribiendo en cada conversación («Ana está escribiendo…», `PresenceFacade.typists`), y en las respuestas Enter envía (Shift+Enter, otra línea). Si tiene subtareas, «Seguir todo» avisa de ella y de todo lo que cuelga, también lo que se añada (también desde Épicas). «Recordármelo» pone un aviso solo para mí (dentro de 1 hora, esta tarde, mañana o el lunes a las 9, en una semana o cuando diga), con nota opcional. «☀ Mi día» lo añade a los de hoy. «Pedir revisión» a alguien del equipo: lo ve en «Mi trabajo» («Te piden revisión») y responde «Todo bien» o «Pedir cambios» desde el recuadro Revisiones. Un comentario puede llevar una encuesta («Encuesta»; con su pregunta y de 2 a 6 opciones; el botón pasa a «Publicar encuesta» y el texto del comentario es opcional): se vota pulsando una opción y, al cerrarla, la ganadora queda como decisión. «🎥 Grabar pantalla» (con la voz, si se da permiso al micrófono) y «🎙 Grabar audio» graban en el navegador hasta 3 minutos y lo adjuntan al comentario, que puede ir sin texto; los vídeos y audios adjuntos se reproducen ahí mismo. Al abrirlo, lo que otros han hecho desde tu última visita: un aviso arriba («Desde tu última visita, hace 2 días: 3 comentarios y 1 cambio de Ana y Bob», con «Ver lo nuevo»), los comentarios nuevos marcados («Nuevo», también en una conversación plegada) y los cambios del historial resaltados. Cada comentario se puede «Convertir en ticket» (subtarea de este o enlazado, con el título sacado de su primera línea): el comentario enlaza al ticket nuevo («→ Convertido en WEB-45») |
| `/p/:key/releases` | Releases | | `/p/:key/releases` | Releases. «Página pública» (quien gestiona): un enlace secreto con las notas para clientes, que se copia, renueva o retira |
| `/p/:key/report/:kind/:id` | Informe para imprimir de un sprint (`sprint`) o una release (`release`): datos, totales, notas y tickets por etapa. «Imprimir o guardar en PDF» abre el diálogo del navegador; al imprimir se quitan la cabecera, las pestañas y los fondos (`styles.scss`) | | `/p/:key/report/:kind/:id` | Informe para imprimir de un sprint (`sprint`) o una release (`release`): datos, totales, notas y tickets por etapa. «Imprimir o guardar en PDF» abre el diálogo del navegador; al imprimir se quitan la cabecera, las pestañas y los fondos (`styles.scss`) |
| `/p/:key/roadmap` | Hoja de ruta: épicas en el tiempo, con sprints y releases; flechas «bloquea» / «depende de» entre épicas y aviso si una empieza antes de que acabe la que la bloquea | | `/p/:key/roadmap` | Hoja de ruta: épicas en el tiempo, con sprints y releases; flechas «bloquea» / «depende de» entre épicas y aviso si una empieza antes de que acabe la que la bloquea. Los bloqueos con tickets de otros proyectos (en los dos sentidos, `externalDependencies`) salen en «De otros proyectos» con barra discontinua, sus flechas y el mismo aviso si las fechas no encajan; los que no tienen fechas o no se pueden leer se nombran debajo |
| `/p/:key/dashboard` | Seguimiento: cifras, flujo por estado, lo que ha cambiado desde tu última visita (guardada en este navegador), sprint en curso, tickets en riesgo, previsión de las próximas releases, antigüedad de lo que está en curso, cuellos de botella, salud del backlog (cada número abre la lista filtrada: `?missing=estimate`, `area`, `assignee` o `?staleDays=90`), calidad (bugs por prioridad y por semana, QA por área, bugs tras cada release), abiertos por un campo de lista a elegir, el recorrido de un ticket (dónde se va el tiempo de creado a hecho y qué parte es trabajo), la actividad de 12 semanas en un mapa de calor, el embudo de propuestas del público (si las hay), equipo con sus puntos abiertos y tipos. Se recarga solo con cada cambio. «Modo pantalla» lo pone a pantalla completa para una tele del equipo: un bloque cada vez, ampliado, que cambia cada 15 s (← → para moverse, espacio para pausar, Esc para salir), con la hora y en directo | | `/p/:key/dashboard` | Arriba, la salud del proyecto (`ts-project-health`): un semáforo (bien, atención, en riesgo) con cada causa y sus tickets, calculado en la web (`projectHealth`) con los mismos datos: atascados, vencidos, bloqueados, bugs críticos o altos, lo que devuelve QA, releases que no llegan y columnas sobre su WIP. Seguimiento: cifras, flujo por estado, lo que ha cambiado desde tu última visita (guardada en este navegador), sprint en curso, tickets en riesgo, previsión de las próximas releases, antigüedad de lo que está en curso, cuellos de botella, salud del backlog (cada número abre la lista filtrada: `?missing=estimate`, `area`, `assignee` o `?staleDays=90`), calidad (bugs por prioridad y por semana, QA por área, bugs tras cada release), abiertos por un campo de lista a elegir, el recorrido de un ticket (dónde se va el tiempo de creado a hecho y qué parte es trabajo), la actividad de 12 semanas en un mapa de calor (pulsar un día abre lo que pasó, ticket a ticket), el embudo de propuestas del público (si las hay), equipo con sus puntos abiertos y tipos. Se recarga solo con cada cambio. «Modo pantalla» lo pone a pantalla completa para una tele del equipo: un bloque cada vez, ampliado, que cambia cada 15 s (← → para moverse, espacio para pausar, Esc para salir), con la hora y en directo |
| `/p/:key/analytics` | Estadísticas: creados vs. resueltos, flujo acumulado, burnup de una release, tiempos de ciclo y entrega, QA y resueltos por persona (30 días a 1 año) | | `/p/:key/analytics` | Estadísticas: creados vs. resueltos, flujo acumulado, burnup de una release, tiempos de ciclo y entrega, QA y resueltos por persona (30 días a 1 año) |
| `/p/:key/settings` | Configuración (propietario y admins; pestaña oculta para el resto), con un menú de secciones (`?section=`): General (visibilidad, propuestas, panel para clientes), Flujo de trabajo (estados, transiciones, definición de «Hecho»), Tickets (tipos, áreas, campos), Equipos, Automatizaciones, Integraciones (Git, webhooks), Importar y exportar y Zona peligrosa; archivar en lugar de borrar, y un punto en el menú donde hay cambios sin guardar | | `/p/:key/settings` | Configuración (propietario y admins; pestaña oculta para el resto), con un menú de secciones (`?section=`): General (visibilidad, propuestas, panel para clientes), Flujo de trabajo (estados, transiciones, definición de «Hecho»), Tickets (tipos, áreas, campos), Equipos, Automatizaciones, Integraciones (Git, alertas → bugs con su URL secreta y cómo conectar Sentry, Uptime Kuma o Grafana, webhooks), Importar y exportar y Zona peligrosa; archivar en lugar de borrar, y un punto en el menú donde hay cambios sin guardar |
| `/p/:key/activity` | Actividad en vivo | | `/p/:key/activity` | Actividad en vivo |
| `/p/:key/propose` | Formulario público para reportar un error o proponer una idea sin cuenta (si el proyecto lo tiene abierto); llegan como tickets con la etiqueta «propuesta» | | `/p/:key/propose` | Formulario público para reportar un error o proponer una idea sin cuenta (si el proyecto lo tiene abierto); llegan como tickets con la etiqueta «propuesta» |
| `/share/:token` | Panel para clientes, sin sesión: los bloques que eligió el proyecto (flujo, sprint, releases, épicas, actividad), sin enlaces hacia dentro de la aplicación; se vuelve a leer cada minuto. Si el enlace se renovó o retiró, «Este enlace ya no funciona» | | `/share/:token` | Panel para clientes, sin sesión: los bloques que eligió el proyecto (flujo, sprint, releases, épicas, actividad), sin enlaces hacia dentro de la aplicación; se vuelve a leer cada minuto. Si el enlace se renovó o retiró, «Este enlace ya no funciona» |
| `/notes/:token` | Notas de una release para sus clientes, sin cuenta: las escritas o las de sus tickets terminados |
| `/p/:key/members` | Miembros, con su rol (propietario, admin, miembro, lector o invitado). Un invitado de un proyecto privado solo tiene Tablero, Lista y Miembros, ve solo sus tickets y abre tickets sin asignarlos ni planificarlos | | `/p/:key/members` | Miembros, con su rol (propietario, admin, miembro, lector o invitado). Un invitado de un proyecto privado solo tiene Tablero, Lista y Miembros, ve solo sus tickets y abre tickets sin asignarlos ni planificarlos |
Solo `/` está protegida por `authGuard` (redirige a `/login?returnUrl=…`); `/login` y `/auth/callback` son para quien Solo `/` está protegida por `authGuard` (redirige a `/login?returnUrl=…`); `/login` y `/auth/callback` son para quien

View File

@@ -36,7 +36,10 @@ genéricos, el DNS de Docker devuelve también los suyos y nginx reparte las pet
de las llamadas a `/api/*` responden `404 Cannot GET …` y el login dice «no configurado»). Si añades un servicio, de las llamadas a `/api/*` responden `404 Cannot GET …` y el login dice «no configurado»). Si añades un servicio,
dale su alias `task-stream-*` y úsalo en las URLs. dale su alias `task-stream-*` y úsalo en las URLs.
Todos tienen healthcheck; `web` espera a que `api` esté sana, y `api` a las tres bases de datos. Todos tienen healthcheck; `web` espera a que `api` esté sana, y `api` a las tres bases de datos. `GET /api/health` responde 503 si cae una base de datos; con
las tres en pie, `status: degraded` (200) avisa de eventos que no llegan a la lectura (`events.problems`). Los eventos
apartados por fallar una y otra vez se ven con `redis-cli XRANGE task-stream:events:dead - +`; arreglado el fallo, se
reconstruye la lectura (abajo) o se vuelven a publicar.
### Imágenes ### Imágenes

View File

@@ -51,10 +51,10 @@ flowchart LR
| | `get_portfolio` | Todos mis proyectos activos de un vistazo: abiertos y en riesgo, sprint, previsión de releases y épicas | | | `get_portfolio` | Todos mis proyectos activos de un vistazo: abiertos y en riesgo, sprint, previsión de releases y épicas |
| | `get_my_week` | Mi semana: lo mío que vence en 7 días, fin de sprints y releases; lo terminado por mí y por mis equipos, racha; sprints en curso y qué podría coger | | | `get_my_week` | Mi semana: lo mío que vence en 7 días, fin de sprints y releases; lo terminado por mí y por mis equipos, racha; sprints en curso y qué podría coger |
| | `get_project_insights` | El panel: sprint, riesgo, antigüedad, cuellos de botella, releases, equipo, backlog, calidad, campos, actividad por día, recorrido de un ticket, propuestas y, con `since`, los cambios | | | `get_project_insights` | El panel: sprint, riesgo, antigüedad, cuellos de botella, releases, equipo, backlog, calidad, campos, actividad por día, recorrido de un ticket, propuestas y, con `since`, los cambios |
| | `get_project_activity` | Actividad reciente | | | `get_project_activity` | Actividad reciente, o la de un día (`day`) |
| Tickets | `my_issues` | Mi trabajo en todos los proyectos (o de cualquiera, por categoría; o los que sigo); también por prioridad, solo bugs o vencidos | | Tickets | `my_issues` | Mi trabajo en todos los proyectos (o de cualquiera, por categoría; o los que sigo); también por prioridad, solo bugs o vencidos; `reviewing`: los que me piden revisar |
| | `search_issues` | Buscar por texto y filtros (épica, sprint, fechas, campos…); el backlog: `noSprint` y orden `RANK` | | | `search_issues` | Buscar por texto y filtros (épica, sprint, fechas, campos…); el backlog: `noSprint` y orden `RANK` |
| | `get_issue` | Detalle: épica, lista de comprobación, relaciones, commits, seguidores, transiciones, comentarios | | | `get_issue` | Detalle: épica, lista de comprobación, relaciones, commits, seguidores, transiciones, decisiones y comentarios |
| | `create_issue` | Crear un ticket (también colgado de una épica) | | | `create_issue` | Crear un ticket (también colgado de una épica) |
| | `update_issue` | Cambiar título, descripción, tipo, área, prioridad, etiquetas, fechas, campos personalizados… | | | `update_issue` | Cambiar título, descripción, tipo, área, prioridad, etiquetas, fechas, campos personalizados… |
| | `change_issue_status` | Mover de estado (con motivo cuando el estado lo pide) | | | `change_issue_status` | Mover de estado (con motivo cuando el estado lo pide) |
@@ -62,10 +62,20 @@ flowchart LR
| | `set_issue_release` | Meter en una release o sacar | | | `set_issue_release` | Meter en una release o sacar |
| | `add_comment` / `edit_comment` / `delete_comment` | Comentar (o responder a un comentario), corregir o borrar | | | `add_comment` / `edit_comment` / `delete_comment` | Comentar (o responder a un comentario), corregir o borrar |
| | `link_issues` / `unlink_issues` | Relacionar tickets (`DEPENDS_ON`, `BLOCKS`, `TESTS`…) o quitar la relación | | | `link_issues` / `unlink_issues` | Relacionar tickets (`DEPENDS_ON`, `BLOCKS`, `TESTS`…) o quitar la relación |
| | `watch_issue` | Seguir un ticket o dejar de seguirlo | | | `watch_issue` | Seguir un ticket o dejar de seguirlo; con `tree`, una épica con todo lo que cuelga de ella |
| | `vote_issue` | Votar un ticket o quitar el voto | | | `vote_issue` | Votar un ticket o quitar el voto |
| | `duplicate_issue` | Crear otro ticket con lo mismo (sin estado, persona ni comentarios) | | | `duplicate_issue` | Crear otro ticket con lo mismo (sin estado, persona ni comentarios) |
| | `react_to_comment` | Reaccionar a un comentario (👍 🎉…) o quitar la reacción | | | `react_to_comment` | Reaccionar a un comentario (👍 🎉…) o quitar la reacción |
| | `mark_decision` | Marcar un comentario como decisión del ticket, o quitarla |
| | `resolve_thread` | Resolver una conversación (con conclusión opcional, que queda como decisión) o reabrirla |
| | `remind_me` | Recordármelo: un aviso solo para mí sobre un ticket, a una fecha y hora, con nota (o quitarlo) |
| | `my_day` | Mi día: los tickets elegidos para hoy (y lo que quedó del último día); añadir o quitar uno |
| | `request_review` | Pedir a alguien del proyecto que revise un ticket |
| | `answer_review` | Responder una revisión: todo bien o cambios |
| | `vote_poll` | Votar en la encuesta de un comentario (o retirar el voto) |
| | `close_poll` | Cerrar una encuesta; la ganadora queda como decisión |
| | `turn_comment_into_issue` | Convertir un comentario en ticket: subtarea del suyo o enlazado; su texto es la descripción |
| | `search_decisions` | Qué se decidió: decisiones por su texto, de un proyecto o de todos los míos |
| | `add_checklist_item` / `update_checklist_item` / `remove_checklist_item` | La lista de comprobación: añadir, marcar o reescribir, quitar | | | `add_checklist_item` / `update_checklist_item` / `remove_checklist_item` | La lista de comprobación: añadir, marcar o reescribir, quitar |
| Organización | `list_epics` | Épicas con el progreso de lo que cuelga de cada una | | Organización | `list_epics` | Épicas con el progreso de lo que cuelga de cada una |
| | `set_issue_parent` | Colgar un ticket de una épica u otro ticket, o soltarlo | | | `set_issue_parent` | Colgar un ticket de una épica u otro ticket, o soltarlo |

View File

@@ -132,3 +132,6 @@ Mucho trabajo para lo que aportan hoy; se pueden recuperar si alguien los necesi
directo y con la hora. directo y con la hora.
- Panel para clientes: un enlace de solo lectura, sin cuenta, con los bloques que elijan el propietario y los admins - Panel para clientes: un enlace de solo lectura, sin cuenta, con los bloques que elijan el propietario y los admins
(flujo, sprint, releases, épicas, actividad); se renueva o se retira desde Configuración. (flujo, sprint, releases, épicas, actividad); se renueva o se retira desde Configuración.
- De escritura a lectura: si un evento no se puede proyectar, se reintenta en su sitio (el siguiente espera) hasta
que Mongo vuelve, sin reiniciar ni perder cambios; los que fallan por sí mismos se apartan a
`task-stream:events:dead`, y `GET /api/health` avisa de eventos atascados o apartados.

Binary file not shown.

Binary file not shown.

View File

@@ -12,6 +12,9 @@ Event store en PostgreSQL y el camino de los eventos hasta la lectura.
- `EventStoreRelay`: copia los eventos nuevos al Redis Stream (`FOR UPDATE SKIP LOCKED`). - `EventStoreRelay`: copia los eventos nuevos al Redis Stream (`FOR UPDATE SKIP LOCKED`).
- `EventsBridge`: consume el stream y entrega cada evento a sus `@EventsHandler`, en orden y esperando (ACK al final); - `EventsBridge`: consume el stream y entrega cada evento a sus `@EventsHandler`, en orden y esperando (ACK al final);
después ejecuta los `@Saga()` (el `EventBus` en memoria nunca ve los eventos guardados) y sus comandos, uno a uno. después ejecuta los `@Saga()` (el `EventBus` en memoria nunca ve los eventos guardados) y sus comandos, uno a uno.
- `EventStreamConsumer`: reintenta en su sitio el evento que falla (el siguiente espera); los fallos de
infraestructura (`isTransientError`) sin límite, los del propio evento 5 veces y luego a `<stream>:dead`.
- `EventPipelineStatus`: bandeja de salida, pendientes y apartados, para `GET /api/health`.
- Conexiones Redis (`REDIS_CLIENT`, `GRAPHQL_PUB_SUB`) y `SharedInfrastructureModule.forRootAsync`. - Conexiones Redis (`REDIS_CLIENT`, `GRAPHQL_PUB_SUB`) y `SharedInfrastructureModule.forRootAsync`.
Flujo completo: [Arquitectura](../../../../docs/02-arquitectura.md#22-flujo-completo-de-una-escritura). Flujo completo: [Arquitectura](../../../../docs/02-arquitectura.md#22-flujo-completo-de-una-escritura).

View File

@@ -6,3 +6,4 @@ export * from './lib/event-stream/event-stream.consumer';
export * from './lib/event-store/entities/event.entity'; export * from './lib/event-store/entities/event.entity';
export * from './lib/event-store/deserializers/event.deserializer'; export * from './lib/event-store/deserializers/event.deserializer';
export * from './lib/event-store/serializers/event.serializer'; export * from './lib/event-store/serializers/event.serializer';
export * from './lib/event-store/event-pipeline.status';

View File

@@ -0,0 +1,66 @@
import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { DataSource } from 'typeorm';
import { deadLetterKey } from '../event-stream/event-stream.consumer';
import {
EVENT_STREAM_OPTIONS,
EventStreamOptions,
} from '../event-stream/event-stream.options';
import { REDIS_CLIENT } from '../redis/redis.tokens';
import { EVENTS_BRIDGE_GROUP } from './events-bridge';
/** How write reaches read, for the health check. */
export interface EventPipelineReading {
/** Events in Postgres not yet copied to the Redis stream (the outbox). */
unpublished: number;
/** Seconds the oldest of them has waited (null: none). */
oldestUnpublishedSeconds: number | null;
/** Entries handed to the read side and not yet projected (the inbox). */
pending: number;
/** Events set aside after failing again and again. */
dead: number;
}
/**
* Reads the backlog at each step from the event store to the read model:
* a growing one means the read side is falling behind.
*/
@Injectable()
export class EventPipelineStatus {
constructor(
private readonly dataSource: DataSource,
@Inject(REDIS_CLIENT) private readonly redis: Redis,
@Inject(EVENT_STREAM_OPTIONS) private readonly stream: EventStreamOptions,
) {}
async read(): Promise<EventPipelineReading> {
const [outbox, pending, dead] = await Promise.all([
this.dataSource.query(
`SELECT count(*)::int AS count,
EXTRACT(EPOCH FROM now() - min(created_at))::int AS age
FROM events WHERE published_at IS NULL`,
) as Promise<{ count: number; age: number | null }[]>,
this.pending(),
this.redis.xlen(deadLetterKey(this.stream.streamKey)),
]);
return {
unpublished: outbox[0]?.count ?? 0,
oldestUnpublishedSeconds: outbox[0]?.age ?? null,
pending,
dead,
};
}
/** XPENDING's summary; no group yet (nothing consumed) means none. */
private async pending(): Promise<number> {
try {
const summary = (await this.redis.xpending(
this.stream.streamKey,
EVENTS_BRIDGE_GROUP,
)) as [number, ...unknown[]];
return Number(summary[0] ?? 0);
} catch {
return 0;
}
}
}

View File

@@ -30,6 +30,8 @@ import { RedisConnectionFactory } from '../redis/redis-connection.factory';
import { EventDeserializer } from './deserializers/event.deserializer'; import { EventDeserializer } from './deserializers/event.deserializer';
export const EVENTS_BRIDGE_ENABLED = Symbol('EVENTS_BRIDGE_ENABLED'); export const EVENTS_BRIDGE_ENABLED = Symbol('EVENTS_BRIDGE_ENABLED');
/** The Redis consumer group of the read side. */
export const EVENTS_BRIDGE_GROUP = 'events-bridge';
/** Metadata written by @EventsHandler(...events) and @Saga() (@nestjs/cqrs). */ /** Metadata written by @EventsHandler(...events) and @Saga() (@nestjs/cqrs). */
const EVENTS_HANDLER_METADATA = '__eventsHandler__'; const EVENTS_HANDLER_METADATA = '__eventsHandler__';
@@ -84,7 +86,7 @@ export class EventsBridge
this.connections.create('events-bridge'), this.connections.create('events-bridge'),
{ {
streamKey: this.stream.streamKey, streamKey: this.stream.streamKey,
group: 'events-bridge', group: EVENTS_BRIDGE_GROUP,
consumer: hostname(), consumer: hostname(),
}, },
(event) => this.handleEvent(event), (event) => this.handleEvent(event),

View File

@@ -0,0 +1,178 @@
import { SerializableEvent } from '@task-stream/api/shared/domain';
import Redis from 'ioredis';
import { deadLetterKey, EventStreamConsumer } from './event-stream.consumer';
import { isTransientError } from './transient-error';
const KEY = 'test:events';
/** Just enough of a Redis stream with a consumer group. */
class FakeRedis {
acked: string[] = [];
dead: Record<string, string>[] = [];
private handedOut = false;
constructor(private readonly entries: [string, string[]][]) {}
async xgroup() {
return 'OK';
}
async xautoclaim() {
return ['0-0', []];
}
async xreadgroup(...args: string[]) {
const cursor = args[args.length - 1];
if (cursor === '>' && !this.handedOut) {
this.handedOut = true;
return [[KEY, this.entries]];
}
await new Promise((resolve) => setTimeout(resolve, 2));
return null;
}
async xack(_key: string, _group: string, id: string) {
this.acked.push(id);
return 1;
}
async xadd(key: string, _id: string, ...fields: string[]) {
const entry: Record<string, string> = { key };
for (let i = 0; i < fields.length; i += 2) entry[fields[i]] = fields[i + 1];
this.dead.push(entry);
return '1-0';
}
disconnect() {
return undefined;
}
}
const entry = (id: string, position: number): [string, string[]] => [
id,
[
'event',
JSON.stringify({ streamId: 's', type: 'Moved', position, data: {} }),
],
];
async function until(done: () => boolean) {
const deadline = Date.now() + 2000;
while (!done()) {
if (Date.now() > deadline) throw new Error('timed out');
await new Promise((resolve) => setTimeout(resolve, 2));
}
}
function consumer(
redis: FakeRedis,
handle: (event: SerializableEvent) => Promise<void>,
) {
return new EventStreamConsumer(
redis as unknown as Redis,
{
streamKey: KEY,
group: 'g',
consumer: 'c',
retryBaseMs: 1,
maxRetryMs: 2,
maxAttempts: 3,
},
handle,
);
}
const mongoDown = () =>
Object.assign(new Error('connection refused'), {
name: 'MongoNetworkError',
});
describe('EventStreamConsumer', () => {
it('retries a failing event in place: the next one waits for it', async () => {
const redis = new FakeRedis([entry('1-0', 1), entry('2-0', 2)]);
const handled: number[] = [];
let failures = 2;
const c = consumer(redis, async (event) => {
if (event.position === 1 && failures-- > 0) throw mongoDown();
handled.push(event.position);
});
await c.start();
await until(() => redis.acked.length === 2);
await c.stop();
expect(handled).toEqual([1, 2]);
expect(redis.acked).toEqual(['1-0', '2-0']);
expect(redis.dead).toEqual([]);
});
it('waits out the infrastructure however long: it never sets it aside', async () => {
const redis = new FakeRedis([entry('1-0', 1)]);
let failures = 10; // well past maxAttempts
const c = consumer(redis, async () => {
if (failures-- > 0) throw mongoDown();
});
await c.start();
await until(() => redis.acked.length === 1);
await c.stop();
expect(redis.dead).toEqual([]);
});
it('sets aside an event that keeps failing on its own, and goes on', async () => {
const redis = new FakeRedis([entry('1-0', 1), entry('2-0', 2)]);
const handled: number[] = [];
let calls = 0;
const c = consumer(redis, async (event) => {
if (event.position === 1) {
calls++;
throw new Error('Cannot read properties of undefined');
}
handled.push(event.position);
});
await c.start();
await until(() => redis.acked.length === 2);
await c.stop();
expect(calls).toBe(3);
expect(handled).toEqual([2]);
expect(redis.dead).toHaveLength(1);
expect(redis.dead[0]).toMatchObject({
key: deadLetterKey(KEY),
attempts: '3',
sourceId: '1-0',
error: 'Cannot read properties of undefined',
});
expect(JSON.parse(redis.dead[0]['event'])).toMatchObject({ position: 1 });
});
it('stopping while it retries leaves the event pending', async () => {
const redis = new FakeRedis([entry('1-0', 1)]);
let calls = 0;
const c = consumer(redis, async () => {
calls++;
throw mongoDown();
});
await c.start();
await until(() => calls >= 2);
await c.stop();
expect(redis.acked).toEqual([]);
expect(redis.dead).toEqual([]);
});
});
describe('isTransientError', () => {
it('tells the infrastructure being down from a fault of its own', () => {
expect(isTransientError(mongoDown())).toBe(true);
expect(
isTransientError(Object.assign(new Error('x'), { code: 'ECONNRESET' })),
).toBe(true);
expect(
isTransientError(
Object.assign(new Error('write failed'), {
cause: Object.assign(new Error('y'), {
name: 'MongoServerSelectionError',
}),
}),
),
).toBe(true);
expect(isTransientError(new Error('Connection is closed.'))).toBe(true);
expect(isTransientError(new TypeError('x is undefined'))).toBe(false);
expect(isTransientError(new Error('E11000 duplicate key'))).toBe(false);
});
});

View File

@@ -1,6 +1,7 @@
import { Logger } from '@nestjs/common'; import { Logger } from '@nestjs/common';
import Redis from 'ioredis'; import Redis from 'ioredis';
import { SerializableEvent } from '@task-stream/api/shared/domain'; import { SerializableEvent } from '@task-stream/api/shared/domain';
import { isTransientError } from './transient-error';
type StreamEntry = [id: string, fields: string[]]; type StreamEntry = [id: string, fields: string[]];
type StreamReply = [stream: string, entries: StreamEntry[]][] | null; type StreamReply = [stream: string, entries: StreamEntry[]][] | null;
@@ -11,17 +12,35 @@ export interface EventStreamConsumerOptions {
consumer: string; consumer: string;
batchSize?: number; batchSize?: number;
blockMs?: number; blockMs?: number;
/** First wait before retrying an event; it doubles up to `maxRetryMs`. */
retryBaseMs?: number;
maxRetryMs?: number;
/** Attempts of an event that keeps failing for a reason of its own. */
maxAttempts?: number;
} }
/** Where events that keep failing go, next to the stream: `<key>:dead`. */
export const deadLetterKey = (streamKey: string) => `${streamKey}:dead`;
/** /**
* Reads the event stream with a Redis consumer group. Entries are ACKed only * Reads the event stream with a Redis consumer group (the read side's inbox).
* after the handler succeeds; failed ones stay pending and are retried on * Entries are ACKed only after the handler succeeds.
*
* An event that fails is retried in place, waiting longer each time, and the
* next one waits for it: skipping ahead would apply a later change first, and
* the version check of the projections would then drop the earlier one for
* good. When the infrastructure is down (Mongo, Redis, the network) it waits
* as long as it takes; when the event itself keeps failing, after
* `maxAttempts` it goes to the dead-letter stream (`<key>:dead`) so that it
* does not hold up the rest. Entries still pending at a stop are retried on
* the next start (or by another consumer of the group). * the next start (or by another consumer of the group).
*/ */
export class EventStreamConsumer { export class EventStreamConsumer {
private readonly logger: Logger; private readonly logger: Logger;
private running = false; private running = false;
private loop?: Promise<void>; private loop?: Promise<void>;
/** Ends the current wait between retries (on stop). */
private wake?: () => void;
constructor( constructor(
private readonly redis: Redis, private readonly redis: Redis,
@@ -39,6 +58,7 @@ export class EventStreamConsumer {
async stop(): Promise<void> { async stop(): Promise<void> {
this.running = false; this.running = false;
this.wake?.();
this.redis.disconnect(); this.redis.disconnect();
await this.loop?.catch(() => undefined); await this.loop?.catch(() => undefined);
} }
@@ -108,15 +128,98 @@ export class EventStreamConsumer {
return; return;
} }
const event = JSON.parse(fields[index + 1]) as SerializableEvent; const event = JSON.parse(fields[index + 1]) as SerializableEvent;
const name = `${event.type} (${event.streamId}#${event.position})`;
const maxAttempts = this.options.maxAttempts ?? 5;
for (let attempt = 1; this.running; attempt++) {
try { try {
await this.handle(event); await this.handle(event);
await this.redis.xack(this.options.streamKey, this.options.group, id); await this.redis.xack(this.options.streamKey, this.options.group, id);
if (attempt > 1)
this.logger.log(`${name} handled on attempt ${attempt}`);
return;
} catch (error) { } catch (error) {
// Left pending: it will be retried after a restart. const transient = isTransientError(error);
if (!transient && attempt >= maxAttempts) {
if (
await this.deadLetter(id, fields[index + 1], name, error, attempt)
)
return;
}
const wait = this.backoff(attempt);
const reason = (error as Error).message;
if (attempt === 1)
this.logger.error( this.logger.error(
`Failed to handle ${event.type} (${event.streamId}#${event.position}): ${(error as Error).message}`, `Failed to handle ${name}: ${reason}; retrying in ${wait} ms`,
(error as Error).stack, (error as Error).stack,
); );
else
this.logger.warn(
`${name} still failing (attempt ${attempt}${transient ? ', infrastructure' : `/${maxAttempts}`}): ${reason}; retrying in ${wait} ms`,
);
await this.sleep(wait);
} }
} }
// Stopped while retrying: it stays pending for the next start.
}
/**
* Moves an event that keeps failing aside, with why, and lets the stream
* go on. False if even that failed (Redis down): it is then retried.
*/
private async deadLetter(
id: string,
payload: string,
name: string,
error: unknown,
attempts: number,
): Promise<boolean> {
try {
await this.redis.xadd(
deadLetterKey(this.options.streamKey),
'*',
'event',
payload,
'error',
(error as Error).message ?? String(error),
'attempts',
String(attempts),
'group',
this.options.group,
'sourceId',
id,
'failedAt',
new Date().toISOString(),
);
await this.redis.xack(this.options.streamKey, this.options.group, id);
this.logger.error(
`${name} failed ${attempts} times and went to ${deadLetterKey(this.options.streamKey)}: ${(error as Error).message}`,
);
return true;
} catch (failure) {
this.logger.error(
`Could not set ${name} aside: ${(failure as Error).message}`,
);
return false;
}
}
private backoff(attempt: number): number {
const base = this.options.retryBaseMs ?? 500;
return Math.min(
this.options.maxRetryMs ?? 30_000,
base * 2 ** (attempt - 1),
);
}
private sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
const timer = setTimeout(done, ms);
function done() {
clearTimeout(timer);
resolve();
}
this.wake = done;
});
}
} }

View File

@@ -0,0 +1,36 @@
/** Errors of the infrastructure itself: waiting is the cure, not skipping. */
const TRANSIENT_NAMES =
/^(Mongo(Network|NetworkTimeout|ServerSelection|NotConnected|TopologyClosed|PoolCleared)Error|MaxRetriesPerRequestError)$/;
const TRANSIENT_CODES = new Set([
'ECONNREFUSED',
'ECONNRESET',
'ETIMEDOUT',
'EPIPE',
'EHOSTUNREACH',
'ENETUNREACH',
'ENOTFOUND',
'EAI_AGAIN',
]);
const TRANSIENT_MESSAGES =
/connection (is )?closed|connection refused|timed out|getaddrinfo|socket hang up/i;
/**
* Whether an error comes from a database or the network being down (and
* will go away by itself) rather than from the event or the code that
* handles it. Follows `cause`, as drivers wrap the original error.
*/
export function isTransientError(error: unknown): boolean {
for (let current = error, depth = 0; current && depth < 5; depth++) {
const e = current as {
name?: string;
code?: string;
message?: string;
cause?: unknown;
};
if (e.name && TRANSIENT_NAMES.test(e.name)) return true;
if (e.code && TRANSIENT_CODES.has(e.code)) return true;
if (e.message && TRANSIENT_MESSAGES.test(e.message)) return true;
current = e.cause;
}
return false;
}

View File

@@ -6,6 +6,7 @@ import { EventStore } from '@task-stream/api/shared/application';
import { RedisPubSub } from 'graphql-redis-subscriptions'; import { RedisPubSub } from 'graphql-redis-subscriptions';
import { EventDeserializer } from './event-store/deserializers/event.deserializer'; import { EventDeserializer } from './event-store/deserializers/event.deserializer';
import { EventEntity } from './event-store/entities/event.entity'; import { EventEntity } from './event-store/entities/event.entity';
import { EventPipelineStatus } from './event-store/event-pipeline.status';
import { EventStoreRelay } from './event-store/event-store.relay'; import { EventStoreRelay } from './event-store/event-store.relay';
import { EventStoreSignal } from './event-store/event-store.signal'; import { EventStoreSignal } from './event-store/event-store.signal';
import { import {
@@ -103,6 +104,7 @@ export class SharedInfrastructureModule {
EventStreamPublisher, EventStreamPublisher,
EventStoreRelay, EventStoreRelay,
EventsBridge, EventsBridge,
EventPipelineStatus,
], ],
exports: [ exports: [
EventStore, EventStore,
@@ -111,6 +113,7 @@ export class SharedInfrastructureModule {
REDIS_CLIENT, REDIS_CLIENT,
GRAPHQL_PUB_SUB, GRAPHQL_PUB_SUB,
EVENT_STREAM_OPTIONS, EVENT_STREAM_OPTIONS,
EventPipelineStatus,
], ],
}; };
} }

View File

@@ -33,6 +33,30 @@ export * from './lib/git/git-payloads';
export * from './lib/saved-filters/saved-filters'; export * from './lib/saved-filters/saved-filters';
export * from './lib/saved-filters/my-views'; export * from './lib/saved-filters/my-views';
export * from './lib/ports/my-views.repository'; export * from './lib/ports/my-views.repository';
export * from './lib/saved-filters/pins';
export * from './lib/ports/pins.repository';
export * from './lib/pins.service';
export * from './lib/alerts/alert-payloads';
export * from './lib/alerts/alerts';
export * from './lib/ports/alert-integrations.repository';
export * from './lib/alerts.service';
export * from './lib/follows/tree-follows';
export * from './lib/ports/tree-follows.repository';
export * from './lib/tree-follows.service';
export * from './lib/visits/issue-visits';
export * from './lib/ports/issue-visits.repository';
export * from './lib/issue-visits.service';
export * from './lib/reminders/issue-reminders';
export * from './lib/ports/issue-reminders.repository';
export * from './lib/issue-reminders.service';
export * from './lib/my-day/my-day';
export * from './lib/ports/my-days.repository';
export * from './lib/my-day.service';
export * from './lib/commands/reviews';
export * from './lib/commands/polls';
export * from './lib/commands/turn-comment-into-issue';
export * from './lib/sharing/release-notes-shares';
export * from './lib/ports/release-note-shares.repository';
export * from './lib/tracker-application.module'; export * from './lib/tracker-application.module';
export * from './lib/ports/presence.store'; export * from './lib/ports/presence.store';
export * from './lib/presence.service'; export * from './lib/presence.service';

View File

@@ -0,0 +1,86 @@
import { timingSafeEqual } from 'node:crypto';
import { CommandRunner } from '@task-stream/api/shared/application';
import { Injectable } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs';
import { ForbiddenError } from '@task-stream/api/shared/domain';
import { alertOf } from './alerts/alert-payloads';
import {
AlertIntegration,
AlertOutcome,
AlertSettings,
DisableAlertIntegrationCommand,
GetAlertIntegrationQuery,
ReceiveAlertCommand,
RotateAlertTokenCommand,
SaveAlertIntegrationCommand,
} from './alerts/alerts';
import { AlertIntegrationsRepository } from './ports/alert-integrations.repository';
import { FindProjectsRepository } from './ports/find-projects.repository';
/** What a monitoring tool sent to a project's alert URL. */
export interface AlertDelivery {
/** Project id or key, from the URL. */
project: string;
token: string;
body: unknown;
headers: Record<string, string | undefined>;
}
/** Alerts → bugs: the project's secret URL, and what arrives through it. */
@Injectable()
export class AlertsService {
constructor(
private readonly commands: CommandRunner,
private readonly queryBus: QueryBus,
private readonly findProjects: FindProjectsRepository,
private readonly integrations: AlertIntegrationsRepository,
) {}
get(viewerId: string, projectId: string): Promise<AlertIntegration> {
return this.queryBus.execute(
new GetAlertIntegrationQuery(viewerId, projectId),
);
}
save(
actorId: string,
projectId: string,
settings: AlertSettings,
): Promise<AlertIntegration> {
return this.commands.execute(
new SaveAlertIntegrationCommand(actorId, projectId, settings),
);
}
rotateToken(actorId: string, projectId: string): Promise<AlertIntegration> {
return this.commands.execute(
new RotateAlertTokenCommand(actorId, projectId),
);
}
disable(actorId: string, projectId: string): Promise<void> {
return this.commands.execute(
new DisableAlertIntegrationCommand(actorId, projectId),
);
}
/** Lets an alert in only with the project's current token. */
async receive(delivery: AlertDelivery): Promise<AlertOutcome> {
const project =
(await this.findProjects.findById(delivery.project)) ??
(await this.findProjects.findByKey(delivery.project.toUpperCase()));
const config = project ? await this.integrations.find(project.id) : null;
// One answer for an unknown project, the integration off or a bad token.
if (!project || !config || !sameToken(config.token, delivery.token))
throw new ForbiddenError('Unknown project, alerts off or bad token');
const alert = alertOf(delivery.body, delivery.headers);
if (!alert) return { action: 'ignored', issueKey: null };
return this.commands.execute(new ReceiveAlertCommand(project.id, alert));
}
}
function sameToken(expected: string, given: string): boolean {
const a = Buffer.from(expected);
const b = Buffer.from(given ?? '');
return a.length === b.length && timingSafeEqual(a, b);
}

View File

@@ -0,0 +1,112 @@
import { alertOf } from './alert-payloads';
describe('alertOf', () => {
it('reads a Sentry issue (internal integration), resolved too', () => {
const body = {
action: 'created',
data: {
issue: {
id: '42',
title: 'TypeError: x is undefined',
culprit: 'app/checkout.ts',
permalink: 'https://sentry.io/organizations/acme/issues/42/',
level: 'error',
},
},
};
const alert = alertOf(body, { 'sentry-hook-resource': 'issue' });
expect(alert).toMatchObject({
source: 'sentry',
fingerprint: 'sentry:42',
title: 'TypeError: x is undefined',
url: 'https://sentry.io/organizations/acme/issues/42/',
resolved: false,
});
expect(alert?.details).toContain('app/checkout.ts');
expect(
alertOf(
{ ...body, action: 'resolved' },
{ 'sentry-hook-resource': 'issue' },
)?.resolved,
).toBe(true);
});
it('reads a Sentry issue alert and the legacy webhook', () => {
expect(
alertOf(
{
action: 'triggered',
data: {
event: { issue_id: '7', title: 'Boom', web_url: 'https://s.io/7' },
triggered_rule: 'Errores nuevos',
},
},
{ 'sentry-hook-resource': 'event_alert' },
),
).toMatchObject({ fingerprint: 'sentry:7', title: 'Boom' });
expect(
alertOf({
id: '99',
project_name: 'web',
message: 'Boom',
url: 'https://s.io/99',
event: { title: 'ReferenceError: y' },
}),
).toMatchObject({ fingerprint: 'sentry:99', title: 'ReferenceError: y' });
});
it('reads Uptime Kuma: down opens, up resolves', () => {
const down = {
heartbeat: { status: 0, msg: 'timeout', time: '2026-10-17 10:00' },
monitor: { id: 3, name: 'API', url: 'https://api.acme.dev' },
msg: '[API] [🔴 Down] timeout',
};
expect(alertOf(down)).toMatchObject({
source: 'uptime-kuma',
fingerprint: 'uptime-kuma:3',
title: 'API no responde',
resolved: false,
});
expect(alertOf({ ...down, heartbeat: { status: 1 } })?.resolved).toBe(true);
});
it('reads Alertmanager and Grafana', () => {
expect(
alertOf({
status: 'firing',
groupKey: '{}:{alertname="HighLatency"}',
alerts: [
{
labels: { alertname: 'HighLatency', service: 'api' },
annotations: { summary: 'p95 por encima de 2 s' },
generatorURL: 'https://grafana.acme.dev/alerting/1',
},
],
}),
).toMatchObject({
source: 'alertmanager',
fingerprint: 'alertmanager:{}:{alertname="HighLatency"}',
title: 'p95 por encima de 2 s',
resolved: false,
});
});
it('takes a plain title, and nothing without one', () => {
expect(
alertOf({ title: 'Cola atascada', fingerprint: 'queue', resolved: true }),
).toMatchObject({
source: 'generic',
fingerprint: 'generic:queue',
resolved: true,
});
expect(alertOf({ title: 'Cola atascada' })?.fingerprint).toBe(
'generic:cola atascada',
);
expect(alertOf({ ping: true })).toBeNull();
expect(alertOf('nonsense')).toBeNull();
});
it('only links http(s) addresses', () => {
expect(alertOf({ title: 'x', url: 'javascript:alert(1)' })?.url).toBeNull();
});
});

View File

@@ -0,0 +1,199 @@
/*
* What monitoring tools send when something breaks, read into one shape.
* Each tool has its own payload; none of them is trusted beyond being text.
*/
export type AlertSource = 'sentry' | 'uptime-kuma' | 'alertmanager' | 'generic';
export interface Alert {
source: AlertSource;
/**
* The same problem gives the same fingerprint every time: repeats go to
* the ticket it opened instead of opening another.
*/
fingerprint: string;
title: string;
/** Markdown for the ticket's description. */
details: string;
url: string | null;
/** The tool says it is over (back up, resolved). */
resolved: boolean;
}
const MAX_TITLE = 200;
const MAX_DETAILS = 4000;
type Json = Record<string, unknown>;
const obj = (value: unknown): Json =>
value && typeof value === 'object' && !Array.isArray(value)
? (value as Json)
: {};
const str = (value: unknown): string =>
typeof value === 'string'
? value.trim()
: typeof value === 'number'
? String(value)
: '';
/** An http(s) link, or null: anything else is not offered as a link. */
const link = (value: unknown): string | null => {
const text = str(value);
return /^https?:\/\/\S+$/i.test(text) ? text.slice(0, 500) : null;
};
/** The alert in a payload, or null when it is not one (a test ping…). */
export function alertOf(
body: unknown,
headers: Record<string, string | undefined> = {},
): Alert | null {
const payload = obj(body);
const alert =
sentry(payload, headers) ??
uptimeKuma(payload) ??
alertmanager(payload) ??
generic(payload);
if (!alert?.title || !alert.fingerprint) return null;
return {
...alert,
title: alert.title.replace(/\s+/g, ' ').slice(0, MAX_TITLE),
details: alert.details.slice(0, MAX_DETAILS),
fingerprint: alert.fingerprint.slice(0, 300),
};
}
/**
* Sentry: an internal integration (header `sentry-hook-resource`: `issue`
* or `event_alert`) or the legacy webhooks plugin (`project_name`, `event`).
*/
function sentry(
payload: Json,
headers: Record<string, string | undefined>,
): Alert | null {
const resource = str(headers['sentry-hook-resource']);
const data = obj(payload['data']);
if (resource === 'issue') {
const issue = obj(data['issue']);
const id = str(issue['id']);
if (!id) return null;
const action = str(payload['action']);
return {
source: 'sentry',
fingerprint: `sentry:${id}`,
title: str(issue['title']),
details: lines([
str(issue['culprit']) && `En \`${str(issue['culprit'])}\``,
str(issue['level']) && `Nivel: ${str(issue['level'])}`,
]),
url: link(issue['permalink'] ?? issue['web_url']),
resolved: action === 'resolved',
};
}
if (resource === 'event_alert') {
const event = obj(data['event']);
const id = str(event['issue_id']) || str(event['event_id']);
if (!id) return null;
return {
source: 'sentry',
fingerprint: `sentry:${id}`,
title: str(event['title']) || str(event['message']),
details: lines([
str(event['culprit']) && `En \`${str(event['culprit'])}\``,
str(event['level']) && `Nivel: ${str(event['level'])}`,
str(data['triggered_rule']) && `Regla: ${str(data['triggered_rule'])}`,
]),
url: link(event['web_url'] ?? event['url']),
resolved: false,
};
}
if ('project_name' in payload && 'event' in payload) {
const event = obj(payload['event']);
const id = str(payload['id']) || str(event['event_id']);
if (!id) return null;
return {
source: 'sentry',
fingerprint: `sentry:${id}`,
title: str(event['title']) || str(payload['message']),
details: lines([
str(payload['culprit']) && `En \`${str(payload['culprit'])}\``,
str(payload['level']) && `Nivel: ${str(payload['level'])}`,
str(payload['project_name']) &&
`Proyecto de Sentry: ${str(payload['project_name'])}`,
]),
url: link(payload['url']),
resolved: false,
};
}
return null;
}
/** Uptime Kuma's webhook: `monitor` and `heartbeat` (status 0 down, 1 up). */
function uptimeKuma(payload: Json): Alert | null {
const monitor = obj(payload['monitor']);
const heartbeat = obj(payload['heartbeat']);
if (!('monitor' in payload) || !('heartbeat' in payload)) return null;
const name = str(monitor['name']);
const id = str(monitor['id']) || name;
if (!id) return null;
const up = heartbeat['status'] === 1;
return {
source: 'uptime-kuma',
fingerprint: `uptime-kuma:${id}`,
title: `${name || 'Un monitor'} no responde`,
details: lines([
str(heartbeat['msg']) && `Respuesta: ${str(heartbeat['msg'])}`,
str(monitor['url']) && `Vigila: ${str(monitor['url'])}`,
str(heartbeat['time']) && `Desde: ${str(heartbeat['time'])}`,
]),
url: link(monitor['url']),
resolved: up,
};
}
/** Prometheus Alertmanager and Grafana: `status` and `alerts[]`. */
function alertmanager(payload: Json): Alert | null {
if (!Array.isArray(payload['alerts'])) return null;
const first = obj(payload['alerts'][0]);
const labels = obj(first['labels']);
const annotations = obj(first['annotations']);
const key = str(payload['groupKey']) || str(first['fingerprint']);
if (!key) return null;
return {
source: 'alertmanager',
fingerprint: `alertmanager:${key}`,
title:
str(annotations['summary']) ||
str(labels['alertname']) ||
str(payload['title']),
details: lines([
str(annotations['description']) || str(payload['message']),
Object.keys(labels).length > 0 &&
`Etiquetas: ${Object.entries(labels)
.map(([k, v]) => `\`${k}=${str(v)}\``)
.join(' ')}`,
]),
url: link(first['generatorURL'] ?? payload['externalURL']),
resolved: str(payload['status']) === 'resolved',
};
}
/**
* Anything else that says what broke: `title` (or `message`), and
* optionally `fingerprint`, `description`, `url` and `resolved`.
*/
function generic(payload: Json): Alert | null {
const title = str(payload['title']) || str(payload['message']);
if (!title) return null;
return {
source: 'generic',
fingerprint: `generic:${str(payload['fingerprint']) || title.toLowerCase()}`,
title,
details: str(payload['description']),
url: link(payload['url']),
resolved:
payload['resolved'] === true || str(payload['status']) === 'resolved',
};
}
function lines(parts: (string | false | undefined)[]): string {
return parts.filter((part): part is string => !!part).join('\n\n');
}

View File

@@ -0,0 +1,220 @@
import {
CommandBus,
CommandHandler,
CqrsModule,
ICommandHandler,
} from '@nestjs/cqrs';
import { Test } from '@nestjs/testing';
import { CommandRunner } from '@task-stream/api/shared/application';
import {
IssuePriority,
IssueReadModel,
StatusCategory,
SYSTEM_ACTOR_ID,
} from '@task-stream/api/tracker/domain';
import { AddCommentCommand } from '../commands/add-comment.command';
import { CreateIssueCommand } from '../commands/create-issue.command';
import { WriteAccess } from '../commands/write-access';
import {
AlertIntegrationConfig,
AlertIntegrationsRepository,
AlertTrace,
} from '../ports/alert-integrations.repository';
import { FindIssuesRepository } from '../ports/find-issues.repository';
import { FindProjectsRepository } from '../ports/find-projects.repository';
import { ReadAccess } from '../queries/read-access';
import { Alert } from './alert-payloads';
import { ALERT_HANDLERS, ReceiveAlertCommand, REPEAT_QUIET_MS } from './alerts';
class InMemoryAlerts extends AlertIntegrationsRepository {
configs = new Map<string, AlertIntegrationConfig>();
traces = new Map<string, AlertTrace>();
async find(projectId: string) {
return this.configs.get(projectId) ?? null;
}
async save(config: AlertIntegrationConfig) {
this.configs.set(config.projectId, config);
}
async remove(projectId: string) {
this.configs.delete(projectId);
}
async trace(projectId: string, fingerprint: string) {
return this.traces.get(`${projectId}:${fingerprint}`) ?? null;
}
async saveTrace(trace: AlertTrace) {
this.traces.set(`${trace.projectId}:${trace.fingerprint}`, trace);
}
}
/** The tickets alerts open, and what TaskStream says on them. */
const issues = new Map<string, IssueReadModel>();
const created: CreateIssueCommand[] = [];
const comments: AddCommentCommand[] = [];
@CommandHandler(CreateIssueCommand)
class FakeCreate implements ICommandHandler<CreateIssueCommand> {
async execute(command: CreateIssueCommand) {
created.push(command);
const id = `i${created.length}`;
const key = `WEB-${created.length}`;
issues.set(id, {
id,
key,
statusCategory: StatusCategory.TODO,
trashedAt: null,
} as IssueReadModel);
return { id, key, version: 1 };
}
}
@CommandHandler(AddCommentCommand)
class FakeComment implements ICommandHandler<AddCommentCommand> {
async execute(command: AddCommentCommand) {
comments.push(command);
return { id: 'c', version: 1 };
}
}
const alert = (over: Partial<Alert> = {}): Alert => ({
source: 'uptime-kuma',
fingerprint: 'uptime-kuma:3',
title: 'API no responde',
details: 'timeout',
url: 'https://api.acme.dev',
resolved: false,
...over,
});
async function setup() {
issues.clear();
created.length = 0;
comments.length = 0;
const repo = new InMemoryAlerts();
await repo.save({
projectId: 'p1',
token: 't',
typeId: null,
priority: IssuePriority.HIGH,
createdAt: '2026-10-01T00:00:00Z',
});
const moduleRef = await Test.createTestingModule({
imports: [CqrsModule.forRoot()],
providers: [
...ALERT_HANDLERS,
FakeCreate,
FakeComment,
CommandRunner,
{ provide: AlertIntegrationsRepository, useValue: repo },
{
provide: FindProjectsRepository,
useValue: {
findById: async () => ({
id: 'p1',
settings: {
issueTypes: [
{ id: 'task', icon: 'task', archived: false },
{ id: 'bug', icon: 'bug', archived: false },
],
},
}),
},
},
{
provide: FindIssuesRepository,
useValue: { findById: async (id: string) => issues.get(id) ?? null },
},
{ provide: WriteAccess, useValue: {} },
{ provide: ReadAccess, useValue: {} },
],
}).compile();
await moduleRef.init();
const bus = moduleRef.get(CommandBus);
return {
repo,
receive: (a: Alert) => bus.execute(new ReceiveAlertCommand('p1', a)),
};
}
describe('alerts → bugs', () => {
it('opens a bug as TaskStream, with the bug type and the priority set', async () => {
const { receive } = await setup();
expect(await receive(alert())).toEqual({
action: 'created',
issueKey: 'WEB-1',
});
const [command] = created;
expect(command.actorId).toBe(SYSTEM_ACTOR_ID);
expect(command.type).toBe('bug');
expect(command.details.priority).toBe(IssuePriority.HIGH);
expect(command.details.labels).toEqual(['alerta']);
expect(command.details.description).toContain('Uptime Kuma');
});
it('sends repeats to the open bug, telling it at most every half hour', async () => {
const { receive, repo } = await setup();
await receive(alert());
expect(await receive(alert())).toEqual({
action: 'repeated',
issueKey: 'WEB-1',
});
// Just told when it opened: this repeat stays quiet.
expect(comments).toHaveLength(0);
const trace = await repo.trace('p1', 'uptime-kuma:3');
if (!trace) throw new Error('no trace');
expect(trace.count).toBe(2);
await repo.saveTrace({
...trace,
notedAt: new Date(Date.now() - REPEAT_QUIET_MS - 1000).toISOString(),
});
await receive(alert());
expect(comments).toHaveLength(1);
expect(comments[0].body).toContain('3 veces');
expect(created).toHaveLength(1);
});
it('says on the bug when it is resolved, and ignores one with nothing open', async () => {
const { receive } = await setup();
expect(await receive(alert({ resolved: true }))).toEqual({
action: 'ignored',
issueKey: null,
});
await receive(alert());
expect(await receive(alert({ resolved: true }))).toEqual({
action: 'resolved',
issueKey: 'WEB-1',
});
expect(comments[0].body).toContain('se ha resuelto');
});
it('opens a new bug when the old one is closed, naming it', async () => {
const { receive } = await setup();
await receive(alert());
issues.set('i1', {
...(issues.get('i1') as IssueReadModel),
statusCategory: StatusCategory.DONE,
});
expect(await receive(alert())).toEqual({
action: 'created',
issueKey: 'WEB-2',
});
expect(created[1].details.description).toContain('Ya pasó antes: WEB-1');
});
it('sends a repeat to a bug not yet in the read model', async () => {
const { receive } = await setup();
await receive(alert());
issues.clear();
expect(await receive(alert())).toEqual({
action: 'repeated',
issueKey: 'WEB-1',
});
expect(created).toHaveLength(1);
});
it('opens one bug when the same alert arrives twice at once', async () => {
const { receive } = await setup();
const both = await Promise.all([receive(alert()), receive(alert())]);
expect(both.map((o) => o.action).sort()).toEqual(['created', 'repeated']);
expect(created).toHaveLength(1);
});
});

View File

@@ -0,0 +1,357 @@
import { randomBytes } from 'node:crypto';
import { CommandRunner } from '@task-stream/api/shared/application';
import {
Command,
CommandHandler,
ICommandHandler,
IQueryHandler,
Query,
QueryHandler,
} from '@nestjs/cqrs';
import { assertThat, NotFoundError } from '@task-stream/api/shared/domain';
import {
IssuePriority,
ProjectRole,
StatusCategory,
SYSTEM_ACTOR_ID,
} from '@task-stream/api/tracker/domain';
import { AddCommentCommand } from '../commands/add-comment.command';
import { CommandResult } from '../commands/command-result';
import { CreateIssueCommand } from '../commands/create-issue.command';
import { WriteAccess } from '../commands/write-access';
import {
AlertIntegrationConfig,
AlertIntegrationsRepository,
} from '../ports/alert-integrations.repository';
import { FindIssuesRepository } from '../ports/find-issues.repository';
import { FindProjectsRepository } from '../ports/find-projects.repository';
import { ReadAccess } from '../queries/read-access';
import { Alert, AlertSource } from './alert-payloads';
/*
* Alerts → bugs: monitoring tools (Sentry, Uptime Kuma, Grafana…) call a
* project's secret URL; a new problem opens a bug, a repeat goes to the bug
* it opened while that one is open, and «resolved» is said on it. Nobody's
* ticket: TaskStream opens and comments them.
*/
export interface AlertIntegration {
enabled: boolean;
/** Only for whoever manages the project. */
token: string | null;
typeId: string | null;
priority: IssuePriority;
}
export interface AlertSettings {
typeId?: string | null;
priority?: IssuePriority;
}
export type AlertOutcome =
| { action: 'created' | 'repeated' | 'resolved'; issueKey: string }
| { action: 'ignored'; issueKey: null };
/** Repeats tell the ticket at most this often. */
export const REPEAT_QUIET_MS = 30 * 60_000;
const SOURCE_NAME: Record<AlertSource, string> = {
sentry: 'Sentry',
'uptime-kuma': 'Uptime Kuma',
alertmanager: 'Alertmanager',
generic: 'la alerta',
};
const OFF: AlertIntegration = {
enabled: false,
token: null,
typeId: null,
priority: IssuePriority.HIGH,
};
const newToken = () => randomBytes(24).toString('hex');
/** Turns it on, or changes what it opens (the token stays). */
export class SaveAlertIntegrationCommand extends Command<AlertIntegration> {
constructor(
public readonly actorId: string,
public readonly projectId: string,
public readonly settings: AlertSettings,
) {
super();
}
}
/** A new URL; the old one stops working at once. */
export class RotateAlertTokenCommand extends Command<AlertIntegration> {
constructor(
public readonly actorId: string,
public readonly projectId: string,
) {
super();
}
}
export class DisableAlertIntegrationCommand extends Command<void> {
constructor(
public readonly actorId: string,
public readonly projectId: string,
) {
super();
}
}
/** An alert already let in (its token checked by the caller). */
export class ReceiveAlertCommand extends Command<AlertOutcome> {
constructor(
public readonly projectId: string,
public readonly alert: Alert,
) {
super();
}
}
export class GetAlertIntegrationQuery extends Query<AlertIntegration> {
constructor(
public readonly viewerId: string,
public readonly projectId: string,
) {
super();
}
}
/** What owners and admins see: the token included. */
const view = (config: AlertIntegrationConfig): AlertIntegration => ({
enabled: true,
token: config.token,
typeId: config.typeId,
priority: config.priority,
});
@CommandHandler(SaveAlertIntegrationCommand)
export class SaveAlertIntegrationCommandHandler
implements ICommandHandler<SaveAlertIntegrationCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly findProjects: FindProjectsRepository,
private readonly integrations: AlertIntegrationsRepository,
) {}
async execute(
command: SaveAlertIntegrationCommand,
): Promise<AlertIntegration> {
(await this.access.project(command.projectId)).assertCanManage(
command.actorId,
);
const { typeId, priority } = command.settings;
if (typeId) {
const project = await this.findProjects.findById(command.projectId);
assertThat(
!!project?.settings.issueTypes.some(
(t) => t.id === typeId && !t.archived,
),
`Unknown ticket type: ${typeId}`,
);
}
const current = await this.integrations.find(command.projectId);
const config: AlertIntegrationConfig = {
projectId: command.projectId,
token: current?.token ?? newToken(),
typeId: typeId === undefined ? (current?.typeId ?? null) : typeId,
priority: priority ?? current?.priority ?? IssuePriority.HIGH,
createdAt: current?.createdAt ?? new Date().toISOString(),
};
await this.integrations.save(config);
return view(config);
}
}
@CommandHandler(RotateAlertTokenCommand)
export class RotateAlertTokenCommandHandler
implements ICommandHandler<RotateAlertTokenCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly integrations: AlertIntegrationsRepository,
) {}
async execute(command: RotateAlertTokenCommand): Promise<AlertIntegration> {
(await this.access.project(command.projectId)).assertCanManage(
command.actorId,
);
const current = await this.integrations.find(command.projectId);
if (!current)
throw new NotFoundError('Alert integration', command.projectId);
const rotated = { ...current, token: newToken() };
await this.integrations.save(rotated);
return view(rotated);
}
}
@CommandHandler(DisableAlertIntegrationCommand)
export class DisableAlertIntegrationCommandHandler
implements ICommandHandler<DisableAlertIntegrationCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly integrations: AlertIntegrationsRepository,
) {}
async execute(command: DisableAlertIntegrationCommand): Promise<void> {
(await this.access.project(command.projectId)).assertCanManage(
command.actorId,
);
await this.integrations.remove(command.projectId);
}
}
@CommandHandler(ReceiveAlertCommand)
export class ReceiveAlertCommandHandler
implements ICommandHandler<ReceiveAlertCommand>
{
/** One alert of a project after another: two at once open one ticket. */
private readonly queues = new Map<string, Promise<unknown>>();
constructor(
private readonly integrations: AlertIntegrationsRepository,
private readonly findProjects: FindProjectsRepository,
private readonly findIssues: FindIssuesRepository,
private readonly commands: CommandRunner,
) {}
execute(command: ReceiveAlertCommand): Promise<AlertOutcome> {
const previous = this.queues.get(command.projectId) ?? Promise.resolve();
const next = previous.catch(() => null).then(() => this.receive(command));
this.queues.set(command.projectId, next);
void next.finally(() => {
if (this.queues.get(command.projectId) === next)
this.queues.delete(command.projectId);
});
return next;
}
private async receive({
projectId,
alert,
}: ReceiveAlertCommand): Promise<AlertOutcome> {
const config = await this.integrations.find(projectId);
if (!config) throw new NotFoundError('Alert integration', projectId);
const now = new Date().toISOString();
const trace = await this.integrations.trace(projectId, alert.fingerprint);
const opened = trace ? await this.findIssues.findById(trace.issueId) : null;
// Not in the read model yet: it was opened a moment ago, so it is open.
const open = !trace
? null
: !opened
? { id: trace.issueId, key: trace.issueKey }
: !opened.trashedAt &&
opened.statusCategory !== StatusCategory.DONE &&
opened.statusCategory !== StatusCategory.CANCELLED
? opened
: null;
const source = SOURCE_NAME[alert.source];
if (trace && open) {
if (alert.resolved) {
await this.comment(open.id, `✅ Según ${source}, se ha resuelto.`);
await this.integrations.saveTrace({ ...trace, notedAt: now });
return { action: 'resolved', issueKey: open.key };
}
const count = trace.count + 1;
const quiet = Date.now() - Date.parse(trace.notedAt) < REPEAT_QUIET_MS;
if (!quiet)
await this.comment(
open.id,
`🔁 Ha vuelto a pasar: ${count} veces desde ${trace.firstAt.slice(0, 16).replace('T', ' ')} (UTC).`,
);
await this.integrations.saveTrace({
...trace,
count,
lastAt: now,
notedAt: quiet ? trace.notedAt : now,
});
return { action: 'repeated', issueKey: open.key };
}
// Over before anyone looked, or about a ticket already closed.
if (alert.resolved) return { action: 'ignored', issueKey: null };
const project = await this.findProjects.findById(projectId);
const types = (project?.settings.issueTypes ?? []).filter(
(t) => !t.archived,
);
const type =
types.find((t) => t.id === config.typeId) ??
types.find((t) => t.icon === 'bug') ??
types[0];
if (!type) throw new NotFoundError('Ticket type', config.typeId ?? 'bug');
const description = [
alert.details,
alert.url && `[Ver en ${source}](${alert.url})`,
opened && `Ya pasó antes: ${opened.key}.`,
`_Abierto por una alerta de ${source}._`,
]
.filter(Boolean)
.join('\n\n');
const result: CommandResult = await this.commands.execute(
new CreateIssueCommand(
SYSTEM_ACTOR_ID,
projectId,
type.id,
alert.title,
{ description, priority: config.priority, labels: ['alerta'] },
null,
null,
null,
null,
false,
),
);
await this.integrations.saveTrace({
projectId,
fingerprint: alert.fingerprint,
issueId: result.id,
issueKey: result.key ?? result.id,
count: 1,
firstAt: now,
lastAt: now,
notedAt: now,
});
return { action: 'created', issueKey: result.key ?? result.id };
}
private comment(issueId: string, body: string): Promise<CommandResult> {
return this.commands.execute(
new AddCommentCommand(SYSTEM_ACTOR_ID, issueId, body),
);
}
}
@QueryHandler(GetAlertIntegrationQuery)
export class GetAlertIntegrationQueryHandler
implements IQueryHandler<GetAlertIntegrationQuery, AlertIntegration>
{
constructor(
private readonly access: ReadAccess,
private readonly integrations: AlertIntegrationsRepository,
) {}
async execute(query: GetAlertIntegrationQuery): Promise<AlertIntegration> {
const role = await this.access.assertSeesWholeProject(
query.projectId,
query.viewerId,
);
const config = await this.integrations.find(query.projectId);
if (!config) return OFF;
const manages = role === ProjectRole.OWNER || role === ProjectRole.ADMIN;
return { ...view(config), token: manages ? config.token : null };
}
}
export const ALERT_HANDLERS = [
SaveAlertIntegrationCommandHandler,
RotateAlertTokenCommandHandler,
DisableAlertIntegrationCommandHandler,
ReceiveAlertCommandHandler,
GetAlertIntegrationQueryHandler,
];

View File

@@ -9,6 +9,7 @@ import {
ProjectChange, ProjectChange,
ReleaseChange, ReleaseChange,
SprintChange, SprintChange,
Typing,
} from './ports/change-feed'; } from './ports/change-feed';
import { CanViewProjectQuery } from './queries/can-view-project.query'; import { CanViewProjectQuery } from './queries/can-view-project.query';
import { GetIssueQuery } from './queries/get-issue.query'; import { GetIssueQuery } from './queries/get-issue.query';
@@ -53,6 +54,15 @@ export class ChangesService {
return this.changeFeed.comments(issueId); return this.changeFeed.comments(issueId);
} }
/** Who is writing on the ticket (the client leaves itself out). */
async watchTyping(
viewerId: string,
issueId: string,
): Promise<AsyncIterableIterator<Typing>> {
await this.queryBus.execute(new GetIssueQuery(viewerId, issueId)); // access check
return this.changeFeed.typing(issueId);
}
async watchActivity( async watchActivity(
viewerId: string, viewerId: string,
projectId: string, projectId: string,

View File

@@ -1,6 +1,9 @@
import { CommandHandler, EventPublisher, ICommandHandler } from '@nestjs/cqrs'; import { CommandHandler, EventPublisher, ICommandHandler } from '@nestjs/cqrs';
import { BusinessRuleError } from '@task-stream/api/shared/domain'; import { BusinessRuleError } from '@task-stream/api/shared/domain';
import { CommentFactory } from '@task-stream/api/tracker/domain'; import {
CommentFactory,
SYSTEM_ACTOR_ID,
} from '@task-stream/api/tracker/domain';
import { AddCommentCommand } from './add-comment.command'; import { AddCommentCommand } from './add-comment.command';
import { CommandResult, ack } from './command-result'; import { CommandResult, ack } from './command-result';
import { WriteAccess } from './write-access'; import { WriteAccess } from './write-access';
@@ -16,9 +19,16 @@ export class AddCommentCommandHandler
) {} ) {}
async execute(command: AddCommentCommand): Promise<CommandResult> { async execute(command: AddCommentCommand): Promise<CommandResult> {
const { issue } = await this.access.issueForReporter( // TaskStream itself (alerts that repeat) is no member; only internal
command.issueId, // commands act as it, never a request from outside.
command.actorId, const issue =
command.actorId === SYSTEM_ACTOR_ID
? await this.access.issue(command.issueId)
: (await this.access.issueForReporter(command.issueId, command.actorId))
.issue;
if (issue.trashedAt)
throw new BusinessRuleError(
`${issue.key} is in the trash: restore it to change it`,
); );
const comment = this.commentFactory.create({ const comment = this.commentFactory.create({
issueId: issue.id, issueId: issue.id,
@@ -28,6 +38,7 @@ export class AddCommentCommandHandler
replyTo: command.replyTo replyTo: command.replyTo
? await this.threadOf(command.replyTo, issue.id) ? await this.threadOf(command.replyTo, issue.id)
: null, : null,
poll: command.poll,
}); });
this.eventPublisher.mergeObjectContext(comment); this.eventPublisher.mergeObjectContext(comment);

View File

@@ -8,6 +8,8 @@ export class AddCommentCommand extends Command<CommandResult> {
public readonly body: string, public readonly body: string,
/** Comment it answers; a reply to a reply joins the same thread. */ /** Comment it answers; a reply to a reply joins the same thread. */
public readonly replyTo: string | null = null, public readonly replyTo: string | null = null,
/** A quick poll's options (2–6), if any. */
public readonly poll: string[] | null = null,
) { ) {
super(); super();
} }

View File

@@ -1,4 +1,9 @@
import { ReactToCommentCommandHandler } from './react-to-comment.command-handler'; import { ReactToCommentCommandHandler } from './react-to-comment.command-handler';
import { MarkDecisionCommandHandler } from './mark-decision.command-handler';
import { ResolveThreadCommandHandler } from './resolve-thread.command-handler';
import { REVIEW_HANDLERS } from './reviews';
import { POLL_HANDLERS } from './polls';
import { TURN_INTO_ISSUE_HANDLERS } from './turn-comment-into-issue';
import { VoteIssueCommandHandler } from './vote-issue.command-handler'; import { VoteIssueCommandHandler } from './vote-issue.command-handler';
import { CreateProjectCommandHandler } from './create-project.command-handler'; import { CreateProjectCommandHandler } from './create-project.command-handler';
import { UpdateProjectCommandHandler } from './update-project.command-handler'; import { UpdateProjectCommandHandler } from './update-project.command-handler';
@@ -46,6 +51,11 @@ import {
export const COMMAND_HANDLERS = [ export const COMMAND_HANDLERS = [
VoteIssueCommandHandler, VoteIssueCommandHandler,
ReactToCommentCommandHandler, ReactToCommentCommandHandler,
MarkDecisionCommandHandler,
ResolveThreadCommandHandler,
...REVIEW_HANDLERS,
...POLL_HANDLERS,
...TURN_INTO_ISSUE_HANDLERS,
CreateProjectCommandHandler, CreateProjectCommandHandler,
UpdateProjectCommandHandler, UpdateProjectCommandHandler,
UpdateProjectSettingsCommandHandler, UpdateProjectSettingsCommandHandler,

View File

@@ -15,10 +15,12 @@ import {
import { import {
Comment, Comment,
Issue, Issue,
IssueLinkType,
IssueStatus, IssueStatus,
Project, Project,
IssuePriority, IssuePriority,
IssueType, IssueType,
ReviewVerdict,
ProjectRole, ProjectRole,
TRACKER_FACTORIES, TRACKER_FACTORIES,
defaultProjectSettings, defaultProjectSettings,
@@ -77,6 +79,15 @@ import { UserDirectory } from '../ports/user-directory';
import { AttachmentStorage } from '../ports/attachment-storage'; import { AttachmentStorage } from '../ports/attachment-storage';
import { AddCommentCommand } from './add-comment.command'; import { AddCommentCommand } from './add-comment.command';
import { ReactToCommentCommand } from './react-to-comment.command'; import { ReactToCommentCommand } from './react-to-comment.command';
import { MarkDecisionCommand } from './mark-decision.command';
import { ResolveThreadCommand } from './resolve-thread.command';
import { ClosePollCommand, VotePollCommand } from './polls';
import { TurnCommentIntoIssueCommand } from './turn-comment-into-issue';
import {
AnswerReviewCommand,
CancelReviewCommand,
RequestReviewCommand,
} from './reviews';
import { UpdateProjectCommand } from './update-project.command'; import { UpdateProjectCommand } from './update-project.command';
import { VoteIssueCommand } from './vote-issue.command'; import { VoteIssueCommand } from './vote-issue.command';
import { AddProjectMemberCommand } from './add-project-member.command'; import { AddProjectMemberCommand } from './add-project-member.command';
@@ -916,6 +927,255 @@ describe('tracker commands (event sourced)', () => {
).rejects.toThrow(ForbiddenError); ).rejects.toThrow(ForbiddenError);
}); });
it('lets the team mark a comment as a decision, and only the team', async () => {
const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('dev', projectId, IssueType.TASK, 'Caché', {}),
);
const comment = await run(
new AddCommentCommand('qa', issue.id, 'Usamos Redis'),
);
await run(new MarkDecisionCommand('dev', comment.id, true));
// Twice is still once.
const again = await run(new MarkDecisionCommand('dev', comment.id, true));
expect(again.version).toBe(2);
expect((await rehydrator.rehydrate(comment.id, Comment)).decision).toBe(
true,
);
// A viewer reads the decisions but does not make them.
await expect(
run(new MarkDecisionCommand('pm', comment.id, false)),
).rejects.toThrow(ForbiddenError);
await run(new MarkDecisionCommand('owner', comment.id, false));
expect((await rehydrator.rehydrate(comment.id, Comment)).decision).toBe(
false,
);
});
it('makes a ticket of a comment, as a subtask or linked, and marks the comment', async () => {
const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('dev', projectId, IssueType.BUG, 'Pago', {}),
);
const comment = await run(
new AddCommentCommand('qa', issue.id, 'También falla en **Android**'),
);
// Viewers comment and react; making tickets is for the team.
await expect(
run(
new TurnCommentIntoIssueCommand(
'pm',
comment.id,
'Android',
IssueType.BUG,
false,
),
),
).rejects.toThrow(ForbiddenError);
const linked = await run(
new TurnCommentIntoIssueCommand(
'dev',
comment.id,
'Falla en Android',
IssueType.BUG,
false,
),
);
const sub = await run(
new TurnCommentIntoIssueCommand(
'dev',
comment.id,
'Probar en Android',
IssueType.TASK,
true,
),
);
const fromLink = await rehydrator.rehydrate(linked.id, Issue);
expect(fromLink.title).toBe('Falla en Android');
expect(fromLink.description).toBe(
'También falla en **Android**\n\n---\n_Sale de un comentario de user qa en TS-1._',
);
expect(fromLink.links).toEqual([
expect.objectContaining({
type: IssueLinkType.RELATES_TO,
targetIssueId: issue.id,
}),
]);
expect((await rehydrator.rehydrate(sub.id, Issue)).parentId).toBe(issue.id);
expect((await rehydrator.rehydrate(comment.id, Comment)).spawned).toEqual([
{ id: linked.id, key: 'TS-2' },
{ id: sub.id, key: 'TS-3' },
]);
});
it('takes votes in a comment poll and keeps the winner as a decision', async () => {
const { run, rehydrator, store } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('dev', projectId, IssueType.TASK, 'Pagos', {}),
);
await expect(
run(new AddCommentCommand('dev', issue.id, '¿Cuál?', null, ['Solo'])),
).rejects.toThrow(ValidationError);
const poll = await run(
new AddCommentCommand('dev', issue.id, '¿Cuál?', null, [
' Stripe ',
'Redsys',
]),
);
await run(new VotePollCommand('qa', poll.id, 0));
await run(new VotePollCommand('pm', poll.id, 1));
await run(new VotePollCommand('pm', poll.id, 0));
await run(new VotePollCommand('owner', poll.id, 1));
await expect(run(new VotePollCommand('qa', poll.id, 5))).rejects.toThrow(
ValidationError,
);
// Only whoever started it (or an admin) closes it.
await expect(run(new ClosePollCommand('qa', poll.id))).rejects.toThrow(
ForbiddenError,
);
await run(new ClosePollCommand('dev', poll.id));
const closed = await rehydrator.rehydrate(poll.id, Comment);
expect([closed.poll, closed.pollClosed, closed.pollWinner]).toEqual([
['Stripe', 'Redsys'],
true,
0,
]);
await expect(run(new VotePollCommand('qa', poll.id, 1))).rejects.toThrow(
BusinessRuleError,
);
const decided = store.events.find(
(e) =>
e.type === 'CommentAddedEvent' &&
(e.data as { comment: { body: string } }).comment.body.startsWith(
'Decidido',
),
);
expect((decided?.data as { comment: { body: string } }).comment.body).toBe(
'Decidido: **Stripe** (2 de 3 votos)',
);
expect(
(await rehydrator.rehydrate(decided?.streamId ?? '', Comment)).decision,
).toBe(true);
});
it('asks a teammate to review a ticket, who answers it', async () => {
const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('dev', projectId, IssueType.TASK, 'Login', {}),
);
await run(
new RequestReviewCommand('dev', issue.id, 'qa', ' Mira el móvil '),
);
// Not oneself, not twice the same open one, not outsiders.
await expect(
run(new RequestReviewCommand('dev', issue.id, 'dev')),
).rejects.toThrow(ValidationError);
await expect(
run(new RequestReviewCommand('dev', issue.id, 'qa')),
).rejects.toThrow(BusinessRuleError);
await expect(
run(new RequestReviewCommand('dev', issue.id, 'stranger')),
).rejects.toThrow(BusinessRuleError);
// A viewer can be asked and answer, but not ask.
await run(new RequestReviewCommand('dev', issue.id, 'pm'));
await expect(
run(new RequestReviewCommand('pm', issue.id, 'qa')),
).rejects.toThrow(ForbiddenError);
let reviews = (await rehydrator.rehydrate(issue.id, Issue)).reviews;
expect(reviews.map((r) => [r.reviewerId, r.note, r.verdict])).toEqual([
['qa', 'Mira el móvil', null],
['pm', null, null],
]);
const [forQa, forPm] = reviews;
await expect(
run(
new AnswerReviewCommand(
'dev',
issue.id,
forQa.id,
ReviewVerdict.APPROVED,
),
),
).rejects.toThrow(ForbiddenError);
await run(
new AnswerReviewCommand(
'qa',
issue.id,
forQa.id,
ReviewVerdict.CHANGES,
'Falla en iOS',
),
);
await expect(
run(
new AnswerReviewCommand(
'qa',
issue.id,
forQa.id,
ReviewVerdict.APPROVED,
),
),
).rejects.toThrow(BusinessRuleError);
await run(new CancelReviewCommand('dev', issue.id, forPm.id));
reviews = (await rehydrator.rehydrate(issue.id, Issue)).reviews;
expect(reviews.map((r) => [r.reviewerId, r.verdict, r.answer])).toEqual([
['qa', ReviewVerdict.CHANGES, 'Falla en iOS'],
]);
});
it('settles a conversation, keeping its conclusion as a decision', async () => {
const { run, rehydrator, store } = await setup();
const projectId = await projectWithTeam(run);
const issue = await run(
new CreateIssueCommand('dev', projectId, IssueType.TASK, 'Pagos', {}),
);
const thread = await run(
new AddCommentCommand('qa', issue.id, '¿Stripe o Redsys?'),
);
const reply = await run(
new AddCommentCommand('dev', issue.id, 'Stripe', thread.id),
);
// A reply is not a conversation; a viewer does not settle one.
await expect(
run(new ResolveThreadCommand('dev', reply.id, true)),
).rejects.toThrow(BusinessRuleError);
await expect(
run(new ResolveThreadCommand('pm', thread.id, true)),
).rejects.toThrow(ForbiddenError);
await run(
new ResolveThreadCommand('dev', thread.id, true, ' Vamos con Stripe '),
);
expect((await rehydrator.rehydrate(thread.id, Comment)).resolved).toBe(
true,
);
const conclusion = store.events.find(
(e) =>
e.type === 'CommentAddedEvent' &&
(e.data as { comment: { body: string } }).comment.body ===
'Vamos con Stripe',
);
expect(conclusion).toBeDefined();
const added = await rehydrator.rehydrate(
conclusion?.streamId ?? '',
Comment,
);
expect(added).toMatchObject({ replyTo: thread.id, decision: true });
await run(new ResolveThreadCommand('owner', thread.id, false));
expect((await rehydrator.rehydrate(thread.id, Comment)).resolved).toBe(
false,
);
});
it('takes votes from members, and from anyone once it is public', async () => { it('takes votes from members, and from anyone once it is public', async () => {
const { run, rehydrator } = await setup(); const { run, rehydrator } = await setup();
const projectId = await projectWithTeam(run); const projectId = await projectWithTeam(run);

View File

@@ -0,0 +1,20 @@
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { CommandResult, ack } from './command-result';
import { MarkDecisionCommand } from './mark-decision.command';
import { WriteAccess } from './write-access';
/** The team decides: whoever can change the ticket marks its decisions. */
@CommandHandler(MarkDecisionCommand)
export class MarkDecisionCommandHandler
implements ICommandHandler<MarkDecisionCommand>
{
constructor(private readonly access: WriteAccess) {}
async execute(command: MarkDecisionCommand): Promise<CommandResult> {
const comment = await this.access.comment(command.commentId);
await this.access.issueForContributor(comment.issueId, command.actorId);
comment.markDecision(command.actorId, command.on);
await comment.commitAndWait();
return ack(comment);
}
}

View File

@@ -0,0 +1,13 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
/** Marks a comment as a decision of its ticket (`on`) or unmarks it. */
export class MarkDecisionCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly commentId: string,
public readonly on: boolean,
) {
super();
}
}

View File

@@ -0,0 +1,108 @@
import {
Command,
CommandHandler,
EventPublisher,
ICommandHandler,
} from '@nestjs/cqrs';
import { ForbiddenError } from '@task-stream/api/shared/domain';
import { CommentFactory, ProjectRole } from '@task-stream/api/tracker/domain';
import { CommandResult, ack } from './command-result';
import { WriteAccess } from './write-access';
/*
* A quick poll in a comment («¿Stripe o Redsys?»): members vote, one vote
* each; whoever started it closes it, and the winner can stay as a decision.
*/
export class VotePollCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly commentId: string,
/** Null takes the vote back. */
public readonly option: number | null,
) {
super();
}
}
export class ClosePollCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly commentId: string,
/** Keep the winner as a decision of the ticket (a reply marked so). */
public readonly decide = true,
) {
super();
}
}
/** Voting is for members, viewers included: like reacting. */
@CommandHandler(VotePollCommand)
export class VotePollCommandHandler
implements ICommandHandler<VotePollCommand>
{
constructor(private readonly access: WriteAccess) {}
async execute(command: VotePollCommand): 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}`,
);
this.access.assertSees(
project,
await this.access.issue(comment.issueId),
command.actorId,
);
comment.votePoll(command.actorId, command.option);
await comment.commitAndWait();
return ack(comment);
}
}
@CommandHandler(ClosePollCommand)
export class ClosePollCommandHandler
implements ICommandHandler<ClosePollCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly commentFactory: CommentFactory,
private readonly eventPublisher: EventPublisher,
) {}
async execute(command: ClosePollCommand): 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}`,
);
const role = project.roleOf(command.actorId);
const voters = Object.keys(comment.pollVotes).length;
const winner = comment.closePoll(
command.actorId,
role === ProjectRole.OWNER || role === ProjectRole.ADMIN,
);
await comment.commitAndWait();
if (command.decide && winner !== null && comment.poll) {
const votes = Object.values(comment.pollVotes).filter(
(v) => v === winner,
).length;
// The result, as a decision above the ticket.
const decision = this.commentFactory.create({
issueId: comment.issueId,
projectId: comment.projectId,
authorId: command.actorId,
body: `Decidido: **${comment.poll[winner]}** (${votes} de ${voters} ${voters === 1 ? 'voto' : 'votos'})`,
replyTo: comment.replyTo ?? comment.id,
});
decision.markDecision(command.actorId, true);
this.eventPublisher.mergeObjectContext(decision);
await decision.commitAndWait();
}
return ack(comment);
}
}
export const POLL_HANDLERS = [VotePollCommandHandler, ClosePollCommandHandler];

View File

@@ -0,0 +1,44 @@
import { CommandHandler, EventPublisher, ICommandHandler } from '@nestjs/cqrs';
import { BusinessRuleError } from '@task-stream/api/shared/domain';
import { CommentFactory } from '@task-stream/api/tracker/domain';
import { CommandResult, ack } from './command-result';
import { ResolveThreadCommand } from './resolve-thread.command';
import { WriteAccess } from './write-access';
/** The team settles its conversations: whoever can change the ticket. */
@CommandHandler(ResolveThreadCommand)
export class ResolveThreadCommandHandler
implements ICommandHandler<ResolveThreadCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly commentFactory: CommentFactory,
private readonly eventPublisher: EventPublisher,
) {}
async execute(command: ResolveThreadCommand): Promise<CommandResult> {
const thread = await this.access.comment(command.commentId);
if (thread.replyTo)
throw new BusinessRuleError(
'Only a conversation is resolved, not a reply',
);
await this.access.issueForContributor(thread.issueId, command.actorId);
const conclusion = command.conclusion?.trim();
if (command.resolved && conclusion && !thread.resolved) {
// What was settled stays as a decision, shown above the ticket.
const reply = this.commentFactory.create({
issueId: thread.issueId,
projectId: thread.projectId,
authorId: command.actorId,
body: conclusion,
replyTo: thread.id,
});
reply.markDecision(command.actorId, true);
this.eventPublisher.mergeObjectContext(reply);
await reply.commitAndWait();
}
thread.resolveThread(command.actorId, command.resolved);
await thread.commitAndWait();
return ack(thread);
}
}

View File

@@ -0,0 +1,17 @@
import { Command } from '@nestjs/cqrs';
import { CommandResult } from './command-result';
/**
* Settles a conversation (`resolved`) or reopens it. A conclusion, if
* given, is added as a reply marked as a decision before it closes.
*/
export class ResolveThreadCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly commentId: string,
public readonly resolved: boolean,
public readonly conclusion: string | null = null,
) {
super();
}
}

View File

@@ -0,0 +1,132 @@
import { randomUUID } from 'node:crypto';
import { Command, CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import {
BusinessRuleError,
ForbiddenError,
} from '@task-stream/api/shared/domain';
import { ProjectRole, ReviewVerdict } from '@task-stream/api/tracker/domain';
import { CommandResult, ack } from './command-result';
import { WriteAccess } from './write-access';
/*
* «Ana, can you review this?»: a request on a ticket that the reviewer
* answers (all good, or changes wanted). Events of the ticket, so they show
* in its history and in the activity feed.
*/
export class RequestReviewCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,
public readonly reviewerId: string,
public readonly note: string | null = null,
) {
super();
}
}
export class AnswerReviewCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,
public readonly reviewId: string,
public readonly verdict: ReviewVerdict,
public readonly answer: string | null = null,
) {
super();
}
}
export class CancelReviewCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly issueId: string,
public readonly reviewId: string,
) {
super();
}
}
/** The team asks for reviews: whoever can change the ticket. */
@CommandHandler(RequestReviewCommand)
export class RequestReviewCommandHandler
implements ICommandHandler<RequestReviewCommand>
{
constructor(private readonly access: WriteAccess) {}
async execute(command: RequestReviewCommand): Promise<CommandResult> {
const { issue, project } = await this.access.issueForContributor(
command.issueId,
command.actorId,
);
// Someone who reads the whole project: a guest would not see the ticket.
const role = project.roleOf(command.reviewerId);
if (!role || (role === ProjectRole.GUEST && !project.isPublic))
throw new BusinessRuleError(
`Only members of ${project.key} can be asked to review`,
);
issue.requestReview(
command.actorId,
randomUUID(),
command.reviewerId,
command.note,
);
await issue.commitAndWait();
return ack(issue);
}
}
/** The person asked answers; reading the ticket is enough (viewers too). */
@CommandHandler(AnswerReviewCommand)
export class AnswerReviewCommandHandler
implements ICommandHandler<AnswerReviewCommand>
{
constructor(private readonly access: WriteAccess) {}
async execute(command: AnswerReviewCommand): Promise<CommandResult> {
const issue = await this.access.issue(command.issueId);
const project = await this.access.project(issue.projectId);
if (!project.isMember(command.actorId))
throw new ForbiddenError(
`You are not a member of project ${project.key}`,
);
issue.answerReview(
command.actorId,
command.reviewId,
command.verdict,
command.answer,
);
await issue.commitAndWait();
return ack(issue);
}
}
@CommandHandler(CancelReviewCommand)
export class CancelReviewCommandHandler
implements ICommandHandler<CancelReviewCommand>
{
constructor(private readonly access: WriteAccess) {}
async execute(command: CancelReviewCommand): Promise<CommandResult> {
const issue = await this.access.issue(command.issueId);
const project = await this.access.project(issue.projectId);
if (!project.isMember(command.actorId))
throw new ForbiddenError(
`You are not a member of project ${project.key}`,
);
const role = project.roleOf(command.actorId);
issue.cancelReview(
command.actorId,
command.reviewId,
role === ProjectRole.OWNER || role === ProjectRole.ADMIN,
);
await issue.commitAndWait();
return ack(issue);
}
}
export const REVIEW_HANDLERS = [
RequestReviewCommandHandler,
AnswerReviewCommandHandler,
CancelReviewCommandHandler,
];

View File

@@ -0,0 +1,94 @@
import {
Command,
CommandBus,
CommandHandler,
ICommandHandler,
} from '@nestjs/cqrs';
import { BusinessRuleError } from '@task-stream/api/shared/domain';
import { IssueLinkType } from '@task-stream/api/tracker/domain';
import { UserDirectory } from '../ports/user-directory';
import { CommandResult } from './command-result';
import { CreateIssueCommand } from './create-issue.command';
import { LinkIssuesCommand } from './link-issues.command';
import { WriteAccess } from './write-access';
/*
* «Convertir en ticket»: a comment that turns out to be work of its own
* («también falla en Android») becomes a ticket, as a subtask of the one it
* was said on or linked to it. Its text is the new description, and the
* comment shows where it went («→ WEB-45»).
*/
export class TurnCommentIntoIssueCommand extends Command<CommandResult> {
constructor(
public readonly actorId: string,
public readonly commentId: string,
public readonly title: string,
/** Ticket type id of the project's settings. */
public readonly type: string,
/** Hang it from the ticket of the comment; otherwise, link them. */
public readonly asSubtask: boolean,
) {
super();
}
}
/** Answers the new ticket (id, key, version). */
@CommandHandler(TurnCommentIntoIssueCommand)
export class TurnCommentIntoIssueCommandHandler
implements ICommandHandler<TurnCommentIntoIssueCommand>
{
constructor(
private readonly access: WriteAccess,
private readonly commandBus: CommandBus,
private readonly users: UserDirectory,
) {}
async execute(command: TurnCommentIntoIssueCommand): Promise<CommandResult> {
const comment = await this.access.comment(command.commentId);
const source = await this.access.issue(comment.issueId);
const project = await this.access.project(comment.projectId);
this.access.assertSees(project, source, command.actorId);
// Creating and linking tickets is for the team: those commands check it.
project.assertCanContribute(command.actorId);
if (comment.deleted) throw new BusinessRuleError('Comment was deleted');
const author = (await this.users.refs([comment.authorId])).of(
comment.authorId,
);
const created = await this.commandBus.execute(
new CreateIssueCommand(
command.actorId,
project.id,
command.type,
command.title,
{
description: `${comment.body}\n\n---\n_Sale de un comentario de ${author.name} en ${source.key}._`,
},
null,
null,
command.asSubtask ? source.id : null,
null,
// The comment is the content: no template on top of it.
false,
),
);
if (!command.asSubtask)
await this.commandBus.execute(
new LinkIssuesCommand(
command.actorId,
created.id,
IssueLinkType.RELATES_TO,
source.id,
),
);
comment.turnedInto(command.actorId, {
id: created.id,
key: created.key ?? '',
});
await comment.commitAndWait();
return created;
}
}
export const TURN_INTO_ISSUE_HANDLERS = [TurnCommentIntoIssueCommandHandler];

View File

@@ -1,14 +1,25 @@
import { CommandRunner } from '@task-stream/api/shared/application'; import { CommandRunner } from '@task-stream/api/shared/application';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs'; import { QueryBus } from '@nestjs/cqrs';
import { CommentReadModel } from '@task-stream/api/tracker/domain'; import {
CommentReadModel,
DecisionReadModel,
} from '@task-stream/api/tracker/domain';
import { AddCommentCommand } from './commands/add-comment.command'; import { AddCommentCommand } from './commands/add-comment.command';
import { CommandResult } from './commands/command-result'; import { CommandResult } from './commands/command-result';
import { DeleteCommentCommand } from './commands/delete-comment.command'; import { DeleteCommentCommand } from './commands/delete-comment.command';
import { EditCommentCommand } from './commands/edit-comment.command'; import { EditCommentCommand } from './commands/edit-comment.command';
import { ReactToCommentCommand } from './commands/react-to-comment.command'; import { ReactToCommentCommand } from './commands/react-to-comment.command';
import { MarkDecisionCommand } from './commands/mark-decision.command';
import { TurnCommentIntoIssueCommand } from './commands/turn-comment-into-issue';
import { ResolveThreadCommand } from './commands/resolve-thread.command';
import { ClosePollCommand, VotePollCommand } from './commands/polls';
import { Page } from './ports/find-issues.repository'; import { Page } from './ports/find-issues.repository';
import { GetCommentsQuery } from './queries/get-comments.query'; import { GetCommentsQuery } from './queries/get-comments.query';
import {
GetIssueDecisionsQuery,
SearchDecisionsQuery,
} from './queries/decisions.query';
@Injectable() @Injectable()
export class CommentsService { export class CommentsService {
@@ -22,9 +33,32 @@ export class CommentsService {
issueId: string, issueId: string,
body: string, body: string,
replyTo: string | null = null, replyTo: string | null = null,
poll: string[] | null = null,
): Promise<CommandResult> { ): Promise<CommandResult> {
return this.commands.execute( return this.commands.execute(
new AddCommentCommand(actorId, issueId, body, replyTo), new AddCommentCommand(actorId, issueId, body, replyTo, poll),
);
}
/** Votes in a comment's poll (null takes the vote back). */
votePoll(
actorId: string,
commentId: string,
option: number | null,
): Promise<CommandResult> {
return this.commands.execute(
new VotePollCommand(actorId, commentId, option),
);
}
/** Closes a poll; with `decide`, its winner stays as a decision. */
closePoll(
actorId: string,
commentId: string,
decide = true,
): Promise<CommandResult> {
return this.commands.execute(
new ClosePollCommand(actorId, commentId, decide),
); );
} }
@@ -50,6 +84,69 @@ export class CommentsService {
); );
} }
/** Marks it as a decision of its ticket (`on`) or unmarks it: the team does. */
markDecision(
actorId: string,
commentId: string,
on: boolean,
): Promise<CommandResult> {
return this.commands.execute(
new MarkDecisionCommand(actorId, commentId, on),
);
}
/**
* Settles a conversation or reopens it; a conclusion stays as a reply
* marked as a decision.
*/
resolveThread(
actorId: string,
commentId: string,
resolved: boolean,
conclusion: string | null = null,
): Promise<CommandResult> {
return this.commands.execute(
new ResolveThreadCommand(actorId, commentId, resolved, conclusion),
);
}
/** Makes a ticket of a comment: a subtask of its ticket, or linked to it. */
turnIntoIssue(
actorId: string,
commentId: string,
title: string,
type: string,
asSubtask: boolean,
): Promise<CommandResult> {
return this.commands.execute(
new TurnCommentIntoIssueCommand(
actorId,
commentId,
title,
type,
asSubtask,
),
);
}
/** A ticket's decisions, oldest first. */
decisions(
viewerId: string | null,
issueId: string,
): Promise<CommentReadModel[]> {
return this.queryBus.execute(new GetIssueDecisionsQuery(viewerId, issueId));
}
/** Decisions by their text: of a project, or of all mine without one. */
searchDecisions(
viewerId: string | null,
filter: { projectId?: string; search?: string; limit?: number },
): Promise<DecisionReadModel[]> {
return this.queryBus.execute(
new SearchDecisionsQuery(viewerId, { limit: 20, ...filter }),
);
}
delete(actorId: string, commentId: string): Promise<CommandResult> { delete(actorId: string, commentId: string): Promise<CommandResult> {
return this.commands.execute(new DeleteCommentCommand(actorId, commentId)); return this.commands.execute(new DeleteCommentCommand(actorId, commentId));
} }

View File

@@ -9,6 +9,10 @@ import {
IssueChecklistItemRemovedEvent, IssueChecklistItemRemovedEvent,
IssueChecklistItemUpdatedEvent, IssueChecklistItemUpdatedEvent,
IssueParentChangedEvent, IssueParentChangedEvent,
IssueReviewAnsweredEvent,
IssueReviewCancelledEvent,
IssueReviewRequestedEvent,
ReviewVerdict,
IssueDevLinkRecordedEvent, IssueDevLinkRecordedEvent,
IssueTrashedEvent, IssueTrashedEvent,
IssueRestoredEvent, IssueRestoredEvent,
@@ -191,6 +195,14 @@ export function describeEvent(
: 'abierta'; : 'abierta';
return `Pull request ${ref} ${verb} para ${issueKey}${who}`; return `Pull request ${ref} ${verb} para ${issueKey}${who}`;
} }
if (event instanceof IssueReviewRequestedEvent)
return `${actor} pidió a ${ctx.user(event.reviewerId)} que revise ${issueKey}`;
if (event instanceof IssueReviewAnsweredEvent)
return event.verdict === ReviewVerdict.APPROVED
? `${actor} dio por bueno ${issueKey} al revisarlo`
: `${actor} pidió cambios en ${issueKey} al revisarlo`;
if (event instanceof IssueReviewCancelledEvent)
return `${actor} retiró una petición de revisión de ${issueKey}`;
if (event instanceof IssueParentChangedEvent) { if (event instanceof IssueParentChangedEvent) {
return event.parentKey return event.parentKey
? `${actor} colocó ${issueKey} bajo ${event.parentKey}` ? `${actor} colocó ${issueKey} bajo ${event.parentKey}`

View File

@@ -11,6 +11,9 @@ import {
IssueChecklistItemRemovedEvent, IssueChecklistItemRemovedEvent,
IssueChecklistItemUpdatedEvent, IssueChecklistItemUpdatedEvent,
IssueParentChangedEvent, IssueParentChangedEvent,
IssueReviewAnsweredEvent,
IssueReviewCancelledEvent,
IssueReviewRequestedEvent,
IssueDevLinkRecordedEvent, IssueDevLinkRecordedEvent,
IssueTrashedEvent, IssueTrashedEvent,
IssueRestoredEvent, IssueRestoredEvent,
@@ -75,6 +78,9 @@ import { versionOf } from './read-model-notifier';
IssueAttachmentAddedEvent, IssueAttachmentAddedEvent,
IssueAttachmentRemovedEvent, IssueAttachmentRemovedEvent,
IssueParentChangedEvent, IssueParentChangedEvent,
IssueReviewRequestedEvent,
IssueReviewAnsweredEvent,
IssueReviewCancelledEvent,
IssueDevLinkRecordedEvent, IssueDevLinkRecordedEvent,
IssueTrashedEvent, IssueTrashedEvent,
IssueRestoredEvent, IssueRestoredEvent,
@@ -127,6 +133,7 @@ export class ActivityEventHandler implements IEventHandler<TrackerEvent> {
event.actorId, event.actorId,
(event as { userId?: string }).userId, (event as { userId?: string }).userId,
(event as { assigneeId?: string }).assigneeId, (event as { assigneeId?: string }).assigneeId,
(event as { reviewerId?: string }).reviewerId,
]; ];
const users = await this.users.refs(mentioned); const users = await this.users.refs(mentioned);
const actorOf = (id: string) => const actorOf = (id: string) =>

View File

@@ -30,6 +30,20 @@ export class CommentAddedEventHandler
replyTo: comment.replyTo ?? null, replyTo: comment.replyTo ?? null,
deleted: false, deleted: false,
reactions: [], reactions: [],
decision: false,
decidedBy: null,
decidedAt: null,
poll: comment.poll?.length
? {
options: comment.poll.map((text) => ({ text, voters: [] })),
closed: false,
winner: null,
}
: null,
resolved: false,
resolvedBy: null,
resolvedAt: null,
spawned: [],
createdAt: comment.createdAt, createdAt: comment.createdAt,
editedAt: null, editedAt: null,
version: versionOf(event), version: versionOf(event),

View File

@@ -0,0 +1,30 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CommentDecisionMarkedEvent } 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(CommentDecisionMarkedEvent)
export class CommentDecisionMarkedEventHandler
implements IEventHandler<CommentDecisionMarkedEvent>
{
constructor(
private readonly upsertMaterializedCommentRepository: UpsertMaterializedCommentRepository,
private readonly users: UserDirectory,
private readonly notifier: ReadModelNotifier,
) {}
async handle(event: CommentDecisionMarkedEvent) {
const refs = await this.users.refs([event.actorId]);
await this.upsertMaterializedCommentRepository.upsert({
id: event.aggregateId,
decision: event.decision,
decidedBy: event.decision ? refs.of(event.actorId) : null,
decidedAt: event.decision ? event.occurredAt : null,
version: versionOf(event),
});
await this.notifier.comment(event.aggregateId, event.issueId, event);
// The ticket shows its decisions on top: its page reloads them.
await this.notifier.issue(event.issueId, event);
}
}

View File

@@ -0,0 +1,48 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import {
CommentPollClosedEvent,
CommentPollVotedEvent,
} from '@task-stream/api/tracker/domain';
import { FindCommentsRepository } from '../ports/find-comments.repository';
import { UpsertMaterializedCommentRepository } from '../ports/upsert-materialized-comment.repository';
import { UserDirectory } from '../ports/user-directory';
import { ReadModelNotifier, versionOf } from './read-model-notifier';
/** A comment's poll as the read side shows it: who voted each option. */
@EventsHandler(CommentPollVotedEvent, CommentPollClosedEvent)
export class CommentPollEventHandler
implements IEventHandler<CommentPollVotedEvent | CommentPollClosedEvent>
{
constructor(
private readonly upsertMaterializedCommentRepository: UpsertMaterializedCommentRepository,
private readonly findComments: FindCommentsRepository,
private readonly users: UserDirectory,
private readonly notifier: ReadModelNotifier,
) {}
async handle(event: CommentPollVotedEvent | CommentPollClosedEvent) {
const comment = await this.findComments.findById(event.aggregateId);
if (!comment?.poll) return;
let poll = comment.poll;
if (event instanceof CommentPollVotedEvent) {
const refs = await this.users.refs(Object.keys(event.votes));
poll = {
...poll,
options: poll.options.map((option, index) => ({
text: option.text,
voters: Object.entries(event.votes)
.filter(([, vote]) => vote === index)
.map(([userId]) => refs.of(userId)),
})),
};
} else {
poll = { ...poll, closed: true, winner: event.winner };
}
await this.upsertMaterializedCommentRepository.upsert({
id: event.aggregateId,
poll,
version: versionOf(event),
});
await this.notifier.comment(event.aggregateId, event.issueId, event);
}
}

View File

@@ -0,0 +1,28 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CommentThreadResolvedEvent } 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(CommentThreadResolvedEvent)
export class CommentThreadResolvedEventHandler
implements IEventHandler<CommentThreadResolvedEvent>
{
constructor(
private readonly upsertMaterializedCommentRepository: UpsertMaterializedCommentRepository,
private readonly users: UserDirectory,
private readonly notifier: ReadModelNotifier,
) {}
async handle(event: CommentThreadResolvedEvent) {
const refs = await this.users.refs([event.actorId]);
await this.upsertMaterializedCommentRepository.upsert({
id: event.aggregateId,
resolved: event.resolved,
resolvedBy: event.resolved ? refs.of(event.actorId) : null,
resolvedAt: event.resolved ? event.occurredAt : null,
version: versionOf(event),
});
await this.notifier.comment(event.aggregateId, event.issueId, event);
}
}

View File

@@ -0,0 +1,23 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { CommentTurnedIntoIssueEvent } from '@task-stream/api/tracker/domain';
import { UpsertMaterializedCommentRepository } from '../ports/upsert-materialized-comment.repository';
import { ReadModelNotifier, versionOf } from './read-model-notifier';
@EventsHandler(CommentTurnedIntoIssueEvent)
export class CommentTurnedIntoIssueEventHandler
implements IEventHandler<CommentTurnedIntoIssueEvent>
{
constructor(
private readonly upsertMaterializedCommentRepository: UpsertMaterializedCommentRepository,
private readonly notifier: ReadModelNotifier,
) {}
async handle(event: CommentTurnedIntoIssueEvent) {
await this.upsertMaterializedCommentRepository.upsert({
id: event.aggregateId,
spawned: event.spawned,
version: versionOf(event),
});
await this.notifier.comment(event.aggregateId, event.issueId, event);
}
}

View File

@@ -3,6 +3,11 @@ import { CommentAddedEventHandler } from './comment-added.event-handler';
import { CommentDeletedEventHandler } from './comment-deleted.event-handler'; import { CommentDeletedEventHandler } from './comment-deleted.event-handler';
import { CommentEditedEventHandler } from './comment-edited.event-handler'; import { CommentEditedEventHandler } from './comment-edited.event-handler';
import { CommentReactedEventHandler } from './comment-reacted.event-handler'; import { CommentReactedEventHandler } from './comment-reacted.event-handler';
import { CommentDecisionMarkedEventHandler } from './comment-decision-marked.event-handler';
import { CommentThreadResolvedEventHandler } from './comment-thread-resolved.event-handler';
import { CommentTurnedIntoIssueEventHandler } from './comment-turned-into-issue.event-handler';
import { IssueReviewsEventHandler } from './issue-reviews.event-handler';
import { CommentPollEventHandler } from './comment-poll.event-handler';
import { IssueVotedEventHandler } from './issue-voted.event-handler'; import { IssueVotedEventHandler } from './issue-voted.event-handler';
import { IssueAssignedEventHandler } from './issue-assigned.event-handler'; import { IssueAssignedEventHandler } from './issue-assigned.event-handler';
import { IssueCreatedEventHandler } from './issue-created.event-handler'; import { IssueCreatedEventHandler } from './issue-created.event-handler';
@@ -50,6 +55,11 @@ export const EVENT_HANDLERS = [
CommentDeletedEventHandler, CommentDeletedEventHandler,
CommentEditedEventHandler, CommentEditedEventHandler,
CommentReactedEventHandler, CommentReactedEventHandler,
CommentDecisionMarkedEventHandler,
CommentThreadResolvedEventHandler,
CommentTurnedIntoIssueEventHandler,
IssueReviewsEventHandler,
CommentPollEventHandler,
IssueVotedEventHandler, IssueVotedEventHandler,
IssueAssignedEventHandler, IssueAssignedEventHandler,
IssueCreatedEventHandler, IssueCreatedEventHandler,

View File

@@ -0,0 +1,74 @@
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
import {
IssueReviewAnsweredEvent,
IssueReviewCancelledEvent,
IssueReviewRequestedEvent,
} from '@task-stream/api/tracker/domain';
import { FindIssuesRepository } from '../ports/find-issues.repository';
import { UpsertMaterializedIssueRepository } from '../ports/upsert-materialized-issue.repository';
import { UserDirectory } from '../ports/user-directory';
import { ReadModelNotifier, versionOf } from './read-model-notifier';
type ReviewEvent =
| IssueReviewRequestedEvent
| IssueReviewAnsweredEvent
| IssueReviewCancelledEvent;
/** The ticket's review requests, as its page and «my work» show them. */
@EventsHandler(
IssueReviewRequestedEvent,
IssueReviewAnsweredEvent,
IssueReviewCancelledEvent,
)
export class IssueReviewsEventHandler implements IEventHandler<ReviewEvent> {
constructor(
private readonly upsertMaterializedIssueRepository: UpsertMaterializedIssueRepository,
private readonly findIssues: FindIssuesRepository,
private readonly users: UserDirectory,
private readonly notifier: ReadModelNotifier,
) {}
async handle(event: ReviewEvent) {
const issue = await this.findIssues.findById(event.aggregateId);
if (!issue) return;
// Events of a stream come in order: the list read is the one before.
let reviews = issue.reviews ?? [];
if (event instanceof IssueReviewRequestedEvent) {
if (reviews.some((r) => r.id === event.reviewId)) return;
const refs = await this.users.refs([event.actorId, event.reviewerId]);
reviews = [
...reviews,
{
id: event.reviewId,
requester: refs.of(event.actorId),
reviewer: refs.of(event.reviewerId),
note: event.note,
requestedAt: event.occurredAt,
verdict: null,
answer: null,
answeredAt: null,
},
];
} else if (event instanceof IssueReviewAnsweredEvent) {
reviews = reviews.map((r) =>
r.id === event.reviewId
? {
...r,
verdict: event.verdict,
answer: event.answer,
answeredAt: event.occurredAt,
}
: r,
);
} else {
reviews = reviews.filter((r) => r.id !== event.reviewId);
}
// A review is not a change to the ticket itself: `updatedAt` stays.
await this.upsertMaterializedIssueRepository.upsert({
id: event.aggregateId,
reviews,
version: versionOf(event),
});
await this.notifier.issue(event.aggregateId, event);
}
}

View File

@@ -0,0 +1,82 @@
import {
Command,
CommandHandler,
ICommandHandler,
IQueryHandler,
Query,
QueryBus,
QueryHandler,
} from '@nestjs/cqrs';
import { NotFoundError } from '@task-stream/api/shared/domain';
import { IssueReadModel } from '@task-stream/api/tracker/domain';
import { TreeFollowsRepository } from '../ports/tree-follows.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
/*
* Following a ticket with everything under it (an epic, or a ticket split
* into subtasks): told of its changes and of every ticket that hangs from
* it, at any depth, also the ones created later. Personal, no history
* (like pinned tickets).
*/
export class FollowTreeCommand extends Command<void> {
constructor(
public readonly userId: string,
public readonly issueId: string,
/** False: stop following it. */
public readonly on: boolean,
) {
super();
}
}
export class IsFollowingTreeQuery extends Query<boolean> {
constructor(
public readonly userId: string,
public readonly issueId: string,
) {
super();
}
}
@CommandHandler(FollowTreeCommand)
export class FollowTreeCommandHandler
implements ICommandHandler<FollowTreeCommand>
{
constructor(
private readonly follows: TreeFollowsRepository,
private readonly queryBus: QueryBus,
) {}
async execute(command: FollowTreeCommand): Promise<void> {
const { userId, issueId } = command;
if (!command.on) return this.follows.unfollow(userId, issueId);
const [issue]: IssueReadModel[] = await this.queryBus.execute(
new GetIssuesByIdsQuery(userId, [issueId]),
);
// A ticket I cannot read does not exist, as far as I know.
if (!issue || issue.trashedAt) throw new NotFoundError('Issue', issueId);
await this.follows.follow({
userId,
issueId,
projectId: issue.projectId,
since: new Date().toISOString(),
});
}
}
@QueryHandler(IsFollowingTreeQuery)
export class IsFollowingTreeQueryHandler
implements IQueryHandler<IsFollowingTreeQuery, boolean>
{
constructor(private readonly follows: TreeFollowsRepository) {}
execute(query: IsFollowingTreeQuery): Promise<boolean> {
return this.follows.isFollowing(query.userId, query.issueId);
}
}
export const TREE_FOLLOWS = [
FollowTreeCommandHandler,
IsFollowingTreeQueryHandler,
];

View File

@@ -0,0 +1,53 @@
import { CommandRunner } from '@task-stream/api/shared/application';
import { Injectable } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs';
import { IssueReadModel } from '@task-stream/api/tracker/domain';
import { IssueReminder } from './ports/issue-reminders.repository';
import {
ClearIssueReminderCommand,
GetIssueReminderQuery,
GetMyRemindersQuery,
SendIssueRemindersCommand,
SetIssueReminderCommand,
} from './reminders/issue-reminders';
/** «Remind me on Thursday»: one's own reminders on tickets. */
@Injectable()
export class IssueRemindersService {
constructor(
private readonly commands: CommandRunner,
private readonly queryBus: QueryBus,
) {}
set(
userId: string,
issueId: string,
at: string,
note: string | null,
): Promise<IssueReminder> {
return this.commands.execute(
new SetIssueReminderCommand(userId, issueId, at, note),
);
}
clear(userId: string, issueId: string): Promise<void> {
return this.commands.execute(
new ClearIssueReminderCommand(userId, issueId),
);
}
of(userId: string, issueId: string): Promise<IssueReminder | null> {
return this.queryBus.execute(new GetIssueReminderQuery(userId, issueId));
}
mine(
userId: string,
): Promise<{ reminder: IssueReminder; issue: IssueReadModel }[]> {
return this.queryBus.execute(new GetMyRemindersQuery(userId));
}
/** Scheduler only. */
sendDue(): Promise<number> {
return this.commands.execute(new SendIssueRemindersCommand());
}
}

View File

@@ -0,0 +1,14 @@
import { CommandRunner } from '@task-stream/api/shared/application';
import { Injectable } from '@nestjs/common';
import { VisitIssueCommand } from './visits/issue-visits';
/** When I last opened a ticket, to tell what is new since. */
@Injectable()
export class IssueVisitsService {
constructor(private readonly commands: CommandRunner) {}
/** Notes that I opened it now; returns my visit before (null: never). */
visit(userId: string, issueId: string): Promise<string | null> {
return this.commands.execute(new VisitIssueCommand(userId, issueId));
}
}

View File

@@ -9,6 +9,7 @@ import {
IssueLinkType, IssueLinkType,
IssuePriority, IssuePriority,
IssueReadModel, IssueReadModel,
ReviewVerdict,
SYSTEM_ACTOR_ID, SYSTEM_ACTOR_ID,
} from '@task-stream/api/tracker/domain'; } from '@task-stream/api/tracker/domain';
import { BulkChange, BulkResult, MAX_BULK } from './bulk-change'; import { BulkChange, BulkResult, MAX_BULK } from './bulk-change';
@@ -21,6 +22,11 @@ import {
} from './commands/attach-file.command'; } from './commands/attach-file.command';
import { DetachFileCommand } from './commands/detach-file.command'; import { DetachFileCommand } from './commands/detach-file.command';
import { WatchIssueCommand } from './commands/watch-issue.command'; import { WatchIssueCommand } from './commands/watch-issue.command';
import {
AnswerReviewCommand,
CancelReviewCommand,
RequestReviewCommand,
} from './commands/reviews';
import { SetIssueParentCommand } from './commands/set-issue-parent.command'; import { SetIssueParentCommand } from './commands/set-issue-parent.command';
import { RankIssueCommand } from './commands/rank-issue.command'; import { RankIssueCommand } from './commands/rank-issue.command';
import { DeleteIssueCommand } from './commands/delete-issue.command'; import { DeleteIssueCommand } from './commands/delete-issue.command';
@@ -212,6 +218,41 @@ export class IssuesService {
); );
} }
/** Asks `reviewerId` (a member) to review the ticket. */
requestReview(
actorId: string,
issueId: string,
reviewerId: string,
note: string | null,
): Promise<CommandResult> {
return this.commands.execute(
new RequestReviewCommand(actorId, issueId, reviewerId, note),
);
}
/** The person asked answers: all good, or changes wanted. */
answerReview(
actorId: string,
issueId: string,
reviewId: string,
verdict: ReviewVerdict,
answer: string | null,
): Promise<CommandResult> {
return this.commands.execute(
new AnswerReviewCommand(actorId, issueId, reviewId, verdict, answer),
);
}
cancelReview(
actorId: string,
issueId: string,
reviewId: string,
): Promise<CommandResult> {
return this.commands.execute(
new CancelReviewCommand(actorId, issueId, reviewId),
);
}
/** A ticket's file, with its bytes, for whoever can read the ticket. */ /** A ticket's file, with its bytes, for whoever can read the ticket. */
download( download(
viewerId: string | null, viewerId: string | null,
@@ -432,6 +473,7 @@ export class IssuesService {
issueId?: string; issueId?: string;
limit?: number; limit?: number;
before?: string; before?: string;
after?: string;
}, },
): Promise<ActivityReadModel[]> { ): Promise<ActivityReadModel[]> {
return this.queryBus.execute( return this.queryBus.execute(
@@ -441,6 +483,7 @@ export class IssuesService {
params.issueId, params.issueId,
params.limit, params.limit,
params.before, params.before,
params.after,
), ),
); );
} }

View File

@@ -0,0 +1,32 @@
import { CommandRunner } from '@task-stream/api/shared/application';
import { Injectable } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs';
import {
AddToMyDayCommand,
GetMyDayQuery,
MyDay,
RemoveFromMyDayCommand,
} from './my-day/my-day';
/** «Mi día»: the tickets I picked for today. */
@Injectable()
export class MyDayService {
constructor(
private readonly commands: CommandRunner,
private readonly queryBus: QueryBus,
) {}
get(userId: string, day: string): Promise<MyDay> {
return this.queryBus.execute(new GetMyDayQuery(userId, day));
}
add(userId: string, day: string, issueIds: string[]): Promise<void> {
return this.commands.execute(new AddToMyDayCommand(userId, day, issueIds));
}
remove(userId: string, day: string, issueId: string): Promise<void> {
return this.commands.execute(
new RemoveFromMyDayCommand(userId, day, issueId),
);
}
}

View File

@@ -0,0 +1,145 @@
import {
CommandBus,
CqrsModule,
IQueryHandler,
QueryBus,
QueryHandler,
} from '@nestjs/cqrs';
import { Test } from '@nestjs/testing';
import {
BusinessRuleError,
NotFoundError,
ValidationError,
} from '@task-stream/api/shared/domain';
import {
IssueReadModel,
StatusCategory,
} from '@task-stream/api/tracker/domain';
import { MyDayRecord, MyDaysRepository } from '../ports/my-days.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
import {
AddToMyDayCommand,
GetMyDayQuery,
MAX_MY_DAY,
MY_DAY,
MyDay,
RemoveFromMyDayCommand,
} from './my-day';
class InMemoryDays extends MyDaysRepository {
rows: MyDayRecord[] = [];
async find(userId: string, day: string) {
return this.rows.find((r) => r.userId === userId && r.day === day) ?? null;
}
async latestBefore(userId: string, day: string) {
return (
this.rows
.filter((r) => r.userId === userId && r.day < day)
.sort((a, b) => b.day.localeCompare(a.day))[0] ?? null
);
}
async save(record: MyDayRecord) {
this.rows = [
...this.rows.filter(
(r) => !(r.userId === record.userId && r.day === record.day),
),
record,
];
}
}
/** Ana reads i0…i11; i3 is done. */
const issues = new Map<string, IssueReadModel>();
@QueryHandler(GetIssuesByIdsQuery)
class FakeIssuesByIds implements IQueryHandler<GetIssuesByIdsQuery> {
async execute(query: GetIssuesByIdsQuery) {
return query.viewerId === 'ana'
? query.ids.flatMap((id) => issues.get(id) ?? [])
: [];
}
}
const day = (offset: number) =>
new Date(Date.now() + offset * 86_400_000).toISOString().slice(0, 10);
async function setup() {
issues.clear();
for (let i = 0; i < 12; i++)
issues.set(`i${i}`, {
id: `i${i}`,
key: `WEB-${i}`,
statusCategory: i === 3 ? StatusCategory.DONE : StatusCategory.TODO,
trashedAt: null,
} as IssueReadModel);
const rows = new InMemoryDays();
const moduleRef = await Test.createTestingModule({
imports: [CqrsModule.forRoot()],
providers: [
...MY_DAY,
FakeIssuesByIds,
{ provide: MyDaysRepository, useValue: rows },
],
}).compile();
await moduleRef.init();
const commands = moduleRef.get(CommandBus);
const queries = moduleRef.get(QueryBus);
return {
rows,
commands,
keys: async (d: string) => {
const myDay: MyDay = await queries.execute(new GetMyDayQuery('ana', d));
return {
issues: myDay.issues.map((i) => i.key),
leftover: myDay.leftover?.issues.map((i) => i.key) ?? null,
};
},
};
}
describe('Mi día', () => {
it('keeps the tickets picked for today, in order, once each', async () => {
const { commands, keys } = await setup();
await commands.execute(new AddToMyDayCommand('ana', day(0), ['i1', 'i2']));
await commands.execute(new AddToMyDayCommand('ana', day(0), ['i2', 'i3']));
await commands.execute(new RemoveFromMyDayCommand('ana', day(0), 'i1'));
expect((await keys(day(0))).issues).toEqual(['WEB-2', 'WEB-3']);
});
it(`takes ${MAX_MY_DAY} at most, only readable tickets, only around today`, async () => {
const { commands } = await setup();
const many = Array.from({ length: MAX_MY_DAY + 1 }, (_, i) => `i${i}`);
await expect(
commands.execute(new AddToMyDayCommand('ana', day(0), many)),
).rejects.toBeInstanceOf(BusinessRuleError);
await expect(
commands.execute(new AddToMyDayCommand('ana', day(0), ['nope'])),
).rejects.toBeInstanceOf(NotFoundError);
await expect(
commands.execute(new AddToMyDayCommand('ana', day(5), ['i1'])),
).rejects.toBeInstanceOf(ValidationError);
await expect(
commands.execute(new AddToMyDayCommand('ana', '20-10-2026', ['i1'])),
).rejects.toBeInstanceOf(ValidationError);
});
it('offers what was left unfinished on the last day, but not the done ones', async () => {
const { commands, rows, keys } = await setup();
rows.rows.push({
userId: 'ana',
day: day(-1),
issueIds: ['i1', 'i3', 'i4'],
updatedAt: '',
});
expect(await keys(day(0))).toEqual({
issues: [],
leftover: ['WEB-1', 'WEB-4'],
});
// Carried over: no longer offered.
await commands.execute(new AddToMyDayCommand('ana', day(0), ['i1', 'i4']));
expect(await keys(day(0))).toEqual({
issues: ['WEB-1', 'WEB-4'],
leftover: null,
});
});
});

View File

@@ -0,0 +1,194 @@
import {
Command,
CommandHandler,
ICommandHandler,
IQueryHandler,
Query,
QueryBus,
QueryHandler,
} from '@nestjs/cqrs';
import {
BusinessRuleError,
NotFoundError,
assertThat,
} from '@task-stream/api/shared/domain';
import {
IssueReadModel,
StatusCategory,
} from '@task-stream/api/tracker/domain';
import { MyDayRecord, MyDaysRepository } from '../ports/my-days.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
/*
* «Mi día»: the few tickets someone picks each morning for today, and at
* the end what got done. The day is the person's own (`YYYY-MM-DD` from
* their browser). Private, no history.
*/
export const MAX_MY_DAY = 10;
/** How far back what was left counts as «from before». */
const CARRY_OVER_DAYS = 7;
const DAY_FORMAT = /^\d{4}-\d{2}-\d{2}$/;
const DAY_MS = 86_400_000;
const finished = (issue: IssueReadModel) =>
issue.statusCategory === StatusCategory.DONE ||
issue.statusCategory === StatusCategory.CANCELLED;
/** A day of the person's: well formed and near today (time zones apart). */
export function assertDay(day: string, now = Date.now()): void {
const at = Date.parse(`${day}T12:00:00Z`);
assertThat(DAY_FORMAT.test(day) && !Number.isNaN(at), 'A day is YYYY-MM-DD');
assertThat(
Math.abs(at - now) <= 2 * DAY_MS,
'Only today can be planned (in your time zone)',
);
}
export interface MyDay {
day: string;
/** Picked for the day, in order (done ones included). */
issues: IssueReadModel[];
/** What was left unfinished on the latest earlier day, if recent. */
leftover: { day: string; issues: IssueReadModel[] } | null;
}
export class AddToMyDayCommand extends Command<void> {
constructor(
public readonly userId: string,
public readonly day: string,
/** Several at once: carrying over what was left. */
public readonly issueIds: string[],
) {
super();
}
}
export class RemoveFromMyDayCommand extends Command<void> {
constructor(
public readonly userId: string,
public readonly day: string,
public readonly issueId: string,
) {
super();
}
}
export class GetMyDayQuery extends Query<MyDay> {
constructor(
public readonly userId: string,
public readonly day: string,
) {
super();
}
}
@CommandHandler(AddToMyDayCommand)
export class AddToMyDayCommandHandler
implements ICommandHandler<AddToMyDayCommand>
{
constructor(
private readonly days: MyDaysRepository,
private readonly queryBus: QueryBus,
) {}
async execute(command: AddToMyDayCommand): Promise<void> {
assertDay(command.day);
const wanted = [...new Set(command.issueIds)];
const readable: IssueReadModel[] = await this.queryBus.execute(
new GetIssuesByIdsQuery(command.userId, wanted),
);
const ok = new Set(readable.filter((i) => !i.trashedAt).map((i) => i.id));
// One I cannot read does not exist, as far as I know.
const missing = wanted.find((id) => !ok.has(id));
if (missing) throw new NotFoundError('Issue', missing);
const current = await this.days.find(command.userId, command.day);
const issueIds = [
...(current?.issueIds ?? []),
...wanted.filter((id) => !current?.issueIds.includes(id)),
];
if (issueIds.length > MAX_MY_DAY)
throw new BusinessRuleError(
`Mi día takes ${MAX_MY_DAY} tickets at most: finish or take some out first`,
);
await this.days.save({
userId: command.userId,
day: command.day,
issueIds,
updatedAt: new Date().toISOString(),
});
}
}
@CommandHandler(RemoveFromMyDayCommand)
export class RemoveFromMyDayCommandHandler
implements ICommandHandler<RemoveFromMyDayCommand>
{
constructor(private readonly days: MyDaysRepository) {}
async execute(command: RemoveFromMyDayCommand): Promise<void> {
assertDay(command.day);
const current = await this.days.find(command.userId, command.day);
if (!current?.issueIds.includes(command.issueId)) return;
await this.days.save({
...current,
issueIds: current.issueIds.filter((id) => id !== command.issueId),
updatedAt: new Date().toISOString(),
});
}
}
@QueryHandler(GetMyDayQuery)
export class GetMyDayQueryHandler
implements IQueryHandler<GetMyDayQuery, MyDay>
{
constructor(
private readonly days: MyDaysRepository,
private readonly queryBus: QueryBus,
) {}
async execute(query: GetMyDayQuery): Promise<MyDay> {
assertDay(query.day);
const [today, before] = await Promise.all([
this.days.find(query.userId, query.day),
this.days.latestBefore(query.userId, query.day),
]);
const recent =
before &&
Date.parse(`${query.day}T00:00:00Z`) -
Date.parse(`${before.day}T00:00:00Z`) <=
CARRY_OVER_DAYS * DAY_MS
? before
: null;
const ids = [
...new Set([...(today?.issueIds ?? []), ...(recent?.issueIds ?? [])]),
];
const found: IssueReadModel[] = ids.length
? await this.queryBus.execute(new GetIssuesByIdsQuery(query.userId, ids))
: [];
const byId = new Map(
found.filter((i) => !i.trashedAt).map((i) => [i.id, i]),
);
const pick = (record: MyDayRecord | null) =>
(record?.issueIds ?? []).flatMap((id) => byId.get(id) ?? []);
const issues = pick(today);
const leftover = pick(recent).filter(
(i) => !finished(i) && !today?.issueIds.includes(i.id),
);
return {
day: query.day,
issues,
leftover:
recent && leftover.length
? { day: recent.day, issues: leftover }
: null,
};
}
}
export const MY_DAY = [
AddToMyDayCommandHandler,
RemoveFromMyDayCommandHandler,
GetMyDayQueryHandler,
];

View File

@@ -3,7 +3,11 @@ import {
CommentAddedEvent, CommentAddedEvent,
IssueAssignedEvent, IssueAssignedEvent,
IssueCreatedEvent, IssueCreatedEvent,
IssueParentChangedEvent,
IssuePriority, IssuePriority,
IssueReviewAnsweredEvent,
IssueReviewRequestedEvent,
ReviewVerdict,
IssueSprintChangedEvent, IssueSprintChangedEvent,
IssueStatusChangedEvent, IssueStatusChangedEvent,
IssueUpdatedEvent, IssueUpdatedEvent,
@@ -24,6 +28,7 @@ import { FindCommentsRepository } from '../ports/find-comments.repository';
import { FindIssuesRepository } from '../ports/find-issues.repository'; import { FindIssuesRepository } from '../ports/find-issues.repository';
import { FindProjectsRepository } from '../ports/find-projects.repository'; import { FindProjectsRepository } from '../ports/find-projects.repository';
import { FindSprintsRepository } from '../ports/find-sprints.repository'; import { FindSprintsRepository } from '../ports/find-sprints.repository';
import { TreeFollowsRepository } from '../ports/tree-follows.repository';
import { UserDirectory } from '../ports/user-directory'; import { UserDirectory } from '../ports/user-directory';
import { NotificationDraft, Notifier } from './notifier'; import { NotificationDraft, Notifier } from './notifier';
@@ -61,10 +66,14 @@ const excerpt = (text: string, max = 120) => {
*/ */
@EventsHandler( @EventsHandler(
IssueCreatedEvent, IssueCreatedEvent,
IssueParentChangedEvent,
IssueAssignedEvent, IssueAssignedEvent,
IssueStatusChangedEvent, IssueStatusChangedEvent,
IssueUpdatedEvent, IssueUpdatedEvent,
IssueSprintChangedEvent, IssueSprintChangedEvent,
IssueParentChangedEvent,
IssueReviewRequestedEvent,
IssueReviewAnsweredEvent,
CommentAddedEvent, CommentAddedEvent,
ProjectMemberAddedEvent, ProjectMemberAddedEvent,
) )
@@ -76,6 +85,7 @@ export class NotificationsEventHandler implements IEventHandler<TrackerEvent> {
private readonly users: UserDirectory, private readonly users: UserDirectory,
private readonly findComments: FindCommentsRepository, private readonly findComments: FindCommentsRepository,
private readonly findSprints: FindSprintsRepository, private readonly findSprints: FindSprintsRepository,
private readonly treeFollows: TreeFollowsRepository,
) {} ) {}
async handle(event: TrackerEvent): Promise<void> { async handle(event: TrackerEvent): Promise<void> {
@@ -118,9 +128,23 @@ export class NotificationsEventHandler implements IEventHandler<TrackerEvent> {
const assigneeId = const assigneeId =
'assigneeId' in issue ? issue.assigneeId : (issue.assignee?.id ?? null); 'assigneeId' in issue ? issue.assigneeId : (issue.assignee?.id ?? null);
const ticket = `${issue.key}: ${issue.title}`; const ticket = `${issue.key}: ${issue.title}`;
const watcherIds =
'watchers' in issue ? issue.watchers.map((w) => w.id) : [];
const memberIds = new Set(project.members.map((m) => m.user.id)); const memberIds = new Set(project.members.map((m) => m.user.id));
// Who follows it with everything under it, or any ticket above it.
// Placed under another ticket: its new place counts (the read model may
// not have it yet).
const parentId =
event instanceof IssueParentChangedEvent
? event.parentId
: 'parent' in issue
? (issue.parent?.id ?? null)
: null;
const tree = await this.treeFollowersOf(issue.id, parentId, project);
const watcherIds = [
...new Set([
...('watchers' in issue ? issue.watchers.map((w) => w.id) : []),
...tree.followers,
]),
];
const drafts: NotificationDraft[] = []; const drafts: NotificationDraft[] = [];
// A proposal from the public form: whoever runs the project should know. // A proposal from the public form: whoever runs the project should know.
@@ -142,6 +166,39 @@ export class NotificationsEventHandler implements IEventHandler<TrackerEvent> {
}); });
} }
} }
if (event instanceof IssueReviewRequestedEvent) {
const note = event.note ? `: «${excerpt(event.note)}»` : '';
drafts.push({
userId: event.reviewerId,
kind: NotificationKind.REVIEW_REQUESTED,
summary: `${actor} te pide que revises ${ticket}${note}`,
});
}
if (event instanceof IssueReviewAnsweredEvent) {
const review = ('reviews' in issue ? (issue.reviews ?? []) : []).find(
(r) => r.id === event.reviewId,
);
const answer = event.answer ? `: «${excerpt(event.answer)}»` : '';
if (review)
drafts.push({
userId: review.requester.id,
kind: NotificationKind.REVIEW_ANSWERED,
summary:
event.verdict === ReviewVerdict.APPROVED
? `${actor} revisó ${ticket} y lo da por bueno${answer}`
: `${actor} revisó ${ticket} y pide cambios${answer}`,
});
}
// A ticket new under a followed one (created there or moved in): the
// only way to hear of it.
if (event instanceof IssueParentChangedEvent && event.parentId) {
for (const userId of tree.followers)
drafts.push({
userId,
kind: NotificationKind.WATCHED,
summary: `${actor} añadió ${ticket} a ${event.parentKey ?? tree.parentKey}`,
});
}
if (event instanceof IssueCreatedEvent && assigneeId) { if (event instanceof IssueCreatedEvent && assigneeId) {
drafts.push({ drafts.push({
userId: assigneeId, userId: assigneeId,
@@ -271,6 +328,40 @@ export class NotificationsEventHandler implements IEventHandler<TrackerEvent> {
); );
} }
/**
* Those following the ticket with its subtree, or any ticket above it
* (an epic, a parent), who can read it all: members that are not guests
* limited to their own tickets. Also the key of its parent.
*/
private async treeFollowersOf(
issueId: string,
parentId: string | null,
project: {
isPublic: boolean;
members: { user: { id: string }; role: ProjectRole }[];
},
): Promise<{ followers: string[]; parentKey: string | null }> {
const ids = [issueId];
let parentKey: string | null = null;
let next = parentId;
// A few levels: epic → story → subtask is as deep as trees go.
for (let depth = 0; next && depth < 5 && !ids.includes(next); depth++) {
ids.push(next);
const parent = await this.findIssues.findById(next);
parentKey ??= parent?.key ?? null;
next = parent?.parent?.id ?? null;
}
const readers = new Set(
project.members
.filter((m) => project.isPublic || m.role !== ProjectRole.GUEST)
.map((m) => m.user.id),
);
const followers = (await this.treeFollows.followersOf(ids)).filter((id) =>
readers.has(id),
);
return { followers, parentKey };
}
/** /**
* What a follower should hear of a change of priority, due date or * What a follower should hear of a change of priority, due date or
* sprint; null for the other edits (title, labels…), too small to tell. * sprint; null for the other edits (title, labels…), too small to tell.

View File

@@ -5,6 +5,7 @@ import {
IssuePriority, IssuePriority,
IssueSprintChangedEvent, IssueSprintChangedEvent,
IssueStatusChangedEvent, IssueStatusChangedEvent,
IssueParentChangedEvent,
IssueUpdatedEvent, IssueUpdatedEvent,
NotificationKind, NotificationKind,
NotificationReadModel, NotificationReadModel,
@@ -23,6 +24,7 @@ import { FindProjectsRepository } from '../ports/find-projects.repository';
import { NotificationMailer } from '../ports/notification-mailer'; import { NotificationMailer } from '../ports/notification-mailer';
import { NotificationsRepository } from '../ports/notifications.repository'; import { NotificationsRepository } from '../ports/notifications.repository';
import { NotificationsEventHandler } from './notifications.event-handler'; import { NotificationsEventHandler } from './notifications.event-handler';
import { TreeFollowsRepository } from '../ports/tree-follows.repository';
import { Notifier } from './notifier'; import { Notifier } from './notifier';
import { import {
PushPayload, PushPayload,
@@ -62,7 +64,12 @@ const at = <T extends TrackerEvent>(event: T, version = 2): T =>
occurredAt: '2026-10-08T10:00:00.000Z', occurredAt: '2026-10-08T10:00:00.000Z',
}); });
function setup(mailEnabled = false, pushEnabled = false) { function setup(
mailEnabled = false,
pushEnabled = false,
/** Ticket id → who follows it with everything under it. */
follows: Record<string, string[]> = {},
) {
const repo = new InMemoryNotifications(); const repo = new InMemoryNotifications();
const published: NotificationReadModel[] = []; const published: NotificationReadModel[] = [];
const mailed: string[] = []; const mailed: string[] = [];
@@ -74,7 +81,9 @@ function setup(mailEnabled = false, pushEnabled = false) {
.add('ana') .add('ana')
.add('bob') .add('bob')
.add('qa') .add('qa')
.add('pm'); .add('pm')
.add('lia')
.add('gus');
const issue = { const issue = {
id: 'i-1', id: 'i-1',
key: 'WEB-1', key: 'WEB-1',
@@ -85,7 +94,10 @@ function setup(mailEnabled = false, pushEnabled = false) {
{ id: 'pm', name: 'PM' }, { id: 'pm', name: 'PM' },
{ id: 'bob', name: 'Bob' }, { id: 'bob', name: 'Bob' },
], ],
parent: { id: 'e-1', key: 'WEB-10', title: 'Checkout' },
}; };
/** The epic it hangs from. */
const epic = { id: 'e-1', key: 'WEB-10', title: 'Checkout', parent: null };
const notifier = new Notifier( const notifier = new Notifier(
repo, repo,
{ {
@@ -118,15 +130,23 @@ function setup(mailEnabled = false, pushEnabled = false) {
); );
const handler = new NotificationsEventHandler( const handler = new NotificationsEventHandler(
notifier, notifier,
{ findById: async () => issue } as unknown as FindIssuesRepository, {
findById: async (id: string) => (id === 'e-1' ? epic : issue),
} as unknown as FindIssuesRepository,
{ {
findById: async () => ({ findById: async () => ({
id: 'p-1', id: 'p-1',
key: 'WEB', key: 'WEB',
name: 'Web', name: 'Web',
members: ['ana', 'bob', 'qa', 'pm'].map((id) => ({ isPublic: false,
members: ['ana', 'bob', 'qa', 'pm', 'lia', 'gus'].map((id) => ({
user: { id, name: id }, user: { id, name: id },
role: id === 'ana' ? ProjectRole.OWNER : ProjectRole.MEMBER, role:
id === 'ana'
? ProjectRole.OWNER
: id === 'gus'
? ProjectRole.GUEST
: ProjectRole.MEMBER,
})), })),
}), }),
} as unknown as FindProjectsRepository, } as unknown as FindProjectsRepository,
@@ -142,11 +162,49 @@ function setup(mailEnabled = false, pushEnabled = false) {
findById: async (id: string) => findById: async (id: string) =>
id === 's-14' ? { id, name: 'Sprint 14' } : null, id === 's-14' ? { id, name: 'Sprint 14' } : null,
} as unknown as FindSprintsRepository, } as unknown as FindSprintsRepository,
{
followersOf: async (ids: string[]) => [
...new Set(ids.flatMap((id) => follows[id] ?? [])),
],
} as unknown as TreeFollowsRepository,
); );
return { repo, published, mailed, pushed, devices, forgotten, handler }; return { repo, published, mailed, pushed, devices, forgotten, handler };
} }
describe('notifications', () => { describe('notifications', () => {
it('tells whoever follows the epic of what happens to its tickets, not guests', async () => {
const { handler, repo } = setup(false, false, { 'e-1': ['lia', 'gus'] });
await handler.handle(
at(
new IssueStatusChangedEvent(
'ana',
'i-1',
'p-1',
'TODO',
'IN_PROGRESS',
null,
),
),
);
const lia = repo.all.filter((n) => n.userId === 'lia');
expect(lia.map((n) => n.kind)).toEqual([NotificationKind.WATCHED]);
expect(lia[0].summary).toContain('WEB-1');
// A guest only sees their own tickets: not told of the epic's.
expect(repo.all.some((n) => n.userId === 'gus')).toBe(false);
});
it('tells whoever follows the epic of a ticket added to it', async () => {
const { handler, repo } = setup(false, false, { 'e-1': ['lia'] });
await handler.handle(
at(
new IssueParentChangedEvent('ana', 'i-1', 'p-1', 'e-1', 'WEB-10', null),
),
);
expect(repo.all.map((n) => [n.userId, n.summary])).toEqual([
['lia', expect.stringContaining('añadió WEB-1: Login roto a WEB-10')],
]);
});
it('tells whoever a ticket is assigned to, not whoever assigned it', async () => { it('tells whoever a ticket is assigned to, not whoever assigned it', async () => {
const { handler, repo, published } = setup(); const { handler, repo, published } = setup();
await handler.handle( await handler.handle(

View File

@@ -0,0 +1,31 @@
import { CommandRunner } from '@task-stream/api/shared/application';
import { Injectable } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs';
import { IssueReadModel } from '@task-stream/api/tracker/domain';
import {
GetMyPinsQuery,
IsIssuePinnedQuery,
PinIssueCommand,
} from './saved-filters/pins';
/** Pinned tickets: the few someone keeps at hand, across projects. */
@Injectable()
export class PinsService {
constructor(
private readonly commands: CommandRunner,
private readonly queryBus: QueryBus,
) {}
/** Mine, most recently pinned first. */
mine(ownerId: string): Promise<IssueReadModel[]> {
return this.queryBus.execute(new GetMyPinsQuery(ownerId));
}
isPinned(ownerId: string, issueId: string): Promise<boolean> {
return this.queryBus.execute(new IsIssuePinnedQuery(ownerId, issueId));
}
pin(ownerId: string, issueId: string, pinned: boolean): Promise<void> {
return this.commands.execute(new PinIssueCommand(ownerId, issueId, pinned));
}
}

View File

@@ -0,0 +1,35 @@
import { IssuePriority } from '@task-stream/api/tracker/domain';
/** A project's door for alerts: who knows the token opens bugs. */
export interface AlertIntegrationConfig {
projectId: string;
token: string;
/** Ticket type to open; null: the project's first bug type. */
typeId: string | null;
priority: IssuePriority;
createdAt: string;
}
/** Which ticket a problem opened, and how often it came back. */
export interface AlertTrace {
projectId: string;
fingerprint: string;
issueId: string;
issueKey: string;
count: number;
firstAt: string;
lastAt: string;
/** Last time the ticket was told (so repeats do not flood it). */
notedAt: string;
}
export abstract class AlertIntegrationsRepository {
abstract find(projectId: string): Promise<AlertIntegrationConfig | null>;
abstract save(config: AlertIntegrationConfig): Promise<void>;
abstract remove(projectId: string): Promise<void>;
abstract trace(
projectId: string,
fingerprint: string,
): Promise<AlertTrace | null>;
abstract saveTrace(trace: AlertTrace): Promise<void>;
}

View File

@@ -46,6 +46,15 @@ export interface ProjectChange extends Change {
* Live stream of read-model changes: event handlers publish once the read * Live stream of read-model changes: event handlers publish once the read
* model is up to date, GraphQL subscriptions watch. * model is up to date, GraphQL subscriptions watch.
*/ */
/** Someone is writing on a ticket: never stored, gone in a few seconds. */
export interface Typing {
issueId: string;
user: { id: string; name: string };
/** The conversation being answered; null: a new comment. */
threadId: string | null;
at: string;
}
export abstract class ChangeFeed { export abstract class ChangeFeed {
abstract publishIssue(change: IssueChange): Promise<void>; abstract publishIssue(change: IssueChange): Promise<void>;
abstract publishComment(change: CommentChange): Promise<void>; abstract publishComment(change: CommentChange): Promise<void>;
@@ -64,6 +73,8 @@ export abstract class ChangeFeed {
abstract issues(projectId: string): AsyncIterableIterator<IssueChange>; abstract issues(projectId: string): AsyncIterableIterator<IssueChange>;
abstract comments(issueId: string): AsyncIterableIterator<CommentChange>; abstract comments(issueId: string): AsyncIterableIterator<CommentChange>;
abstract publishTyping(typing: Typing): Promise<void>;
abstract typing(issueId: string): AsyncIterableIterator<Typing>;
abstract activity( abstract activity(
projectId: string, projectId: string,
): AsyncIterableIterator<ActivityReadModel>; ): AsyncIterableIterator<ActivityReadModel>;

View File

@@ -7,6 +7,8 @@ export abstract class FindActivityRepository {
limit: number; limit: number;
/** ISO date cursor: only activity strictly older than this. */ /** ISO date cursor: only activity strictly older than this. */
before?: string; before?: string;
/** ISO date: only activity at or after this. */
after?: string;
}): Promise<ActivityReadModel[]>; }): Promise<ActivityReadModel[]>;
/** The latest of several projects, newest first. */ /** The latest of several projects, newest first. */
abstract findAcross( abstract findAcross(

View File

@@ -11,4 +11,14 @@ export abstract class FindCommentsRepository {
/** Comments still standing (deleted ones kept for their replies do not count). */ /** Comments still standing (deleted ones kept for their replies do not count). */
abstract countByIssue(issueId: string): Promise<number>; abstract countByIssue(issueId: string): Promise<number>;
abstract countReplies(commentId: string): Promise<number>; abstract countReplies(commentId: string): Promise<number>;
/**
* Comments marked as decisions (not deleted): of one ticket, or of some
* projects, oldest first for a ticket and most recent first otherwise.
*/
abstract findDecisions(filter: {
issueId?: string;
projectIds?: string[];
search?: string;
limit: number;
}): Promise<CommentReadModel[]>;
} }

View File

@@ -47,6 +47,8 @@ export interface IssueFilter {
watching?: boolean; watching?: boolean;
/** Only the ones this person follows. */ /** Only the ones this person follows. */
watcherId?: string; watcherId?: string;
/** Only the ones this person was asked to review and has not answered. */
reviewerId?: string;
/** Only the ones this person opened, has or follows (a guest's view). */ /** Only the ones this person opened, has or follows (a guest's view). */
participantId?: string; participantId?: string;
/** RECENT (default): last updated first. RANK: backlog order. */ /** RECENT (default): last updated first. RANK: backlog order. */
@@ -62,6 +64,8 @@ export interface CrossProjectIssueFilter {
assigneeId?: string; assigneeId?: string;
/** Only the ones this person follows. */ /** Only the ones this person follows. */
watcherId?: string; watcherId?: string;
/** Only the ones this person was asked to review and has not answered. */
reviewerId?: string;
statuses?: string[]; statuses?: string[];
categories?: StatusCategory[]; categories?: StatusCategory[];
priorities?: IssuePriority[]; priorities?: IssuePriority[];

View File

@@ -0,0 +1,29 @@
/** «Remind me on Thursday»: one person's, on one ticket. */
export interface IssueReminder {
id: string;
userId: string;
issueId: string;
projectId: string;
/** When to tell (ISO, UTC). */
at: string;
/** What to remember, in one line. */
note: string | null;
createdAt: string;
/** When it was told (null: still waiting). */
sentAt: string | null;
}
export abstract class IssueRemindersRepository {
/** Each person has at most one waiting per ticket: setting it replaces it. */
abstract save(reminder: IssueReminder): Promise<void>;
abstract waitingFor(
userId: string,
issueId: string,
): Promise<IssueReminder | null>;
/** One person's waiting reminders, soonest first. */
abstract waitingOf(userId: string): Promise<IssueReminder[]>;
abstract remove(userId: string, issueId: string): Promise<void>;
/** Waiting ones whose time has come, oldest first. */
abstract due(now: string, limit: number): Promise<IssueReminder[]>;
abstract markSent(id: string, at: string): Promise<void>;
}

View File

@@ -0,0 +1,11 @@
/** When someone last opened a ticket: personal, no history. */
export interface IssueVisit {
userId: string;
issueId: string;
seenAt: string;
}
export abstract class IssueVisitsRepository {
/** Notes this visit; returns when the one before it was (null: never). */
abstract visit(visit: IssueVisit): Promise<string | null>;
}

View File

@@ -0,0 +1,19 @@
/** The tickets someone picked for one day of theirs. */
export interface MyDayRecord {
userId: string;
/** `YYYY-MM-DD` in the person's own time zone. */
day: string;
/** In the order they were picked. */
issueIds: string[];
updatedAt: string;
}
export abstract class MyDaysRepository {
abstract find(userId: string, day: string): Promise<MyDayRecord | null>;
/** The latest day before `day`, if any (to carry over what was left). */
abstract latestBefore(
userId: string,
day: string,
): Promise<MyDayRecord | null>;
abstract save(record: MyDayRecord): Promise<void>;
}

View File

@@ -0,0 +1,12 @@
import { PinnedIssueReadModel } from '@task-stream/api/tracker/domain';
/** Pinned tickets: one person's shortcuts, no history. */
export abstract class PinsRepository {
/** Most recently pinned first. */
abstract findByOwner(ownerId: string): Promise<PinnedIssueReadModel[]>;
abstract isPinned(ownerId: string, issueId: string): Promise<boolean>;
abstract countByOwner(ownerId: string): Promise<number>;
/** Pinning again keeps the first date. */
abstract pin(pin: PinnedIssueReadModel): Promise<void>;
abstract unpin(ownerId: string, issueId: string): Promise<void>;
}

View File

@@ -0,0 +1,16 @@
/** A release's public notes page: whoever has the link reads them. */
export interface ReleaseNotesShare {
releaseId: string;
projectId: string;
/** Random and long; kept as it is so the link can be copied again. */
token: string;
createdAt: string;
}
export abstract class ReleaseNoteSharesRepository {
abstract findByRelease(releaseId: string): Promise<ReleaseNotesShare | null>;
abstract findByToken(token: string): Promise<ReleaseNotesShare | null>;
/** Replaces the release's link, if any. */
abstract save(share: ReleaseNotesShare): Promise<void>;
abstract remove(releaseId: string): Promise<void>;
}

View File

@@ -0,0 +1,16 @@
/** Who follows a ticket with everything under it: personal, no history. */
export interface TreeFollow {
userId: string;
issueId: string;
projectId: string;
since: string;
}
export abstract class TreeFollowsRepository {
/** Following it again keeps the first date. */
abstract follow(follow: TreeFollow): Promise<void>;
abstract unfollow(userId: string, issueId: string): Promise<void>;
abstract isFollowing(userId: string, issueId: string): Promise<boolean>;
/** Everyone following any of these tickets (each once). */
abstract followersOf(issueIds: string[]): Promise<string[]>;
}

View File

@@ -1,5 +1,6 @@
import { ForbiddenError, NotFoundError } from '@task-stream/api/shared/domain'; import { ForbiddenError, NotFoundError } from '@task-stream/api/shared/domain';
import { IssueReadModel } from '@task-stream/api/tracker/domain'; import { IssueReadModel } from '@task-stream/api/tracker/domain';
import { ChangeFeed, Typing } from './ports/change-feed';
import { FindIssuesRepository } from './ports/find-issues.repository'; import { FindIssuesRepository } from './ports/find-issues.repository';
import { PresenceEntry, PresenceStore } from './ports/presence.store'; import { PresenceEntry, PresenceStore } from './ports/presence.store';
import { PRESENCE_TTL_MS, PresenceService } from './presence.service'; import { PRESENCE_TTL_MS, PresenceService } from './presence.service';
@@ -40,10 +41,23 @@ const access = {
}, },
} as unknown as ReadAccess; } as unknown as ReadAccess;
/** What would go out to the ticket's open pages. */
const feed = () => {
const published: Typing[] = [];
return {
published,
feed: {
publishTyping: async (typing: Typing) => {
published.push(typing);
},
} as unknown as ChangeFeed,
};
};
describe('PresenceService', () => { describe('PresenceService', () => {
it('tells who else is on a ticket, the ones editing first', async () => { it('tells who else is on a ticket, the ones editing first', async () => {
const store = new MemoryPresence(); const store = new MemoryPresence();
const presence = new PresenceService(store, issues, access); const presence = new PresenceService(store, issues, access, feed().feed);
await presence.touch({ id: 'ana', name: 'Ana' }, 'i1', false); await presence.touch({ id: 'ana', name: 'Ana' }, 'i1', false);
await presence.touch({ id: 'cris', name: 'Cris' }, 'i1', true); await presence.touch({ id: 'cris', name: 'Cris' }, 'i1', true);
const seen = await presence.touch({ id: 'bob', name: 'Bob' }, 'i1', false); const seen = await presence.touch({ id: 'bob', name: 'Bob' }, 'i1', false);
@@ -62,8 +76,33 @@ describe('PresenceService', () => {
).toEqual([]); ).toEqual([]);
}); });
it('tells at once who is writing, and where, to whoever can read it', async () => {
const { published, feed: changeFeed } = feed();
const presence = new PresenceService(
new MemoryPresence(),
issues,
access,
changeFeed,
);
await presence.typing({ id: 'ana', name: 'Ana' }, 'i1', 'c1');
await presence.typing({ id: 'bob', name: 'Bob' }, 'i1', null);
expect(published.map((t) => [t.issueId, t.user.name, t.threadId])).toEqual([
['i1', 'Ana', 'c1'],
['i1', 'Bob', null],
]);
await expect(
presence.typing({ id: 'eve', name: 'Eve' }, 'i1', null),
).rejects.toBeInstanceOf(ForbiddenError);
expect(published).toHaveLength(2);
});
it('only for whoever can read the ticket', async () => { it('only for whoever can read the ticket', async () => {
const presence = new PresenceService(new MemoryPresence(), issues, access); const presence = new PresenceService(
new MemoryPresence(),
issues,
access,
feed().feed,
);
await expect( await expect(
presence.touch({ id: 'eve', name: 'Eve' }, 'i1', false), presence.touch({ id: 'eve', name: 'Eve' }, 'i1', false),
).rejects.toBeInstanceOf(ForbiddenError); ).rejects.toBeInstanceOf(ForbiddenError);

View File

@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { NotFoundError } from '@task-stream/api/shared/domain'; import { NotFoundError } from '@task-stream/api/shared/domain';
import { ChangeFeed } from './ports/change-feed';
import { FindIssuesRepository } from './ports/find-issues.repository'; import { FindIssuesRepository } from './ports/find-issues.repository';
import { PresenceEntry, PresenceStore } from './ports/presence.store'; import { PresenceEntry, PresenceStore } from './ports/presence.store';
import { ReadAccess } from './queries/read-access'; import { ReadAccess } from './queries/read-access';
@@ -17,6 +18,7 @@ export class PresenceService {
private readonly store: PresenceStore, private readonly store: PresenceStore,
private readonly findIssues: FindIssuesRepository, private readonly findIssues: FindIssuesRepository,
private readonly access: ReadAccess, private readonly access: ReadAccess,
private readonly changeFeed: ChangeFeed,
) {} ) {}
/** /**
@@ -54,6 +56,24 @@ export class PresenceService {
); );
} }
/**
* I am writing on the ticket (an answer to `threadId`, or a new comment):
* told at once to whoever has it open, and forgotten.
*/
async typing(
viewer: { id: string; name: string },
issueId: string,
threadId: string | null,
): Promise<void> {
await this.assertCanView(viewer.id, issueId);
await this.changeFeed.publishTyping({
issueId,
user: { id: viewer.id, name: viewer.name },
threadId,
at: new Date().toISOString(),
});
}
/** I left the ticket's page. */ /** I left the ticket's page. */
leave(viewerId: string, issueId: string): Promise<void> { leave(viewerId: string, issueId: string): Promise<void> {
return this.store.leave(issueId, viewerId); return this.store.leave(issueId, viewerId);

View File

@@ -0,0 +1,112 @@
import { IQueryHandler, Query, QueryHandler } from '@nestjs/cqrs';
import {
CommentReadModel,
DecisionReadModel,
} from '@task-stream/api/tracker/domain';
import { FindCommentsRepository } from '../ports/find-comments.repository';
import { FindIssuesRepository } from '../ports/find-issues.repository';
import { FindProjectsRepository } from '../ports/find-projects.repository';
import { ReadAccess } from './read-access';
/** The decisions of a ticket, oldest first (shown above its conversation). */
export class GetIssueDecisionsQuery extends Query<CommentReadModel[]> {
constructor(
/** Null: anonymous (public projects only). */
public readonly viewerId: string | null,
public readonly issueId: string,
) {
super();
}
}
/**
* Decisions by their text, most recently decided first: of one project, or
* (without one) of every project the viewer belongs to.
*/
export class SearchDecisionsQuery extends Query<DecisionReadModel[]> {
constructor(
public readonly viewerId: string | null,
public readonly filter: {
projectId?: string;
search?: string;
limit: number;
},
) {
super();
}
}
@QueryHandler(GetIssueDecisionsQuery)
export class GetIssueDecisionsQueryHandler
implements IQueryHandler<GetIssueDecisionsQuery, CommentReadModel[]>
{
constructor(
private readonly findIssues: FindIssuesRepository,
private readonly findComments: FindCommentsRepository,
private readonly access: ReadAccess,
) {}
async execute(query: GetIssueDecisionsQuery): Promise<CommentReadModel[]> {
const issue = this.access.assertFound(
await this.findIssues.findById(query.issueId),
'Issue',
query.issueId,
);
await this.access.assertCanViewIssue(issue, query.viewerId);
return this.findComments.findDecisions({ issueId: issue.id, limit: 50 });
}
}
@QueryHandler(SearchDecisionsQuery)
export class SearchDecisionsQueryHandler
implements IQueryHandler<SearchDecisionsQuery, DecisionReadModel[]>
{
constructor(
private readonly findProjects: FindProjectsRepository,
private readonly findIssues: FindIssuesRepository,
private readonly findComments: FindCommentsRepository,
private readonly access: ReadAccess,
) {}
async execute(query: SearchDecisionsQuery): Promise<DecisionReadModel[]> {
const { filter, viewerId } = query;
let projectIds: string[];
if (filter.projectId) {
await this.access.assertCanView(filter.projectId, viewerId);
projectIds = [filter.projectId];
} else {
if (!viewerId) return [];
projectIds = (await this.findProjects.findByMember(viewerId)).map(
(p) => p.id,
);
}
if (projectIds.length === 0) return [];
const limit = Math.min(filter.limit, 100);
// Read a few more: some may sit in the trash or, for a guest, in
// tickets they do not take part in.
const comments = await this.findComments.findDecisions({
projectIds,
search: filter.search?.trim().slice(0, 200) || undefined,
limit: limit * 2,
});
const issues = new Map(
(
await this.findIssues.findByIds([
...new Set(comments.map((c) => c.issueId)),
])
).map((issue) => [issue.id, issue]),
);
const found: DecisionReadModel[] = [];
for (const comment of comments) {
const issue = issues.get(comment.issueId);
if (!issue || issue.trashedAt) continue;
if (!(await this.access.canViewIssue(issue, viewerId))) continue;
found.push({
comment,
issue: { id: issue.id, key: issue.key, title: issue.title },
});
if (found.length === limit) break;
}
return found;
}
}

View File

@@ -35,6 +35,7 @@ export class GetActivityQueryHandler
issueId: query.issueId, issueId: query.issueId,
limit: Math.min(query.limit, 200), limit: Math.min(query.limit, 200),
before: query.before, before: query.before,
after: query.after,
}); });
} }
} }

View File

@@ -10,6 +10,8 @@ export class GetActivityQuery extends Query<ActivityReadModel[]> {
public readonly limit = 50, public readonly limit = 50,
/** ISO date cursor: only activity strictly older than this. */ /** ISO date cursor: only activity strictly older than this. */
public readonly before?: string, public readonly before?: string,
/** ISO date: only activity at or after this (with `before`, a window). */
public readonly after?: string,
) { ) {
super(); super();
} }

View File

@@ -26,6 +26,10 @@ import { GetReleaseNotesDraftQueryHandler } from './get-release-notes-draft.quer
import { GetTrashQueryHandler } from './get-trash.query'; import { GetTrashQueryHandler } from './get-trash.query';
import { GetShowcaseQueryHandler } from './get-showcase.query'; import { GetShowcaseQueryHandler } from './get-showcase.query';
import { SearchMyIssuesQueryHandler } from './search-my-issues.query-handler'; import { SearchMyIssuesQueryHandler } from './search-my-issues.query-handler';
import {
GetIssueDecisionsQueryHandler,
SearchDecisionsQueryHandler,
} from './decisions.query';
export const QUERY_HANDLERS = [ export const QUERY_HANDLERS = [
GetPublicProjectsQueryHandler, GetPublicProjectsQueryHandler,
@@ -33,6 +37,8 @@ export const QUERY_HANDLERS = [
GetActivityQueryHandler, GetActivityQueryHandler,
GetBoardQueryHandler, GetBoardQueryHandler,
GetCommentsQueryHandler, GetCommentsQueryHandler,
GetIssueDecisionsQueryHandler,
SearchDecisionsQueryHandler,
GetIssueQueryHandler, GetIssueQueryHandler,
GetIssuesByIdsQueryHandler, GetIssuesByIdsQueryHandler,
GetMyProjectsQueryHandler, GetMyProjectsQueryHandler,

View File

@@ -56,6 +56,7 @@ export class SearchMyIssuesQueryHandler
: undefined, : undefined,
assigneeId: query.filter.assignedToMe ? query.viewerId : undefined, assigneeId: query.filter.assignedToMe ? query.viewerId : undefined,
watcherId: query.filter.watching ? query.viewerId : undefined, watcherId: query.filter.watching ? query.viewerId : undefined,
reviewerId: query.filter.reviewing ? query.viewerId : undefined,
statuses: query.filter.statuses, statuses: query.filter.statuses,
categories: filter.overdue categories: filter.overdue
? (filter.categories?.length ? filter.categories : open).filter((c) => ? (filter.categories?.length ? filter.categories : open).filter((c) =>

View File

@@ -11,6 +11,8 @@ export interface MyIssuesFilter {
assignedToMe: boolean; assignedToMe: boolean;
/** Only the tickets the viewer follows. */ /** Only the tickets the viewer follows. */
watching?: boolean; watching?: boolean;
/** Only the tickets the viewer was asked to review (unanswered). */
reviewing?: boolean;
statuses?: string[]; statuses?: string[];
/** e.g. TODO + IN_PROGRESS + QA = still open, whatever the project calls them. */ /** e.g. TODO + IN_PROGRESS + QA = still open, whatever the project calls them. */
categories?: StatusCategory[]; categories?: StatusCategory[];

View File

@@ -0,0 +1,171 @@
import {
CommandBus,
CqrsModule,
IQueryHandler,
QueryBus,
QueryHandler,
} from '@nestjs/cqrs';
import { Test } from '@nestjs/testing';
import { NotFoundError, ValidationError } from '@task-stream/api/shared/domain';
import {
IssueReadModel,
NotificationReadModel,
} from '@task-stream/api/tracker/domain';
import { Notifier } from '../notifications/notifier';
import {
IssueReminder,
IssueRemindersRepository,
} from '../ports/issue-reminders.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
import {
GetMyRemindersQuery,
ISSUE_REMINDERS,
SendIssueRemindersCommand,
SetIssueReminderCommand,
} from './issue-reminders';
class InMemoryReminders extends IssueRemindersRepository {
rows: IssueReminder[] = [];
async save(reminder: IssueReminder) {
await this.remove(reminder.userId, reminder.issueId);
this.rows.push(reminder);
}
async waitingFor(userId: string, issueId: string) {
return (
this.rows.find(
(r) => r.userId === userId && r.issueId === issueId && !r.sentAt,
) ?? null
);
}
async waitingOf(userId: string) {
return this.rows
.filter((r) => r.userId === userId && !r.sentAt)
.sort((a, b) => a.at.localeCompare(b.at));
}
async remove(userId: string, issueId: string) {
this.rows = this.rows.filter(
(r) => !(r.userId === userId && r.issueId === issueId && !r.sentAt),
);
}
async due(now: string) {
return this.rows.filter((r) => !r.sentAt && r.at <= now);
}
async markSent(id: string, at: string) {
const row = this.rows.find((r) => r.id === id);
if (row) row.sentAt = at;
}
}
/** Ana reads i1 and i2; i2 goes to the trash in one test. */
const issues = new Map<string, IssueReadModel>();
@QueryHandler(GetIssuesByIdsQuery)
class FakeIssuesByIds implements IQueryHandler<GetIssuesByIdsQuery> {
async execute(query: GetIssuesByIdsQuery) {
return query.viewerId === 'ana'
? query.ids.flatMap((id) => issues.get(id) ?? [])
: [];
}
}
const inHours = (h: number) =>
new Date(Date.now() + h * 3_600_000).toISOString();
async function setup() {
issues.clear();
for (const id of ['i1', 'i2'])
issues.set(id, {
id,
key: id === 'i1' ? 'WEB-1' : 'WEB-2',
title: 'Pagos',
projectId: 'p1',
projectKey: 'WEB',
trashedAt: null,
} as IssueReadModel);
const rows = new InMemoryReminders();
const sent: NotificationReadModel[] = [];
const moduleRef = await Test.createTestingModule({
imports: [CqrsModule.forRoot()],
providers: [
...ISSUE_REMINDERS,
FakeIssuesByIds,
{ provide: IssueRemindersRepository, useValue: rows },
{
provide: Notifier,
useValue: {
send: async (n: NotificationReadModel[]) => void sent.push(...n),
},
},
],
}).compile();
await moduleRef.init();
return {
rows,
sent,
commands: moduleRef.get(CommandBus),
queries: moduleRef.get(QueryBus),
};
}
describe('ticket reminders', () => {
it('keeps one per person and ticket, in the future and within a year', async () => {
const { commands, queries } = await setup();
await commands.execute(
new SetIssueReminderCommand('ana', 'i1', inHours(2)),
);
await commands.execute(
new SetIssueReminderCommand('ana', 'i1', inHours(5), ' Llamar a QA '),
);
await commands.execute(
new SetIssueReminderCommand('ana', 'i2', inHours(1)),
);
const mine = await queries.execute(new GetMyRemindersQuery('ana'));
expect(mine.map((m: { issue: IssueReadModel }) => m.issue.key)).toEqual([
'WEB-2',
'WEB-1',
]);
expect(mine[1].reminder.note).toBe('Llamar a QA');
await expect(
commands.execute(new SetIssueReminderCommand('ana', 'i1', inHours(-2))),
).rejects.toBeInstanceOf(ValidationError);
await expect(
commands.execute(
new SetIssueReminderCommand('ana', 'i1', inHours(24 * 400)),
),
).rejects.toBeInstanceOf(ValidationError);
await expect(
commands.execute(new SetIssueReminderCommand('eve', 'i1', inHours(2))),
).rejects.toBeInstanceOf(NotFoundError);
});
it('tells the ones whose time came, once, and forgets those out of reach', async () => {
const { commands, rows, sent } = await setup();
await commands.execute(
new SetIssueReminderCommand('ana', 'i1', inHours(1), 'Revisar el PR'),
);
await commands.execute(
new SetIssueReminderCommand('ana', 'i2', inHours(1)),
);
await commands.execute(
new SetIssueReminderCommand('ana', 'i1', inHours(1)),
);
expect(await commands.execute(new SendIssueRemindersCommand())).toBe(0);
issues.set('i2', {
...(issues.get('i2') as IssueReadModel),
trashedAt: 'x',
});
const later = inHours(2);
expect(await commands.execute(new SendIssueRemindersCommand(later))).toBe(
1,
);
expect(sent.map((n) => [n.userId, n.issueKey, n.summary])).toEqual([
['ana', 'WEB-1', 'Recordatorio: WEB-1 · Pagos'],
]);
expect(rows.rows.every((r) => r.sentAt)).toBe(true);
// Run again: nothing left.
expect(await commands.execute(new SendIssueRemindersCommand(later))).toBe(
0,
);
});
});

View File

@@ -0,0 +1,232 @@
import { randomUUID } from 'node:crypto';
import {
Command,
CommandHandler,
ICommandHandler,
IQueryHandler,
Query,
QueryBus,
QueryHandler,
} from '@nestjs/cqrs';
import { assertThat, NotFoundError } from '@task-stream/api/shared/domain';
import {
IssueReadModel,
NotificationKind,
SYSTEM_ACTOR_ID,
SYSTEM_ACTOR_NAME,
} from '@task-stream/api/tracker/domain';
import { Notifier } from '../notifications/notifier';
import {
IssueReminder,
IssueRemindersRepository,
} from '../ports/issue-reminders.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
/*
* «Remind me on Thursday»: a person's own reminder on a ticket, told as a
* notification (bell, push, e-mail) when its time comes. One waiting per
* person and ticket; private, no history.
*/
/** As far ahead as a reminder goes. */
export const MAX_REMINDER_DAYS = 366;
export const MAX_REMINDER_NOTE = 280;
export class SetIssueReminderCommand extends Command<IssueReminder> {
constructor(
public readonly userId: string,
public readonly issueId: string,
/** ISO date-time. */
public readonly at: string,
public readonly note: string | null = null,
) {
super();
}
}
export class ClearIssueReminderCommand extends Command<void> {
constructor(
public readonly userId: string,
public readonly issueId: string,
) {
super();
}
}
/** Scheduler only: tells the reminders whose time has come. */
export class SendIssueRemindersCommand extends Command<number> {
constructor(public readonly now: string = new Date().toISOString()) {
super();
}
}
export class GetIssueReminderQuery extends Query<IssueReminder | null> {
constructor(
public readonly userId: string,
public readonly issueId: string,
) {
super();
}
}
/** My waiting reminders with their tickets, soonest first. */
export class GetMyRemindersQuery extends Query<
{ reminder: IssueReminder; issue: IssueReadModel }[]
> {
constructor(public readonly userId: string) {
super();
}
}
@CommandHandler(SetIssueReminderCommand)
export class SetIssueReminderCommandHandler
implements ICommandHandler<SetIssueReminderCommand>
{
constructor(
private readonly reminders: IssueRemindersRepository,
private readonly queryBus: QueryBus,
) {}
async execute(command: SetIssueReminderCommand): Promise<IssueReminder> {
const at = Date.parse(command.at);
const now = Date.now();
assertThat(!Number.isNaN(at), 'A reminder needs a date and time');
assertThat(at > now - 60_000, 'A reminder must be in the future');
assertThat(
at <= now + MAX_REMINDER_DAYS * 86_400_000,
`A reminder can be at most a year ahead`,
);
const note = command.note?.replace(/\s+/g, ' ').trim() || null;
assertThat(
!note || note.length <= MAX_REMINDER_NOTE,
`A reminder's note takes ${MAX_REMINDER_NOTE} characters at most`,
);
const [issue]: IssueReadModel[] = await this.queryBus.execute(
new GetIssuesByIdsQuery(command.userId, [command.issueId]),
);
// A ticket I cannot read does not exist, as far as I know.
if (!issue || issue.trashedAt)
throw new NotFoundError('Issue', command.issueId);
const reminder: IssueReminder = {
id: randomUUID(),
userId: command.userId,
issueId: issue.id,
projectId: issue.projectId,
at: new Date(at).toISOString(),
note,
createdAt: new Date(now).toISOString(),
sentAt: null,
};
await this.reminders.save(reminder);
return reminder;
}
}
@CommandHandler(ClearIssueReminderCommand)
export class ClearIssueReminderCommandHandler
implements ICommandHandler<ClearIssueReminderCommand>
{
constructor(private readonly reminders: IssueRemindersRepository) {}
execute(command: ClearIssueReminderCommand): Promise<void> {
return this.reminders.remove(command.userId, command.issueId);
}
}
@CommandHandler(SendIssueRemindersCommand)
export class SendIssueRemindersCommandHandler
implements ICommandHandler<SendIssueRemindersCommand>
{
constructor(
private readonly reminders: IssueRemindersRepository,
private readonly queryBus: QueryBus,
private readonly notifier: Notifier,
) {}
async execute(command: SendIssueRemindersCommand): Promise<number> {
const due = await this.reminders.due(command.now, 200);
let sent = 0;
for (const reminder of due) {
const [issue]: IssueReadModel[] = await this.queryBus.execute(
new GetIssuesByIdsQuery(reminder.userId, [reminder.issueId]),
);
// Out of reach or in the trash by now: nothing to remind of.
if (issue && !issue.trashedAt) {
// Its id makes it idempotent: two instances tell it once.
await this.notifier.send([
{
id: `issue-reminder:${reminder.id}`,
userId: reminder.userId,
kind: NotificationKind.REMINDER,
projectId: issue.projectId,
projectKey: issue.projectKey,
issueId: issue.id,
issueKey: issue.key,
actor: { id: SYSTEM_ACTOR_ID, name: SYSTEM_ACTOR_NAME },
summary: reminder.note
? `Recordatorio de ${issue.key}: ${reminder.note}`
: `Recordatorio: ${issue.key} · ${issue.title}`,
readAt: null,
createdAt: command.now,
},
]);
sent++;
}
await this.reminders.markSent(reminder.id, command.now);
}
return sent;
}
}
@QueryHandler(GetIssueReminderQuery)
export class GetIssueReminderQueryHandler
implements IQueryHandler<GetIssueReminderQuery, IssueReminder | null>
{
constructor(private readonly reminders: IssueRemindersRepository) {}
execute(query: GetIssueReminderQuery): Promise<IssueReminder | null> {
return this.reminders.waitingFor(query.userId, query.issueId);
}
}
@QueryHandler(GetMyRemindersQuery)
export class GetMyRemindersQueryHandler
implements
IQueryHandler<
GetMyRemindersQuery,
{ reminder: IssueReminder; issue: IssueReadModel }[]
>
{
constructor(
private readonly reminders: IssueRemindersRepository,
private readonly queryBus: QueryBus,
) {}
async execute(
query: GetMyRemindersQuery,
): Promise<{ reminder: IssueReminder; issue: IssueReadModel }[]> {
const waiting = await this.reminders.waitingOf(query.userId);
if (!waiting.length) return [];
const issues: IssueReadModel[] = await this.queryBus.execute(
new GetIssuesByIdsQuery(
query.userId,
waiting.map((r) => r.issueId),
),
);
const byId = new Map(
issues.filter((i) => !i.trashedAt).map((i) => [i.id, i]),
);
return waiting.flatMap((reminder) => {
const issue = byId.get(reminder.issueId);
return issue ? [{ reminder, issue }] : [];
});
}
}
export const ISSUE_REMINDERS = [
SetIssueReminderCommandHandler,
ClearIssueReminderCommandHandler,
SendIssueRemindersCommandHandler,
GetIssueReminderQueryHandler,
GetMyRemindersQueryHandler,
];

View File

@@ -0,0 +1,142 @@
import {
CommandBus,
CqrsModule,
IQueryHandler,
QueryBus,
QueryHandler,
} from '@nestjs/cqrs';
import { Test } from '@nestjs/testing';
import {
BusinessRuleError,
NotFoundError,
} from '@task-stream/api/shared/domain';
import {
IssueReadModel,
PinnedIssueReadModel,
} from '@task-stream/api/tracker/domain';
import { PinsRepository } from '../ports/pins.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
import {
GetMyPinsQuery,
IsIssuePinnedQuery,
MAX_PINS,
PINS,
PinIssueCommand,
} from './pins';
class InMemoryPins extends PinsRepository {
rows: PinnedIssueReadModel[] = [];
async findByOwner(ownerId: string) {
return this.rows
.filter((p) => p.ownerId === ownerId)
.sort((a, b) => b.pinnedAt.localeCompare(a.pinnedAt));
}
async isPinned(ownerId: string, issueId: string) {
return this.rows.some(
(p) => p.ownerId === ownerId && p.issueId === issueId,
);
}
async countByOwner(ownerId: string) {
return this.rows.filter((p) => p.ownerId === ownerId).length;
}
async pin(pin: PinnedIssueReadModel) {
if (!(await this.isPinned(pin.ownerId, pin.issueId))) this.rows.push(pin);
}
async unpin(ownerId: string, issueId: string) {
this.rows = this.rows.filter(
(p) => !(p.ownerId === ownerId && p.issueId === issueId),
);
}
}
/** What each person can read: `ana` all but `hidden`, in the trash `old`. */
const issues = new Map<string, IssueReadModel>();
const readable = (viewerId: string | null, id: string) =>
viewerId === 'ana' && id !== 'hidden';
@QueryHandler(GetIssuesByIdsQuery)
class FakeIssuesByIds implements IQueryHandler<GetIssuesByIdsQuery> {
async execute(query: GetIssuesByIdsQuery) {
return query.ids
.filter((id) => readable(query.viewerId, id))
.map(
(id) =>
issues.get(id) ??
({
id,
trashedAt: id === 'old' ? '2026-01-01' : null,
} as IssueReadModel),
);
}
}
async function setup() {
const rows = new InMemoryPins();
const moduleRef = await Test.createTestingModule({
imports: [CqrsModule.forRoot()],
providers: [
...PINS,
FakeIssuesByIds,
{ provide: PinsRepository, useValue: rows },
],
}).compile();
await moduleRef.init();
return {
rows,
commands: moduleRef.get(CommandBus),
queries: moduleRef.get(QueryBus),
};
}
describe('pinned tickets', () => {
it('pins, lists most recent first and unpins', async () => {
const { commands, queries } = await setup();
await commands.execute(new PinIssueCommand('ana', 'a', true));
await new Promise((r) => setTimeout(r, 2));
await commands.execute(new PinIssueCommand('ana', 'b', true));
// Twice is still once.
await commands.execute(new PinIssueCommand('ana', 'b', true));
const mine = await queries.execute(new GetMyPinsQuery('ana'));
expect(mine.map((i: IssueReadModel) => i.id)).toEqual(['b', 'a']);
expect(await queries.execute(new IsIssuePinnedQuery('ana', 'a'))).toBe(
true,
);
await commands.execute(new PinIssueCommand('ana', 'a', false));
expect(await queries.execute(new IsIssuePinnedQuery('ana', 'a'))).toBe(
false,
);
});
it('does not pin what I cannot read, nor what is in the trash', async () => {
const { commands } = await setup();
await expect(
commands.execute(new PinIssueCommand('ana', 'hidden', true)),
).rejects.toBeInstanceOf(NotFoundError);
await expect(
commands.execute(new PinIssueCommand('ana', 'old', true)),
).rejects.toBeInstanceOf(NotFoundError);
});
it('keeps a pin to a trashed ticket but does not list it', async () => {
const { commands, queries, rows } = await setup();
await commands.execute(new PinIssueCommand('ana', 'a', true));
await rows.pin({ ownerId: 'ana', issueId: 'old', pinnedAt: '2026-01-02' });
const mine = await queries.execute(new GetMyPinsQuery('ana'));
expect(mine.map((i: IssueReadModel) => i.id)).toEqual(['a']);
expect(rows.rows).toHaveLength(2);
});
it(`stops at ${MAX_PINS}, after forgetting the ones out of reach`, async () => {
const { commands, rows } = await setup();
for (let i = 0; i < MAX_PINS - 1; i++)
await rows.pin({ ownerId: 'ana', issueId: `t${i}`, pinnedAt: `${i}` });
await rows.pin({ ownerId: 'ana', issueId: 'hidden', pinnedAt: 'x' });
// Full, but one is out of reach: it makes room.
await commands.execute(new PinIssueCommand('ana', 'new', true));
expect(await rows.isPinned('ana', 'hidden')).toBe(false);
expect(await rows.countByOwner('ana')).toBe(MAX_PINS);
await expect(
commands.execute(new PinIssueCommand('ana', 'one-more', true)),
).rejects.toBeInstanceOf(BusinessRuleError);
});
});

View File

@@ -0,0 +1,150 @@
import {
Command,
CommandHandler,
ICommandHandler,
IQueryHandler,
Query,
QueryBus,
QueryHandler,
} from '@nestjs/cqrs';
import {
BusinessRuleError,
NotFoundError,
} from '@task-stream/api/shared/domain';
import { IssueReadModel } from '@task-stream/api/tracker/domain';
import { PinsRepository } from '../ports/pins.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
/*
* Pinned tickets: the few someone keeps at hand, on their home page and in
* the search palette. Private, across projects, no history (like the views
* of «my work»).
*/
/** A person keeps at most this many. */
export const MAX_PINS = 20;
export class PinIssueCommand extends Command<void> {
constructor(
public readonly ownerId: string,
public readonly issueId: string,
/** False: unpin. */
public readonly pinned: boolean,
) {
super();
}
}
/** My pinned tickets that I can still read and are not in the trash. */
export class GetMyPinsQuery extends Query<IssueReadModel[]> {
constructor(public readonly ownerId: string) {
super();
}
}
export class IsIssuePinnedQuery extends Query<boolean> {
constructor(
public readonly ownerId: string,
public readonly issueId: string,
) {
super();
}
}
@CommandHandler(PinIssueCommand)
export class PinIssueCommandHandler
implements ICommandHandler<PinIssueCommand>
{
constructor(
private readonly pins: PinsRepository,
private readonly queryBus: QueryBus,
) {}
async execute(command: PinIssueCommand): Promise<void> {
const { ownerId, issueId } = command;
if (!command.pinned) return this.pins.unpin(ownerId, issueId);
const [issue] = await this.queryBus.execute(
new GetIssuesByIdsQuery(ownerId, [issueId]),
);
// A ticket I cannot read does not exist, as far as I know.
if (!issue || issue.trashedAt) throw new NotFoundError('Issue', issueId);
if (await this.pins.isPinned(ownerId, issueId)) return;
if (
(await this.pins.countByOwner(ownerId)) >= MAX_PINS &&
(await this.dropUnreadable(ownerId)) >= MAX_PINS
)
throw new BusinessRuleError(
`You already keep ${MAX_PINS} pinned tickets; unpin one first`,
);
await this.pins.pin({
ownerId,
issueId,
pinnedAt: new Date().toISOString(),
});
}
/**
* Forgets the pins of tickets I can no longer read (I left the project,
* it was deleted) so they do not hold a place; returns how many remain.
*/
private async dropUnreadable(ownerId: string): Promise<number> {
const pins = await this.pins.findByOwner(ownerId);
const readable = new Set(
(
await this.queryBus.execute(
new GetIssuesByIdsQuery(
ownerId,
pins.map((p) => p.issueId),
),
)
).map((issue) => issue.id),
);
for (const pin of pins)
if (!readable.has(pin.issueId))
await this.pins.unpin(ownerId, pin.issueId);
return readable.size;
}
}
@QueryHandler(GetMyPinsQuery)
export class GetMyPinsQueryHandler
implements IQueryHandler<GetMyPinsQuery, IssueReadModel[]>
{
constructor(
private readonly pins: PinsRepository,
private readonly queryBus: QueryBus,
) {}
async execute(query: GetMyPinsQuery): Promise<IssueReadModel[]> {
const pins = await this.pins.findByOwner(query.ownerId);
if (pins.length === 0) return [];
const issues: IssueReadModel[] = await this.queryBus.execute(
new GetIssuesByIdsQuery(
query.ownerId,
pins.map((p) => p.issueId),
),
);
// In the trash or out of reach: kept, in case it comes back.
const byId = new Map(
issues.filter((i) => !i.trashedAt).map((i) => [i.id, i]),
);
return pins.flatMap((p) => byId.get(p.issueId) ?? []);
}
}
@QueryHandler(IsIssuePinnedQuery)
export class IsIssuePinnedQueryHandler
implements IQueryHandler<IsIssuePinnedQuery, boolean>
{
constructor(private readonly pins: PinsRepository) {}
execute(query: IsIssuePinnedQuery): Promise<boolean> {
return this.pins.isPinned(query.ownerId, query.issueId);
}
}
export const PINS = [
PinIssueCommandHandler,
GetMyPinsQueryHandler,
IsIssuePinnedQueryHandler,
];

View File

@@ -11,8 +11,16 @@ import {
ShareDashboardCommand, ShareDashboardCommand,
UnshareDashboardCommand, UnshareDashboardCommand,
} from './sharing/dashboard-shares'; } from './sharing/dashboard-shares';
import { ReleaseNotesShare } from './ports/release-note-shares.repository';
import {
GetPublicReleaseNotesQuery,
GetReleaseNotesShareQuery,
PublicReleaseNotes,
ShareReleaseNotesCommand,
UnshareReleaseNotesCommand,
} from './sharing/release-notes-shares';
/** The project's dashboard for clients, behind a secret link. */ /** The project's dashboard and its releases' notes, behind secret links. */
@Injectable() @Injectable()
export class SharingService { export class SharingService {
constructor( constructor(
@@ -48,6 +56,38 @@ export class SharingService {
); );
} }
/** A release's public notes link, if any (owners and admins). */
releaseNotesShare(
viewerId: string,
releaseId: string,
): Promise<ReleaseNotesShare | null> {
return this.queryBus.execute(
new GetReleaseNotesShareQuery(viewerId, releaseId),
);
}
/** Turns a release's public notes on; `renew` makes a new secret. */
shareReleaseNotes(
actorId: string,
releaseId: string,
renew = false,
): Promise<ReleaseNotesShare> {
return this.commands.execute(
new ShareReleaseNotesCommand(actorId, releaseId, renew),
);
}
unshareReleaseNotes(actorId: string, releaseId: string): Promise<void> {
return this.commands.execute(
new UnshareReleaseNotesCommand(actorId, releaseId),
);
}
/** A release's notes for anyone with the link, or null. */
publicReleaseNotes(token: string): Promise<PublicReleaseNotes | null> {
return this.queryBus.execute(new GetPublicReleaseNotesQuery(token));
}
/** What a link shows now, or null if no project has it. */ /** What a link shows now, or null if no project has it. */
shared(token: string): Promise<SharedDashboardReadModel | null> { shared(token: string): Promise<SharedDashboardReadModel | null> {
return this.queryBus.execute(new GetSharedDashboardQuery(token)); return this.queryBus.execute(new GetSharedDashboardQuery(token));

View File

@@ -0,0 +1,160 @@
import { CommandBus, CqrsModule, QueryBus } from '@nestjs/cqrs';
import { Test } from '@nestjs/testing';
import { ForbiddenError } from '@task-stream/api/shared/domain';
import {
DEFAULT_PROJECT_SETTINGS,
IssueReadModel,
ReleaseReadModel,
ReleaseStatus,
StatusCategory,
} from '@task-stream/api/tracker/domain';
import { WriteAccess } from '../commands/write-access';
import { FindIssuesRepository } from '../ports/find-issues.repository';
import { FindProjectsRepository } from '../ports/find-projects.repository';
import { FindReleasesRepository } from '../ports/find-releases.repository';
import {
ReleaseNoteSharesRepository,
ReleaseNotesShare,
} from '../ports/release-note-shares.repository';
import {
GetPublicReleaseNotesQuery,
RELEASE_NOTES_SHARES,
ShareReleaseNotesCommand,
UnshareReleaseNotesCommand,
} from './release-notes-shares';
class InMemoryShares extends ReleaseNoteSharesRepository {
rows = new Map<string, ReleaseNotesShare>();
async findByRelease(releaseId: string) {
return this.rows.get(releaseId) ?? null;
}
async findByToken(token: string) {
return [...this.rows.values()].find((s) => s.token === token) ?? null;
}
async save(share: ReleaseNotesShare) {
this.rows.set(share.releaseId, share);
}
async remove(releaseId: string) {
this.rows.delete(releaseId);
}
}
const release: ReleaseReadModel = {
id: 'r1',
projectId: 'p1',
name: 'v2.0',
description: 'Pagos nuevos',
targetDate: '2026-11-15',
status: ReleaseStatus.PLANNED,
releasedAt: null,
notes: null,
createdAt: '',
version: 1,
};
async function setup() {
release.notes = null;
const shares = new InMemoryShares();
const moduleRef = await Test.createTestingModule({
imports: [CqrsModule.forRoot()],
providers: [
...RELEASE_NOTES_SHARES,
{ provide: ReleaseNoteSharesRepository, useValue: shares },
{
provide: FindReleasesRepository,
useValue: {
findById: async (id: string) => (id === 'r1' ? release : null),
},
},
{
provide: FindProjectsRepository,
useValue: {
findById: async () => ({
id: 'p1',
key: 'WEB',
name: 'Web',
settings: DEFAULT_PROJECT_SETTINGS,
}),
},
},
{
provide: FindIssuesRepository,
useValue: {
search: async () => ({
items: [
{
key: 'WEB-1',
number: 1,
title: 'Pago con Bizum',
type: 'FEATURE',
statusCategory: StatusCategory.DONE,
} as IssueReadModel,
],
total: 1,
}),
},
},
{
provide: WriteAccess,
useValue: {
project: async () => {
const assertManages = (userId: string) => {
if (userId !== 'owner') throw new ForbiddenError('No');
};
return { assertManages, assertCanManage: assertManages };
},
},
},
],
}).compile();
await moduleRef.init();
return {
commands: moduleRef.get(CommandBus),
queries: moduleRef.get(QueryBus),
};
}
describe("a release's public notes", () => {
it('opens for whoever manages the project, and keeps its link until renewed', async () => {
const { commands } = await setup();
await expect(
commands.execute(new ShareReleaseNotesCommand('dev', 'r1')),
).rejects.toBeInstanceOf(ForbiddenError);
const first = await commands.execute(
new ShareReleaseNotesCommand('owner', 'r1'),
);
expect(first.token.length).toBeGreaterThan(30);
expect(
(await commands.execute(new ShareReleaseNotesCommand('owner', 'r1')))
.token,
).toBe(first.token);
const renewed = await commands.execute(
new ShareReleaseNotesCommand('owner', 'r1', true),
);
expect(renewed.token).not.toBe(first.token);
});
it('shows the notes written, or the draft without repeating the title', async () => {
const { commands, queries } = await setup();
const { token } = await commands.execute(
new ShareReleaseNotesCommand('owner', 'r1'),
);
const drafted = await queries.execute(
new GetPublicReleaseNotesQuery(token),
);
expect(drafted).toMatchObject({ releaseName: 'v2.0', written: false });
expect(drafted?.notes).toContain('Pago con Bizum (WEB-1)');
expect(drafted?.notes).not.toContain('## v2.0');
expect(drafted?.notes).not.toContain('Pagos nuevos');
release.notes = '## Novedades\n- Bizum';
expect(
await queries.execute(new GetPublicReleaseNotesQuery(token)),
).toMatchObject({ notes: '## Novedades\n- Bizum', written: true });
await commands.execute(new UnshareReleaseNotesCommand('owner', 'r1'));
expect(
await queries.execute(new GetPublicReleaseNotesQuery(token)),
).toBeNull();
});
});

View File

@@ -0,0 +1,235 @@
import { randomBytes } from 'node:crypto';
import {
Command,
CommandHandler,
ICommandHandler,
IQueryHandler,
Query,
QueryHandler,
} from '@nestjs/cqrs';
import { NotFoundError } from '@task-stream/api/shared/domain';
import {
DEFAULT_PROJECT_SETTINGS,
ProjectWorkflow,
ReleaseStatus,
} from '@task-stream/api/tracker/domain';
import { WriteAccess } from '../commands/write-access';
import { FindIssuesRepository } from '../ports/find-issues.repository';
import { FindProjectsRepository } from '../ports/find-projects.repository';
import { FindReleasesRepository } from '../ports/find-releases.repository';
import {
ReleaseNoteSharesRepository,
ReleaseNotesShare,
} from '../ports/release-note-shares.repository';
import { draftReleaseNotes } from '../releases/release-notes';
/*
* A release's notes as a public page, for clients: a secret link (also for
* private projects) that shows the notes written, or the ones drawn from
* its finished tickets while there are none.
*/
/** What the public page shows. */
export interface PublicReleaseNotes {
projectName: string;
projectKey: string;
releaseName: string;
description: string | null;
status: ReleaseStatus;
targetDate: string | null;
releasedAt: string | null;
/** Markdown. */
notes: string;
/** False: drawn from its finished tickets (nobody wrote them yet). */
written: boolean;
}
/** Turns the link on; with `renew` (or the first time) a new secret. */
export class ShareReleaseNotesCommand extends Command<ReleaseNotesShare> {
constructor(
public readonly actorId: string,
public readonly releaseId: string,
public readonly renew = false,
) {
super();
}
}
export class UnshareReleaseNotesCommand extends Command<void> {
constructor(
public readonly actorId: string,
public readonly releaseId: string,
) {
super();
}
}
/** The release's link, for whoever manages the project. */
export class GetReleaseNotesShareQuery extends Query<ReleaseNotesShare | null> {
constructor(
public readonly viewerId: string,
public readonly releaseId: string,
) {
super();
}
}
/** The page, for anyone with the link; null for an unknown one. */
export class GetPublicReleaseNotesQuery extends Query<PublicReleaseNotes | null> {
constructor(public readonly token: string) {
super();
}
}
async function releaseOf(
findReleases: FindReleasesRepository,
releaseId: string,
) {
const release = await findReleases.findById(releaseId);
if (!release) throw new NotFoundError('Release', releaseId);
return release;
}
@CommandHandler(ShareReleaseNotesCommand)
export class ShareReleaseNotesCommandHandler
implements ICommandHandler<ShareReleaseNotesCommand>
{
constructor(
private readonly shares: ReleaseNoteSharesRepository,
private readonly findReleases: FindReleasesRepository,
private readonly access: WriteAccess,
) {}
async execute(command: ShareReleaseNotesCommand): Promise<ReleaseNotesShare> {
const release = await releaseOf(this.findReleases, command.releaseId);
(await this.access.project(release.projectId)).assertCanManage(
command.actorId,
);
const current = await this.shares.findByRelease(release.id);
if (current && !command.renew) return current;
const share: ReleaseNotesShare = {
releaseId: release.id,
projectId: release.projectId,
// 32 random bytes: nobody guesses it.
token: randomBytes(32).toString('base64url'),
createdAt: new Date().toISOString(),
};
await this.shares.save(share);
return share;
}
}
@CommandHandler(UnshareReleaseNotesCommand)
export class UnshareReleaseNotesCommandHandler
implements ICommandHandler<UnshareReleaseNotesCommand>
{
constructor(
private readonly shares: ReleaseNoteSharesRepository,
private readonly findReleases: FindReleasesRepository,
private readonly access: WriteAccess,
) {}
async execute(command: UnshareReleaseNotesCommand): Promise<void> {
const release = await releaseOf(this.findReleases, command.releaseId);
(await this.access.project(release.projectId)).assertManages(
command.actorId,
);
await this.shares.remove(release.id);
}
}
@QueryHandler(GetReleaseNotesShareQuery)
export class GetReleaseNotesShareQueryHandler
implements IQueryHandler<GetReleaseNotesShareQuery, ReleaseNotesShare | null>
{
constructor(
private readonly shares: ReleaseNoteSharesRepository,
private readonly findReleases: FindReleasesRepository,
private readonly access: WriteAccess,
) {}
async execute(
query: GetReleaseNotesShareQuery,
): Promise<ReleaseNotesShare | null> {
const release = await releaseOf(this.findReleases, query.releaseId);
(await this.access.project(release.projectId)).assertManages(
query.viewerId,
);
return this.shares.findByRelease(release.id);
}
}
@QueryHandler(GetPublicReleaseNotesQuery)
export class GetPublicReleaseNotesQueryHandler
implements
IQueryHandler<GetPublicReleaseNotesQuery, PublicReleaseNotes | null>
{
constructor(
private readonly shares: ReleaseNoteSharesRepository,
private readonly findReleases: FindReleasesRepository,
private readonly findProjects: FindProjectsRepository,
private readonly findIssues: FindIssuesRepository,
) {}
async execute(
query: GetPublicReleaseNotesQuery,
): Promise<PublicReleaseNotes | null> {
const share = await this.shares.findByToken(query.token);
if (!share) return null;
const [release, project] = await Promise.all([
this.findReleases.findById(share.releaseId),
this.findProjects.findById(share.projectId),
]);
// The release or the project was deleted: the link went with them.
if (!release || !project) return null;
const written = !!release.notes?.trim();
const notes = written
? (release.notes as string)
: withoutHeading(
draftReleaseNotes({
release,
issues: (
await this.findIssues.search({
projectId: release.projectId,
releaseId: release.id,
limit: 500,
offset: 0,
})
).items,
workflow: new ProjectWorkflow(
project.settings ?? DEFAULT_PROJECT_SETTINGS,
),
}),
release.description,
);
return {
projectName: project.name,
projectKey: project.key,
releaseName: release.name,
description: release.description,
status: release.status,
targetDate: release.targetDate,
releasedAt: release.releasedAt,
notes,
written,
};
}
}
/**
* The draft without its title line (and description): the page shows the
* release's name, date and description above it already.
*/
function withoutHeading(draft: string, description: string | null): string {
let lines = draft.split('\n').slice(1);
if (description && lines[0] === '' && lines[1] === description)
lines = lines.slice(2);
return lines.join('\n').trim() + '\n';
}
export const RELEASE_NOTES_SHARES = [
ShareReleaseNotesCommandHandler,
UnshareReleaseNotesCommandHandler,
GetReleaseNotesShareQueryHandler,
GetPublicReleaseNotesQueryHandler,
];

View File

@@ -35,6 +35,19 @@ import {
import { SAVED_FILTERS } from './saved-filters/saved-filters'; import { SAVED_FILTERS } from './saved-filters/saved-filters';
import { MY_VIEWS } from './saved-filters/my-views'; import { MY_VIEWS } from './saved-filters/my-views';
import { PINS } from './saved-filters/pins';
import { ALERT_HANDLERS } from './alerts/alerts';
import { TREE_FOLLOWS } from './follows/tree-follows';
import { ISSUE_VISITS } from './visits/issue-visits';
import { IssueVisitsService } from './issue-visits.service';
import { ISSUE_REMINDERS } from './reminders/issue-reminders';
import { MY_DAY } from './my-day/my-day';
import { RELEASE_NOTES_SHARES } from './sharing/release-notes-shares';
import { MyDayService } from './my-day.service';
import { IssueRemindersService } from './issue-reminders.service';
import { TreeFollowsService } from './tree-follows.service';
import { AlertsService } from './alerts.service';
import { PinsService } from './pins.service';
import { SendDueRemindersCommandHandler } from './notifications/reminders'; import { SendDueRemindersCommandHandler } from './notifications/reminders';
import { SavedFiltersService } from './saved-filters.service'; import { SavedFiltersService } from './saved-filters.service';
import { SprintsService } from './sprints.service'; import { SprintsService } from './sprints.service';
@@ -78,6 +91,12 @@ const SERVICES = [
BlockersService, BlockersService,
NotificationsService, NotificationsService,
SavedFiltersService, SavedFiltersService,
PinsService,
AlertsService,
TreeFollowsService,
IssueVisitsService,
IssueRemindersService,
MyDayService,
SprintsService, SprintsService,
GitService, GitService,
WebhooksService, WebhooksService,
@@ -108,6 +127,13 @@ const SERVICES = [
...NOTIFICATIONS, ...NOTIFICATIONS,
...SAVED_FILTERS, ...SAVED_FILTERS,
...MY_VIEWS, ...MY_VIEWS,
...PINS,
...ALERT_HANDLERS,
...TREE_FOLLOWS,
...ISSUE_VISITS,
...ISSUE_REMINDERS,
...MY_DAY,
...RELEASE_NOTES_SHARES,
...GIT_HANDLERS, ...GIT_HANDLERS,
...WEBHOOK_HANDLERS, ...WEBHOOK_HANDLERS,
...TRANSFER_HANDLERS, ...TRANSFER_HANDLERS,

View File

@@ -0,0 +1,24 @@
import { CommandRunner } from '@task-stream/api/shared/application';
import { Injectable } from '@nestjs/common';
import { QueryBus } from '@nestjs/cqrs';
import {
FollowTreeCommand,
IsFollowingTreeQuery,
} from './follows/tree-follows';
/** Following a ticket with everything under it (an epic). */
@Injectable()
export class TreeFollowsService {
constructor(
private readonly commands: CommandRunner,
private readonly queryBus: QueryBus,
) {}
follow(userId: string, issueId: string, on: boolean): Promise<void> {
return this.commands.execute(new FollowTreeCommand(userId, issueId, on));
}
isFollowing(userId: string, issueId: string): Promise<boolean> {
return this.queryBus.execute(new IsFollowingTreeQuery(userId, issueId));
}
}

View File

@@ -0,0 +1,51 @@
import {
Command,
CommandHandler,
ICommandHandler,
QueryBus,
} from '@nestjs/cqrs';
import { NotFoundError } from '@task-stream/api/shared/domain';
import { IssueReadModel } from '@task-stream/api/tracker/domain';
import { IssueVisitsRepository } from '../ports/issue-visits.repository';
import { GetIssuesByIdsQuery } from '../queries/get-issues-by-ids.query';
/*
* «Lo nuevo desde tu última visita»: opening a ticket notes the moment, and
* says when the visit before was, so the client can tell what others did
* meanwhile. Personal, no history (like pinned tickets).
*/
export class VisitIssueCommand extends Command<string | null> {
constructor(
public readonly userId: string,
public readonly issueId: string,
) {
super();
}
}
@CommandHandler(VisitIssueCommand)
export class VisitIssueCommandHandler
implements ICommandHandler<VisitIssueCommand>
{
constructor(
private readonly visits: IssueVisitsRepository,
private readonly queryBus: QueryBus,
) {}
async execute(command: VisitIssueCommand): Promise<string | null> {
const { userId, issueId } = command;
const [issue]: IssueReadModel[] = await this.queryBus.execute(
new GetIssuesByIdsQuery(userId, [issueId]),
);
// A ticket I cannot read does not exist, as far as I know.
if (!issue) throw new NotFoundError('Issue', issueId);
return this.visits.visit({
userId,
issueId,
seenAt: new Date().toISOString(),
});
}
}
export const ISSUE_VISITS = [VisitIssueCommandHandler];

View File

@@ -8,6 +8,7 @@ export * from './lib/issue/issue-hierarchy';
export * from './lib/issue/issue-checklist'; export * from './lib/issue/issue-checklist';
export * from './lib/issue/issue-rank'; export * from './lib/issue/issue-rank';
export * from './lib/issue/dev-link'; export * from './lib/issue/dev-link';
export * from './lib/issue/review';
export * from './lib/project/project-settings'; export * from './lib/project/project-settings';
export * from './lib/comment/comment'; export * from './lib/comment/comment';
export * from './lib/release/release'; export * from './lib/release/release';

View File

@@ -5,6 +5,13 @@ import {
assertThat, assertThat,
} from '@task-stream/api/shared/domain'; } from '@task-stream/api/shared/domain';
import { CommentAddedEvent } from '../events/comment-added.event'; import { CommentAddedEvent } from '../events/comment-added.event';
import { CommentDecisionMarkedEvent } from '../events/comment-decision-marked.event';
import { CommentThreadResolvedEvent } from '../events/comment-thread-resolved.event';
import { CommentTurnedIntoIssueEvent } from '../events/comment-turned-into-issue.event';
import {
CommentPollClosedEvent,
CommentPollVotedEvent,
} from '../events/comment-poll.events';
import { CommentDeletedEvent } from '../events/comment-deleted.event'; import { CommentDeletedEvent } from '../events/comment-deleted.event';
import { CommentEditedEvent } from '../events/comment-edited.event'; import { CommentEditedEvent } from '../events/comment-edited.event';
import { CommentReactedEvent } from '../events/comment-reacted.event'; import { CommentReactedEvent } from '../events/comment-reacted.event';
@@ -28,6 +35,32 @@ export interface CommentProps {
deleted: boolean; deleted: boolean;
createdAt: string; createdAt: string;
editedAt: string | null; editedAt: string | null;
/** A quick poll's options (2–6); absent without one. */
poll?: string[] | null;
}
export const MIN_POLL_OPTIONS = 2;
export const MAX_POLL_OPTIONS = 6;
const MAX_POLL_OPTION = 80;
/** A poll's options, trimmed: 2 to 6, different, short. */
export function validPoll(options: string[]): string[] {
const clean = options
.map((o) => o.replace(/\s+/g, ' ').trim())
.filter(Boolean);
assertThat(
clean.length >= MIN_POLL_OPTIONS && clean.length <= MAX_POLL_OPTIONS,
`A poll takes ${MIN_POLL_OPTIONS} to ${MAX_POLL_OPTIONS} options`,
);
assertThat(
clean.every((o) => o.length <= MAX_POLL_OPTION),
`A poll option takes ${MAX_POLL_OPTION} characters at most`,
);
assertThat(
new Set(clean.map((o) => o.toLowerCase())).size === clean.length,
'Poll options must be different',
);
return clean;
} }
const MAX_BODY = 20_000; const MAX_BODY = 20_000;
@@ -41,6 +74,17 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
public replyTo: string | null = null; public replyTo: string | null = null;
/** Who chose each emoji (only the ones somebody chose). */ /** Who chose each emoji (only the ones somebody chose). */
public reactions: Record<string, string[]> = {}; public reactions: Record<string, string[]> = {};
/** What was decided on the ticket: shown above it and searchable. */
public decision = false;
/** A top-level comment whose conversation was settled. */
public resolved = false;
/** A quick poll: its options, who voted what, and whether it closed. */
public poll: string[] | null = null;
public pollVotes: Record<string, number> = {};
public pollClosed = false;
public pollWinner: number | null = null;
/** Tickets made from it, oldest first. */
public spawned: { id: string; key: string }[] = [];
public deleted = false; public deleted = false;
public createdAt!: string; public createdAt!: string;
public editedAt: string | null = null; public editedAt: string | null = null;
@@ -93,6 +137,103 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
); );
} }
/**
* Marks it as a decision of the ticket (`on`) or unmarks it; repeating it
* changes nothing. Who may do it (the team) is the caller's check.
*/
markDecision(actorId: string, on: boolean): void {
this.assertAlive();
if (on === this.decision) return;
this.apply(
new CommentDecisionMarkedEvent(
actorId,
this.id,
this.projectId,
this.issueId,
on,
),
);
}
/**
* Settles the conversation this comment opens (`on`) or reopens it;
* repeating it changes nothing. Only a top-level comment opens one.
*/
resolveThread(actorId: string, on: boolean): void {
this.assertAlive();
if (this.replyTo)
throw new BusinessRuleError(
'Only a conversation is resolved, not a reply',
);
if (on === this.resolved) return;
this.apply(
new CommentThreadResolvedEvent(
actorId,
this.id,
this.projectId,
this.issueId,
on,
),
);
}
/** Votes `option` in its poll (null takes the vote back); repeating it changes nothing. */
votePoll(actorId: string, option: number | null): void {
this.assertAlive();
if (!this.poll) throw new BusinessRuleError('This comment has no poll');
if (this.pollClosed) throw new BusinessRuleError('The poll is closed');
assertThat(
option === null ||
(Number.isInteger(option) && option >= 0 && option < this.poll.length),
'No such option',
);
if ((this.pollVotes[actorId] ?? null) === option) return;
const votes = { ...this.pollVotes };
if (option === null) delete votes[actorId];
else votes[actorId] = option;
this.apply(
new CommentPollVotedEvent(
actorId,
this.id,
this.projectId,
this.issueId,
votes,
),
);
}
/**
* Closes the poll: its author, or (`canModerate`) whoever manages the
* project. The winner is the most voted option; none on a tie.
*/
closePoll(actorId: string, canModerate: boolean): number | null {
this.assertAlive();
if (!this.poll) throw new BusinessRuleError('This comment has no poll');
if (this.pollClosed) throw new BusinessRuleError('The poll is closed');
if (actorId !== this.authorId && !canModerate)
throw new ForbiddenError(
'Only whoever started the poll or a project admin can close it',
);
const counts = this.poll.map(
(_, i) => Object.values(this.pollVotes).filter((v) => v === i).length,
);
const most = Math.max(...counts);
const winner =
most > 0 && counts.filter((c) => c === most).length === 1
? counts.indexOf(most)
: null;
this.apply(
new CommentPollClosedEvent(
actorId,
this.id,
this.projectId,
this.issueId,
winner,
),
);
return winner;
}
/** @param canModerate whether the actor manages the project (may delete others' comments). */ /** @param canModerate whether the actor manages the project (may delete others' comments). */
delete(actorId: string, canModerate: boolean): void { delete(actorId: string, canModerate: boolean): void {
this.assertAlive(); this.assertAlive();
@@ -110,6 +251,16 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
onCommentAddedEvent({ comment }: CommentAddedEvent): void { onCommentAddedEvent({ comment }: CommentAddedEvent): void {
Object.assign(this, comment); Object.assign(this, comment);
this.poll = comment.poll ?? null;
}
onCommentPollVotedEvent(event: CommentPollVotedEvent): void {
this.pollVotes = event.votes;
}
onCommentPollClosedEvent(event: CommentPollClosedEvent): void {
this.pollClosed = true;
this.pollWinner = event.winner;
} }
onCommentEditedEvent(event: CommentEditedEvent): void { onCommentEditedEvent(event: CommentEditedEvent): void {
@@ -121,10 +272,40 @@ export class Comment extends VersionedAggregateRoot implements CommentProps {
this.reactions = event.reactions; this.reactions = event.reactions;
} }
onCommentDecisionMarkedEvent(event: CommentDecisionMarkedEvent): void {
this.decision = event.decision;
}
onCommentThreadResolvedEvent(event: CommentThreadResolvedEvent): void {
this.resolved = event.resolved;
}
onCommentTurnedIntoIssueEvent(event: CommentTurnedIntoIssueEvent): void {
this.spawned = event.spawned;
}
onCommentDeletedEvent(): void { onCommentDeletedEvent(): void {
this.deleted = true; this.deleted = true;
} }
/**
* Notes a ticket made from it (its text became the ticket's description).
* Who may create it is the caller's check.
*/
turnedInto(actorId: string, issue: { id: string; key: string }): void {
this.assertAlive();
if (this.spawned.some((s) => s.id === issue.id)) return;
this.apply(
new CommentTurnedIntoIssueEvent(
actorId,
this.id,
this.projectId,
this.issueId,
[...this.spawned, issue],
),
);
}
private assertAlive(): void { private assertAlive(): void {
if (this.deleted) throw new BusinessRuleError('Comment was deleted'); if (this.deleted) throw new BusinessRuleError('Comment was deleted');
} }

View File

@@ -0,0 +1,17 @@
import { AutowiredEvent } from '@task-stream/api/shared/domain';
import { TrackerEvent } from './tracker.event';
/** A comment was marked as a decision of the ticket, or unmarked. */
@AutowiredEvent
export class CommentDecisionMarkedEvent extends TrackerEvent {
constructor(
actorId: string,
commentId: string,
projectId: string,
readonly issueId: string,
/** False: it is no longer a decision. */
readonly decision: boolean,
) {
super(actorId, commentId, projectId);
}
}

View File

@@ -0,0 +1,31 @@
import { AutowiredEvent } from '@task-stream/api/shared/domain';
import { TrackerEvent } from './tracker.event';
/** Someone voted in a comment's poll, changed or took back their vote. */
@AutowiredEvent
export class CommentPollVotedEvent extends TrackerEvent {
constructor(
actorId: string,
commentId: string,
projectId: string,
readonly issueId: string,
/** Every vote after the change: user id → option index. */
readonly votes: Record<string, number>,
) {
super(actorId, commentId, projectId);
}
}
/** A comment's poll was closed; `winner` is null on a tie or no votes. */
@AutowiredEvent
export class CommentPollClosedEvent extends TrackerEvent {
constructor(
actorId: string,
commentId: string,
projectId: string,
readonly issueId: string,
readonly winner: number | null,
) {
super(actorId, commentId, projectId);
}
}

View File

@@ -0,0 +1,17 @@
import { AutowiredEvent } from '@task-stream/api/shared/domain';
import { TrackerEvent } from './tracker.event';
/** A conversation (a top-level comment and its replies) was settled, or reopened. */
@AutowiredEvent
export class CommentThreadResolvedEvent extends TrackerEvent {
constructor(
actorId: string,
commentId: string,
projectId: string,
readonly issueId: string,
/** False: reopened. */
readonly resolved: boolean,
) {
super(actorId, commentId, projectId);
}
}

View File

@@ -0,0 +1,17 @@
import { AutowiredEvent } from '@task-stream/api/shared/domain';
import { TrackerEvent } from './tracker.event';
/** A ticket of its own was made from a comment («→ WEB-45» on it). */
@AutowiredEvent
export class CommentTurnedIntoIssueEvent extends TrackerEvent {
constructor(
actorId: string,
commentId: string,
projectId: string,
readonly issueId: string,
/** Every ticket made from it so far, this one last. */
readonly spawned: { id: string; key: string }[],
) {
super(actorId, commentId, projectId);
}
}

View File

@@ -15,6 +15,11 @@ export * from './issue-release-changed.event';
export * from './comment-added.event'; export * from './comment-added.event';
export * from './comment-edited.event'; export * from './comment-edited.event';
export * from './comment-reacted.event'; export * from './comment-reacted.event';
export * from './comment-decision-marked.event';
export * from './comment-thread-resolved.event';
export * from './comment-turned-into-issue.event';
export * from './issue-review.events';
export * from './comment-poll.events';
export * from './comment-deleted.event'; export * from './comment-deleted.event';
export * from './release-created.event'; export * from './release-created.event';
export * from './release-updated.event'; export * from './release-updated.event';

Some files were not shown because too many files have changed in this diff Show More