Commit 4ab92ec6 authored by Christos Tranoris's avatar Christos Tranoris
Browse files

fixing inventiry zero metrics

parent 5c7bb60e
Loading
Loading
Loading
Loading
+111
Changes for docs/20260809_1418_inventory_zero_metrics.md: 111 added lines, 0 removed lines.
Original line number Diff line number Diff line
# Inventory page — every metric but Pools read zero

**2026-08-09 14:18**

> *"The /inventory page shows 0 in all metrics except pools."*

## Cause

The domain type described an endpoint that does not exist. `PoolInventory` carried

```ts
memberships: ResourceSummary[];   // a list of resources
```

but `GET /api/v1/inventory` returns **counts**:

```json
{ "pool": { … }, "membershipCount": 5, "danglingCount": 0,
  "membershipsByStatus": { "AVAILABLE": 3, "ALARM": 1, "SUSPENDED": 1 } }
```

There is no resource array in the response, so the codec could not produce one — it
hardcoded `memberships: []`, and its unit test asserted exactly that, titled
*"memberships always []"*. Everything downstream then derived its numbers from that
empty list:

```ts
const allResources   = (inventories ?? []).flatMap(inv => inv.memberships);
const totalResources = allResources.length;              // always 0
const totalAvailable = allResources.filter(…).length;    // always 0
```

Pools was the one card that read right because it counted the inventories
themselves. `membershipCount` and `membershipsByStatus` were decoded by nobody, and
the per-pool Resources column, the utilization bar, and the expanded panel's status
breakdown were all reading the same empty array. Dangling was decoded correctly, so
it showed a real number — zero, in this deployment.

The unit tests passed throughout because every fixture hand-built a `memberships`
array that no server response can produce. That is the shape of this bug: the tests
tested the invented type, not the contract.

## Fix

**`domain/inventory.ts`** — `PoolInventory` now describes the response:

```ts
export interface PoolInventory {
  poolId: string;
  poolName?: string;          // the response embeds the whole PoolEntity
  category?: ResourceCategory;
  membershipCount: number;
  danglingCount: number;
  membershipsByStatus: Record<string, number>;
}
```

plus `inventoryStatusCount(inv, status)` — a status the server did not report is a
status nothing is in, so it reads 0 rather than `undefined` — and `totalByStatus`.

**`mappers/entities.ts`** — `decodePoolInventory` decodes all of it, drops any
non-numeric entry from the status map, and lifts name and category off the embedded
pool. `membershipCount` is authoritative; the per-status total stands in only when a
server sends a breakdown without a total, the one case where reporting 0 would
contradict the rest of the same response.

**`InventoryListPage`** — every card and column now sums the reported counts.
Because the response embeds the pool, the page no longer calls `usePools()` and
joins on id; it reads `poolName`/`category` straight off each row, which is one
fewer request and one fewer join that can miss.

`UtilizationBar` divides up the status map rather than a resource list, and takes
its total from the map, not from `membershipCount` — those two can disagree, and a
bar whose segments don't fill their own width is worse than no bar.

**`PoolInventoryDetail`** — the status breakdown comes from the map. The *Resources*
table had no data source at all in this endpoint, so it now fetches the pool's
memberships (`useMembershipsInPool`, one page of 100) when a row is expanded, and
shows name, status and capacity unit from them. It distinguishes *loading* from *this
pool has no members* instead of showing an empty table for both, marks a dangling
membership as dangling rather than by its stale last-known status, and says how many
members were left unfetched rather than presenting one page as the whole pool.

The unused `poolName` prop went with the rewrite (it also clears a pre-existing
`TS6133`).

## Tests

**+9**, 1008 → **1017**. Six `as any` casts left the page test with the `usePools`
mock, so lint drops 112 → 106.

- `entities.test.ts` — the old *"memberships always []"* test is replaced by four:
  full decode including pool name and category, an empty `{}` response reading as
  zeroes, the per-status fallback when `membershipCount` is absent, and
  `membershipCount` winning when both are present.
- `gateways.test.ts` — asserts the decoded counts rather than an empty array; the
  MSW fixture gained a `membershipsByStatus` and a category so it looks like a real
  response.
- `InventoryListPage.test.tsx` — the stat cards total from reported counts
  (the regression test), the same status summed across pools, the utilization bar
  present with a breakdown and a dash without one, and the pool-id fallback when the
  response carries no name.
