refactor: complete v2 refactoring plan (Phases 1-5)
Phase 1 — Quick Wins: centralize formatMoney/formatCents, extract findUniqueOrThrow helper (19 routers), shared Prisma select constants, useInvalidatePlanningViews hook, status badge consolidation, composite DB indexes. Phase 2 — Timeline Split: extract TimelineContext, TimelineResourcePanel, TimelineProjectPanel; split 28-dep useMemo into 3 focused memos. TimelineView.tsx reduced from 1,903 to 538 lines. Phase 3 — Query Performance: server-side filtering for getEntriesView, remove availability from timeline resource select, SSE event debouncing (50ms batch window). Phase 4 — Estimate Workspace: extract 7 tab components and 3 editor components. EstimateWorkspaceClient 1,298→306 lines, EstimateWorkspaceDraftEditor 1,205→581 lines. Phase 5 — Package Cleanup: split commit-dispo-import-batch (1,112→573 lines), extract shared pagination helper with 11 tests. All tests pass: 209 API, 254 engine, 67 application. Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
import { SSE_EVENT_TYPES } from "@planarchy/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
cancelPendingEvents,
|
||||
eventBus,
|
||||
flushPendingEvents,
|
||||
type SseEvent,
|
||||
} from "../sse/event-bus.js";
|
||||
|
||||
// Mock Redis so the module loads without a real connection.
|
||||
// publish() throws so the event bus falls back to local-only delivery,
|
||||
// which is the path that exercises the debounce buffer.
|
||||
vi.mock("ioredis", () => {
|
||||
const RedisMock = vi.fn().mockImplementation(() => ({
|
||||
on: vi.fn(),
|
||||
subscribe: vi.fn().mockResolvedValue(undefined),
|
||||
publish: vi.fn().mockImplementation(() => {
|
||||
throw new Error("Redis unavailable (test)");
|
||||
}),
|
||||
}));
|
||||
return { Redis: RedisMock };
|
||||
});
|
||||
|
||||
describe("event-bus debounce", () => {
|
||||
let received: SseEvent[];
|
||||
let unsubscribe: () => void;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
received = [];
|
||||
unsubscribe = eventBus.subscribe((event) => {
|
||||
received.push(event);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
unsubscribe();
|
||||
cancelPendingEvents();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("delivers a single event after the debounce window", () => {
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_CREATED, { id: "a1" });
|
||||
|
||||
// Not yet delivered — still in the debounce window
|
||||
expect(received).toHaveLength(0);
|
||||
|
||||
vi.advanceTimersByTime(50);
|
||||
|
||||
// Now delivered
|
||||
expect(received).toHaveLength(1);
|
||||
expect(received[0]!.type).toBe(SSE_EVENT_TYPES.ALLOCATION_CREATED);
|
||||
expect(received[0]!.payload).toEqual({ id: "a1" });
|
||||
});
|
||||
|
||||
it("aggregates multiple events of the same type into a single _batch event", () => {
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_UPDATED, { id: "a1" });
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_UPDATED, { id: "a2" });
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_UPDATED, { id: "a3" });
|
||||
|
||||
expect(received).toHaveLength(0);
|
||||
|
||||
vi.advanceTimersByTime(50);
|
||||
|
||||
expect(received).toHaveLength(1);
|
||||
expect(received[0]!.type).toBe(SSE_EVENT_TYPES.ALLOCATION_UPDATED);
|
||||
expect(received[0]!.payload).toEqual({
|
||||
_batch: [{ id: "a1" }, { id: "a2" }, { id: "a3" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps different event types separate", () => {
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_CREATED, { id: "a1" });
|
||||
eventBus.emit(SSE_EVENT_TYPES.ROLE_UPDATED, { id: "r1" });
|
||||
|
||||
vi.advanceTimersByTime(50);
|
||||
|
||||
expect(received).toHaveLength(2);
|
||||
const types = received.map((e) => e.type);
|
||||
expect(types).toContain(SSE_EVENT_TYPES.ALLOCATION_CREATED);
|
||||
expect(types).toContain(SSE_EVENT_TYPES.ROLE_UPDATED);
|
||||
|
||||
// Both should be single payloads (not batched)
|
||||
for (const event of received) {
|
||||
expect(event.payload).not.toHaveProperty("_batch");
|
||||
}
|
||||
});
|
||||
|
||||
it("resets the debounce timer when new events arrive within the window", () => {
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_UPDATED, { id: "a1" });
|
||||
|
||||
// Advance 30ms (still within window)
|
||||
vi.advanceTimersByTime(30);
|
||||
expect(received).toHaveLength(0);
|
||||
|
||||
// Emit another — this resets the timer
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_UPDATED, { id: "a2" });
|
||||
|
||||
// Advance another 30ms (60ms total from first, but only 30ms from second)
|
||||
vi.advanceTimersByTime(30);
|
||||
expect(received).toHaveLength(0);
|
||||
|
||||
// Advance remaining 20ms (now 50ms from second event)
|
||||
vi.advanceTimersByTime(20);
|
||||
expect(received).toHaveLength(1);
|
||||
expect(received[0]!.payload).toEqual({
|
||||
_batch: [{ id: "a1" }, { id: "a2" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("flushPendingEvents delivers immediately", () => {
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_CREATED, { id: "a1" });
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_CREATED, { id: "a2" });
|
||||
|
||||
expect(received).toHaveLength(0);
|
||||
|
||||
flushPendingEvents();
|
||||
|
||||
expect(received).toHaveLength(1);
|
||||
expect(received[0]!.payload).toEqual({
|
||||
_batch: [{ id: "a1" }, { id: "a2" }],
|
||||
});
|
||||
|
||||
// Timer should not fire again
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(received).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("cancelPendingEvents discards events without delivering", () => {
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_CREATED, { id: "a1" });
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_CREATED, { id: "a2" });
|
||||
|
||||
cancelPendingEvents();
|
||||
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(received).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("preserves the timestamp of the first event in a batch", () => {
|
||||
const before = new Date().toISOString();
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_UPDATED, { id: "a1" });
|
||||
|
||||
// Advance a bit, emit another
|
||||
vi.advanceTimersByTime(10);
|
||||
eventBus.emit(SSE_EVENT_TYPES.ALLOCATION_UPDATED, { id: "a2" });
|
||||
|
||||
vi.advanceTimersByTime(50);
|
||||
|
||||
expect(received).toHaveLength(1);
|
||||
// The timestamp should be from the first event (not later)
|
||||
expect(received[0]!.timestamp).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { paginate, paginateCursor } from "../db/pagination.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test data
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeItems(n: number) {
|
||||
return Array.from({ length: n }, (_, i) => ({
|
||||
id: `id_${String(i + 1).padStart(3, "0")}`,
|
||||
name: `Item ${i + 1}`,
|
||||
}));
|
||||
}
|
||||
|
||||
const ALL_ITEMS = makeItems(55);
|
||||
|
||||
function mockFindMany(items: typeof ALL_ITEMS) {
|
||||
return async ({ skip, take }: { skip: number; take: number }) =>
|
||||
items.slice(skip, skip + take);
|
||||
}
|
||||
|
||||
function mockCount(items: typeof ALL_ITEMS) {
|
||||
return async () => items.length;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// paginate()
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("paginate", () => {
|
||||
it("returns first page with correct metadata", async () => {
|
||||
const result = await paginate(
|
||||
mockFindMany(ALL_ITEMS),
|
||||
mockCount(ALL_ITEMS),
|
||||
{ page: 1, limit: 20 },
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(20);
|
||||
expect(result.total).toBe(55);
|
||||
expect(result.page).toBe(1);
|
||||
expect(result.limit).toBe(20);
|
||||
expect(result.nextCursor).toBe("id_020");
|
||||
});
|
||||
|
||||
it("returns last page without nextCursor", async () => {
|
||||
const result = await paginate(
|
||||
mockFindMany(ALL_ITEMS),
|
||||
mockCount(ALL_ITEMS),
|
||||
{ page: 3, limit: 20 },
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(15);
|
||||
expect(result.total).toBe(55);
|
||||
expect(result.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("skips zero when cursor is provided", async () => {
|
||||
let capturedSkip = -1;
|
||||
const result = await paginate(
|
||||
async ({ skip, take }) => {
|
||||
capturedSkip = skip;
|
||||
return ALL_ITEMS.slice(skip, skip + take);
|
||||
},
|
||||
mockCount(ALL_ITEMS),
|
||||
{ page: 3, limit: 10, cursor: "irrelevant" },
|
||||
);
|
||||
|
||||
expect(capturedSkip).toBe(0);
|
||||
// When cursor is given skip=0, so we get from the start of the pre-filtered data
|
||||
expect(result.items).toHaveLength(10);
|
||||
});
|
||||
|
||||
it("uses defaults when page and limit omitted", async () => {
|
||||
const result = await paginate(
|
||||
mockFindMany(ALL_ITEMS),
|
||||
mockCount(ALL_ITEMS),
|
||||
{},
|
||||
);
|
||||
|
||||
expect(result.page).toBe(1);
|
||||
expect(result.limit).toBe(50);
|
||||
expect(result.items).toHaveLength(50);
|
||||
expect(result.nextCursor).toBe("id_050");
|
||||
});
|
||||
|
||||
it("handles empty result set", async () => {
|
||||
const result = await paginate(
|
||||
mockFindMany([]),
|
||||
mockCount([]),
|
||||
{ page: 1, limit: 20 },
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(0);
|
||||
expect(result.total).toBe(0);
|
||||
expect(result.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("returns no nextCursor when items exactly equal limit", async () => {
|
||||
const items = makeItems(20);
|
||||
const result = await paginate(
|
||||
mockFindMany(items),
|
||||
mockCount(items),
|
||||
{ page: 1, limit: 20 },
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(20);
|
||||
expect(result.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("supports custom getId", async () => {
|
||||
const items = [{ uuid: "abc" }, { uuid: "def" }, { uuid: "ghi" }];
|
||||
const result = await paginate(
|
||||
async ({ skip, take }) => items.slice(skip, skip + take),
|
||||
async () => items.length,
|
||||
{ page: 1, limit: 2 },
|
||||
(item) => item.uuid,
|
||||
);
|
||||
|
||||
expect(result.nextCursor).toBe("def");
|
||||
expect(result.items).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// paginateCursor()
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("paginateCursor", () => {
|
||||
it("returns items and nextCursor when more exist", async () => {
|
||||
const result = await paginateCursor(
|
||||
async ({ take }) => ALL_ITEMS.slice(0, take),
|
||||
{ limit: 10 },
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(10);
|
||||
expect(result.nextCursor).toBe("id_010");
|
||||
});
|
||||
|
||||
it("returns null cursor when no more items", async () => {
|
||||
const items = makeItems(5);
|
||||
const result = await paginateCursor(
|
||||
async ({ take }) => items.slice(0, take),
|
||||
{ limit: 10 },
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(5);
|
||||
expect(result.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("handles empty result", async () => {
|
||||
const result = await paginateCursor(
|
||||
async () => [],
|
||||
{ limit: 10 },
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(0);
|
||||
expect(result.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("uses default limit", async () => {
|
||||
const result = await paginateCursor(
|
||||
async ({ take }) => ALL_ITEMS.slice(0, take),
|
||||
{},
|
||||
);
|
||||
|
||||
expect(result.items).toHaveLength(50);
|
||||
expect(result.nextCursor).toBe("id_050");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user