feat: per-project workflow settings, statistics and "my work" home

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-06 20:53:45 +02:00
parent 240ea9a539
commit 0e301ad545
143 changed files with 10291 additions and 1052 deletions

View File

@@ -0,0 +1,600 @@
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
signal,
untracked,
} from '@angular/core';
import {
PiIconComponent,
PiNoteComponent,
PiSegmentedControlComponent,
PiSelectFieldComponent,
PiSkeletonComponent,
type PiSelectFieldOption,
type SegmentedControlOption,
} from '@pi/ui';
import { ProjectFacade } from '@task-stream/web/tracker/application';
import {
DurationStats,
ReleaseStatus,
StatusCategory,
} from '@task-stream/web/tracker/domain';
import { CATEGORY } from '../ui/copy';
import { ChartSeries, last, SeriesChartComponent } from '../ui/series-chart';
const PERIODS: SegmentedControlOption<number>[] = [
{ value: 30, label: '30 días' },
{ value: 90, label: '90 días' },
{ value: 180, label: '6 meses' },
{ value: 365, label: '1 año' },
];
/** Flow stages, bottom band first; the ordinal ramp darkens towards done. */
const FLOW: { category: StatusCategory; color: string }[] = [
{ category: StatusCategory.DONE, color: 'var(--ts-viz-ramp-4)' },
{ category: StatusCategory.QA, color: 'var(--ts-viz-ramp-3)' },
{ category: StatusCategory.IN_PROGRESS, color: 'var(--ts-viz-ramp-2)' },
{ category: StatusCategory.TODO, color: 'var(--ts-viz-ramp-1)' },
];
/** "2026-10-06" → "6 oct" (UTC: the API counts days and weeks in UTC). */
const day = (iso: string, month: 'short' | 'long' = 'short') =>
new Date(`${iso}T00:00:00Z`).toLocaleDateString('es', {
day: 'numeric',
month,
timeZone: 'UTC',
});
const decimal = new Intl.NumberFormat('es', { maximumFractionDigits: 1 });
/** "Estadísticas": how the project flows over time (owners and team alike). */
@Component({
selector: 'ts-analytics-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
PiIconComponent,
PiNoteComponent,
PiSegmentedControlComponent,
PiSelectFieldComponent,
PiSkeletonComponent,
SeriesChartComponent,
],
template: `
<div class="ts-section-header">
<div>
<h2>Estadísticas</h2>
<p>
Cómo avanza el trabajo, según las categorías de los estados del
proyecto.
</p>
</div>
<pi-segmented-control
ariaLabel="Periodo"
[options]="periods"
[value]="facade.analyticsDays()"
(valueChange)="facade.loadAnalytics($any($event))"
/>
</div>
@if (facade.analyticsError(); as error) {
<pi-note
gap="xs"
status="error"
appearance="fill"
type="status"
title="No se pudieron calcular las estadísticas"
[text]="error"
/>
} @else if (facade.analytics(); as stats) {
<div
class="ts-stats"
[class.is-refreshing]="facade.analyticsLoading()"
[attr.aria-busy]="facade.analyticsLoading()"
>
<section class="ts-tiles" aria-label="Resumen del periodo">
<article class="ts-panel ts-tile">
<p class="ts-tile__label">Resueltos</p>
<p class="ts-tile__value">{{ resolved() }}</p>
<p class="ts-tile__sub">de {{ created() }} creados</p>
</article>
<article class="ts-panel ts-tile">
<p class="ts-tile__label">Tiempo de ciclo</p>
<p class="ts-tile__value">{{ days(stats.cycleTime) }}</p>
<p class="ts-tile__sub">{{ p85(stats.cycleTime) }}</p>
</article>
<article class="ts-panel ts-tile">
<p class="ts-tile__label">Tiempo de entrega</p>
<p class="ts-tile__value">{{ days(stats.leadTime) }}</p>
<p class="ts-tile__sub">{{ p85(stats.leadTime) }}</p>
</article>
<article class="ts-panel ts-tile">
<p class="ts-tile__label">Fallo en QA</p>
<p class="ts-tile__value">{{ failureRate() }}</p>
@if (stats.qa.passed + stats.qa.failed; as total) {
<div
class="ts-meter"
role="img"
[attr.aria-label]="
stats.qa.passed +
' superados y ' +
stats.qa.failed +
' fallidos'
"
>
<span
class="ts-meter__good"
[style.flex-grow]="stats.qa.passed"
></span>
<span
class="ts-meter__bad"
[style.flex-grow]="stats.qa.failed"
></span>
</div>
<p class="ts-tile__sub ts-tile__qa">
<span
><pi-icon icon="check-rounded" size="x-small" />
{{ stats.qa.passed }} superados</span
>
<span
><pi-icon icon="exclamation" size="x-small" />
{{ stats.qa.failed }} fallidos</span
>
</p>
} @else {
<p class="ts-tile__sub">Nada ha salido de QA aún</p>
}
</article>
</section>
<div class="ts-charts">
<section class="ts-panel ts-chart-card" aria-labelledby="cvr-title">
<header>
<h3 id="cvr-title">Creados y resueltos</h3>
<p class="ts-muted">Tickets por semana (lunes a domingo)</p>
</header>
<ts-series-chart
axisLabel="Semana"
[labels]="weekLabels()"
[longLabels]="weekLongLabels()"
[series]="createdVsResolved()"
[summary]="
'Creados y resueltos por semana: ' +
created() +
' creados y ' +
resolved() +
' resueltos en el periodo'
"
/>
</section>
<section class="ts-panel ts-chart-card" aria-labelledby="flow-title">
<header>
<h3 id="flow-title">Flujo acumulado</h3>
<p class="ts-muted">
Tickets en cada categoría al final de cada día (sin cancelados).
Una banda que engorda es trabajo que se atasca.
</p>
</header>
<ts-series-chart
[stacked]="true"
[labels]="dayLabels()"
[longLabels]="dayLongLabels()"
[series]="flow()"
summary="Flujo acumulado de tickets por categoría y día"
/>
</section>
<section
class="ts-panel ts-chart-card"
aria-labelledby="burnup-title"
>
<header class="ts-chart-card__head">
<div>
<h3 id="burnup-title">Burnup de la release</h3>
<p class="ts-muted">{{ burnupNote() }}</p>
</div>
@if (releaseOptions().length) {
<pi-select-field
class="ts-chart-card__select"
[options]="releaseOptions()"
[value]="releaseId()"
(valueChange)="pickRelease($any($event))"
>
<span class="visually-hidden">Release</span>
</pi-select-field>
}
</header>
@if (!releaseOptions().length) {
<p class="ts-empty">
Crea una release y mete tickets en ella para ver su avance.
</p>
} @else if (facade.burnup(); as burnup) {
<ts-series-chart
[labels]="burnupLabels()"
[longLabels]="burnupLongLabels()"
[series]="burnupSeries()"
[marker]="targetMarker()"
[summary]="
'Burnup: ' +
(last(burnup.done) ?? 0) +
' de ' +
(last(burnup.scope) ?? 0) +
' tickets hechos'
"
/>
} @else {
<pi-skeleton shape="block" height="15rem" />
}
</section>
<section class="ts-panel ts-chart-card" aria-labelledby="tp-title">
<header>
<h3 id="tp-title">Tickets resueltos por persona</h3>
<p class="ts-muted">
Quién tenía el ticket asignado al pasarlo a hecho.
</p>
</header>
@if (throughput().length) {
<ul class="ts-hbars">
@for (row of throughput(); track row.name) {
<li [attr.title]="row.name + ': ' + row.count + ' resueltos'">
<span class="ts-hbars__name">{{ row.name }}</span>
<span class="ts-hbars__track"
><span
class="ts-hbars__bar"
[style.width.%]="(row.count / maxThroughput()) * 100"
></span
></span>
<span class="ts-hbars__value">{{ row.count }}</span>
</li>
}
</ul>
} @else {
<p class="ts-empty">Nadie ha terminado tickets en el periodo.</p>
}
</section>
</div>
</div>
} @else {
<div class="ts-stats">
<section class="ts-tiles">
@for (i of [1, 2, 3, 4]; track i) {
<pi-skeleton shape="block" height="7.5rem" />
}
</section>
<div class="ts-charts">
@for (i of [1, 2, 3, 4]; track i) {
<pi-skeleton shape="block" height="20rem" />
}
</div>
</div>
}
`,
styles: `
.ts-section-header pi-segmented-control {
max-width: 100%;
}
.ts-stats {
display: grid;
gap: 1rem;
transition: opacity 0.2s ease;
&.is-refreshing {
opacity: 0.55;
}
}
.ts-tiles {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 9.5rem), 1fr));
gap: 1rem;
}
.ts-tile {
display: grid;
align-content: start;
gap: 0.25rem;
padding: 1rem 1.125rem;
p {
margin: 0;
}
}
.ts-tile__label {
font-size: 0.8125rem;
font-weight: 600;
color: var(--ts-muted);
}
.ts-tile__value {
font-size: 2rem;
font-weight: 700;
line-height: 1.1;
color: var(--ts-ink);
}
.ts-tile__sub {
font-size: 0.75rem;
color: var(--ts-muted);
}
.ts-tile__qa {
display: flex;
gap: 0.75rem;
span {
display: inline-flex;
align-items: center;
gap: 0.25rem;
}
}
.ts-meter {
display: flex;
gap: 2px;
height: 0.5rem;
margin: 0.375rem 0 0.125rem;
span {
min-width: 2px;
border-radius: 2px;
}
}
.ts-meter__good {
background: var(--ts-viz-good);
}
.ts-meter__bad {
background: var(--ts-viz-critical);
}
.ts-charts {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 30rem), 1fr));
gap: 1rem;
}
.ts-chart-card {
display: grid;
align-content: start;
gap: 1rem;
min-width: 0;
padding: 1.25rem;
h3 {
margin: 0;
font-size: 1rem;
font-weight: 700;
}
header p {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
}
}
.ts-chart-card__head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.ts-chart-card__select {
width: 12rem;
max-width: 100%;
}
.ts-empty {
margin: 0;
padding: 2rem 0;
text-align: center;
color: var(--ts-muted);
font-size: 0.875rem;
}
.ts-hbars {
display: grid;
gap: 0.625rem;
margin: 0;
padding: 0;
list-style: none;
li {
display: grid;
grid-template-columns: minmax(6rem, 10rem) 1fr 2rem;
align-items: center;
gap: 0.75rem;
font-size: 0.875rem;
}
}
.ts-hbars__name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ts-hbars__track {
height: 0.875rem;
}
.ts-hbars__bar {
display: block;
height: 100%;
min-width: 2px;
border-radius: 0 4px 4px 0;
background: var(--ts-viz-1);
}
.ts-hbars__value {
font-family: var(--ts-font-mono);
font-variant-numeric: tabular-nums;
text-align: right;
color: var(--ts-ink-soft);
}
`,
})
export class AnalyticsPage {
protected readonly facade = inject(ProjectFacade);
protected readonly periods = PERIODS;
/** Release shown in the burnup ('' until the releases arrive). */
protected readonly releaseId = signal('');
constructor() {
// (Re)load whenever the open project changes.
effect(() => {
const projectId = this.facade.project()?.id;
if (projectId) untracked(() => this.facade.loadAnalytics());
});
// Default burnup: the next planned release, else the last shipped one.
effect(() => {
const options = this.releaseOptions();
const current = untracked(this.releaseId);
if (!options.length || options.some((o) => o.value === current)) return;
untracked(() => this.pickRelease(options[0].value));
});
}
private readonly stats = this.facade.analytics;
protected readonly created = computed(() =>
(this.stats()?.createdVsResolved ?? []).reduce((s, w) => s + w.created, 0),
);
protected readonly resolved = computed(() =>
(this.stats()?.createdVsResolved ?? []).reduce((s, w) => s + w.resolved, 0),
);
protected readonly weekLabels = computed(() =>
(this.stats()?.createdVsResolved ?? []).map((w) => day(w.week)),
);
protected readonly weekLongLabels = computed(() =>
(this.stats()?.createdVsResolved ?? []).map(
(w) => `Semana del ${day(w.week, 'long')}`,
),
);
protected readonly createdVsResolved = computed<ChartSeries[]>(() => {
const weeks = this.stats()?.createdVsResolved ?? [];
return [
{
label: 'Creados',
values: weeks.map((w) => w.created),
color: 'var(--ts-viz-1)',
},
{
label: 'Resueltos',
values: weeks.map((w) => w.resolved),
color: 'var(--ts-viz-2)',
},
];
});
protected readonly dayLabels = computed(() =>
(this.stats()?.cumulativeFlow.dates ?? []).map((d) => day(d)),
);
protected readonly dayLongLabels = computed(() =>
(this.stats()?.cumulativeFlow.dates ?? []).map((d) => day(d, 'long')),
);
/** Statuses summed by category: custom statuses keep the chart readable. */
protected readonly flow = computed<ChartSeries[]>(() => {
const stats = this.stats();
if (!stats) return [];
const workflow = this.facade.workflow();
const length = stats.cumulativeFlow.dates.length;
return FLOW.map(({ category, color }) => {
const values = new Array(length).fill(0) as number[];
for (const series of stats.cumulativeFlow.series) {
if (workflow.status(series.status).category !== category) continue;
series.counts.forEach((count, i) => (values[i] += count));
}
return { label: CATEGORY[category].label, values, color };
});
});
protected readonly throughput = computed(() => {
const totals = new Map<string, { name: string; count: number }>();
for (const row of this.stats()?.throughput ?? []) {
const id = row.user?.id ?? '';
const entry = totals.get(id) ?? {
name: row.user?.name ?? 'Sin asignar',
count: 0,
};
entry.count += row.count;
totals.set(id, entry);
}
return [...totals.values()].sort(
(a, b) => b.count - a.count || a.name.localeCompare(b.name, 'es'),
);
});
protected readonly maxThroughput = computed(() =>
Math.max(1, ...this.throughput().map((r) => r.count)),
);
protected readonly failureRate = computed(() => {
const rate = this.stats()?.qa.failureRate;
return rate === null || rate === undefined
? '—'
: `${decimal.format(rate * 100)} %`;
});
/* Burnup */
protected readonly releaseOptions = computed<PiSelectFieldOption<string>[]>(
() => {
const releases = this.facade
.releases()
.filter((r) => r.status !== ReleaseStatus.ARCHIVED);
// Planned: soonest target first (no date last).
const planned = releases
.filter((r) => r.status === ReleaseStatus.PLANNED)
.sort((a, b) =>
(a.targetDate ?? '9999').localeCompare(b.targetDate ?? '9999'),
);
const shipped = releases
.filter((r) => r.status === ReleaseStatus.RELEASED)
.sort((a, b) => (b.releasedAt ?? '').localeCompare(a.releasedAt ?? ''));
return [...planned, ...shipped].map((r) => ({
value: r.id,
label: r.status === ReleaseStatus.RELEASED ? `${r.name} ✓` : r.name,
}));
},
);
private readonly burnup = computed(() => {
const burnup = this.facade.burnup();
return burnup?.releaseId === this.releaseId() ? burnup : null;
});
protected readonly burnupLabels = computed(() =>
(this.burnup()?.dates ?? []).map((d) => day(d)),
);
protected readonly burnupLongLabels = computed(() =>
(this.burnup()?.dates ?? []).map((d) => day(d, 'long')),
);
protected readonly burnupSeries = computed<ChartSeries[]>(() => {
const burnup = this.burnup();
if (!burnup) return [];
return [
{ label: 'Alcance', values: burnup.scope, color: 'var(--ts-muted)' },
{
label: 'Hechos',
values: burnup.done,
color: 'var(--ts-viz-1)',
area: true,
},
];
});
protected readonly targetMarker = computed(() => {
const burnup = this.burnup();
if (!burnup?.targetDate) return null;
const index = burnup.dates.indexOf(burnup.targetDate.slice(0, 10));
return index === -1 ? null : { index, label: 'Objetivo' };
});
protected readonly burnupNote = computed(() => {
const burnup = this.burnup();
if (!burnup) return 'Tickets en la release frente a los ya hechos.';
const scope = last(burnup.scope) ?? 0;
const done = last(burnup.done) ?? 0;
const target = burnup.targetDate
? ` · objetivo ${day(burnup.targetDate.slice(0, 10), 'long')}`
: '';
return `${done} de ${scope} tickets hechos${target}`;
});
protected readonly last = last;
protected pickRelease(releaseId: string): void {
this.releaseId.set(releaseId);
if (releaseId) this.facade.loadBurnup(releaseId);
}
protected days(stats: DurationStats): string {
return stats.averageDays === null
? '—'
: `${decimal.format(stats.averageDays)} d`;
}
protected p85(stats: DurationStats): string {
if (!stats.count) return 'Sin tickets terminados';
return `85 % en ≤ ${decimal.format(stats.p85Days ?? 0)} d · ${stats.count} tickets`;
}
}

