PAP-60: IA Phase 4 — Projects list task count + budget data wiring

Surface per-project task count and budget on the projects list view.

- shared: add ProjectBudgetSummary + optional taskCount/budget on Project
  (list-only payload fields).
- server: projectService.list attaches taskCount + budget via two aggregate
  queries (count(*) grouped by project, active billed_cents project budget
  policies) — no N+1. Extracted buildProjectListMetricMaps as a pure helper
  with unit coverage.
- ui: render task count and budget (when set) in each Projects row; add
  formatProjectBudget (/mo suffix for monthly, bare amount for lifetime).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
scotttongandClaude Opus 4.8 committed 2026-06-05 15:13:29 -07:00
1 parent 59f2c8fc32
commit bf58599848
8 files changed
+202 -6

No files matched your search

+1
View File
@@ -398,6 +398,7 @@ export type {
AdapterEnvironmentTestResult,
AssetImage,
Project,
ProjectBudgetSummary,
ProjectCodebase,
ProjectCodebaseOrigin,
ProjectGoalRef,
+1 -1
View File
@@ -159,7 +159,7 @@ export type {
DocumentTextRange,
UpdateDocumentAnnotationThreadRequest,
} from "./document-annotation.js";
export type { Project, ProjectCodebase, ProjectCodebaseOrigin, ProjectGoalRef, ProjectManagedByPlugin, ProjectWorkspace } from "./project.js";
export type { Project, ProjectBudgetSummary, ProjectCodebase, ProjectCodebaseOrigin, ProjectGoalRef, ProjectManagedByPlugin, ProjectWorkspace } from "./project.js";
export type {
CompanySearchHighlight,
CompanySearchIssueSummary,
+22 -1
View File
@@ -1,4 +1,4 @@
import type { PauseReason, ProjectStatus } from "../constants.js";
import type { BudgetWindowKind, PauseReason, ProjectStatus } from "../constants.js";
import type {
ProjectExecutionWorkspacePolicy,
ProjectWorkspaceRuntimeConfig,
@@ -14,6 +14,17 @@ export interface ProjectGoalRef {
title: string;
}
/**
* Lightweight per-project budget summary surfaced on the projects list payload
* (IA Phase 4 — PAP-60). Reflects the active `billed_cents` budget policy scoped
* to the project, when one is set.
*/
export interface ProjectBudgetSummary {
/** Budget limit in cents. */
amountCents: number;
windowKind: BudgetWindowKind;
}
export interface ProjectWorkspace {
id: string;
companyId: string;
@@ -86,6 +97,16 @@ export interface Project {
workspaces: ProjectWorkspace[];
primaryWorkspace: ProjectWorkspace | null;
managedByPlugin?: ProjectManagedByPlugin | null;
/**
* Number of tasks (issues) in the project. Populated by the projects list
* endpoint (IA Phase 4 — PAP-60); omitted on single-project payloads.
*/
taskCount?: number;
/**
* Active budget for the project, when set. Populated by the projects list
* endpoint (IA Phase 4 — PAP-60); omitted on single-project payloads.
*/
budget?: ProjectBudgetSummary | null;
archivedAt: Date | null;
createdAt: Date;
updatedAt: Date;
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { buildProjectListMetricMaps } from "../services/projects.ts";
describe("buildProjectListMetricMaps", () => {
it("maps task counts by project, coercing string counts to numbers", () => {
const { taskCountByProjectId } = buildProjectListMetricMaps(
[
{ projectId: "p1", count: 24 },
{ projectId: "p2", count: 11 as unknown as number },
],
[],
);
expect(taskCountByProjectId.get("p1")).toBe(24);
expect(taskCountByProjectId.get("p2")).toBe(11);
});
it("ignores task-count rows with a null project id", () => {
const { taskCountByProjectId } = buildProjectListMetricMaps(
[{ projectId: null, count: 5 }],
[],
);
expect(taskCountByProjectId.size).toBe(0);
});
it("maps positive budgets with their window kind", () => {
const { budgetByProjectId } = buildProjectListMetricMaps(
[],
[
{ scopeId: "p1", amount: 120_000, windowKind: "calendar_month_utc" },
{ scopeId: "p2", amount: 50_000, windowKind: "lifetime" },
],
);
expect(budgetByProjectId.get("p1")).toEqual({ amountCents: 120_000, windowKind: "calendar_month_utc" });
expect(budgetByProjectId.get("p2")).toEqual({ amountCents: 50_000, windowKind: "lifetime" });
});
it("omits zero/negative budgets so they do not surface as 'set'", () => {
const { budgetByProjectId } = buildProjectListMetricMaps(
[],
[
{ scopeId: "p1", amount: 0, windowKind: "lifetime" },
{ scopeId: "p2", amount: -10, windowKind: "lifetime" },
],
);
expect(budgetByProjectId.size).toBe(0);
});
});
+89 -2
View File
@@ -1,9 +1,11 @@
import { and, asc, desc, eq, inArray } from "drizzle-orm";
import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
projects,
projectGoals,
goals,
issues,
budgetPolicies,
pluginManagedResources,
plugins,
projectWorkspaces,
@@ -15,6 +17,8 @@ import {
hasNonAsciiContent,
isUuidLike,
normalizeProjectUrlKey,
type BudgetWindowKind,
type ProjectBudgetSummary,
type ProjectCodebase,
type ProjectExecutionWorkspacePolicy,
type ProjectGoalRef,
@@ -62,6 +66,8 @@ interface ProjectWithGoals extends Omit<ProjectRow, "executionWorkspacePolicy">
workspaces: ProjectWorkspace[];
primaryWorkspace: ProjectWorkspace | null;
managedByPlugin: ProjectManagedByPlugin | null;
taskCount?: number;
budget?: ProjectBudgetSummary | null;
}
interface ProjectShortnameRow {
@@ -315,6 +321,86 @@ async function attachWorkspaces(db: Db, rows: ProjectWithGoals[]): Promise<Proje
});
}
type TaskCountRow = { projectId: string | null; count: number };
type ProjectBudgetRow = { scopeId: string; amount: number; windowKind: string };
/**
* Build the per-project task-count and budget lookups from the aggregate query
* rows. Pure (no DB) so the merge logic can be unit-tested in isolation.
* Only active policies with a positive amount surface as a budget.
*/
export function buildProjectListMetricMaps(taskCountRows: TaskCountRow[], budgetRows: ProjectBudgetRow[]) {
const taskCountByProjectId = new Map<string, number>();
for (const row of taskCountRows) {
if (row.projectId) taskCountByProjectId.set(row.projectId, Number(row.count) || 0);
}
const budgetByProjectId = new Map<string, ProjectBudgetSummary>();
for (const row of budgetRows) {
if (row.amount > 0) {
budgetByProjectId.set(row.scopeId, {
amountCents: row.amount,
windowKind: row.windowKind as BudgetWindowKind,
});
}
}
return { taskCountByProjectId, budgetByProjectId };
}
/**
* Attach lightweight list-only metrics (task count + budget) to a set of
* projects using two aggregate queries (no N+1). Used by the projects list
* view (IA Phase 4 — PAP-60).
*/
async function attachListMetrics(
db: Db,
companyId: string,
rows: ProjectWithGoals[],
): Promise<ProjectWithGoals[]> {
if (rows.length === 0) return rows;
const projectIds = rows.map((r) => r.id);
const [taskCountRows, budgetRows] = await Promise.all([
db
.select({
projectId: issues.projectId,
count: sql<number>`count(*)::int`,
})
.from(issues)
.where(and(eq(issues.companyId, companyId), inArray(issues.projectId, projectIds)))
.groupBy(issues.projectId),
db
.select({
scopeId: budgetPolicies.scopeId,
amount: budgetPolicies.amount,
windowKind: budgetPolicies.windowKind,
})
.from(budgetPolicies)
.where(
and(
eq(budgetPolicies.companyId, companyId),
eq(budgetPolicies.scopeType, "project"),
eq(budgetPolicies.metric, "billed_cents"),
eq(budgetPolicies.isActive, true),
inArray(budgetPolicies.scopeId, projectIds),
),
),
]);
const { taskCountByProjectId, budgetByProjectId } = buildProjectListMetricMaps(
taskCountRows,
budgetRows,
);
return rows.map((row) => ({
...row,
taskCount: taskCountByProjectId.get(row.id) ?? 0,
budget: budgetByProjectId.get(row.id) ?? null,
}));
}
/** Sync the project_goals join table for a single project. */
async function syncGoalLinks(db: Db, projectId: string, companyId: string, goalIds: string[]) {
// Delete existing links
@@ -512,7 +598,8 @@ export function projectService(db: Db) {
list: async (companyId: string): Promise<ProjectWithGoals[]> => {
const rows = await db.select().from(projects).where(eq(projects.companyId, companyId));
const withGoals = await attachGoals(db, rows);
return attachWorkspaces(db, withGoals);
const withWorkspaces = await attachWorkspaces(db, withGoals);
return attachListMetrics(db, companyId, withWorkspaces);
},
listByIds: async (companyId: string, ids: string[]): Promise<ProjectWithGoals[]> => {
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { formatProjectBudget } from "./utils";
describe("formatProjectBudget", () => {
it("renders a /mo suffix for monthly budgets", () => {
expect(formatProjectBudget({ amountCents: 120_000, windowKind: "calendar_month_utc" })).toBe("$1,200.00/mo");
});
it("renders the bare amount for lifetime budgets", () => {
expect(formatProjectBudget({ amountCents: 50_000, windowKind: "lifetime" })).toBe("$500.00");
});
it("formats sub-dollar amounts with cents", () => {
expect(formatProjectBudget({ amountCents: 150, windowKind: "lifetime" })).toBe("$1.50");
});
});
+9
View File
@@ -29,6 +29,15 @@ export function formatNumber(n: number): string {
return n.toLocaleString("en-US");
}
/**
* Format a project's budget for the projects list view (IA Phase 4 — PAP-60).
* Monthly budgets render a `/mo` suffix; lifetime budgets show the bare amount.
*/
export function formatProjectBudget(budget: { amountCents: number; windowKind: string }): string {
const amount = formatCents(budget.amountCents);
return budget.windowKind === "calendar_month_utc" ? `${amount}/mo` : amount;
}
export function formatDate(date: Date | string): string {
return new Date(date).toLocaleDateString("en-US", {
month: "short",
+13 -2
View File
@@ -12,7 +12,7 @@ import { StatusBadge } from "../components/StatusBadge";
import { MembershipAction } from "../components/MembershipAction";
import { EmptyState } from "../components/EmptyState";
import { PageSkeleton } from "../components/PageSkeleton";
import { formatDate, projectUrl } from "../lib/utils";
import { formatDate, formatNumber, formatProjectBudget, projectUrl } from "../lib/utils";
import {
resourceMembershipState,
useResourceMembershipMutation,
@@ -215,8 +215,19 @@ export function Projects() {
className={state === "left" ? "group text-foreground/55" : "group"}
trailing={
<div className="flex items-center gap-3">
<span
className="hidden text-xs text-muted-foreground tabular-nums sm:inline"
title={`${formatNumber(project.taskCount ?? 0)} task${(project.taskCount ?? 0) === 1 ? "" : "s"}`}
>
{formatNumber(project.taskCount ?? 0)} task{(project.taskCount ?? 0) === 1 ? "" : "s"}
</span>
{project.budget && (
<span className="hidden text-xs text-muted-foreground tabular-nums sm:inline">
{formatProjectBudget(project.budget)}
</span>
)}
{project.targetDate && (
<span className="text-xs text-muted-foreground">
<span className="hidden text-xs text-muted-foreground md:inline">
{formatDate(project.targetDate)}
</span>
)}