⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(dashboards): add a burnup widget with a projected completion date (#285)
Andrei Shkarin62461525eff2
diff --git a/README.md b/README.mdindex 2b36f445..97033d8d 100644--- a/README.md+++ b/README.md@@ -78,7 +78,8 @@ release.- Cycles that time-box the work. Unfinished issues move to the next cycle- Subtasks, checklists, attachments, and links between issues: blocks, relates, duplicates- Comment threads with replies, and @username mentions of people and agents-- Configurable dashboards for project analytics: throughput, breakdown, pulse+- Configurable dashboards for project analytics: throughput, burnup with a projected+ completion date, breakdown, pulse- Quick actions that run on an issue, and auto-assignment when an issue moves into a state- Docs: shared Markdown pages in a tree, with revision history, private and locked pages,favorites, embedded files, and links to the issues they describediff --git a/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts b/apps/api/src/modules/analytics/__tests__/integration/analytics.test.tsindex 0e17e86a..2326334a 100644--- a/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts+++ b/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts@@ -34,6 +34,7 @@ async function createIssue(dueDate?: string | null;assigneeUserId?: string | null;typeId?: number | null;+ initiativeId?: number | null;} = {},) {const { title = 'Task', ...rest } = extra;@@ -416,6 +417,99 @@ describe('analytics', () => {});});+ describe('burnup', () => {+ const burnup = (api: Api, query: Record<string, number> = {}) =>+ api.projects({ projectKey: 'MKT' }).analytics.burnup.get({ query });++ // Treaty turns date-shaped strings into Date objects on the way in; compare the+ // calendar day.+ const dayOf = (v: unknown) => new Date(v as string).toISOString().slice(0, 10);++ it('returns a flat zero series and no forecast for an empty project', async () => {+ const { asOwner } = await setupProject();+ const res = await burnup(asOwner);+ expect(res.status).toBe(200);+ expect(res.data?.days).toHaveLength(90);+ expect(res.data?.days.at(-1)).toMatchObject({ scope: 0, started: 0, completed: 0 });+ expect(res.data?.forecast).toEqual({+ windowDays: 28,+ velocityPerDay: 0,+ scopeGrowthPerDay: 0,+ remaining: 0,+ projectedScope: 0,+ projectedDate: null,+ optimisticDate: null,+ pessimisticDate: null,+ });+ expect(res.data?.targetDate).toBeNull();+ });++ it('counts the state of every issue at the end of today and projects a date', async () => {+ const { asOwner, col } = await setupProject();+ const a = await createIssue(asOwner, col.started);+ await createIssue(asOwner, col.started);+ await createIssue(asOwner, col.backlog);+ await moveIssue(asOwner, a.id, col.completed);++ const res = await burnup(asOwner);+ expect(res.status).toBe(200);+ const today = res.data!.days.at(-1)!;+ expect(today).toMatchObject({ scope: 3, started: 2, completed: 1 });+ expect(dayOf(today.date)).toBe(dayOf(new Date()));+ // One closing in the latest of the four weeks, weighted 4 of 10 → 4/70 per+ // day, two issues left.+ expect(res.data?.forecast).toMatchObject({ windowDays: 28, remaining: 2 });+ expect(res.data?.forecast.velocityPerDay).toBeCloseTo(0.06, 2);+ const { optimisticDate, projectedDate, pessimisticDate } = res.data!.forecast;+ expect(projectedDate).not.toBeNull();+ expect(dayOf(projectedDate) > dayOf(today.date)).toBe(true);+ expect(dayOf(optimisticDate) < dayOf(projectedDate)).toBe(true);+ expect(dayOf(pessimisticDate) > dayOf(projectedDate)).toBe(true);+ });++ it('drops canceled issues from the scope and gives no date without closings', async () => {+ const { asOwner, col } = await setupProject();+ await createIssue(asOwner, col.backlog);+ const b = await createIssue(asOwner, col.backlog);+ await moveIssue(asOwner, b.id, col.canceled);++ const res = await burnup(asOwner);+ expect(res.status).toBe(200);+ expect(res.data?.days.at(-1)).toMatchObject({ scope: 1, started: 0, completed: 0 });+ expect(res.data?.forecast).toMatchObject({ remaining: 1, projectedDate: null });+ });++ it('limits the series to one initiative and returns its target date', async () => {+ const { asOwner, col } = await setupProject();+ const created = await asOwner+ .projects({ projectKey: 'MKT' })+ .initiatives.post({ title: 'Launch', targetDate: '2030-06-30' });+ expect(created.status).toBe(201);+ const initiativeId = created.data!.id;+ await createIssue(asOwner, col.started, { initiativeId });+ await createIssue(asOwner, col.started);++ const res = await burnup(asOwner, { initiativeId });+ expect(res.status).toBe(200);+ expect(res.data?.days.at(-1)).toMatchObject({ scope: 1, started: 1, completed: 0 });+ expect(dayOf(res.data?.targetDate)).toBe('2030-06-30');+ });++ it('returns 404 for an initiative that is not in the project', async () => {+ const { asOwner } = await setupProject();+ const res = await burnup(asOwner, { initiativeId: 999999 });+ expect(res.status).toBe(404);+ });++ it('clamps the window to at least a week and the forecast window to a week', async () => {+ const { asOwner } = await setupProject();+ const res = await burnup(asOwner, { days: 1, forecastWeeks: 0 });+ expect(res.status).toBe(200);+ expect(res.data?.days).toHaveLength(7);+ expect(res.data?.forecast.windowDays).toBe(6);+ });+ });+describe('activity', () => {it('returns the feed with issue context, newest first', async () => {const { asOwner, col } = await setupProject();@@ -683,6 +777,7 @@ describe('analytics', () => {expect((await scope.analytics.breakdown.get({ query: { by: 'status' } })).status).toBe(403);expect((await scope.analytics.pulse.get()).status).toBe(403);expect((await scope.analytics.throughput.get()).status).toBe(403);+ expect((await scope.analytics.burnup.get()).status).toBe(403);expect((await scope.analytics.activity.get()).status).toBe(403);expect((await scope['analytics']['agent-runs'].get()).status).toBe(403);expect((await scope['analytics']['agent-run-stats'].get()).status).toBe(403);diff --git a/apps/api/src/modules/analytics/__tests__/unit/forecast.test.ts b/apps/api/src/modules/analytics/__tests__/unit/forecast.test.tsnew file mode 100644index 00000000..8ca3a255--- /dev/null+++ b/apps/api/src/modules/analytics/__tests__/unit/forecast.test.ts@@ -0,0 +1,151 @@+import { describe, it, expect } from 'bun:test';+import { forecastCompletion, type BurnupDay } from '../../service';++// forecastCompletion projects a completion date from the closing rate and the+// scope growth rate over the last `windowDays` points of a burnup series: the+// remaining issues plus the ones expected to appear while they are closed, at the+// closing rate, bracketed with a ±40% buffer on the days to go. It gives no date+// when nothing closed in the window or nothing is left.++function series(completed: number[], scope = 10): BurnupDay[] {+ return completed.map((c, i) => ({+ date: `2026-03-${String(i + 1).padStart(2, '0')}`,+ scope,+ started: c,+ completed: c,+ }));+}++describe('forecastCompletion', () => {+ it('returns an empty forecast for an empty series', () => {+ expect(forecastCompletion([], 28)).toEqual({+ windowDays: 0,+ velocityPerDay: 0,+ scopeGrowthPerDay: 0,+ remaining: 0,+ projectedScope: 0,+ projectedDate: null,+ optimisticDate: null,+ pessimisticDate: null,+ });+ });++ it('takes the rate over the window and applies it to what is left', () => {+ // Last two days: 2 → 4, so 1/day; 6 left → 6 days after 5 March, bracketed by+ // 6 × 0.6 = 3.6 → 4 and 6 × 1.4 = 8.4 → 9 days.+ const f = forecastCompletion(series([0, 1, 2, 3, 4]), 2);+ expect(f).toEqual({+ windowDays: 2,+ velocityPerDay: 1,+ scopeGrowthPerDay: 0,+ remaining: 6,+ projectedScope: 10,+ projectedDate: '2026-03-11',+ optimisticDate: '2026-03-09',+ pessimisticDate: '2026-03-14',+ });+ });++ it('weights the latest whole week heaviest', () => {+ // Two weeks: 1/day, then 3/day; weights 1 and 2 → (1 + 6) / 3 = 2.33/day.+ const completed = [0, 1, 2, 3, 4, 5, 6, 7, 10, 13, 16, 19, 22, 25, 28];+ const f = forecastCompletion(series(completed, 100), 14);+ expect(f.velocityPerDay).toBe(2.33);+ // 72 left → 30.9 → 31 days after 15 March; 18.5 → 19 and 43.2 → 44 around it.+ expect(f.optimisticDate).toBe('2026-04-03');+ expect(f.projectedDate).toBe('2026-04-15');+ expect(f.pessimisticDate).toBe('2026-04-28');+ });++ it('keeps the range closed when a week closed nothing', () => {+ // 0/day then 1/day → 2/3 per day; 13 left → 19.5 → 20 days after 15 March.+ const completed = [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7];+ const f = forecastCompletion(series(completed, 20), 14);+ expect(f.velocityPerDay).toBe(0.67);+ expect(f.projectedDate).toBe('2026-04-04');+ expect(f.pessimisticDate).toBe('2026-04-12');+ });++ it('uses the whole series when it is shorter than the window', () => {+ const f = forecastCompletion(series([0, 1, 2, 3, 4]), 28);+ expect(f.windowDays).toBe(4);+ expect(f.velocityPerDay).toBe(1);+ });++ it('rounds the rate to two decimals and rounds the days up', () => {+ // 2 closings over 3 days → 0.67/day; 9 left → 13.5 → 14 days after 4 March.+ const f = forecastCompletion(series([0, 0, 0, 2], 11), 3);+ expect(f.velocityPerDay).toBe(0.67);+ expect(f.projectedDate).toBe('2026-03-18');+ });++ it('adds the issues expected while the remaining ones are closed', () => {+ // Closing 1/day, scope growing 0.5/day (1 issue every other day); 6 left take+ // 6 days, during which 3 more appear → 9 days after 5 March, bracketed by+ // 5.4 → 6 and 12.6 → 13.+ const days = series([0, 1, 2, 3, 4]).map((d, i) => ({ ...d, scope: 8 + Math.floor(i / 2) }));+ const f = forecastCompletion(days, 4);+ expect(f).toMatchObject({+ velocityPerDay: 1,+ scopeGrowthPerDay: 0.5,+ remaining: 6,+ projectedScope: 13,+ optimisticDate: '2026-03-11',+ projectedDate: '2026-03-14',+ pessimisticDate: '2026-03-18',+ });+ });++ it('still gives a date when new issues outpace closings', () => {+ // 1/day closed, 2/day new; 8 left take 8 days, 16 more appear → 24 days.+ const days = series([0, 1, 2]).map((d, i) => ({ ...d, scope: 6 + 2 * i }));+ const f = forecastCompletion(days, 2);+ expect(f).toMatchObject({+ velocityPerDay: 1,+ scopeGrowthPerDay: 2,+ remaining: 8,+ projectedScope: 26,+ projectedDate: '2026-03-27',+ });+ });++ it('does not extrapolate a shrinking scope', () => {+ const days = series([0, 1, 2]).map((d, i) => ({ ...d, scope: 10 - 2 * i }));+ const f = forecastCompletion(days, 2);+ expect(f).toMatchObject({+ scopeGrowthPerDay: 0,+ projectedScope: 6,+ projectedDate: '2026-03-07',+ });+ });++ it('gives no date when nothing closed in the window', () => {+ const f = forecastCompletion(series([3, 3, 3]), 2);+ expect(f).toMatchObject({ velocityPerDay: 0, remaining: 7, projectedDate: null });+ });++ it('gives no date when issues were reopened faster than closed', () => {+ const f = forecastCompletion(series([4, 3, 2]), 2);+ expect(f).toMatchObject({ velocityPerDay: -1, projectedDate: null });+ });++ it('gives no date when everything is done', () => {+ const f = forecastCompletion(series([8, 9, 10]), 2);+ expect(f).toMatchObject({ remaining: 0, projectedDate: null });+ });++ it('gives no date from a single point', () => {+ const f = forecastCompletion(series([5]), 28);+ expect(f).toMatchObject({ windowDays: 0, velocityPerDay: 0, projectedDate: null });+ });++ it('crosses a month end and a year end when adding days', () => {+ const days: BurnupDay[] = [+ { date: '2026-12-29', scope: 4, started: 0, completed: 0 },+ { date: '2026-12-30', scope: 4, started: 2, completed: 2 },+ ];+ expect(forecastCompletion(days, 1).projectedDate).toBe('2026-12-31');+ for (const d of days) d.scope = 6;+ expect(forecastCompletion(days, 1).projectedDate).toBe('2027-01-01');+ });+});diff --git a/apps/api/src/modules/analytics/index.ts b/apps/api/src/modules/analytics/index.tsindex f22d441b..cf31a915 100644--- a/apps/api/src/modules/analytics/index.ts+++ b/apps/api/src/modules/analytics/index.ts@@ -10,6 +10,7 @@ import {AgentRunStatsDto,AgentWorkloadListResponse,BreakdownListResponse,+ BurnupDto,PulseListResponse,StatsDto,ThroughputListResponse,@@ -17,6 +18,7 @@ import {activityQuery,agentRunFeedQuery,breakdownQuery,+ burnupQuery,daysQuery,pulseQuery,throughputQuery,@@ -26,6 +28,7 @@ import {getBreakdown,getPulse,getThroughput,+ getBurnup,listActivity,listAgentRunFeed,getAgentRunStats,@@ -131,6 +134,31 @@ export const analyticsRoutes = new Elysia({},)+ .get(+ '/projects/:projectKey/analytics/burnup',+ async ({ project, query }) => {+ const days = query.days != null ? Math.min(Math.max(query.days, 7), 730) : 90;+ const forecastWeeks =+ query.forecastWeeks != null ? Math.min(Math.max(query.forecastWeeks, 1), 12) : 4;+ return getBurnup(project.id, {+ days,+ initiativeId: query.initiativeId ?? null,+ forecastWeeks,+ });+ },+ {+ query: burnupQuery,+ permission: ['dashboards', 'read'],+ response: { 200: BurnupDto, ...commonErrors },+ detail: {+ summary: 'Get project burnup',+ description:+ 'Scope, started and completed issue counts at the end of each day, with a completion date projected from the recent closing rate and scope growth. Optionally limited to one initiative.',+ ...mcpTool('get_project_burnup'),+ },+ },+ )+.get('/projects/:projectKey/analytics/activity',async ({ project, query }) => {diff --git a/apps/api/src/modules/analytics/model.ts b/apps/api/src/modules/analytics/model.tsindex b08dd0ba..f0f37f9e 100644--- a/apps/api/src/modules/analytics/model.ts+++ b/apps/api/src/modules/analytics/model.ts@@ -28,6 +28,28 @@ const ThroughputWeek = t.Object({closed: t.Number(),});+const BurnupDay = t.Object({+ date: t.String(),+ scope: t.Number(),+ started: t.Number(),+ completed: t.Number(),+});++export const BurnupDto = t.Object({+ days: t.Array(BurnupDay),+ forecast: t.Object({+ windowDays: t.Number(),+ velocityPerDay: t.Number(),+ scopeGrowthPerDay: t.Number(),+ remaining: t.Number(),+ projectedScope: t.Number(),+ projectedDate: t.Nullable(t.String()),+ optimisticDate: t.Nullable(t.String()),+ pessimisticDate: t.Nullable(t.String()),+ }),+ targetDate: t.Nullable(t.String()),+});+const ActivityItem = t.Object({id: t.Number(),issueId: t.Number(),@@ -124,6 +146,12 @@ export const pulseQuery = t.Object({export const throughputQuery = t.Object({ weeks: t.Optional(t.Numeric()) });+export const burnupQuery = t.Object({+ days: t.Optional(t.Numeric()),+ initiativeId: t.Optional(t.Numeric()),+ forecastWeeks: t.Optional(t.Numeric()),+});+export const activityQuery = t.Object({limit: t.Optional(t.Numeric()),cursor: t.Optional(t.String()),diff --git a/apps/api/src/modules/analytics/service.ts b/apps/api/src/modules/analytics/service.tsindex 5de8d0b4..abe23c54 100644--- a/apps/api/src/modules/analytics/service.ts+++ b/apps/api/src/modules/analytics/service.ts@@ -10,10 +10,11 @@ import {agentRun,webhook,webhookDelivery,+ initiative,type ActivityPayload,} from '@repo/db';import { and, desc, eq, inArray, isNull, isNotNull, sql } from 'drizzle-orm';-import { iso } from '#shared/lib';+import { HttpError, iso } from '#shared/lib';// Read-only project metrics for the dashboards feature. Every figure is derived// from the existing issue / project_column / issue_activity / issue_status tables —@@ -335,6 +336,177 @@ export async function getThroughput(projectId: number, weeks: number): Promise<Treturn rows.map((r) => ({ week: r.week, created: Number(r.created), closed: Number(r.closed) }));}+// --- Burnup (scope / started / completed per day, with a forecast) ---------------++export interface BurnupDay {+ date: string;+ scope: number;+ started: number;+ completed: number;+}++export interface BurnupForecast {+ windowDays: number;+ velocityPerDay: number;+ // The scope's growth rate over the same window, never negative: cancellations+ // are not a trend.+ scopeGrowthPerDay: number;+ remaining: number;+ // The scope the projection ends at: today's plus the issues expected to appear,+ // at scopeGrowthPerDay, while today's remaining ones are closed.+ projectedScope: number;+ projectedDate: string | null;+ // The projected date with the days to go shortened and lengthened by+ // RANGE_BUFFER: the range the widget can draw around the projection. Null+ // together with projectedDate.+ optimisticDate: string | null;+ pessimisticDate: string | null;+}++export interface BurnupDto {+ days: BurnupDay[];+ forecast: BurnupForecast;+ targetDate: string | null;+}++export interface BurnupParams {+ days: number;+ initiativeId: number | null;+ forecastWeeks: number;+}++// Unlike closings() above, which dates each issue by the moment it was closed, the+// burnup asks what state every issue was in at the end of each day: the status row+// whose stretch covers that midnight. So an issue that was reopened leaves the+// completed line for the days it was open again, and a canceled issue leaves the+// scope line — the chart is a history of the project, not of the events.+export async function getBurnup(projectId: number, params: BurnupParams): Promise<BurnupDto> {+ const targetDate = await initiativeTargetDate(projectId, params.initiativeId);+ const initiativeFilter =+ params.initiativeId == null ? sql`` : sql`AND i.initiative_id = ${params.initiativeId}::int`;+ const rows = (await db.execute(sql`+ WITH d AS (+ SELECT generate_series(current_date - ${params.days - 1}::int, current_date, '1 day')::date AS day+ )+ SELECT to_char(d.day, 'YYYY-MM-DD') AS date,+ (count(s.issue_id) FILTER (WHERE s.state_type IS DISTINCT FROM 'canceled'))::int AS scope,+ (count(s.issue_id) FILTER (WHERE s.state_type IN ('started', 'completed')))::int AS started,+ (count(s.issue_id) FILTER (WHERE s.state_type = 'completed'))::int AS completed+ FROM d+ LEFT JOIN (+ SELECT s.issue_id, s.state_type, s.entered_at, s.left_at+ FROM issue_status s+ JOIN issue i ON i.id = s.issue_id+ WHERE i.project_id = ${projectId} ${initiativeFilter}+ ) s ON s.entered_at < d.day + 1+ AND (s.left_at IS NULL OR s.left_at >= d.day + 1)+ GROUP BY d.day+ ORDER BY d.day`)) as unknown as BurnupDay[];+ const days = rows.map((r) => ({+ date: r.date,+ scope: Number(r.scope),+ started: Number(r.started),+ completed: Number(r.completed),+ }));+ return { days, forecast: forecastCompletion(days, params.forecastWeeks * 7), targetDate };+}++// The initiative's target date, so the chart can draw it; null when the whole+// project is charted. An initiative from another project is a 404, not an empty+// chart, so a wrong id does not read as an initiative with no issues.+async function initiativeTargetDate(+ projectId: number,+ initiativeId: number | null,+): Promise<string | null> {+ if (initiativeId == null) return null;+ const [row] = await db+ .select({ targetDate: initiative.targetDate })+ .from(initiative)+ .where(and(eq(initiative.id, initiativeId), eq(initiative.projectId, projectId)))+ .limit(1);+ if (!row) throw new HttpError(404, 'Initiative not found');+ return row.targetDate;+}++// The buffer Linear's project graph puts around its projected date.+const RANGE_BUFFER = 0.4;++// A completion date from two rates over the whole weeks inside the last+// `windowDays` days of the series, the latest week weighted heaviest (a window+// with no whole week uses the plain rates): the closing rate, and the scope's+// growth rate. The days to go cover today's remaining issues plus the ones+// expected to appear while they are closed — one round, not compounded, so a+// scope growing faster than it is closed still gets a date. No date when nothing+// was closed in the window or nothing is left — the widget says so instead of+// drawing a line to infinity.+export function forecastCompletion(days: BurnupDay[], windowDays: number): BurnupForecast {+ const last = days[days.length - 1];+ if (!last) {+ return {+ windowDays: 0,+ velocityPerDay: 0,+ scopeGrowthPerDay: 0,+ remaining: 0,+ projectedScope: 0,+ projectedDate: null,+ optimisticDate: null,+ pessimisticDate: null,+ };+ }+ const lastIndex = days.length - 1;+ const startIndex = Math.max(0, lastIndex - windowDays);+ const velocity = rateOver(days, startIndex, 'completed');+ const growth = Math.max(0, rateOver(days, startIndex, 'scope'));+ const remaining = Math.max(0, last.scope - last.completed);+ const daysForRemaining = velocity > 0 && remaining > 0 ? remaining / velocity : null;+ const expected = daysForRemaining === null ? 0 : Math.round(growth * daysForRemaining);+ const daysToGo = daysForRemaining === null ? null : (remaining + expected) / velocity;+ const dateAt = (factor: number) =>+ daysToGo === null ? null : addDays(last.date, Math.ceil(daysToGo * factor));+ return {+ windowDays: lastIndex - startIndex,+ velocityPerDay: round2(velocity),+ scopeGrowthPerDay: round2(growth),+ remaining,+ projectedScope: last.scope + expected,+ projectedDate: dateAt(1),+ optimisticDate: dateAt(1 - RANGE_BUFFER),+ pessimisticDate: dateAt(1 + RANGE_BUFFER),+ };+}++// The daily rate of `key` over the whole weeks between startIndex and the last+// day, the latest week weighted n, the earliest 1; the plain rate over the span+// when there is no whole week, 0 for a single point.+function rateOver(days: BurnupDay[], startIndex: number, key: 'completed' | 'scope'): number {+ const lastIndex = days.length - 1;+ const weeks = Math.floor((lastIndex - startIndex) / 7);+ if (weeks === 0) {+ const span = lastIndex - startIndex;+ return span > 0 ? (days[lastIndex]![key] - days[startIndex]![key]) / span : 0;+ }+ let sum = 0;+ let weightSum = 0;+ for (let i = 0; i < weeks; i++) {+ const end = lastIndex - i * 7;+ const weight = weeks - i;+ sum += (weight * (days[end]![key] - days[end - 7]![key])) / 7;+ weightSum += weight;+ }+ return sum / weightSum;+}++function round2(n: number): number {+ return Math.round(n * 100) / 100;+}++// 'YYYY-MM-DD' plus n days, computed in UTC so the local timezone never shifts the+// calendar date.+function addDays(date: string, n: number): string {+ const [y, m, d] = date.split('-').map(Number) as [number, number, number];+ return new Date(Date.UTC(y, m - 1, d + n)).toISOString().slice(0, 10);+}+// --- Project-wide activity feed --------------------------------------------------export interface ActivityCursor {diff --git a/apps/web/messages/ar/dashboards.json b/apps/web/messages/ar/dashboards.jsonindex a0d3f3ec..2e050f4f 100644--- a/apps/web/messages/ar/dashboards.json+++ b/apps/web/messages/ar/dashboards.json@@ -49,6 +49,10 @@"label": "الإنتاجية","description": "مقارنة بين المهام اللي اتفتحت واللي اتقفلت كل أسبوع"},+ "burnup": {+ "label": "مخطط الإنجاز",+ "description": "النطاق والمهام المبدوءة والمكتملة يوميًا مع تاريخ إنجاز متوقع"+ },"breakdown": {"label": "التوزيع","description": "بيوزّع عدد المهام حسب الحالة أو الأولوية أو النوع أو المسؤول"@@ -152,6 +156,29 @@"created": "مُنشأة","closed": "مُغلقة"},+ "burnup": {+ "empty": "لا توجد مهام في هذه الفترة.",+ "scope": "النطاق",+ "started": "بدأت",+ "completed": "اكتملت",+ "projection": "التوقع",+ "band": "نطاق التوقع",+ "projected": "الإنجاز المتوقع {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "خط التوقع",+ "range": "نطاق التوقع"+ },+ "noForecast": "لا تقدم خلال {weeks, plural, one {الأسبوع الماضي} two {الأسبوعين الماضيين} few {# أسابيع الماضية} many {# أسبوعًا الماضية} other {# أسبوع الماضية}}",+ "allDone": "اكتمل كل شيء",+ "velocity": "{rate}/يوم",+ "growth": "+{rate}/يوم جديدة",+ "target": "الهدف {date}",+ "targetLabel": "الهدف",+ "today": "اليوم",+ "wholeProject": "المشروع بأكمله",+ "forecastWeeks": "المعدل خلال {weeks, plural, one {أسبوع واحد} two {أسبوعين} few {# أسابيع} many {# أسبوعًا} other {# أسبوع}}"+ },"agentRuns": {"empty": "لا توجد تشغيلات وكلاء بعد.","filters": {diff --git a/apps/web/messages/en/dashboards.json b/apps/web/messages/en/dashboards.jsonindex 34d1d5a4..69b52976 100644--- a/apps/web/messages/en/dashboards.json+++ b/apps/web/messages/en/dashboards.json@@ -49,6 +49,10 @@"label": "Throughput","description": "Created vs closed issues per week"},+ "burnup": {+ "label": "Burnup",+ "description": "Scope, started and completed issues per day with a projected completion date"+ },"breakdown": {"label": "Breakdown","description": "Issue counts by status, priority, type, or assignee"@@ -152,6 +156,29 @@"created": "Created","closed": "Closed"},+ "burnup": {+ "empty": "No issues in this period.",+ "scope": "Scope",+ "started": "Started",+ "completed": "Completed",+ "projection": "Projection",+ "band": "Forecast range",+ "projected": "Projected {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "Forecast line",+ "range": "Forecast range"+ },+ "noForecast": "No progress in the last {weeks, plural, one {# week} other {# weeks}}",+ "allDone": "All done",+ "velocity": "{rate}/day",+ "growth": "+{rate}/day new",+ "target": "Target {date}",+ "targetLabel": "Target",+ "today": "Today",+ "wholeProject": "Whole project",+ "forecastWeeks": "Rate over {weeks, plural, one {# week} other {# weeks}}"+ },"agentRuns": {"empty": "No agent runs yet.","filters": {diff --git a/apps/web/messages/es-ES/dashboards.json b/apps/web/messages/es-ES/dashboards.jsonindex a0b3570f..94a7e9e4 100644--- a/apps/web/messages/es-ES/dashboards.json+++ b/apps/web/messages/es-ES/dashboards.json@@ -49,6 +49,10 @@"label": "Rendimiento","description": "Tickets creados frente a cerrados por semana"},+ "burnup": {+ "label": "Burnup",+ "description": "Alcance, tickets iniciados y completados por día con una fecha de finalización prevista"+ },"breakdown": {"label": "Desglose","description": "Recuentos de tickets por estado, prioridad, tipo o asignado"@@ -152,6 +156,29 @@"created": "Creadas","closed": "Cerradas"},+ "burnup": {+ "empty": "No hay tickets en este periodo.",+ "scope": "Alcance",+ "started": "Iniciados",+ "completed": "Completados",+ "projection": "Proyección",+ "band": "Rango de previsión",+ "projected": "Previsto para el {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "Línea de previsión",+ "range": "Rango de previsión"+ },+ "noForecast": "Sin avances en {weeks, plural, one {la última semana} other {las últimas # semanas}}",+ "allDone": "Todo completado",+ "velocity": "{rate}/día",+ "growth": "+{rate}/día nuevos",+ "target": "Objetivo: {date}",+ "targetLabel": "Objetivo",+ "today": "Hoy",+ "wholeProject": "Todo el proyecto",+ "forecastWeeks": "Ritmo de {weeks, plural, one {la última semana} other {las últimas # semanas}}"+ },"agentRuns": {"empty": "Todavía no hay ejecuciones del agente.","filters": {diff --git a/apps/web/messages/fr/dashboards.json b/apps/web/messages/fr/dashboards.jsonindex f62a58f3..e2afa772 100644--- a/apps/web/messages/fr/dashboards.json+++ b/apps/web/messages/fr/dashboards.json@@ -49,6 +49,10 @@"label": "Débit","description": "Tickets créés et fermés par semaine"},+ "burnup": {+ "label": "Burnup",+ "description": "Périmètre, tâches commencées et terminées par jour, avec une date de fin projetée"+ },"breakdown": {"label": "Répartition","description": "Nombre de tickets par état, priorité, type ou responsable"@@ -152,6 +156,29 @@"created": "Créés","closed": "Fermés"},+ "burnup": {+ "empty": "Aucune tâche sur cette période.",+ "scope": "Périmètre",+ "started": "Commencées",+ "completed": "Terminées",+ "projection": "Projection",+ "band": "Fourchette de projection",+ "projected": "Fin projetée {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "Ligne de projection",+ "range": "Fourchette de projection"+ },+ "noForecast": "Aucun progrès {weeks, plural, one {la semaine dernière} other {ces # dernières semaines}}",+ "allDone": "Tout est terminé",+ "velocity": "{rate}/jour",+ "growth": "+{rate}/jour créées",+ "target": "Objectif {date}",+ "targetLabel": "Objectif",+ "today": "Aujourd'hui",+ "wholeProject": "Projet entier",+ "forecastWeeks": "Rythme sur {weeks, plural, one {# semaine} other {# semaines}}"+ },"agentRuns": {"empty": "Aucune exécution d'agent pour l'instant.","filters": {diff --git a/apps/web/messages/id/dashboards.json b/apps/web/messages/id/dashboards.jsonindex 1a29ff4d..234e5406 100644--- a/apps/web/messages/id/dashboards.json+++ b/apps/web/messages/id/dashboards.json@@ -49,6 +49,10 @@"label": "Throughput","description": "Issue yang dibuat dibandingkan dengan yang ditutup setiap minggu"},+ "burnup": {+ "label": "Burnup",+ "description": "Cakupan, issue yang dimulai dan diselesaikan per hari dengan perkiraan tanggal selesai"+ },"breakdown": {"label": "Rincian","description": "Jumlah issue berdasarkan status, prioritas, jenis, atau penerima tugas"@@ -152,6 +156,29 @@"created": "Dibuat","closed": "Ditutup"},+ "burnup": {+ "empty": "Tidak ada issue dalam periode ini.",+ "scope": "Cakupan",+ "started": "Dimulai",+ "completed": "Selesai",+ "projection": "Proyeksi",+ "band": "Rentang perkiraan",+ "projected": "Perkiraan {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "Garis perkiraan",+ "range": "Rentang perkiraan"+ },+ "noForecast": "Tidak ada kemajuan dalam {weeks, plural, other {# minggu terakhir}}",+ "allDone": "Semua selesai",+ "velocity": "{rate}/hari",+ "growth": "+{rate}/hari baru",+ "target": "Target {date}",+ "targetLabel": "Target",+ "today": "Hari ini",+ "wholeProject": "Seluruh proyek",+ "forecastWeeks": "Laju selama {weeks, plural, other {# minggu}}"+ },"agentRuns": {"empty": "Belum ada eksekusi agen.","filters": {diff --git a/apps/web/messages/pt-BR/dashboards.json b/apps/web/messages/pt-BR/dashboards.jsonindex 800a2185..61093581 100644--- a/apps/web/messages/pt-BR/dashboards.json+++ b/apps/web/messages/pt-BR/dashboards.json@@ -49,6 +49,10 @@"label": "Vazão","description": "Issues criadas vs. fechadas por semana"},+ "burnup": {+ "label": "Burnup",+ "description": "Escopo, issues iniciadas e concluídas por dia com uma data de conclusão prevista"+ },"breakdown": {"label": "Distribuição","description": "Contagens de issues por status, prioridade, tipo ou responsável"@@ -152,6 +156,29 @@"created": "Criadas","closed": "Fechadas"},+ "burnup": {+ "empty": "Nenhuma issue neste período.",+ "scope": "Escopo",+ "started": "Iniciadas",+ "completed": "Concluídas",+ "projection": "Projeção",+ "band": "Intervalo da previsão",+ "projected": "Previsto para {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "Linha de previsão",+ "range": "Intervalo de previsão"+ },+ "noForecast": "Sem progresso {weeks, plural, one {na última semana} other {nas últimas # semanas}}",+ "allDone": "Tudo concluído",+ "velocity": "{rate}/dia",+ "growth": "+{rate}/dia novas",+ "target": "Meta: {date}",+ "targetLabel": "Meta",+ "today": "Hoje",+ "wholeProject": "Projeto inteiro",+ "forecastWeeks": "Ritmo {weeks, plural, one {da última semana} other {das últimas # semanas}}"+ },"agentRuns": {"empty": "Nenhuma execução de agente ainda.","filters": {diff --git a/apps/web/messages/ru/dashboards.json b/apps/web/messages/ru/dashboards.jsonindex a3290c4e..bb920b77 100644--- a/apps/web/messages/ru/dashboards.json+++ b/apps/web/messages/ru/dashboards.json@@ -49,6 +49,10 @@"label": "Пропускная способность","description": "Созданные и закрытые задачи за неделю"},+ "burnup": {+ "label": "Burnup",+ "description": "Объём, начатые и завершённые задачи по дням с прогнозом даты завершения"+ },"breakdown": {"label": "Распределение","description": "Количество задач по статусу, приоритету, типу или исполнителю"@@ -152,6 +156,29 @@"created": "Создано","closed": "Закрыто"},+ "burnup": {+ "empty": "За этот период задач нет.",+ "scope": "Объём",+ "started": "Начато",+ "completed": "Завершено",+ "projection": "Прогноз",+ "band": "Диапазон прогноза",+ "projected": "Прогноз: {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "Линия прогноза",+ "range": "Диапазон прогноза"+ },+ "noForecast": "Нет прогресса за {weeks, plural, one {последнюю # неделю} few {последние # недели} many {последние # недель} other {последние # недели}}",+ "allDone": "Всё завершено",+ "velocity": "{rate}/день",+ "growth": "+{rate}/день новых",+ "target": "Цель: {date}",+ "targetLabel": "Цель",+ "today": "Сегодня",+ "wholeProject": "Весь проект",+ "forecastWeeks": "Скорость за {weeks, plural, one {# неделю} few {# недели} many {# недель} other {# недели}}"+ },"agentRuns": {"empty": "Запусков агентов пока нет.","filters": {diff --git a/apps/web/messages/uk/dashboards.json b/apps/web/messages/uk/dashboards.jsonindex 942550da..ea7f2960 100644--- a/apps/web/messages/uk/dashboards.json+++ b/apps/web/messages/uk/dashboards.json@@ -49,6 +49,10 @@"label": "Пропускна здатність","description": "Створені та закриті задачі за тиждень"},+ "burnup": {+ "label": "Burnup",+ "description": "Обсяг, розпочаті та завершені задачі по днях із прогнозом дати завершення"+ },"breakdown": {"label": "Розподіл","description": "Кількість задач за статусом, пріоритетом, типом чи виконавцем"@@ -152,6 +156,29 @@"created": "Створено","closed": "Закрито"},+ "burnup": {+ "empty": "За цей період задач немає.",+ "scope": "Обсяг",+ "started": "Розпочато",+ "completed": "Завершено",+ "projection": "Прогноз",+ "band": "Діапазон прогнозу",+ "projected": "Прогноз: {date}",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "Лінія прогнозу",+ "range": "Діапазон прогнозу"+ },+ "noForecast": "Немає прогресу за {weeks, plural, one {останній # тиждень} few {останні # тижні} many {останні # тижнів} other {останні # тижні}}",+ "allDone": "Усе завершено",+ "velocity": "{rate}/день",+ "growth": "+{rate}/день нових",+ "target": "Ціль: {date}",+ "targetLabel": "Ціль",+ "today": "Сьогодні",+ "wholeProject": "Увесь проєкт",+ "forecastWeeks": "Швидкість за {weeks, plural, one {# тиждень} few {# тижні} many {# тижнів} other {# тижні}}"+ },"agentRuns": {"empty": "Запусків агентів ще немає.","filters": {diff --git a/apps/web/messages/zh-CN/dashboards.json b/apps/web/messages/zh-CN/dashboards.jsonindex 8f981f76..23d373ea 100644--- a/apps/web/messages/zh-CN/dashboards.json+++ b/apps/web/messages/zh-CN/dashboards.json@@ -49,6 +49,10 @@"label": "吞吐量","description": "每周创建和关闭的工作项数量"},+ "burnup": {+ "label": "燃尽上升图",+ "description": "按天统计范围、已开始和已完成的任务,并预测完成日期"+ },"breakdown": {"label": "分类统计","description": "按状态、优先级、类型或负责人统计工作项"@@ -152,6 +156,29 @@"created": "已创建","closed": "已关闭"},+ "burnup": {+ "empty": "此期间没有任务。",+ "scope": "范围",+ "started": "已开始",+ "completed": "已完成",+ "projection": "预测",+ "band": "预测区间",+ "projected": "预计 {date} 完成",+ "range": "{from} – {to}",+ "forecastShape": {+ "line": "预测线",+ "range": "预测区间"+ },+ "noForecast": "最近 {weeks} 周没有进展",+ "allDone": "全部完成",+ "velocity": "{rate}/天",+ "growth": "新增 {rate}/天",+ "target": "目标 {date}",+ "targetLabel": "目标",+ "today": "今天",+ "wholeProject": "整个项目",+ "forecastWeeks": "按最近 {weeks} 周的速度"+ },"agentRuns": {"empty": "暂无代理运行记录。","filters": {diff --git a/apps/web/src/features/dashboards/components/WidgetBody.tsx b/apps/web/src/features/dashboards/components/WidgetBody.tsxindex 412bbc03..faf38ff8 100644--- a/apps/web/src/features/dashboards/components/WidgetBody.tsx+++ b/apps/web/src/features/dashboards/components/WidgetBody.tsx@@ -3,6 +3,7 @@ import type { WidgetInstance } from '@/utils/dashboardWidgets';import StatWidget from './widgets/StatWidget';import BreakdownWidget from './widgets/BreakdownWidget';import ThroughputWidget from './widgets/ThroughputWidget';+import BurnupWidget from './widgets/BurnupWidget';import PulseWidget from './widgets/PulseWidget';import RecentIssuesWidget from './widgets/RecentIssuesWidget';import ActivityFeedWidget from './widgets/ActivityFeedWidget';@@ -30,6 +31,8 @@ export default function WidgetBody({return <BreakdownWidget projectKey={projectKey} config={config} />;case 'throughput':return <ThroughputWidget projectKey={projectKey} config={config} />;+ case 'burnup':+ return <BurnupWidget projectKey={projectKey} config={config} />;case 'pulse':return <PulseWidget projectKey={projectKey} config={config} />;case 'recent_issues':diff --git a/apps/web/src/features/dashboards/components/WidgetSettings.tsx b/apps/web/src/features/dashboards/components/WidgetSettings.tsxindex 5f639937..72b9c73e 100644--- a/apps/web/src/features/dashboards/components/WidgetSettings.tsx+++ b/apps/web/src/features/dashboards/components/WidgetSettings.tsx@@ -2,6 +2,7 @@ import type { WidgetConfig, WidgetInstance, WidgetType } from '@/utils/dashboardimport StatWidgetSettings from './widgets/StatWidgetSettings';import BreakdownWidgetSettings from './widgets/BreakdownWidgetSettings';import ThroughputWidgetSettings from './widgets/ThroughputWidgetSettings';+import BurnupWidgetSettings from './widgets/BurnupWidgetSettings';import PulseWidgetSettings from './widgets/PulseWidgetSettings';import RecentIssuesWidgetSettings from './widgets/RecentIssuesWidgetSettings';import ActivityFeedWidgetSettings from './widgets/ActivityFeedWidgetSettings';@@ -34,6 +35,8 @@ export default function WidgetSettings({return <BreakdownWidgetSettings config={config} onConfigChange={onConfigChange} />;case 'throughput':return <ThroughputWidgetSettings config={config} onConfigChange={onConfigChange} />;+ case 'burnup':+ return <BurnupWidgetSettings config={config} onConfigChange={onConfigChange} />;case 'pulse':return <PulseWidgetSettings config={config} onConfigChange={onConfigChange} />;case 'recent_issues':diff --git a/apps/web/src/features/dashboards/components/widgets/BurnupChart.tsx b/apps/web/src/features/dashboards/components/widgets/BurnupChart.tsxnew file mode 100644index 00000000..b90b02dc--- /dev/null+++ b/apps/web/src/features/dashboards/components/widgets/BurnupChart.tsx@@ -0,0 +1,212 @@+import { Area, CartesianGrid, ComposedChart, Line, ReferenceLine, XAxis, YAxis } from 'recharts';+import { useTranslations } from 'next-intl';+import { formatDate, formatShortDate } from '@/utils/dates';+import {+ ChartContainer,+ ChartLegend,+ ChartLegendContent,+ ChartTooltip,+ ChartTooltipContent,+ type ChartConfig,+} from '@/components/ui/chart';+import type { BurnupPoint } from '../../utils/burnupSeries';++const TODAY_COLOR = '#94a3b8';+const TARGET_COLOR = '#ef4444';++// The legend in reading order (outer line to inner), not the alphabetical default.+const LEGEND_ORDER = ['scope', 'started', 'completed', 'projection', 'band'];+const legendOrder = (item: { dataKey?: unknown }) => LEGEND_ORDER.indexOf(String(item.dataKey));++// The series that continue past today. They also carry a value on today's point+// so that the lines join the history, and the tooltip hides them there.+const FUTURE_KEYS = ['projection', 'band', 'scopeProjection'];++// A tooltip value: a count, or the band's [slow, fast] pair as "168 – 256" (the+// default would print the array as "168,256", which reads as a decimal in many+// locales). An equal pair is one number.+function formatValue(value: unknown): string {+ if (Array.isArray(value)) {+ const [slow, fast] = value as [number, number];+ return slow === fast+ ? fast.toLocaleString()+ : `${slow.toLocaleString()} – ${fast.toLocaleString()}`;+ }+ return typeof value === 'number' ? value.toLocaleString() : String(value);+}++// The change since the previous day, as "(+3)", for a count that moved; the band is a pair.+function formatDelta(points: BurnupPoint[], row: BurnupPoint, key: string): string | null {+ const value = row[key as keyof BurnupPoint];+ const previous = points[points.indexOf(row) - 1]?.[key as keyof BurnupPoint];+ if (typeof value !== 'number' || typeof previous !== 'number') return null;+ const delta = value - previous;+ if (delta === 0) return null;+ return `(${delta > 0 ? '+' : ''}${delta.toLocaleString()})`;+}++// The burnup chart itself: scope and completed as areas, started as a line, the+// projection and the growing scope as dashed lines into the future and, in range+// mode, a band between the optimistic and the pessimistic date. A "today" marker separates the+// history from the projection whenever there is one, and the initiative's target+// date is marked when it falls on the axis.+export default function BurnupChart({+ points,+ config,+ today,+ target,+}: {+ points: BurnupPoint[];+ config: ChartConfig;+ today: string;+ target: string | null;+}) {+ const t = useTranslations('dashboards.burnup');+ const hasFuture = points.at(-1)?.date !== today;+ const showTarget = target != null && points.some((p) => p.date === target);+ const hasProjection = points.some((p) => p.projection != null);+ const hasBand = points.some((p) => p.band != null);+ // Recharts draws to absolute SVG coordinates and does not read the document+ // direction, so a mirrored chart would put its axes and series out of step with+ // each other. The labels and the tooltip are still translated.+ return (+ <ChartContainer dir="ltr" config={config} className="h-full min-h-[180px] w-full">+ <ComposedChart data={points}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="date"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ fontSize={11}+ minTickGap={40}+ tickFormatter={formatShortDate}+ />+ <YAxis width={30} tickLine={false} axisLine={false} fontSize={11} allowDecimals={false} />+ <ChartTooltip+ content={({ active, payload, label }) => (+ <ChartTooltipContent+ active={active}+ label={label}+ payload={payload?.filter(+ (item) =>+ item.payload?.date !== today || !FUTURE_KEYS.includes(String(item.dataKey)),+ )}+ labelFormatter={(value) => formatDate(String(value))}+ formatter={(value, name, item) => (+ <>+ <div+ className="h-2.5 w-2.5 shrink-0 rounded-[2px]"+ style={{ backgroundColor: item.color }}+ />+ <div className="flex flex-1 items-center justify-between gap-3 leading-none">+ <span className="text-muted-foreground">+ {config[String(name)]?.label ?? String(name)}+ </span>+ <span className="font-mono font-medium text-foreground tabular-nums">+ {formatValue(value)}+ {item.payload && (+ <span className="ms-1 font-normal text-muted-foreground">+ {formatDelta(points, item.payload, String(name))}+ </span>+ )}+ </span>+ </div>+ </>+ )}+ />+ )}+ />+ <ChartLegend+ content={<ChartLegendContent className="flex-wrap gap-x-4 gap-y-1" />}+ itemSorter={legendOrder}+ />+ <Area+ type="monotone"+ dataKey="scope"+ stroke="var(--color-scope)"+ fill="var(--color-scope)"+ fillOpacity={0.12}+ dot={false}+ isAnimationActive={false}+ />+ <Line+ type="monotone"+ dataKey="started"+ stroke="var(--color-started)"+ strokeWidth={1.5}+ dot={false}+ isAnimationActive={false}+ />+ <Area+ type="monotone"+ dataKey="completed"+ stroke="var(--color-completed)"+ strokeWidth={1.5}+ fill="var(--color-completed)"+ fillOpacity={0.2}+ dot={false}+ isAnimationActive={false}+ />+ <Area+ dataKey="band"+ stroke="var(--color-band)"+ strokeWidth={1}+ strokeDasharray="2 3"+ fill="var(--color-band)"+ fillOpacity={0.12}+ dot={false}+ connectNulls+ legendType={hasBand ? 'line' : 'none'}+ isAnimationActive={false}+ />+ <Line+ dataKey="scopeProjection"+ stroke="var(--color-scope)"+ strokeWidth={1}+ strokeDasharray="4 4"+ dot={false}+ connectNulls+ legendType="none"+ isAnimationActive={false}+ />+ <Line+ dataKey="projection"+ stroke="var(--color-projection)"+ strokeWidth={1.5}+ strokeDasharray="4 4"+ dot={false}+ connectNulls+ legendType={hasProjection ? 'line' : 'none'}+ isAnimationActive={false}+ />+ {hasFuture && (+ <ReferenceLine+ x={today}+ stroke={TODAY_COLOR}+ strokeDasharray="2 2"+ label={{+ value: t('today'),+ position: 'insideTopRight',+ fontSize: 10,+ fill: TODAY_COLOR,+ }}+ />+ )}+ {showTarget && (+ <ReferenceLine+ x={target}+ stroke={TARGET_COLOR}+ strokeDasharray="2 2"+ label={{+ value: t('targetLabel'),+ position: 'insideTopLeft',+ fontSize: 10,+ fill: TARGET_COLOR,+ }}+ />+ )}+ </ComposedChart>+ </ChartContainer>+ );+}diff --git a/apps/web/src/features/dashboards/components/widgets/BurnupWidget.tsx b/apps/web/src/features/dashboards/components/widgets/BurnupWidget.tsxnew file mode 100644index 00000000..2899319c--- /dev/null+++ b/apps/web/src/features/dashboards/components/widgets/BurnupWidget.tsx@@ -0,0 +1,99 @@+import { useTranslations } from 'next-intl';+import type { BurnupForecast } from '@/lib/api/endpoints/analytics';+import type { WidgetConfig } from '@/utils/dashboardWidgets';+import { formatDate } from '@/utils/dates';+import { Skeleton } from '@/components/ui/skeleton';+import type { ChartConfig } from '@/components/ui/chart';+import { useBurnupQuery } from '../../services/analytics.service';+import { buildBurnupPoints } from '../../utils/burnupSeries';+import BurnupChart from './BurnupChart';++const SERIES_COLOR = {+ scope: '#94a3b8',+ started: '#f59e0b',+ completed: '#22c55e',+ projection: '#16a34a',+ band: '#38bdf8',+};++// Scope, started and completed issues at the end of each day, with a completion+// date projected from the recent closing rate — the project graph of Linear. The+// window, the initiative, the forecast window and the forecast shape (a line or a+// range) are configured settings (see BurnupWidgetSettings), not live controls.+export default function BurnupWidget({+ projectKey,+ config,+}: {+ projectKey: string;+ config: WidgetConfig;+}) {+ const t = useTranslations('dashboards.burnup');+ const tDashboards = useTranslations('dashboards');+ const days = config.days ?? 90;+ const forecastWeeks = config.forecastWeeks ?? 4;+ const initiativeId = config.initiativeId ?? null;+ const range = config.forecast !== 'line';+ const { data, isLoading } = useBurnupQuery(projectKey, { days, initiativeId, forecastWeeks });++ const chartConfig: ChartConfig = {+ scope: { label: t('scope'), color: SERIES_COLOR.scope },+ started: { label: t('started'), color: SERIES_COLOR.started },+ completed: { label: t('completed'), color: SERIES_COLOR.completed },+ projection: { label: t('projection'), color: SERIES_COLOR.projection },+ band: { label: t('band'), color: SERIES_COLOR.band },+ scopeProjection: { label: t('scope'), color: SERIES_COLOR.scope },+ };++ // The caption parts: the projected date (with the range under its own label in+ // range mode), the closing pace and the scope growth, then the target date.+ function caption(forecast: BurnupForecast, targetDate: string | null): string[] {+ const parts: string[] = [];+ if (forecast.remaining === 0) parts.push(t('allDone'));+ else if (forecast.projectedDate == null) parts.push(t('noForecast', { weeks: forecastWeeks }));+ else {+ parts.push(t('projected', { date: formatDate(forecast.projectedDate) }));+ if (range && forecast.optimisticDate && forecast.pessimisticDate) {+ const from = formatDate(forecast.optimisticDate);+ const to = formatDate(forecast.pessimisticDate);+ parts.push(`${t('band')}: ${t('range', { from, to })}`);+ }+ parts.push(t('velocity', { rate: forecast.velocityPerDay }));+ if (forecast.scopeGrowthPerDay > 0)+ parts.push(t('growth', { rate: forecast.scopeGrowthPerDay }));+ }+ if (targetDate) parts.push(t('target', { date: formatDate(targetDate) }));+ return parts;+ }++ function body() {+ if (isLoading) return <Skeleton className="h-[180px] w-full" />;+ const today = data?.days.at(-1);+ if (!data || !today || data.days.every((d) => d.scope === 0)) {+ return <p className="py-10 text-center text-sm text-muted-foreground">{t('empty')}</p>;+ }+ return (+ <>+ <div className="min-h-0 flex-1">+ <BurnupChart+ points={buildBurnupPoints(data, range)}+ config={chartConfig}+ today={today.date}+ target={data.targetDate}+ />+ </div>+ <p className="hidden flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground [@container(min-height:220px)]:flex">+ {caption(data.forecast, data.targetDate).map((part) => (+ <span key={part}>{part}</span>+ ))}+ </p>+ </>+ );+ }++ return (+ <div className="[container-type:size] flex h-full flex-col gap-3">+ <p className="text-xs text-muted-foreground">{tDashboards('lastDays', { days })}</p>+ {body()}+ </div>+ );+}diff --git a/apps/web/src/features/dashboards/components/widgets/BurnupWidgetSettings.tsx b/apps/web/src/features/dashboards/components/widgets/BurnupWidgetSettings.tsxnew file mode 100644index 00000000..18d30b0b--- /dev/null+++ b/apps/web/src/features/dashboards/components/widgets/BurnupWidgetSettings.tsx@@ -0,0 +1,101 @@+import { useTranslations } from 'next-intl';+import { useShell } from '@/context/shellContext';+import type { WidgetConfig } from '@/utils/dashboardWidgets';+import { useInitiativeOptionsQuery } from '@/services/initiatives.service';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';++const DAY_OPTIONS = [30, 60, 90, 180, 365];+const FORECAST_OPTIONS = [2, 4, 8];+const FORECAST_SHAPES = ['line', 'range'] as const;+const WHOLE_PROJECT = 'all';++// The window in days, the initiative (or the whole project), how many recent+// weeks the closing rate is taken from, and whether the forecast is drawn as one+// line or as a range of about ±40% around it.+export default function BurnupWidgetSettings({+ config,+ onConfigChange,+}: {+ config: WidgetConfig;+ onConfigChange: (config: WidgetConfig) => void;+}) {+ const t = useTranslations('dashboards');+ const { project } = useShell();+ const days = config.days ?? 90;+ const forecastWeeks = config.forecastWeeks ?? 4;+ const forecast = config.forecast ?? 'range';+ const initiativeId = config.initiativeId ?? null;+ const { data: initiatives } = useInitiativeOptionsQuery(project?.project.key ?? null, {+ include: initiativeId ?? undefined,+ });+ return (+ <div className="flex flex-wrap items-center gap-2">+ <Select value={String(days)} onValueChange={(v) => onConfigChange({ days: Number(v) })}>+ <SelectTrigger size="sm" className="w-[130px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {DAY_OPTIONS.map((d) => (+ <SelectItem key={d} value={String(d)}>+ {t('lastDays', { days: d })}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ value={initiativeId == null ? WHOLE_PROJECT : String(initiativeId)}+ onValueChange={(v) =>+ onConfigChange({ initiativeId: v === WHOLE_PROJECT ? null : Number(v) })+ }+ >+ <SelectTrigger size="sm" className="w-[180px]">+ <SelectValue placeholder={t('burnup.wholeProject')} />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={WHOLE_PROJECT}>{t('burnup.wholeProject')}</SelectItem>+ {(initiatives ?? []).map((i) => (+ <SelectItem key={i.id} value={String(i.id)}>+ {i.title}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ value={String(forecastWeeks)}+ onValueChange={(v) => onConfigChange({ forecastWeeks: Number(v) })}+ >+ <SelectTrigger size="sm" className="w-[170px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {FORECAST_OPTIONS.map((w) => (+ <SelectItem key={w} value={String(w)}>+ {t('burnup.forecastWeeks', { weeks: w })}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ value={forecast}+ onValueChange={(v) => onConfigChange({ forecast: v as WidgetConfig['forecast'] })}+ >+ <SelectTrigger size="sm" className="w-[150px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {FORECAST_SHAPES.map((shape) => (+ <SelectItem key={shape} value={shape}>+ {t(`burnup.forecastShape.${shape}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}diff --git a/apps/web/src/features/dashboards/services/analytics.service.ts b/apps/web/src/features/dashboards/services/analytics.service.tsindex 3fcb3f05..5bec5471 100644--- a/apps/web/src/features/dashboards/services/analytics.service.ts+++ b/apps/web/src/features/dashboards/services/analytics.service.ts@@ -5,8 +5,10 @@import { useQuery } from '@tanstack/react-query';import {+ type BurnupParams,type PulseUnit,getBreakdown,+ getBurnup,getPulse,getThroughput,getAgentRuns,@@ -46,6 +48,13 @@ export function useThroughputQuery(projectKey: string, weeks: number) {});}+export function useBurnupQuery(projectKey: string, params: BurnupParams) {+ return useQuery({+ queryKey: qk.analytics(projectKey, 'burnup', params),+ queryFn: () => getBurnup(projectKey, params),+ });+}+export function useAgentRunsQuery(projectKey: string,params: { status: string | null; limit: number },diff --git a/apps/web/src/features/dashboards/utils/burnupSeries.test.ts b/apps/web/src/features/dashboards/utils/burnupSeries.test.tsnew file mode 100644index 00000000..fb0af301--- /dev/null+++ b/apps/web/src/features/dashboards/utils/burnupSeries.test.ts@@ -0,0 +1,156 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import type { Burnup, BurnupForecast } from '@/lib/api/endpoints/analytics';+import { buildBurnupPoints, MAX_TAIL_DAYS } from './burnupSeries';++// buildBurnupPoints appends the projection tail to the history: one point per+// future day, the projection running straight from today's completed count to the+// scope on the projected date, and in range mode a band between the optimistic+// and the pessimistic date.++function forecast(overrides: Partial<BurnupForecast> = {}): BurnupForecast {+ return {+ windowDays: 1,+ velocityPerDay: 2,+ scopeGrowthPerDay: 0,+ remaining: 6,+ projectedScope: 10,+ projectedDate: '2026-03-05',+ optimisticDate: '2026-03-04',+ pessimisticDate: '2026-03-07',+ ...overrides,+ };+}++function burnup(overrides: Partial<Burnup> = {}): Burnup {+ return {+ days: [+ { date: '2026-03-01', scope: 10, started: 4, completed: 2 },+ { date: '2026-03-02', scope: 10, started: 5, completed: 4 },+ ],+ forecast: forecast(),+ targetDate: null,+ ...overrides,+ };+}++describe('buildBurnupPoints', () => {+ it('returns the history untouched when there is no forecast and no target', () => {+ const data = burnup({+ forecast: forecast({+ velocityPerDay: 0,+ projectedDate: null,+ optimisticDate: null,+ pessimisticDate: null,+ }),+ });+ assert.deepEqual(buildBurnupPoints(data), data.days);+ assert.deepEqual(buildBurnupPoints(data, true), data.days);+ });++ it('runs the projection from today to the scope on the projected date', () => {+ const points = buildBurnupPoints(burnup());+ assert.equal(points.length, 5);+ assert.deepEqual(points[1], {+ date: '2026-03-02',+ scope: 10,+ started: 5,+ completed: 4,+ projection: 4,+ });+ assert.deepEqual(points.slice(2), [+ { date: '2026-03-03', projection: 6 },+ { date: '2026-03-04', projection: 8 },+ { date: '2026-03-05', projection: 10 },+ ]);+ });++ it('drops the days before the first issue existed', () => {+ const empty = { scope: 0, started: 0, completed: 0 };+ const data = burnup();+ data.days = [{ date: '2026-02-27', ...empty }, { date: '2026-02-28', ...empty }, ...data.days];+ const points = buildBurnupPoints(data);+ assert.equal(points[0]?.date, '2026-03-01');+ assert.equal(points.at(-1)?.date, '2026-03-05');+ });++ it('draws the band to the scope on both dates and extends the axis to the slow one', () => {+ const points = buildBurnupPoints(burnup(), true);+ assert.equal(points.length, 7);+ assert.deepEqual(points[1]?.band, [4, 4]);+ assert.deepEqual(points[2], { date: '2026-03-03', projection: 6, band: [5, 7] });+ assert.deepEqual(points[3], { date: '2026-03-04', projection: 8, band: [6, 10] });+ assert.deepEqual(points[4], { date: '2026-03-05', projection: 10, band: [8, 10] });+ assert.deepEqual(points[5], { date: '2026-03-06', band: [9, 10] });+ assert.deepEqual(points[6], { date: '2026-03-07', band: [10, 10] });+ });++ it('extrapolates a growing scope up to the projected scope', () => {+ // Scope +2/day up to 14; the projection climbs to 14 on 5 March, the fast+ // edge is done on 4 March and follows the scope from there.+ const data = burnup({ forecast: forecast({ scopeGrowthPerDay: 2, projectedScope: 14 }) });+ const points = buildBurnupPoints(data, true);+ assert.deepEqual(points[1], {+ date: '2026-03-02',+ scope: 10,+ started: 5,+ completed: 4,+ projection: 4,+ band: [4, 4],+ scopeProjection: 10,+ });+ assert.deepEqual(points[2], {+ date: '2026-03-03',+ projection: 7,+ band: [6, 9],+ scopeProjection: 12,+ });+ assert.deepEqual(points[4], {+ date: '2026-03-05',+ projection: 14,+ band: [10, 14],+ scopeProjection: 14,+ });+ assert.deepEqual(points[6], { date: '2026-03-07', band: [14, 14], scopeProjection: 14 });+ });++ it('rounds the projected counts to whole issues', () => {+ const data = burnup({ forecast: forecast({ remaining: 6, projectedDate: '2026-03-09' }) });+ for (const p of buildBurnupPoints(data, true)) {+ for (const n of [p.projection, ...(p.band ?? [])]) {+ if (n !== undefined) assert.ok(Number.isInteger(n), `${p.date}: ${n}`);+ }+ }+ });++ it('ignores the range when not asked for it', () => {+ const points = buildBurnupPoints(burnup());+ assert.equal(points.at(-1)?.date, '2026-03-05');+ assert.equal(points[2]?.band, undefined);+ });++ it('extends the axis to a later target date without projecting past the projected date', () => {+ const points = buildBurnupPoints(burnup({ targetDate: '2026-03-07' }));+ assert.deepEqual(points.at(-1), { date: '2026-03-07' });+ assert.deepEqual(points.at(-2), { date: '2026-03-06' });+ assert.deepEqual(points[4], { date: '2026-03-05', projection: 10 });+ });++ it('ignores a target date in the past', () => {+ const points = buildBurnupPoints(burnup({ targetDate: '2026-02-01' }));+ assert.equal(points.at(-1)?.date, '2026-03-05');+ });++ it('cuts the tail at the cap', () => {+ const data = burnup({+ forecast: forecast({ velocityPerDay: 0.01, projectedDate: '2027-12-31' }),+ });+ const points = buildBurnupPoints(data);+ assert.equal(points.length, 2 + MAX_TAIL_DAYS);+ assert.ok((points.at(-1)?.projection ?? 0) < 10);+ });++ it('returns an empty list for an empty series', () => {+ assert.deepEqual(buildBurnupPoints(burnup({ days: [] })), []);+ });+});diff --git a/apps/web/src/features/dashboards/utils/burnupSeries.ts b/apps/web/src/features/dashboards/utils/burnupSeries.tsnew file mode 100644index 00000000..756c40c2--- /dev/null+++ b/apps/web/src/features/dashboards/utils/burnupSeries.ts@@ -0,0 +1,71 @@+import type { Burnup } from '@/lib/api/endpoints/analytics';+import { addDays, daysBetween, parseDate, toDateStr } from '@/utils/dates';++// One point of the burnup chart: the three history series on a past day, the+// projection (and, in range mode, the band) on a future one, and both on the last+// real day, where they meet. `band` is [slow, fast]: the completed count on that+// day at the pessimistic and at the optimistic pace. `scopeProjection` is the+// scope extrapolated at its growth rate up to the projected scope, present only+// when the scope is growing.+export interface BurnupPoint {+ date: string;+ scope?: number;+ started?: number;+ completed?: number;+ projection?: number;+ band?: [number, number];+ scopeProjection?: number;+}++// The future part of the axis is cut here so a slow project cannot squash its+// history into a sliver. The caption still names the full projected date.+export const MAX_TAIL_DAYS = 180;++// The chart points: the history from the first day anything existed (days before+// the first issue are dropped, so a young project does not start with a run of+// empty weeks), then one point per future day up to the projected date (the+// pessimistic one in range mode) or the initiative's target date, whichever is+// later. The projection runs straight from today's completed count to the+// projected scope on the projected date and stops there; each edge of the band+// does the same on its own date. Counts are whole issues, as in the history.+export function buildBurnupPoints(data: Burnup, range = false): BurnupPoint[] {+ const firstReal = data.days.findIndex((d) => d.scope > 0 || d.started > 0 || d.completed > 0);+ const points: BurnupPoint[] = data.days.slice(Math.max(0, firstReal)).map((d) => ({ ...d }));+ const last = data.days.at(-1);+ const lastDate = last ? parseDate(last.date) : null;+ if (!last || !lastDate) return points;++ const { forecast } = data;+ const toProjected = daysAfter(lastDate, forecast.projectedDate);+ const toFast = range ? daysAfter(lastDate, forecast.optimisticDate) : 0;+ const toSlow = range ? daysAfter(lastDate, forecast.pessimisticDate) : 0;+ const tail = Math.min(+ Math.max(toProjected, toSlow, daysAfter(lastDate, data.targetDate)),+ MAX_TAIL_DAYS,+ );+ const scopeAt = (i: number) =>+ Math.min(forecast.projectedScope, Math.round(last.scope + forecast.scopeGrowthPerDay * i));+ const towards = (i: number, span: number) =>+ i >= span+ ? scopeAt(i)+ : Math.round(last.completed + ((scopeAt(span) - last.completed) * i) / span);+ const toScope = forecast.scopeGrowthPerDay > 0 ? Math.max(toProjected, toSlow) : 0;++ if (toProjected > 0) points[points.length - 1]!.projection = last.completed;+ if (toSlow > 0) points[points.length - 1]!.band = [last.completed, last.completed];+ if (toScope > 0) points[points.length - 1]!.scopeProjection = last.scope;+ for (let i = 1; i <= tail; i++) {+ const point: BurnupPoint = { date: toDateStr(addDays(lastDate, i)) };+ if (toProjected > 0 && i <= toProjected) point.projection = towards(i, toProjected);+ if (toSlow > 0 && i <= toSlow) point.band = [towards(i, toSlow), towards(i, toFast)];+ if (toScope > 0 && i <= toScope) point.scopeProjection = scopeAt(i);+ points.push(point);+ }+ return points;+}++// Whole days from `from` to a 'YYYY-MM-DD' date; 0 for null, unparseable, or past.+function daysAfter(from: Date, value: string | null): number {+ const date = parseDate(value);+ return date ? Math.max(0, daysBetween(from, date)) : 0;+}diff --git a/apps/web/src/features/dashboards/utils/widgetCatalog.tsx b/apps/web/src/features/dashboards/utils/widgetCatalog.tsxindex a4cc12b4..6e26b3a7 100644--- a/apps/web/src/features/dashboards/utils/widgetCatalog.tsx+++ b/apps/web/src/features/dashboards/utils/widgetCatalog.tsx@@ -6,6 +6,7 @@ import {Hash,ListChecks,PieChart,+ TrendingUp,Users,Webhook,type LucideIcon,@@ -22,6 +23,7 @@ export const WIDGET_ICON: Record<WidgetType, LucideIcon> = {activity_feed: Activity,pulse: CalendarDays,throughput: BarChart3,+ burnup: TrendingUp,breakdown: PieChart,agent_runs: Bot,agent_health: Activity,@@ -34,7 +36,7 @@ export const WIDGET_ICON: Record<WidgetType, LucideIcon> = {export const WIDGET_GROUPS: { key: 'issues' | 'agents'; types: WidgetType[] }[] = [{key: 'issues',- types: ['stat', 'breakdown', 'throughput', 'pulse', 'recent_issues', 'activity_feed'],+ types: ['stat', 'breakdown', 'throughput', 'burnup', 'pulse', 'recent_issues', 'activity_feed'],},{key: 'agents',diff --git a/apps/web/src/lib/api/endpoints/analytics.ts b/apps/web/src/lib/api/endpoints/analytics.tsindex ee9cf9a2..9904ea16 100644--- a/apps/web/src/lib/api/endpoints/analytics.ts+++ b/apps/web/src/lib/api/endpoints/analytics.ts@@ -34,6 +34,43 @@ export interface ThroughputWeek {closed: number;}+// The state of the project's issues at the end of one day (burnup widget).+export interface BurnupDay {+ date: string;+ scope: number;+ started: number;+ completed: number;+}++// A completion date projected from the rates over the last windowDays days: the+// remaining issues plus the ones expected to appear, at the scope growth rate,+// while they are closed at the closing rate; null when nothing closed in the+// window or nothing is left. projectedScope is the scope the projection ends at.+export interface BurnupForecast {+ windowDays: number;+ velocityPerDay: number;+ scopeGrowthPerDay: number;+ remaining: number;+ projectedScope: number;+ projectedDate: string | null;+ // The projected date with the days to go shortened and lengthened by about+ // 40%; null together with projectedDate.+ optimisticDate: string | null;+ pessimisticDate: string | null;+}++export interface Burnup {+ days: BurnupDay[];+ forecast: BurnupForecast;+ targetDate: string | null;+}++export interface BurnupParams {+ days: number;+ initiativeId: number | null;+ forecastWeeks: number;+}+// One agent run in the project-wide feed (agent runs widget).export interface AgentRunFeedItem {id: number;@@ -93,6 +130,15 @@ export const getPulse = (export const getThroughput = (projectKey: string, weeks = 12) =>request<ThroughputWeek[]>(`/projects/${projectKey}/analytics/throughput?weeks=${weeks}`);+export const getBurnup = (projectKey: string, params: BurnupParams) => {+ const q = new URLSearchParams({+ days: String(params.days),+ forecastWeeks: String(params.forecastWeeks),+ });+ if (params.initiativeId != null) q.set('initiativeId', String(params.initiativeId));+ return request<Burnup>(`/projects/${projectKey}/analytics/burnup?${q}`);+};+export const listActivity = (projectKey: string,params: {diff --git a/apps/web/src/utils/dashboardWidgets.ts b/apps/web/src/utils/dashboardWidgets.tsindex b3dfc1fd..04810a54 100644--- a/apps/web/src/utils/dashboardWidgets.ts+++ b/apps/web/src/utils/dashboardWidgets.ts@@ -13,6 +13,7 @@ export type WidgetType =| 'activity_feed'| 'pulse'| 'throughput'+ | 'burnup'| 'breakdown'| 'agent_runs'| 'agent_health'@@ -59,8 +60,14 @@ export interface WidgetConfig {by?: BreakdownBy;// agent_runs — the run status filter (null = all)runStatus?: 'pending' | 'success' | 'failed' | null;- // agent_health and webhook_health — the window in days+ // agent_health, webhook_health and burnup — the window in daysdays?: number;+ // burnup — one initiative, or null for the whole project+ initiativeId?: number | null;+ // burnup — how many recent weeks the closing rate is taken from+ forecastWeeks?: number;+ // burnup — a single projection line, or a range of about ±40% around it+ forecast?: 'line' | 'range';}export interface WidgetInstance {@@ -89,6 +96,12 @@ export const WIDGET_DEFAULTS: Record<activity_feed: { w: 6, h: 7, minH: 3, config: { limit: 20 } },pulse: { w: 12, h: 5, minH: 5, config: { granularity: 'day' } },throughput: { w: 6, h: 6, minH: 5, config: { weeks: 12 } },+ burnup: {+ w: 6,+ h: 6,+ minH: 5,+ config: { days: 90, initiativeId: null, forecastWeeks: 4, forecast: 'line' },+ },breakdown: { w: 6, h: 6, minH: 5, config: { by: 'status' } },agent_runs: { w: 6, h: 7, minH: 3, config: { limit: 20 } },agent_health: { w: 3, h: 3, minH: 3, config: { days: 30 } },