View File

@@ -36,16 +36,12 @@ import {
} from '@task-stream/web/tracker/application';
import {
BoardColumn,
IssueArea,
IssuePriority,
IssueStatus,
IssueSummary,
IssueType,
REASON_REQUIRED,
ReleaseStatus,
} from '@task-stream/web/tracker/domain';
import { IssueCardComponent } from '../ui/issue-card';
import { AREA, options, PRIORITY, STATUS, TYPE } from '../ui/copy';
import { options, PRIORITY, statusLook } from '../ui/copy';
const ALL = '';
@@ -85,7 +81,7 @@ const ALL = '';
<pi-select-field
class="ts-filter"
placeholder="Área"
[options]="areaOptions"
[options]="areaFilterOptions()"
[(value)]="area"
/>
<span class="ts-board-total"
@@ -127,10 +123,16 @@ const ALL = '';
[id]="column.status"
[cdkDropListData]="column"
[cdkDropListDisabled]="!project.canContribute()"
[cdkDropListEnterPredicate]="canEnter"
(cdkDropListDropped)="drop($event)"
>
@for (issue of column.issues; track issue.id) {
<ts-issue-card cdkDrag [cdkDragData]="issue" [issue]="issue" />
<ts-issue-card
cdkDrag
[cdkDragData]="issue"
[issue]="issue"
[workflow]="project.workflow()"
/>
} @empty {
<p class="ts-column__empty">Nada por aquí</p>
}
@@ -146,11 +148,17 @@ const ALL = '';
(submit)="$event.preventDefault(); create()"
novalidate
>
<pi-segmented-control
ariaLabel="Tipo"
[options]="typeOptions"
[(value)]="newType"
/>
@if (typeOptions().length <= 5) {
<pi-segmented-control
ariaLabel="Tipo"
[options]="typeOptions()"
[(value)]="newType"
/>
} @else {
<pi-select-field [options]="typeOptions()" [(value)]="newType">
<pi-label>Tipo</pi-label>
</pi-select-field>
}
<pi-text-field [formField]="f.title" [placeholder]="titlePlaceholder()">
<pi-label [isRequired]="true">Título</pi-label>
</pi-text-field>
@@ -160,7 +168,7 @@ const ALL = '';
>
<pi-label>Descripción</pi-label>
</pi-textarea>
@if (newType() === 'UI_CHANGE') {
@if (project.workflow().isDesignType(newType())) {
<pi-text-field
[formField]="f.figmaUrl"
placeholder="https://www.figma.com/design/…"
@@ -172,7 +180,7 @@ const ALL = '';
<pi-select-field [formField]="f.priority" [options]="priorityOptions">
<pi-label>Prioridad</pi-label>
</pi-select-field>
<pi-select-field [formField]="f.area" [options]="areaOptions">
<pi-select-field [formField]="f.area" [options]="areaOptions()">
<pi-label>Área</pi-label>
</pi-select-field>
</div>
@@ -262,16 +270,35 @@ export class BoardPage {
.map((r) => ({ value: r.id, label: r.name })),
],
);
protected readonly areaOptions: PiSelectFieldOption<string>[] = [
/** Archived areas still filter (old tickets keep them). */
protected readonly areaFilterOptions = computed<
PiSelectFieldOption<string>[]
>(() => [
{ value: ALL, label: 'Todas las áreas' },
...options(AREA),
];
...this.project
.workflow()
.settings.areas.map((a) => ({ value: a.id, label: a.name })),
]);
protected readonly areaOptions = computed<PiSelectFieldOption<string>[]>(
() => [
{ value: ALL, label: 'Sin área' },
...this.project
.workflow()
.activeAreas()
.map((a) => ({ value: a.id, label: a.name })),
],
);
protected readonly priorityOptions = options(PRIORITY);
protected readonly typeOptions: SegmentedControlOption<IssueType>[] =
options(TYPE);
protected readonly typeOptions = computed<SegmentedControlOption<string>[]>(
() =>
this.project
.workflow()
.activeTypes()
.map((t) => ({ value: t.id, label: t.name })),
);
/* New ticket */
protected readonly newType = signal<IssueType>(IssueType.BUG);
protected readonly newType = signal<string>('');
private readonly model = signal({
title: '',
description: '',
@@ -286,13 +313,13 @@ export class BoardPage {
maxLength(p.title, 255);
});
protected readonly titlePlaceholder = computed(() =>
this.newType() === IssueType.BUG
this.project.workflow().type(this.newType()).icon === 'bug'
? 'El botón de pagar no responde en Safari'
: 'Qué hay que hacer',
);
/* Move needing a reason */
private pendingMove: { issueId: string; to: IssueStatus } | null = null;
private pendingMove: { issueId: string; to: string } | null = null;
private readonly reasonModel = signal({ text: '' });
protected readonly reason = form(this.reasonModel, (p) => required(p.text));
@@ -311,15 +338,27 @@ export class BoardPage {
const filter = {
assigneeId: this.assigneeFilter() || undefined,
releaseId: this.releaseFilter() || undefined,
area: (this.area() || undefined) as IssueArea | undefined,
area: this.area() || undefined,
};
if (!projectId) return;
untracked(() => this.board.show({ projectId, ...filter }));
});
}
protected statusLabel = (status: IssueStatus) => STATUS[status].label;
protected statusTone = (status: IssueStatus) => STATUS[status].tone;
protected statusLabel = (status: string) =>
statusLook(this.project.workflow(), status).label;
protected statusTone = (status: string) =>
statusLook(this.project.workflow(), status).tone;
/** Columns a dragged ticket can enter: its allowed transitions. */
protected readonly canEnter = (
drag: CdkDrag<IssueSummary>,
drop: CdkDropList<BoardColumn>,
) =>
this.project
.workflow()
.allowedFrom(drag.data.status)
.includes(drop.data.status);
protected drop(
event: CdkDragDrop<BoardColumn, BoardColumn, IssueSummary>,
@@ -327,10 +366,10 @@ export class BoardPage {
if (event.previousContainer === event.container) return;
const to = event.container.data.status;
const issueId = event.item.data.id;
if (REASON_REQUIRED.includes(to)) {
if (this.project.workflow().requiresReason(to)) {
this.pendingMove = { issueId, to };
this.reasonModel.set({ text: '' });
this.drawer.open(`Mover a «${STATUS[to].label}»`, this.reasonForm());
this.drawer.open(`Mover a «${this.statusLabel(to)}»`, this.reasonForm());
return;
}
this.board.moveIssue(issueId, to);
@@ -345,6 +384,9 @@ export class BoardPage {
}
protected openCreate(): void {
const types = this.typeOptions();
if (!types.some((t) => t.value === this.newType()))
this.newType.set(types[0]?.value ?? '');
this.model.set({
title: '',
description: '',
@@ -367,11 +409,11 @@ export class BoardPage {
title: v.title,
description: v.description || null,
figmaUrl:
this.newType() === IssueType.UI_CHANGE && v.figmaUrl
this.project.workflow().isDesignType(this.newType()) && v.figmaUrl
? v.figmaUrl
: null,
priority: v.priority as IssuePriority,
area: (v.area || null) as IssueArea | null,
area: v.area || null,
assigneeId: v.assigneeId || null,
releaseId: v.releaseId || null,
});

View File

@@ -8,12 +8,11 @@ import { RouterLink } from '@angular/router';
import { PiSkeletonComponent, PiStatCardComponent } from '@pi/ui';
import { ProjectFacade } from '@task-stream/web/tracker/application';
import {
BOARD_COLUMNS,
IssueStatus,
IssueType,
ProjectRole,
QA_FAILED,
StatusCategory,
} from '@task-stream/web/tracker/domain';
import { initials, ROLE, ROLE_TONE, STATUS, TYPE } from '../ui/copy';
import { initials, ROLE, ROLE_TONE, statusLook, typeLook } from '../ui/copy';
/** "Seguimiento": the state of the whole project at a glance (live). */
@Component({
@@ -366,12 +365,20 @@ export class DashboardPage {
protected readonly facade = inject(ProjectFacade);
protected readonly initialsOf = initials;
private count(status: IssueStatus): number {
private count(status: string): number {
return (
this.facade.stats()?.byStatus.find((s) => s.key === status)?.count ?? 0
);
}
/** Tickets in statuses of a category (whatever the project calls them). */
private countCategory(category: StatusCategory): number {
const workflow = this.facade.workflow();
return (this.facade.stats()?.byStatus ?? [])
.filter((row) => workflow.status(row.key).category === category)
.reduce((sum, row) => sum + row.count, 0);
}
protected readonly kpis = computed<
{
label: string;
@@ -382,7 +389,11 @@ export class DashboardPage {
>(() => {
const stats = this.facade.stats();
if (!stats) return [];
const bugs = stats.byType.find((t) => t.key === IssueType.BUG)?.count ?? 0;
// Bugs: every type drawn with the bug icon.
const workflow = this.facade.workflow();
const bugs = stats.byType
.filter((t) => workflow.type(t.key).icon === 'bug')
.reduce((sum, t) => sum + t.count, 0);
return [
{ label: 'Tickets', value: stats.total, icon: 'list', color: 'primary' },
{
@@ -393,36 +404,50 @@ export class DashboardPage {
},
{ label: 'Bugs (total)', value: bugs, icon: 'bug', color: 'warn' },
{
label: 'Pendientes de QA',
value:
this.count(IssueStatus.READY_FOR_QA) + this.count(IssueStatus.IN_QA),
label: 'En QA',
value: this.countCategory(StatusCategory.QA),
icon: 'qa',
color: 'highlighted',
},
{
label: 'QA fallidos',
value: this.count(IssueStatus.QA_FAILED),
value: this.count(QA_FAILED),
icon: 'exclamation',
color: 'warn',
},
{
label: 'Hechos',
value: this.count(IssueStatus.DONE),
value: this.countCategory(StatusCategory.DONE),
icon: 'check-rounded',
color: 'success',
},
];
});
/** Statuses in workflow order (cancelled at the end). */
protected readonly flow = computed(() =>
[...BOARD_COLUMNS, IssueStatus.CANCELLED].map((status) => ({
status,
label: STATUS[status].label,
tone: STATUS[status].tone,
count: this.count(status),
})),
);
/**
* The project's statuses in board order, cancelled ones last. Archived (or
* no longer configured) statuses only while tickets still sit in them.
*/
protected readonly flow = computed(() => {
const workflow = this.facade.workflow();
const configured = workflow.settings.statuses.map((s) => s.id);
const ids = [
...configured,
...(this.facade.stats()?.byStatus ?? [])
.map((row) => row.key)
.filter((key) => !configured.includes(key)),
];
const cancelled = (id: string) =>
workflow.status(id).category === StatusCategory.CANCELLED;
return [...ids.filter((id) => !cancelled(id)), ...ids.filter(cancelled)]
.map((status) => ({
status,
...statusLook(workflow, status),
archived: workflow.status(status).archived,
count: this.count(status),
}))
.filter((row) => !row.archived || row.count > 0);
});
protected readonly flowLabel = computed(() =>
this.flow()
.filter((s) => s.count)
@@ -471,5 +496,5 @@ export class DashboardPage {
protected readonly roleLabel = (role: ProjectRole) => ROLE[role];
protected readonly roleTone = (role: ProjectRole) => ROLE_TONE[role];
protected readonly typeOf = (key: string) =>
TYPE[key as IssueType] ?? { label: key, tone: 'var(--ts-muted)' };
typeLook(this.facade.workflow(), key);
}

View File

@@ -31,24 +31,20 @@ import {
} from '@task-stream/web/tracker/application';
import {
Comment,
IssueArea,
IssueLink,
IssueLinkType,
IssuePriority,
IssueStatus,
REASON_REQUIRED,
ReleaseStatus,
} from '@task-stream/web/tracker/domain';
import {
AREA,
clock,
initials,
LINK,
options,
PRIORITY,
STATUS,
TYPE,
statusLook,
timeAgo,
typeLook,
} from '../ui/copy';
const NONE = '';
@@ -303,6 +299,14 @@ const NONE = '';
>
<pi-label>Release</pi-label>
</pi-select-field>
<pi-select-field
[options]="typeOptions()"
[disabled]="!project.canContribute()"
[value]="issue.type"
(valueChange)="update({ type: $any($event) })"
>
<pi-label>Tipo</pi-label>
</pi-select-field>
<pi-select-field
[options]="priorityOptions"
[disabled]="!project.canContribute()"
@@ -312,7 +316,7 @@ const NONE = '';
<pi-label>Prioridad</pi-label>
</pi-select-field>
<pi-select-field
[options]="areaOptions"
[options]="areaOptions()"
[disabled]="!project.canContribute()"
[value]="issue.area ?? ''"
(valueChange)="update({ area: $any($event || null) })"
@@ -439,11 +443,11 @@ export class IssuePage {
private readonly commentEditForm =
viewChild.required<TemplateRef<unknown>>('commentEditForm');
protected readonly type = computed(
() => TYPE[this.facade.issue()?.type ?? 'TASK'],
protected readonly type = computed(() =>
typeLook(this.project.workflow(), this.facade.issue()?.type ?? ''),
);
protected readonly status = computed(
() => STATUS[this.facade.issue()?.status ?? IssueStatus.BACKLOG],
protected readonly status = computed(() =>
statusLook(this.project.workflow(), this.facade.issue()?.status ?? ''),
);
protected readonly ago = timeAgo;
@@ -469,10 +473,28 @@ export class IssuePage {
],
);
protected readonly priorityOptions = options(PRIORITY);
protected readonly areaOptions: PiSelectFieldOption<string>[] = [
{ value: NONE, label: 'Sin área' },
...options(AREA),
];
/** Active values, plus the ticket's own even if archived since. */
protected readonly typeOptions = computed<PiSelectFieldOption<string>[]>(
() => {
const workflow = this.project.workflow();
const current = this.facade.issue()?.type;
return workflow.settings.issueTypes
.filter((t) => !t.archived || t.id === current)
.map((t) => ({ value: t.id, label: t.name }));
},
);
protected readonly areaOptions = computed<PiSelectFieldOption<string>[]>(
() => {
const workflow = this.project.workflow();
const current = this.facade.issue()?.area;
return [
{ value: NONE, label: 'Sin área' },
...workflow.settings.areas
.filter((a) => !a.archived || a.id === current)
.map((a) => ({ value: a.id, label: a.name })),
];
},
);
protected readonly linkTypeOptions = (
Object.keys(LINK) as IssueLinkType[]
).map((value) => ({
@@ -485,7 +507,7 @@ export class IssuePage {
protected readonly linkTarget = signal('');
protected readonly commentBody = signal('');
private pendingStatus: IssueStatus | null = null;
private pendingStatus: string | null = null;
private readonly reasonModel = signal({ text: '' });
protected readonly reason = form(this.reasonModel, (p) => required(p.text));
@@ -507,8 +529,10 @@ export class IssuePage {
effect(() => this.facade.open(this.issueKey()));
}
protected statusLabel = (status: IssueStatus) => STATUS[status].label;
protected statusTone = (status: IssueStatus) => STATUS[status].tone;
protected statusLabel = (status: string) =>
statusLook(this.project.workflow(), status).label;
protected statusTone = (status: string) =>
statusLook(this.project.workflow(), status).tone;
protected readonly initialsOf = initials;
protected readonly clock = clock;
protected linkLabel = (link: IssueLink) =>
@@ -516,11 +540,11 @@ export class IssuePage {
? LINK[link.type].outward
: LINK[link.type].inward;
protected move(to: IssueStatus): void {
if (REASON_REQUIRED.includes(to)) {
protected move(to: string): void {
if (this.project.workflow().requiresReason(to)) {
this.pendingStatus = to;
this.reasonModel.set({ text: '' });
this.drawer.open(`Mover a «${STATUS[to].label}»`, this.reasonForm());
this.drawer.open(`Mover a «${this.statusLabel(to)}»`, this.reasonForm());
return;
}
this.facade.changeStatus(to);
@@ -542,8 +566,9 @@ export class IssuePage {
}
protected update(changes: {
type?: string;
priority?: IssuePriority;
area?: IssueArea | null;
area?: string | null;
}): void {
this.facade.update(changes);
}

View File

@@ -0,0 +1,452 @@
import {
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
DOCUMENT,
inject,
OnInit,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { PiIconComponent, PiSkeletonComponent } from '@pi/ui';
import {
HomeFacade,
ProjectsFacade,
} from '@task-stream/web/tracker/application';
import {
IssueSummary,
Release,
StatusCategory,
Workflow,
} from '@task-stream/web/tracker/domain';
import {
CATEGORY,
initials,
projectKeyOf,
projectTone,
releaseWhen,
statusLook,
typeLook,
} from '../ui/copy';
const VISIBLE = 12;
/**
* "Mi trabajo" on the home page, across every project I belong to: my open
* tickets (QA failures first), tickets waiting for QA and upcoming releases.
* Reloads when the tab becomes visible again.
*/
@Component({
selector: 'ts-my-work',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [RouterLink, PiIconComponent, PiSkeletonComponent],
template: `
@if (!home.loaded()) {
<div class="ts-work">
<pi-skeleton shape="block" height="18rem" />
<div class="ts-work__side">
<pi-skeleton shape="block" height="8rem" />
<pi-skeleton shape="block" height="8rem" />
</div>
</div>
} @else {
<div class="ts-work">
<section class="ts-panel ts-work__panel" aria-labelledby="mine-title">
<header class="ts-work__head">
<h2 id="mine-title">Mis tickets</h2>
<span class="ts-muted ts-mono"
>{{ home.mineTotal() }} abiertos</span
>
</header>
@if (home.qaFailed()) {
<p class="ts-work__alert" role="status">
<pi-icon icon="exclamation" size="small" aria-hidden="true" />
{{ home.qaFailed() }}
{{
home.qaFailed() === 1
? 'ticket tuyo ha fallado en QA'
: 'tickets tuyos han fallado en QA'
}}
</p>
}
@for (group of visibleGroups(); track group.category) {
<h3 class="ts-work__group">
<span
class="ts-pill"
[style.--tone]="categoryTone(group.category)"
>{{ categoryLabel(group.category) }}</span
>
<span class="ts-mono">{{ group.issues.length }}</span>
</h3>
<ul class="ts-work__list">
@for (issue of group.issues; track issue.id) {
<li>
<a
class="ts-work__row"
[routerLink]="['/p', keyOf(issue.key), 'issues', issue.key]"
[style.--type]="typeTone(issue)"
>
<span class="ts-key">{{ issue.key }}</span>
<span class="ts-work__title"
><span
class="ts-work__status"
[style.--tone]="statusTone(issue)"
>{{ statusLabel(issue) }}</span
>
{{ issue.title }}</span
>
<span
class="ts-work__project"
[style.--tone]="projectToneOf(issue.key)"
>{{ keyOf(issue.key) }}</span
>
</a>
</li>
}
</ul>
} @empty {
<p class="ts-work__empty">
No tienes tickets abiertos asignados. Buen momento para revisar lo
que espera QA.
</p>
}
@if (home.mineTotal() > shown()) {
<p class="ts-muted ts-work__more">
y {{ home.mineTotal() - shown() }} más, en los tableros de cada
proyecto
</p>
}
</section>
<div class="ts-work__side">
<section class="ts-panel ts-work__panel" aria-labelledby="qa-title">
<header class="ts-work__head">
<h2 id="qa-title">Esperando QA</h2>
<span class="ts-muted ts-mono">{{ home.awaitingQaTotal() }}</span>
</header>
<ul class="ts-work__list">
@for (issue of home.awaitingQa().slice(0, 6); track issue.id) {
<li>
<a
class="ts-work__row ts-work__row--qa"
[routerLink]="['/p', keyOf(issue.key), 'issues', issue.key]"
[style.--type]="statusTone(issue)"
>
<span class="ts-key">{{ issue.key }}</span>
<span class="ts-work__title">{{ issue.title }}</span>
@if (issue.assignee; as assignee) {
<span class="ts-work__who" [attr.title]="assignee.name">{{
initialsOf(assignee.name)
}}</span>
}
</a>
</li>
} @empty {
<li class="ts-work__empty">Nada esperando QA.</li>
}
</ul>
</section>
<section
class="ts-panel ts-work__panel"
aria-labelledby="releases-title"
>
<header class="ts-work__head">
<h2 id="releases-title">Próximas releases</h2>
</header>
<ul class="ts-work__list">
@for (release of home.releases(); track release.id) {
<li>
<a
class="ts-work__release"
[routerLink]="['/p', projectOf(release), 'releases']"
>
<span class="ts-work__version">{{ release.name }}</span>
<span
class="ts-work__project"
[style.--tone]="tone(projectOf(release))"
>{{ projectOf(release) }}</span
>
<span class="ts-work__when ts-mono">{{
when(release)
}}</span>
<span
class="ts-work__meter"
role="progressbar"
aria-valuemin="0"
aria-valuemax="100"
[attr.aria-valuenow]="release.progress.percent"
[attr.aria-label]="'Progreso de ' + release.name"
><span [style.width.%]="release.progress.percent"></span
></span>
<span class="ts-work__percent ts-mono"
>{{ release.progress.finished }}/{{
release.progress.total
}}</span
>
</a>
</li>
} @empty {
<li class="ts-work__empty">Ninguna release planificada.</li>
}
</ul>
</section>
</div>
</div>
}
`,
styles: `
:host {
display: block;
margin-bottom: 2.5rem;
}
.ts-work {
display: grid;
grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
gap: 1.25rem;
align-items: start;
@media (max-width: 960px) {
grid-template-columns: minmax(0, 1fr);
}
}
.ts-work__side {
display: grid;
gap: 1.25rem;
}
.ts-work__panel {
padding: 1.375rem 1.5rem 1.25rem;
}
.ts-work__head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 1rem;
margin-bottom: 0.875rem;
h2 {
margin: 0;
font-size: 1.125rem;
font-weight: 700;
}
.ts-muted {
font-size: 0.75rem;
}
}
.ts-work__alert {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0 0 0.875rem;
padding: 0.5rem 0.75rem;
border-radius: 0.75rem;
background: color-mix(in srgb, var(--ts-s-failed) 10%, var(--ts-surface));
color: color-mix(in srgb, var(--ts-s-failed) 85%, var(--ts-ink));
font-size: 0.875rem;
font-weight: 600;
}
.ts-work__group {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0.875rem 0 0.375rem;
font-size: 0.75rem;
color: var(--ts-muted);
&:first-of-type {
margin-top: 0;
}
}
.ts-work__list {
display: grid;
margin: 0 -0.5rem;
padding: 0;
list-style: none;
li {
margin: 0;
}
}
.ts-work__row {
--type: var(--ts-muted);
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 0.75rem;
min-height: 2.5rem;
padding: 0.25rem 0.5rem 0.25rem 0.75rem;
border-radius: 0.625rem;
color: inherit;
text-decoration: none;
box-shadow: inset 3px 0 0 var(--type);
transition: background-color 0.15s ease;
&:hover {
background: var(--pi-color-primary-25);
}
&:focus-visible {
outline: 2px solid var(--ts-brand);
outline-offset: 1px;
}
}
.ts-work__title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 0.875rem;
}
.ts-work__status {
margin-right: 0.25rem;
font-size: 0.6875rem;
font-weight: 600;
color: var(--tone);
}
.ts-work__project {
font-family: var(--ts-font-mono);
font-size: 0.6875rem;
font-weight: 600;
color: var(--tone);
}
.ts-work__who {
display: inline-grid;
place-items: center;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background: color-mix(in srgb, var(--ts-brand) 16%, var(--ts-surface));
color: color-mix(in srgb, var(--ts-brand) 70%, var(--ts-ink));
font-family: var(--ts-font-mono);
font-size: 0.5625rem;
font-weight: 600;
}
.ts-work__release {
display: grid;
grid-template-columns: auto auto 1fr;
grid-template-areas:
'version project when'
'meter meter percent';
align-items: center;
gap: 0.375rem 0.625rem;
padding: 0.5rem;
border-radius: 0.625rem;
color: inherit;
text-decoration: none;
&:hover {
background: var(--pi-color-primary-25);
}
&:focus-visible {
outline: 2px solid var(--ts-brand);
outline-offset: 1px;
}
}
.ts-work__version {
grid-area: version;
font-family: var(--ts-font-mono);
font-weight: 600;
letter-spacing: -0.02em;
}
.ts-work__release .ts-work__project {
grid-area: project;
}
.ts-work__when {
grid-area: when;
justify-self: end;
font-size: 0.6875rem;
color: var(--ts-muted);
}
.ts-work__meter {
grid-area: meter;
height: 0.375rem;
border-radius: 0.25rem;
background: var(--ts-sunken);
overflow: hidden;
span {
display: block;
height: 100%;
background: var(--ts-s-done);
}
}
.ts-work__percent {
grid-area: percent;
justify-self: end;
font-size: 0.6875rem;
color: var(--ts-muted);
}
.ts-work__empty {
margin: 0;
padding: 0.25rem 0.5rem;
color: var(--ts-muted);
font-size: 0.875rem;
}
.ts-work__more {
margin: 0.75rem 0 0;
font-size: 0.75rem;
}
`,
})
export class MyWorkComponent implements OnInit {
protected readonly home = inject(HomeFacade);
private readonly projects = inject(ProjectsFacade);
private readonly document = inject(DOCUMENT);
private readonly destroyRef = inject(DestroyRef);
/** Groups trimmed to the first VISIBLE tickets overall. */
protected readonly visibleGroups = computed(() => {
let left = VISIBLE;
return this.home
.mineByCategory()
.map((group) => {
const issues = group.issues.slice(0, Math.max(left, 0));
left -= issues.length;
return { ...group, issues };
})
.filter((group) => group.issues.length > 0);
});
protected readonly shown = computed(() =>
this.visibleGroups().reduce((sum, group) => sum + group.issues.length, 0),
);
protected readonly keyOf = projectKeyOf;
protected readonly tone = projectTone;
protected readonly initialsOf = initials;
protected readonly when = releaseWhen;
/** Each ticket is shown with its own project's names and colours. */
private readonly workflows = computed(
() =>
new Map(
this.projects
.projects()
.map((p) => [p.id, new Workflow(p.settings)] as const),
),
);
private workflowOf(issue: IssueSummary): Workflow {
return this.workflows().get(issue.projectId) ?? new Workflow();
}
protected readonly statusLabel = (issue: IssueSummary) =>
statusLook(this.workflowOf(issue), issue.status).label;
protected readonly statusTone = (issue: IssueSummary) =>
statusLook(this.workflowOf(issue), issue.status).tone;
protected readonly typeTone = (issue: IssueSummary) =>
typeLook(this.workflowOf(issue), issue.type).tone;
protected readonly categoryLabel = (category: StatusCategory) =>
CATEGORY[category].label;
protected readonly categoryTone = (category: StatusCategory) =>
CATEGORY[category].tone;
protected readonly projectToneOf = (issueKey: string) =>
projectTone(projectKeyOf(issueKey));
ngOnInit(): void {
this.home.load();
// Back to the tab after a while: refresh my work.
const onVisible = () => {
if (this.document.visibilityState === 'visible') this.home.load();
};
this.document.addEventListener('visibilitychange', onVisible);
this.destroyRef.onDestroy(() =>
this.document.removeEventListener('visibilitychange', onVisible),
);
}
/** Releases carry the project id: shown and linked by the project's key. */
protected projectOf(release: Release): string {
return (
this.projects.projects().find((p) => p.id === release.projectId)?.key ??
release.projectId
);
}
}

View File

@@ -60,8 +60,14 @@ import { projectTone, ROLE } from '../ui/copy';
<a routerLink="board" routerLinkActive="is-active">Tablero</a>
<a routerLink="releases" routerLinkActive="is-active">Releases</a>
<a routerLink="dashboard" routerLinkActive="is-active">Seguimiento</a>
<a routerLink="analytics" routerLinkActive="is-active">Estadísticas</a>
<a routerLink="activity" routerLinkActive="is-active">Actividad</a>
<a routerLink="members" routerLinkActive="is-active">Miembros</a>
@if (facade.canManage()) {
<a routerLink="settings" routerLinkActive="is-active"
>Configuración</a
>
}
</nav>
<router-outlet />
} @else if (facade.error(); as error) {

View File

@@ -1,6 +1,7 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
OnInit,
signal,
@@ -25,7 +26,10 @@ import {
} from '@pi/ui';
import { DrawerService } from '@task-stream/web/shared/ui';
import { ProjectsFacade } from '@task-stream/web/tracker/application';
import { AuthFacade } from '@task-stream/web/identity/application';
import { AvatarsComponent } from '../ui/avatars';
import { GoToComponent } from '../ui/go-to';
import { MyWorkComponent } from './my-work';
import { projectTone, timeAgo } from '../ui/copy';
@Component({
@@ -35,6 +39,8 @@ import { projectTone, timeAgo } from '../ui/copy';
RouterLink,
FormField,
AvatarsComponent,
GoToComponent,
MyWorkComponent,
PiActionButtonComponent,
PiEmptyStateComponent,
PiSkeletonComponent,
@@ -45,20 +51,35 @@ import { projectTone, timeAgo } from '../ui/copy';
template: `
<header class="ts-page-header">
<div>
<p class="ts-eyebrow">
Tus proyectos ·
<span class="ts-mono">{{ pad(facade.projects().length) }}</span>
</p>
<h1>Proyectos</h1>
<p>Los proyectos de los que formas parte, al día en tiempo real.</p>
<p class="ts-eyebrow">Pireon · TaskStream</p>
<h1>
Hola,
<span class="ts-gradient-text">{{ firstName() }}</span>
</h1>
<p>Lo tuyo en todos tus proyectos, al día en tiempo real.</p>
</div>
<div class="ts-home-actions">
<ts-go-to />
<pi-action-button
color="primary"
text="Nuevo proyecto"
(execute)="openCreate()"
/>
</div>
<pi-action-button
color="primary"
text="Nuevo proyecto"
(execute)="openCreate()"
/>
</header>
@if (facade.projects().length) {
<ts-my-work />
<div class="ts-section-header">
<h2>
Proyectos
<span class="ts-mono ts-muted">{{
pad(facade.projects().length)
}}</span>
</h2>
</div>
}
@if (facade.loading() && !facade.projects().length) {
<div class="ts-projects">
@for (i of [1, 2, 3]; track i) {
@@ -141,6 +162,27 @@ import { projectTone, timeAgo } from '../ui/copy';
</ng-template>
`,
styles: `
.ts-home-actions {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
@media (max-width: 640px) {
width: 100%;
ts-go-to {
flex: 1;
}
}
}
.ts-section-header h2 {
display: flex;
align-items: baseline;
gap: 0.625rem;
.ts-mono {
font-size: 0.875rem;
font-weight: 400;
}
}
.ts-projects {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(100%, 20rem), 1fr));
@@ -216,6 +258,10 @@ import { projectTone, timeAgo } from '../ui/copy';
})
export class ProjectsPage implements OnInit {
protected readonly facade = inject(ProjectsFacade);
private readonly auth = inject(AuthFacade);
protected readonly firstName = computed(
() => this.auth.user()?.name.split(/\s+/)[0] ?? '',
);
private readonly drawer = inject(DrawerService);
private readonly createForm =
viewChild.required<TemplateRef<unknown>>('createForm');

View File

@@ -18,7 +18,7 @@ import {
import { DrawerService } from '@task-stream/web/shared/ui';
import { ProjectFacade } from '@task-stream/web/tracker/application';
import { Release, ReleaseStatus } from '@task-stream/web/tracker/domain';
import { RELEASE_STATUS, timeAgo } from '../ui/copy';
import { RELEASE_STATUS, releaseWhen } from '../ui/copy';
@Component({
selector: 'ts-releases-page',
@@ -294,19 +294,7 @@ export class ReleasesPage {
: release.status === ReleaseStatus.ARCHIVED
? 'var(--ts-s-cancelled)'
: 'var(--ts-s-progress)';
/** "publicada hace 2 días", "objetivo 17 oct · en 14 días". */
protected when = (release: Release) => {
if (release.releasedAt) return `publicada ${timeAgo(release.releasedAt)}`;
if (!release.targetDate) return 'sin fecha';
const target = new Date(release.targetDate);
const days = Math.ceil((target.getTime() - Date.now()) / 86_400_000);
const date = target.toLocaleDateString('es', {
day: 'numeric',
month: 'short',
});
if (days < 0) return `objetivo ${date} · retrasada ${-days} d`;
return days === 0 ? `objetivo hoy` : `objetivo ${date} · en ${days} d`;
};
protected readonly when = releaseWhen;
protected openCreate(): void {
this.model.set({ name: '', description: '', targetDate: '' });

View File

@@ -0,0 +1,947 @@
import {
CdkDrag,
CdkDragDrop,
CdkDragHandle,
CdkDropList,
moveItemInArray,
} from '@angular/cdk/drag-drop';
import {
ChangeDetectionStrategy,
Component,
computed,
effect,
inject,
signal,
untracked,
} from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { PiIconComponent, PiNoteComponent } from '@pi/ui';
import { ProjectFacade } from '@task-stream/web/tracker/application';
import {
ProjectSettings,
SETTING_COLORS,
StatusCategory,
TYPE_ICONS,
} from '@task-stream/web/tracker/domain';
import { CATEGORY, COLOR_LABEL, ICON_LABEL, tone } from '../ui/copy';
type Section = 'statuses' | 'issueTypes' | 'areas';
const CATEGORIES = Object.values(StatusCategory);
/** "Datos y análisis" → "DATOS_Y_ANALISIS": ids of new values (they never change after saving). */
function idFrom(name: string): string {
const slug = name
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.replace(/^[^A-Z]+/, '')
.slice(0, 30);
return slug || 'NUEVO';
}
/**
* "Configuración" (owners and admins): the project's statuses, how tickets
* move between them, ticket types and areas. Edits a local draft, saved in
* one go; values can be archived but not removed once saved.
*/
@Component({
selector: 'ts-settings-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [
CdkDropList,
CdkDrag,
CdkDragHandle,
NgTemplateOutlet,
PiIconComponent,
PiNoteComponent,
],
template: `
<div class="ts-section-header">
<div>
<h2>Configuración</h2>
<p>
Estados, transiciones, tipos de ticket y áreas de este proyecto. Lo
que ya se usa no se borra: se archiva y deja de ofrecerse.
</p>
</div>
</div>
@if (!facade.canManage()) {
<pi-note
gap="xs"
status="info"
appearance="fill"
type="status"
title="Solo lectura"
text="Solo el propietario y los admins pueden cambiar la configuración."
/>
}
@if (draft(); as d) {
<form
class="ts-settings"
(submit)="$event.preventDefault(); save()"
novalidate
>
<fieldset [disabled]="!facade.canManage()">
<!-- Statuses -->
<section class="ts-panel ts-block" aria-labelledby="st-title">
<header class="ts-block__head">
<div>
<h3 id="st-title">Estados</h3>
<p class="ts-muted">
En el orden de las columnas del tablero. La categoría dice qué
significa cada uno para releases, «Mi trabajo» y estadísticas.
</p>
</div>
<button type="button" class="ts-add" (click)="addStatus()">
+ Añadir estado
</button>
</header>
<div class="ts-rows-head ts-status-grid" aria-hidden="true">
<span></span><span>Nombre</span><span>Categoría</span
><span>Color</span><span>Pide motivo</span><span></span>
</div>
<ol
class="ts-rows"
cdkDropList
[cdkDropListDisabled]="!facade.canManage()"
(cdkDropListDropped)="reorder($event)"
>
@for (status of d.statuses; track $index; let i = $index) {
<li
class="ts-row ts-status-grid"
cdkDrag
[class.is-archived]="status.archived"
[style.--tone]="toneOf(status.color)"
>
<span
class="ts-grip"
cdkDragHandle
title="Arrastra para reordenar"
aria-hidden="true"
>⠿</span
>
<span class="ts-name">
<span class="ts-swatch" aria-hidden="true"></span>
<input
class="ts-input"
maxlength="40"
[attr.aria-label]="'Nombre del estado ' + (i + 1)"
[value]="status.name"
(input)="setStatusName(i, $any($event.target).value)"
/>
<code class="ts-id">{{ status.id }}</code>
</span>
<select
class="ts-input"
aria-label="Categoría"
[value]="status.category"
[attr.title]="categoryHint(status.category)"
(change)="
edit('statuses', i, {
category: $any($event.target).value,
})
"
>
@for (c of categories; track c) {
<option [value]="c" [selected]="c === status.category">
{{ categoryLabel(c) }}
</option>
}
</select>
<select
class="ts-input"
aria-label="Color"
(change)="
edit('statuses', i, { color: $any($event.target).value })
"
>
@for (c of colors; track c) {
<option [value]="c" [selected]="c === status.color">
{{ colorLabel(c) }}
</option>
}
</select>
<label class="ts-check">
<input
type="checkbox"
[checked]="status.requiresReason"
(change)="
edit('statuses', i, {
requiresReason: $any($event.target).checked,
})
"
/>
<span class="visually-hidden">Pide motivo</span>
</label>
<ng-container
[ngTemplateOutlet]="archive"
[ngTemplateOutletContext]="{
section: 'statuses',
index: i,
item: status,
}"
/>
</li>
}
</ol>
</section>
<!-- Transitions -->
<section class="ts-panel ts-block" aria-labelledby="tr-title">
<header class="ts-block__head">
<div>
<h3 id="tr-title">Transiciones</h3>
<p class="ts-muted">
A qué estados puede pasar un ticket desde cada uno (fila →
columna). Los archivados no reciben tickets.
</p>
</div>
</header>
<div class="ts-matrix-wrap">
<table class="ts-matrix">
<thead>
<tr>
<th scope="col">
<span class="visually-hidden">Desde</span>
</th>
@for (to of activeStatuses(); track to.id) {
<th scope="col">
<span
class="ts-pill"
[style.--tone]="toneOf(to.color)"
>{{ to.name }}</span
>
</th>
}
</tr>
</thead>
<tbody>
@for (from of d.statuses; track from.id) {
<tr [class.is-archived]="from.archived">
<th scope="row">
<span
class="ts-pill"
[style.--tone]="toneOf(from.color)"
>{{ from.name }}</span
>
</th>
@for (to of activeStatuses(); track to.id) {
<td>
@if (from.id !== to.id) {
<input
type="checkbox"
[attr.aria-label]="from.name + ' → ' + to.name"
[checked]="allows(from.id, to.id)"
(change)="
toggleTransition(
from.id,
to.id,
$any($event.target).checked
)
"
/>
}
</td>
}
</tr>
}
</tbody>
</table>
</div>
</section>
<div class="ts-settings__pair">
<!-- Ticket types -->
<section class="ts-panel ts-block" aria-labelledby="ty-title">
<header class="ts-block__head">
<div>
<h3 id="ty-title">Tipos de ticket</h3>
<p class="ts-muted">
Los de icono de paleta piden un frame de Figma.
</p>
</div>
<button type="button" class="ts-add" (click)="addType()">
+ Añadir tipo
</button>
</header>
<ol class="ts-rows">
@for (type of d.issueTypes; track $index; let i = $index) {
<li
class="ts-row ts-type-grid"
[class.is-archived]="type.archived"
[style.--tone]="toneOf(type.color)"
>
<span class="ts-type-icon" aria-hidden="true">
<pi-icon [icon]="type.icon" size="small" />
</span>
<span class="ts-name">
<input
class="ts-input"
maxlength="40"
[attr.aria-label]="'Nombre del tipo ' + (i + 1)"
[value]="type.name"
(input)="
setName('issueTypes', i, $any($event.target).value)
"
/>
<code class="ts-id">{{ type.id }}</code>
</span>
<select
class="ts-input"
aria-label="Icono"
(change)="
edit('issueTypes', i, {
icon: $any($event.target).value,
})
"
>
@for (icon of icons; track icon) {
<option [value]="icon" [selected]="icon === type.icon">
{{ iconLabel(icon) }}
</option>
}
</select>
<select
class="ts-input"
aria-label="Color"
(change)="
edit('issueTypes', i, {
color: $any($event.target).value,
})
"
>
@for (c of colors; track c) {
<option [value]="c" [selected]="c === type.color">
{{ colorLabel(c) }}
</option>
}
</select>
<ng-container
[ngTemplateOutlet]="archive"
[ngTemplateOutletContext]="{
section: 'issueTypes',
index: i,
item: type,
}"
/>
</li>
}
</ol>
</section>
<!-- Areas -->
<section class="ts-panel ts-block" aria-labelledby="ar-title">
<header class="ts-block__head">
<div>
<h3 id="ar-title">Áreas</h3>
<p class="ts-muted">Equipo o capa a la que va el ticket.</p>
</div>
<button type="button" class="ts-add" (click)="addArea()">
+ Añadir área
</button>
</header>
<ol class="ts-rows">
@for (area of d.areas; track $index; let i = $index) {
<li
class="ts-row ts-area-grid"
[class.is-archived]="area.archived"
>
<span class="ts-name">
<input
class="ts-input"
maxlength="40"
[attr.aria-label]="'Nombre del área ' + (i + 1)"
[value]="area.name"
(input)="setName('areas', i, $any($event.target).value)"
/>
<code class="ts-id">{{ area.id }}</code>
</span>
<ng-container
[ngTemplateOutlet]="archive"
[ngTemplateOutletContext]="{
section: 'areas',
index: i,
item: area,
}"
/>
</li>
}
</ol>
</section>
</div>
</fieldset>
@if (facade.canManage() && (dirty() || facade.savingSettings())) {
<footer class="ts-savebar" [class.is-dirty]="dirty()">
<div class="ts-savebar__status" aria-live="polite">
@if (problems().length) {
<ul class="ts-problems">
@for (problem of problems(); track problem) {
<li>
<pi-icon icon="exclamation" size="x-small" />
{{ problem }}
</li>
}
</ul>
} @else {
<span>Cambios sin guardar</span>
}
</div>
<button
type="button"
class="ts-secondary"
[disabled]="!dirty() || facade.savingSettings()"
(click)="discard()"
>
Descartar
</button>
<button
type="submit"
class="ts-primary"
[disabled]="
!dirty() || !!problems().length || facade.savingSettings()
"
>
{{ facade.savingSettings() ? 'Guardando…' : 'Guardar cambios' }}
</button>
</footer>
}
</form>
}
<ng-template
#archive
let-section="section"
let-index="index"
let-item="item"
>
@if (isNew(section, item.id)) {
<button
type="button"
class="ts-icon-button"
title="Quitar (aún no se ha guardado)"
[attr.aria-label]="'Quitar ' + item.name"
(click)="remove(section, index)"
>
<pi-icon icon="trash" size="small" />
</button>
} @else if (item.archived) {
<button
type="button"
class="ts-archive is-archived"
[attr.aria-label]="'Restaurar ' + item.name"
(click)="edit(section, index, { archived: false })"
>
Restaurar
</button>
} @else {
<button
type="button"
class="ts-archive"
[attr.aria-label]="'Archivar ' + item.name"
(click)="edit(section, index, { archived: true })"
>
Archivar
</button>
}
</ng-template>
`,
styles: `
.ts-settings {
display: grid;
gap: 1rem;
padding-bottom: 5rem;
}
fieldset {
display: grid;
gap: 1rem;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.ts-settings__pair {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 26rem), 1fr));
gap: 1rem;
align-items: start;
}
.ts-block {
display: grid;
gap: 0.75rem;
min-width: 0;
padding: 1.25rem;
h3 {
margin: 0;
font-size: 1rem;
font-weight: 700;
}
}
.ts-block__head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
p {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
}
}
.ts-rows {
display: grid;
gap: 0.375rem;
margin: 0;
padding: 0;
list-style: none;
}
.ts-rows-head {
padding: 0 0.5rem;
font-size: 0.6875rem;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ts-muted);
}
.ts-status-grid {
display: grid;
grid-template-columns: 1.25rem minmax(10rem, 1fr) 9rem 8rem 5.5rem 6.5rem;
align-items: center;
gap: 0.5rem;
}
.ts-type-grid {
display: grid;
grid-template-columns: 2rem minmax(8rem, 1fr) 7rem 7rem 6.5rem;
align-items: center;
gap: 0.5rem;
}
.ts-area-grid {
display: grid;
grid-template-columns: minmax(8rem, 1fr) 6.5rem;
align-items: center;
gap: 0.5rem;
}
.ts-row {
--tone: var(--ts-muted);
padding: 0.375rem 0.5rem;
border-radius: 0.625rem;
background: var(--ts-surface);
border: 1px solid var(--ts-line);
&.is-archived {
background: var(--ts-sunken);
.ts-input,
.ts-type-icon {
opacity: 0.6;
}
}
}
.cdk-drag-preview {
box-shadow: var(--ts-lift);
}
.cdk-drag-placeholder {
opacity: 0.35;
}
.ts-grip {
cursor: grab;
color: var(--ts-muted);
text-align: center;
user-select: none;
}
.ts-name {
position: relative;
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
.ts-input {
flex: 1;
min-width: 0;
}
}
.ts-swatch {
flex: none;
width: 0.625rem;
height: 0.625rem;
border-radius: 50%;
background: var(--tone);
}
.ts-id {
flex: 0 0 5.5rem;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--ts-font-mono);
font-size: 0.625rem;
color: var(--ts-muted);
}
.ts-input {
box-sizing: border-box;
height: 2.125rem;
width: 100%;
padding: 0 0.5rem;
border: 1px solid var(--ts-line);
border-radius: 0.5rem;
background: var(--ts-surface);
color: var(--ts-ink);
font: inherit;
font-size: 0.875rem;
&:focus-visible {
outline: 2px solid var(--ts-brand);
outline-offset: 1px;
}
&:disabled {
color: var(--ts-ink-soft);
background: transparent;
}
}
.ts-check {
display: grid;
place-items: center;
}
input[type='checkbox'] {
width: 1rem;
height: 1rem;
accent-color: var(--ts-brand);
cursor: pointer;
}
.ts-type-icon {
display: inline-grid;
place-items: center;
width: 2rem;
height: 2rem;
border-radius: 0.5rem;
color: var(--tone);
background: color-mix(in srgb, var(--tone) 12%, var(--ts-surface));
}
.ts-matrix-wrap {
overflow-x: auto;
}
.ts-matrix {
border-collapse: collapse;
font-size: 0.8125rem;
th,
td {
padding: 0.375rem 0.5rem;
border-bottom: 1px solid var(--ts-line);
text-align: center;
}
th[scope='row'] {
text-align: left;
white-space: nowrap;
}
thead th {
vertical-align: bottom;
}
tr.is-archived th[scope='row'] {
opacity: 0.6;
}
td:hover {
background: var(--pi-color-primary-25);
}
}
/* @pi/ui styles every <button>: these opt back into a compact look. */
.ts-add,
.ts-archive,
.ts-primary,
.ts-secondary {
min-width: 0 !important;
height: 2.125rem;
padding: 0 0.875rem !important;
border-radius: 999px !important;
font: inherit;
font-size: 0.8125rem;
font-weight: 600;
cursor: pointer;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
.ts-add,
.ts-archive,
.ts-secondary {
border: 1px solid var(--ts-line-strong) !important;
background: var(--ts-surface) !important;
color: var(--ts-ink-soft) !important;
}
.ts-archive.is-archived {
border-style: dashed !important;
}
.ts-primary {
border: 0 !important;
background: var(--ts-brand) !important;
color: #fff !important;
}
.ts-savebar {
position: sticky;
bottom: 1rem;
z-index: 3;
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
border-radius: 999px;
background: var(--ts-surface-raised);
border: 1px solid var(--ts-line-strong);
box-shadow: var(--ts-lift);
font-size: 0.875rem;
&.is-dirty {
border-color: var(--ts-brand);
}
}
.ts-savebar__status {
flex: 1;
min-width: 0;
}
.ts-problems {
display: grid;
gap: 0.125rem;
margin: 0;
padding: 0;
list-style: none;
color: var(--ts-c-red);
font-size: 0.8125rem;
li {
display: flex;
align-items: center;
gap: 0.375rem;
}
}
@media (max-width: 720px) {
.ts-rows-head {
display: none;
}
.ts-status-grid,
.ts-type-grid {
grid-template-columns: 1fr 1fr;
}
.ts-grip,
.ts-type-icon {
display: none;
}
.ts-name {
grid-column: 1 / -1;
}
.ts-savebar {
flex-wrap: wrap;
border-radius: var(--ts-radius);
}
}
`,
})
export class SettingsPage {
protected readonly facade = inject(ProjectFacade);
protected readonly categories = CATEGORIES;
protected readonly colors = SETTING_COLORS;
protected readonly icons = TYPE_ICONS;
/** What the API has; the draft is compared against it. */
private readonly saved = computed(
() => this.facade.project()?.settings ?? null,
);
protected readonly draft = signal<ProjectSettings | null>(null);
protected readonly dirty = computed(
() =>
!!this.draft() &&
JSON.stringify(this.draft()) !== JSON.stringify(this.saved()),
);
protected readonly activeStatuses = computed(
() => this.draft()?.statuses.filter((s) => !s.archived) ?? [],
);
/** The same rules the API enforces, shown before saving. */
protected readonly problems = computed(() => {
const d = this.draft();
if (!d) return [];
const problems: string[] = [];
const lists = [d.statuses, d.issueTypes, d.areas];
if (lists.some((list) => list.some((item) => !item.name.trim())))
problems.push('Hay nombres vacíos');
if (
lists.some((list) => {
const ids = list.map((item) => item.id);
return ids.some((id, i) => ids.indexOf(id) !== i);
})
)
problems.push('Hay dos valores con el mismo nombre');
const active = d.statuses.filter((s) => !s.archived);
if (!active.some((s) => s.category === StatusCategory.TODO))
problems.push(
'Falta un estado activo «Pendiente» donde entren los tickets',
);
if (!active.some((s) => s.category === StatusCategory.DONE))
problems.push('Falta un estado activo «Hecho»');
if (!d.issueTypes.some((t) => !t.archived))
problems.push('Hace falta al menos un tipo de ticket activo');
return problems;
});
constructor() {
// Follow the saved settings while there is nothing pending (after saving,
// the project comes back equal to the draft, so it is clean again).
effect(() => {
const saved = this.saved();
if (saved && !untracked(this.dirty))
this.draft.set(structuredClone(saved));
});
}
protected readonly toneOf = tone;
protected readonly categoryLabel = (c: StatusCategory) => CATEGORY[c].label;
protected readonly categoryHint = (c: StatusCategory) => CATEGORY[c].hint;
protected readonly iconLabel = (icon: string) => ICON_LABEL[icon] ?? icon;
protected readonly colorLabel = (c: (typeof SETTING_COLORS)[number]) =>
COLOR_LABEL[c];
/** Values the API does not have yet: they can still be removed or have their id follow the name. */
protected isNew(section: Section, id: string): boolean {
return !this.saved()?.[section].some((item) => item.id === id);
}
protected allows(from: string, to: string): boolean {
return !!this.draft()
?.transitions.find((t) => t.from === from)
?.to.includes(to);
}
protected edit(section: Section, index: number, changes: object): void {
this.patch((d) => Object.assign(d[section][index], changes));
}
protected setName(section: Section, index: number, name: string): void {
this.patch((d) => {
const item = d[section][index];
item.name = name;
if (this.isNew(section, item.id)) {
const id = this.uniqueId(d[section], idFrom(name), index);
if (section === 'statuses') this.renameStatus(d, item.id, id);
item.id = id;
}
});
}
protected setStatusName(index: number, name: string): void {
this.setName('statuses', index, name);
}
protected toggleTransition(from: string, to: string, on: boolean): void {
this.patch((d) => {
let row = d.transitions.find((t) => t.from === from);
if (!row) {
row = { from, to: [] };
d.transitions.push(row);
}
row.to = on
? [...new Set([...row.to, to])]
: row.to.filter((target) => target !== to);
});
}
protected reorder(event: CdkDragDrop<unknown>): void {
this.patch((d) =>
moveItemInArray(d.statuses, event.previousIndex, event.currentIndex),
);
}
protected addStatus(): void {
this.patch((d) => {
const id = this.uniqueId(d.statuses, 'NUEVO_ESTADO');
// Before the done/cancelled statuses, so it lands mid-board.
const at = d.statuses.findIndex(
(s) =>
s.category === StatusCategory.DONE ||
s.category === StatusCategory.CANCELLED,
);
d.statuses.splice(at === -1 ? d.statuses.length : at, 0, {
id,
name: 'Nuevo estado',
category: StatusCategory.IN_PROGRESS,
color: 'teal',
requiresReason: false,
archived: false,
});
d.transitions.push({ from: id, to: [] });
});
}
protected addType(): void {
this.patch((d) =>
d.issueTypes.push({
id: this.uniqueId(d.issueTypes, 'NUEVO_TIPO'),
name: 'Nuevo tipo',
icon: 'flag',
color: 'teal',
archived: false,
}),
);
}
protected addArea(): void {
this.patch((d) =>
d.areas.push({
id: this.uniqueId(d.areas, 'NUEVA_AREA'),
name: 'Nueva área',
archived: false,
}),
);
}
/** Only for values never saved; saved ones are archived instead. */
protected remove(section: Section, index: number): void {
this.patch((d) => {
const [item] = d[section].splice(index, 1);
if (section === 'statuses') {
d.transitions = d.transitions
.filter((t) => t.from !== item.id)
.map((t) => ({ ...t, to: t.to.filter((to) => to !== item.id) }));
}
});
}
protected discard(): void {
const saved = this.saved();
if (saved) this.draft.set(structuredClone(saved));
}
protected save(): void {
const draft = this.draft();
if (!draft || !this.dirty() || this.problems().length) return;
this.facade.saveSettings({
...draft,
// Only rows with targets; unknown ids would be rejected anyway.
transitions: draft.transitions.filter((t) => t.to.length),
});
}
private patch(change: (draft: ProjectSettings) => void): void {
this.draft.update((d) => {
if (!d) return d;
const next = structuredClone(d);
change(next);
return next;
});
}
private uniqueId(list: { id: string }[], base: string, except = -1): string {
const taken = new Set(
list.filter((_, i) => i !== except).map((item) => item.id),
);
let id = base;
for (let n = 2; taken.has(id); n++) id = `${base.slice(0, 27)}_${n}`;
return id;
}
private renameStatus(d: ProjectSettings, from: string, to: string): void {
for (const row of d.transitions) {
if (row.from === from) row.from = to;
row.to = row.to.map((target) => (target === from ? to : target));
}
}
}