- `PoolInventoryDetail` — resources come from the memberships call with the right
  arguments, loading is not reported as empty, an empty pool is, the unfetched
  remainder is counted, and a dangling membership shows as dangling.

## Verification

- Full suite — **1017/1017**, 67 files.
- `npm run lint` — **106**, all pre-existing `no-explicit-any`.
- `npx tsc -b --force` — no new errors; two pre-existing ones gone.
+1
Changes for docs/index.md: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -2,6 +2,7 @@

| Date | File | Description |
|---|---|---|
| 2026-08-09 14:18 | [Inventory page — every metric but Pools read zero](20260809_1418_inventory_zero_metrics.md) | The domain type described an endpoint that doesn't exist: `PoolInventory` carried a `memberships: ResourceSummary[]` list while `GET /inventory` returns **counts** (`membershipCount`, `membershipsByStatus`, `danglingCount`), so the codec hardcoded `memberships: []` — and every card, the Resources column, the utilization bar and the status breakdown derived their numbers from that empty array; Pools was right only because it counted the inventories themselves; the type now matches the response and the page sums the reported counts, dropping the `usePools()` join because the response embeds the pool; the expanded panel's Resources table, which had no data source at all here, now fetches the pool's memberships and separates *loading* from *empty*; the old unit test asserting "memberships always []" is replaced by four real decode tests; +9 tests (1017), lint 112 → 106 |
| 2026-08-08 21:45 | [Reservation purge — permanent deletion, behind a preview](20260808_2145_reservation_purge.md) | Implemented the two new admin endpoints `DELETE /reservations/{id}/purge` and `POST /reservations/purge` as a capability-gated `/purge` page; purge deletes the row rather than releasing the booking, so the design is built around that — `PurgeDraft` makes `force`/`dryRun` required with no defaults, blank filters are dropped instead of sent as `""`, an absent `dryRun` decodes as a *preview*, dry runs invalidate nothing, and **"Purge permanently" is armed only by a successful preview of the exact same filter**, re-disarming on any edit including ticking force; both destructive calls sit behind confirm dialogs and the result panel distinguishes preview from deletion, flags skipped-because-still-live rows and warns on a truncated batch; regenerating the contract widened the problem-code enum, and adding `NOT_PURGEABLE` to `PROBLEM_CODES` fixed a real bug where a 409 refusal rendered as an overlap conflict; `LIFECYCLE_STATES` de-duplicated out of `ActivityPage` into the domain; +65 tests, 1008 total |
| 2026-08-08 20:44 | [Availability Search → Reservation: what "Book" carries across](20260808_2044_availability_book_handoff.md) | Traced the Book handoff with an integration probe: pool, resource and the booked range already arrived intact, but Book landed on the **Hold Request** tab (so the operator re-picked the form, or created a hold that expires instead of the reservation they asked for) and the **capacity dropped** — the search validated the window *for a capacity* and the form then booked without it; new `bookingHandoff.ts` holds both halves of the query-string contract (two capacity params validated against the domain enum, refusing an incomplete pair rather than partly honouring it, plus a `tab` param), `CAPACITY_UNITS`/`isCapacityUnit` moved into the domain so `CapacityInput` stops keeping its own copy, and both forms gained `initialCapacity`; flags a pre-existing mismatch — the contract requires `membershipId` but both forms label the resource optional; +23 tests, 943 total |
| 2026-08-08 19:53 | [Pool detail — Expand all / Collapse all, and a table-level Include past](20260808_1953_pool_detail_expand_all_include_past.md) | Added Expand all / Collapse all to the Members tab of `/pools/{id}`, each disabled when it would do nothing; expansion moved from a single `expandedMemberId` to a `ReadonlySet` because rows used to close each other, which made comparing two resources impossible and left Expand all nothing to expand into; `Include past` hoisted out of each panel to the right-hand end of the table's control row (`ml: 'auto'`) so one tick re-queries every open row instead of one checkbox per resource; `ResourceReservationsPanel` is now owner-controlled via an `includePast` prop; 22 pool tests, 920 total |
+3 −2
Changes for src/adapters/api/gateways/gateways.test.ts: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -252,9 +252,10 @@ describe('InventoryGateway', () => {
    expect(result.danglingCount).toBe(0);
  });

  it('list decodes memberships as empty array', async () => {
  it('list decodes the counts the endpoint actually reports', async () => {
    const result = await gw.list();
    expect(result[0].memberships).toEqual([]);
    expect(result[0].membershipCount).toBe(5);
    expect(result[0].membershipsByStatus).toEqual({ AVAILABLE: 3, ALARM: 1, SUSPENDED: 1 });
  });

  it('get uses /api/v1/inventory/:poolId with the given id', async () => {
+35 −3
Changes for src/adapters/api/mappers/entities.test.ts: 35 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -345,15 +345,47 @@ describe('decodeResourceSummary', () => {
// ─── decodePoolInventory ──────────────────────────────────────────────────

describe('decodePoolInventory', () => {
  it('extracts poolId from pool.id, danglingCount; memberships always []', () => {
  it('decodes the pool, the counts and the per-status breakdown', () => {
    const inv = decodePoolInventory({
      pool: { id: 'pool-99', name: 'P' },
      pool: { id: 'pool-99', name: 'P', category: 'LOGICAL_COUNTABLE' },
      danglingCount: 4,
      membershipCount: 12,
      membershipsByStatus: { AVAILABLE: 9, ALARM: 3 },
    });
    expect(inv.poolId).toBe('pool-99');
    expect(inv.poolName).toBe('P');
    expect(inv.category).toBe('LOGICAL_COUNTABLE');
    expect(inv.membershipCount).toBe(12);
    expect(inv.danglingCount).toBe(4);
    expect(inv.memberships).toEqual([]);
    expect(inv.membershipsByStatus).toEqual({ AVAILABLE: 9, ALARM: 3 });
  });

  it('reads an empty response as zeroes rather than as missing data', () => {
    const inv = decodePoolInventory({});
    expect(inv.poolId).toBe('');
    expect(inv.membershipCount).toBe(0);
    expect(inv.danglingCount).toBe(0);
    expect(inv.membershipsByStatus).toEqual({});
    expect('poolName' in inv).toBe(false);
    expect('category' in inv).toBe(false);
  });

  // Reporting a breakdown but no total is the one case where 0 would contradict the response.
  it('falls back to the per-status total when membershipCount is absent', () => {
    const inv = decodePoolInventory({
      pool: { id: 'p' },
      membershipsByStatus: { AVAILABLE: 2, SUSPENDED: 1 },
    });
    expect(inv.membershipCount).toBe(3);
  });

  it('prefers membershipCount over the breakdown when both are present', () => {
    const inv = decodePoolInventory({
      pool: { id: 'p' },
      membershipCount: 10,
      membershipsByStatus: { AVAILABLE: 2 },
    });
    expect(inv.membershipCount).toBe(10);
  });
});

+17 −2
Changes for src/adapters/api/mappers/entities.ts: 17 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -49,7 +49,7 @@ import {
  decodeDateTime,
} from './primitives';
import { decodeViolatedConstraints, decodeSuggestedAlternative } from './flags';
import { DEFAULT_COVERAGE_MODE, isFailureSignal, requiresAttemptSequence } from '@domain';
import { DEFAULT_COVERAGE_MODE, isFailureSignal, requiresAttemptSequence, totalByStatus } from '@domain';

type WirePool = components['schemas']['PoolEntity'];
type WirePoolRequest = components['schemas']['PoolRequest'];
@@ -243,11 +243,26 @@ export function decodeResourceSummary(w: WireResourceSummary): ResourceSummary {

// ─── PoolInventory ─────────────────────────────────────────────────────────

/** Drops anything the map holds that is not a usable count, so the UI never adds `undefined`. */
function decodeStatusCounts(w: WireInventory['membershipsByStatus']): Record<string, number> {
  const counts: Record<string, number> = {};
  for (const [status, count] of Object.entries(w ?? {})) {
    if (typeof count === 'number' && Number.isFinite(count)) counts[status] = count;
  }
  return counts;
}

export function decodePoolInventory(w: WireInventory): PoolInventory {
  const membershipsByStatus = decodeStatusCounts(w.membershipsByStatus);
  return {
    poolId: w.pool?.id ?? '',
    memberships: [],
    ...(w.pool?.name != null && { poolName: w.pool.name }),
    ...(w.pool?.category != null && { category: w.pool.category }),
    // `membershipCount` is the authority; the per-status total stands in only when the server
    // reported a breakdown without a total, where reading 0 would contradict the breakdown itself.
    membershipCount: w.membershipCount ?? totalByStatus(membershipsByStatus),
    danglingCount: w.danglingCount ?? 0,
    membershipsByStatus,
  };
}

Loading