fix(miniapps): format every remaining displayed number to 2 decimals
Follows the fairshare/ResourceTiles fix (8c434b5) with the same bug class
found everywhere else a continuous/computed value was echoed raw in JSX:
- FarmsScreen: the grow-light power budget echo (same live Fair Share CEEI
allocation ResourceTiles already fixes)
- PlantingInputForm / TemperatureEntryForm: echoed plot area, crop GDD/
yield/kWh, and min/max temperature entries
- shell WalletCard + TransactionHistory: the wallet balance, send-status
amounts, and per-row transaction amounts - the same wallet-balance bug
as fairshare, in the app's single most prominent wallet display
- The Climb's ScheduleTimeline / CongestionHeatmap / ScheduleInputForm:
traced the min-cost-flow solver's own types (ShaftEdge.capacityPerPeriod,
WaveDemandGroup.count, SurfaceCapacityPeriod.capacity) and confirmed none
are integer-constrained, so totalDelivered/totalCost/peopleMoved/queue
lengths/wait totals can all carry real fractional precision
- Water Watch DeviceMonitor: the reported reading feed value
- Light Clock ManualLogForm: the echoed hours/lux manual-log entries
Every fix ships with a proving test mirroring ResourceTiles.test.tsx's
pattern: a sanity-check that the raw value genuinely exceeds 2 decimal
digits before asserting the rendered text is truncated to exactly 2.
Investigated and left unformatted (genuine integer/bounded values,
confirmed by tracing source, not variable-name guessing):
- Housing's fit score and fairness-debt ledger (always an integer sum by
construction - traced buildRankedCyclePreferences/solveHousingAssignment)
- Mentor's dependents-count/holder-count and match score (sum of integers)
- Tunnel Safety's route distance (sums a static, fixed-integer demo graph,
never user input)
- Health Post's triage ageMonths (documented "whole months" field)
- Testimony's median rating (division by 2 only, never exceeds 1 decimal)
Full suite (870 tests / 99 files), npm run build, and npx oxlint all pass.
This commit is contained in:
1 parent
8c434b5cb9
commit
05df4133a1
20 files changed
+422
-29
No files matched your search
@@ -4,7 +4,8 @@ import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { db } from "../../lib/db.ts";
|
||||
import { append } from "../../lib/eventlog.ts";
|
||||
import { append, readAll } from "../../lib/eventlog.ts";
|
||||
import { computeFairshareAllocation } from "../../lib/fairshare.ts";
|
||||
import { getPublicKey, init } from "../../lib/identity.ts";
|
||||
import { toAccountId } from "../../shell/accountId.ts";
|
||||
import { FarmsScreen } from "./FarmsScreen.tsx";
|
||||
@@ -166,7 +167,7 @@ describe("FarmsScreen (grow-light power budget sourced from Fair Share's live al
|
||||
render(<FarmsScreen />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("farms-energy-budget")).toHaveTextContent("1 kWh");
|
||||
expect(screen.getByTestId("farms-energy-budget")).toHaveTextContent("1.00 kWh");
|
||||
});
|
||||
|
||||
await user.clear(screen.getByTestId("farms-base-temp"));
|
||||
@@ -201,10 +202,50 @@ describe("FarmsScreen (grow-light power budget sourced from Fair Share's live al
|
||||
await append({ type: "seed.resource.power", resource: "power", value: 10 });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("farms-energy-budget")).toHaveTextContent("10 kWh");
|
||||
expect(screen.getByTestId("farms-energy-budget")).toHaveTextContent("10.00 kWh");
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("farms-forecast-total")).toHaveTextContent("20.00 kg");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("FarmsScreen (display formatting - coherence audit)", () => {
|
||||
beforeEach(async () => {
|
||||
indexedDB.deleteDatabase(db.name);
|
||||
db.close();
|
||||
await db.open();
|
||||
await init();
|
||||
});
|
||||
|
||||
it("truncates the live Fair Share power allocation to 2 decimals instead of echoing its raw CEEI precision", async () => {
|
||||
const accountId = toAccountId(await getPublicKey());
|
||||
|
||||
// Mirrors ResourceTiles.test.tsx's own proving fixture: a multi-good,
|
||||
// unequal-weight market across power AND water is what makes the CEEI
|
||||
// solve genuinely fractional (a single-resource top-up always
|
||||
// degenerates to a clean 50/50 split). This is exactly how a grower's
|
||||
// real power budget gets populated in production - never a number the
|
||||
// grower typed in themselves.
|
||||
await append({ type: "seed.resource.power", resource: "power", value: 1000 });
|
||||
await append({ type: "seed.resource.water", resource: "water", value: 800 });
|
||||
await append({ type: "fairshare.need", agent: accountId, resource: "power", value: 10 });
|
||||
await append({ type: "fairshare.need", agent: accountId, resource: "water", value: 1 });
|
||||
await append({ type: "fairshare.need", agent: "other-agent", resource: "power", value: 1 });
|
||||
await append({ type: "fairshare.need", agent: "other-agent", resource: "water", value: 10 });
|
||||
|
||||
render(<FarmsScreen />);
|
||||
|
||||
const expectedBudget = computeFairshareAllocation(await readAll()).allocation[accountId].power;
|
||||
// Sanity-check the fixture actually exercises the bug: the real solver
|
||||
// output here must carry more than 2 meaningful decimal digits, or this
|
||||
// test would pass even with the bug still present.
|
||||
expect((String(expectedBudget).split(".")[1] ?? "").length).toBeGreaterThan(2);
|
||||
|
||||
await waitFor(() => {
|
||||
const text = screen.getByTestId("farms-energy-budget").textContent ?? "";
|
||||
expect(text).toContain(expectedBudget.toFixed(2));
|
||||
expect(text).not.toContain(String(expectedBudget));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -104,7 +104,7 @@ export function FarmsScreen() {
|
||||
<span data-testid="farms-energy-budget" className={styles.budgetValue}>
|
||||
{energyBudgetKwh === undefined
|
||||
? "No Fair Share power allocation yet (unlimited)"
|
||||
: `${energyBudgetKwh} kWh`}
|
||||
: `${energyBudgetKwh.toFixed(2)} kWh`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// @vitest-environment happy-dom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { CropMaturityWindow, PlantingPlot } from "../../lib/farms.ts";
|
||||
import { PlantingInputForm } from "./PlantingInputForm.tsx";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("PlantingInputForm (display formatting - coherence audit)", () => {
|
||||
it("formats a fractional plot area to 2 decimals instead of echoing its raw precision", () => {
|
||||
const plots: PlantingPlot[] = [{ plotId: "plot-a", areaM2: 123.456789 }];
|
||||
|
||||
render(
|
||||
<PlantingInputForm
|
||||
plots={plots}
|
||||
onAddPlot={vi.fn()}
|
||||
onRemovePlot={vi.fn()}
|
||||
crops={[]}
|
||||
onAddCrop={vi.fn()}
|
||||
onRemoveCrop={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const list = screen.getByTestId("farms-plots");
|
||||
expect(list).toHaveTextContent((123.456789).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("123.456789");
|
||||
});
|
||||
|
||||
it("formats fractional crop GDD/yield/energy/max-area figures to 2 decimals instead of echoing raw precision", () => {
|
||||
const crops: CropMaturityWindow[] = [
|
||||
{
|
||||
cropId: "wheat",
|
||||
maturityGdd: 111.123456,
|
||||
yieldKgPerM2: 2.987654,
|
||||
kWhPerM2: 1.555555,
|
||||
maxAreaM2: 50.111111,
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<PlantingInputForm
|
||||
plots={[]}
|
||||
onAddPlot={vi.fn()}
|
||||
onRemovePlot={vi.fn()}
|
||||
crops={crops}
|
||||
onAddCrop={vi.fn()}
|
||||
onRemoveCrop={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const list = screen.getByTestId("farms-crops");
|
||||
expect(list).toHaveTextContent((111.123456).toFixed(2));
|
||||
expect(list).toHaveTextContent((2.987654).toFixed(2));
|
||||
expect(list).toHaveTextContent((1.555555).toFixed(2));
|
||||
expect(list).toHaveTextContent((50.111111).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("111.123456");
|
||||
expect(list).not.toHaveTextContent("2.987654");
|
||||
expect(list).not.toHaveTextContent("1.555555");
|
||||
expect(list).not.toHaveTextContent("50.111111");
|
||||
});
|
||||
});
|
||||
@@ -103,7 +103,7 @@ export function PlantingInputForm({
|
||||
{plots.map((plot, index) => (
|
||||
<li className={styles.entryRow} key={`${plot.plotId}-${index}`}>
|
||||
<span>
|
||||
{plot.plotId}: {plot.areaM2} m²
|
||||
{plot.plotId}: {plot.areaM2.toFixed(2)} m²
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
@@ -183,9 +183,9 @@ export function PlantingInputForm({
|
||||
{crops.map((crop, index) => (
|
||||
<li className={styles.entryRow} key={`${crop.cropId}-${index}`}>
|
||||
<span>
|
||||
{crop.cropId}: {crop.maturityGdd} GDD, {crop.yieldKgPerM2} kg/m²,{" "}
|
||||
{crop.kWhPerM2} kWh/m²
|
||||
{crop.maxAreaM2 !== undefined ? `, max ${crop.maxAreaM2} m\u00B2` : ""}
|
||||
{crop.cropId}: {crop.maturityGdd.toFixed(2)} GDD, {crop.yieldKgPerM2.toFixed(2)} kg/m²,{" "}
|
||||
{crop.kWhPerM2.toFixed(2)} kWh/m²
|
||||
{crop.maxAreaM2 !== undefined ? `, max ${crop.maxAreaM2.toFixed(2)} m\u00B2` : ""}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// @vitest-environment happy-dom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { TemperatureEntry } from "../../lib/farms.ts";
|
||||
import { TemperatureEntryForm } from "./TemperatureEntryForm.tsx";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("TemperatureEntryForm (display formatting - coherence audit)", () => {
|
||||
it("formats fractional tmin/tmax readings to 2 decimals instead of echoing raw precision", () => {
|
||||
const entries: TemperatureEntry[] = [
|
||||
{ date: "2026-05-01", tmin: 9.123456789, tmax: 28.987654321 },
|
||||
];
|
||||
|
||||
render(
|
||||
<TemperatureEntryForm
|
||||
baseTempC={10}
|
||||
onBaseTempChange={vi.fn()}
|
||||
entries={entries}
|
||||
onAddEntry={vi.fn()}
|
||||
onRemoveEntry={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const list = screen.getByTestId("farms-temp-entries");
|
||||
expect(list).toHaveTextContent((9.123456789).toFixed(2));
|
||||
expect(list).toHaveTextContent((28.987654321).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("9.123456789");
|
||||
expect(list).not.toHaveTextContent("28.987654321");
|
||||
});
|
||||
});
|
||||
@@ -100,7 +100,7 @@ export function TemperatureEntryForm({
|
||||
{entries.map((entry, index) => (
|
||||
<li className={styles.entryRow} key={`${entry.date}-${index}`}>
|
||||
<span>
|
||||
{entry.date}: {entry.tmin}°C – {entry.tmax}°C
|
||||
{entry.date}: {entry.tmin.toFixed(2)}°C – {entry.tmax.toFixed(2)}°C
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// @vitest-environment happy-dom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ManualLogEntry } from "../../lib/lightclockSensors.ts";
|
||||
import { ManualLogForm } from "./ManualLogForm.tsx";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("ManualLogForm (display formatting - coherence audit)", () => {
|
||||
it("formats a fractional entered hours value to 2 decimals instead of echoing its raw precision", () => {
|
||||
const entries: ManualLogEntry[] = [{ hours: 7.123456789, state: "asleep" }];
|
||||
|
||||
render(<ManualLogForm entries={entries} onAddEntry={vi.fn()} onCompute={vi.fn()} />);
|
||||
|
||||
const list = screen.getByTestId("lightclock-manual-entries");
|
||||
expect(list).toHaveTextContent((7.123456789).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("7.123456789");
|
||||
});
|
||||
|
||||
it("formats a fractional entered lux value to 2 decimals instead of echoing its raw precision", () => {
|
||||
const entries: ManualLogEntry[] = [{ hours: 2, state: "awake", lux: 450.987654321 }];
|
||||
|
||||
render(<ManualLogForm entries={entries} onAddEntry={vi.fn()} onCompute={vi.fn()} />);
|
||||
|
||||
const list = screen.getByTestId("lightclock-manual-entries");
|
||||
expect(list).toHaveTextContent((450.987654321).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("450.987654321");
|
||||
});
|
||||
|
||||
it("still shows the honest 'default' label for an entry with no lux estimate, never a fabricated number", () => {
|
||||
const entries: ManualLogEntry[] = [{ hours: 3, state: "awake" }];
|
||||
|
||||
render(<ManualLogForm entries={entries} onAddEntry={vi.fn()} onCompute={vi.fn()} />);
|
||||
|
||||
expect(screen.getByTestId("lightclock-manual-entries")).toHaveTextContent("default lux");
|
||||
});
|
||||
});
|
||||
@@ -100,9 +100,9 @@ export function ManualLogForm({ entries, onAddEntry, onCompute }: ManualLogFormP
|
||||
<ul className={styles.entryList} data-testid="lightclock-manual-entries">
|
||||
{entries.map((entry, index) => (
|
||||
<li key={`${entry.hours}-${entry.state}-${index}`} className={styles.entryRow}>
|
||||
<span>{entry.hours}h</span>
|
||||
<span>{entry.hours.toFixed(2)}h</span>
|
||||
<span>{entry.state}</span>
|
||||
<span>{entry.lux ?? "default"} lux</span>
|
||||
<span>{entry.lux !== undefined ? entry.lux.toFixed(2) : "default"} lux</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// @vitest-environment happy-dom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { CongestionTimeline } from "../../lib/theclimbCongestion.ts";
|
||||
import { CongestionHeatmap } from "./CongestionHeatmap.tsx";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("CongestionHeatmap (display formatting - coherence audit)", () => {
|
||||
it("formats fractional queue-length/wait values to 2 decimals instead of echoing raw precision", () => {
|
||||
const congestion: CongestionTimeline = {
|
||||
events: [],
|
||||
nodeQueueSamples: [{ nodeId: "SectorA", period: 0, queueLength: 5.123456789 }],
|
||||
maxQueueLength: 5.123456789,
|
||||
totalWaitPersonPeriods: 5.123456789,
|
||||
};
|
||||
|
||||
render(<CongestionHeatmap congestion={congestion} horizonPeriods={1} />);
|
||||
|
||||
const maxQueue = screen.getByTestId("theclimb-max-queue-length");
|
||||
const totalWait = screen.getByTestId("theclimb-total-wait");
|
||||
const cell = screen.getByTestId("theclimb-heatmap-cell-SectorA-0");
|
||||
|
||||
expect(maxQueue).toHaveTextContent((5.123456789).toFixed(2));
|
||||
expect(totalWait).toHaveTextContent((5.123456789).toFixed(2));
|
||||
expect(cell).toHaveTextContent((5.123456789).toFixed(2));
|
||||
|
||||
expect(maxQueue).not.toHaveTextContent("5.123456789");
|
||||
expect(cell).not.toHaveTextContent("5.123456789");
|
||||
});
|
||||
});
|
||||
@@ -27,13 +27,13 @@ export function CongestionHeatmap({ congestion, horizonPeriods }: CongestionHeat
|
||||
<div className={styles.summaryStat}>
|
||||
<span className={styles.summaryLabel}>Max queue length</span>
|
||||
<span className={styles.summaryValue} data-testid="theclimb-max-queue-length">
|
||||
{congestion.maxQueueLength}
|
||||
{congestion.maxQueueLength.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.summaryStat}>
|
||||
<span className={styles.summaryLabel}>Total wait (person-periods)</span>
|
||||
<span className={styles.summaryValue} data-testid="theclimb-total-wait">
|
||||
{congestion.totalWaitPersonPeriods}
|
||||
{congestion.totalWaitPersonPeriods.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -65,7 +65,7 @@ export function CongestionHeatmap({ congestion, horizonPeriods }: CongestionHeat
|
||||
data-testid={`theclimb-heatmap-cell-${nodeId}-${period}`}
|
||||
style={{ background: cellBackground(queueLength, congestion.maxQueueLength) }}
|
||||
>
|
||||
{queueLength}
|
||||
{queueLength.toFixed(2)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// @vitest-environment happy-dom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ShaftEdge, SurfaceCapacityPeriod, WaveDemandGroup } from "../../lib/theclimb.ts";
|
||||
import { ScheduleInputForm } from "./ScheduleInputForm.tsx";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
function renderForm(overrides: {
|
||||
shafts?: ShaftEdge[];
|
||||
demands?: WaveDemandGroup[];
|
||||
surfaceCapacity?: SurfaceCapacityPeriod[];
|
||||
}) {
|
||||
render(
|
||||
<ScheduleInputForm
|
||||
horizonPeriods={6}
|
||||
onHorizonPeriodsChange={vi.fn()}
|
||||
surfaceNodeId="Surface"
|
||||
onSurfaceNodeIdChange={vi.fn()}
|
||||
shafts={overrides.shafts ?? []}
|
||||
onAddShaft={vi.fn()}
|
||||
onRemoveShaft={vi.fn()}
|
||||
demands={overrides.demands ?? []}
|
||||
onAddDemand={vi.fn()}
|
||||
onRemoveDemand={vi.fn()}
|
||||
surfaceCapacity={overrides.surfaceCapacity ?? []}
|
||||
onAddSurfaceCapacity={vi.fn()}
|
||||
onRemoveSurfaceCapacity={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("ScheduleInputForm (display formatting - coherence audit)", () => {
|
||||
it("formats a fractional shaft capacity-per-period to 2 decimals instead of echoing raw precision", () => {
|
||||
renderForm({
|
||||
shafts: [
|
||||
{ id: "shaft1", from: "A", to: "B", capacityPerPeriod: 10.123456789, travelPeriods: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
const list = screen.getByTestId("theclimb-shafts");
|
||||
expect(list).toHaveTextContent((10.123456789).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("10.123456789");
|
||||
});
|
||||
|
||||
it("formats a fractional wave demand count to 2 decimals instead of echoing raw precision", () => {
|
||||
renderForm({
|
||||
demands: [{ id: "wave1", sectorId: "SectorA", readyPeriod: 0, count: 5.123456789 }],
|
||||
});
|
||||
|
||||
const list = screen.getByTestId("theclimb-demands");
|
||||
expect(list).toHaveTextContent((5.123456789).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("5.123456789");
|
||||
});
|
||||
|
||||
it("formats a fractional surface capacity value to 2 decimals instead of echoing raw precision", () => {
|
||||
renderForm({ surfaceCapacity: [{ period: 2, capacity: 200.987654321 }] });
|
||||
|
||||
const list = screen.getByTestId("theclimb-capacity");
|
||||
expect(list).toHaveTextContent((200.987654321).toFixed(2));
|
||||
expect(list).not.toHaveTextContent("200.987654321");
|
||||
});
|
||||
});
|
||||
@@ -247,7 +247,7 @@ export function ScheduleInputForm({
|
||||
{shafts.map((shaft, index) => (
|
||||
<li className={styles.entryRow} key={shaft.id}>
|
||||
<span>
|
||||
{shaft.id}: {shaft.from} → {shaft.to} (cap {shaft.capacityPerPeriod}/period, {shaft.travelPeriods}
|
||||
{shaft.id}: {shaft.from} → {shaft.to} (cap {shaft.capacityPerPeriod.toFixed(2)}/period, {shaft.travelPeriods}
|
||||
{" "}
|
||||
period travel)
|
||||
</span>
|
||||
@@ -317,7 +317,7 @@ export function ScheduleInputForm({
|
||||
{demands.map((demand, index) => (
|
||||
<li className={styles.entryRow} key={demand.id}>
|
||||
<span>
|
||||
{demand.id}: {demand.count} people at {demand.sectorId}, ready period {demand.readyPeriod}
|
||||
{demand.id}: {demand.count.toFixed(2)} people at {demand.sectorId}, ready period {demand.readyPeriod}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
@@ -377,7 +377,7 @@ export function ScheduleInputForm({
|
||||
{surfaceCapacity.map((entry, index) => (
|
||||
<li className={styles.entryRow} key={`${entry.period}`}>
|
||||
<span>
|
||||
Period {entry.period}: capacity {entry.capacity}
|
||||
Period {entry.period}: capacity {entry.capacity.toFixed(2)}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// @vitest-environment happy-dom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { WaveSchedule } from "../../lib/theclimb.ts";
|
||||
import { ScheduleTimeline } from "./ScheduleTimeline.tsx";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("ScheduleTimeline (display formatting - coherence audit)", () => {
|
||||
it("formats fractional min-cost-flow solver outputs to 2 decimals instead of echoing raw precision", () => {
|
||||
const schedule: WaveSchedule = {
|
||||
shaftFlows: [{ shaftId: "shaft1", period: 0, peopleMoved: 5.123456789 }],
|
||||
surfaceArrivals: [],
|
||||
demandOutcomes: [{ demandId: "wave1", delivered: 5.123456789, outstanding: 0.876543211 }],
|
||||
totalDelivered: 5.123456789,
|
||||
totalCost: 5.123456789,
|
||||
tieBreaksResolved: [],
|
||||
};
|
||||
|
||||
render(<ScheduleTimeline schedule={schedule} />);
|
||||
|
||||
const totalDelivered = screen.getByTestId("theclimb-total-delivered");
|
||||
const totalCost = screen.getByTestId("theclimb-total-cost");
|
||||
const timeline = screen.getByTestId("theclimb-timeline-table");
|
||||
const outcomes = screen.getByTestId("theclimb-demand-outcomes-table");
|
||||
|
||||
expect(totalDelivered).toHaveTextContent((5.123456789).toFixed(2));
|
||||
expect(totalCost).toHaveTextContent((5.123456789).toFixed(2));
|
||||
expect(timeline).toHaveTextContent((5.123456789).toFixed(2));
|
||||
expect(outcomes).toHaveTextContent((5.123456789).toFixed(2));
|
||||
expect(outcomes).toHaveTextContent((0.876543211).toFixed(2));
|
||||
|
||||
expect(totalDelivered).not.toHaveTextContent("5.123456789");
|
||||
expect(totalCost).not.toHaveTextContent("5.123456789");
|
||||
expect(outcomes).not.toHaveTextContent("0.876543211");
|
||||
});
|
||||
});
|
||||
@@ -14,13 +14,13 @@ export function ScheduleTimeline({ schedule }: ScheduleTimelineProps) {
|
||||
<div className={styles.summaryStat}>
|
||||
<span className={styles.summaryLabel}>Total delivered</span>
|
||||
<span className={styles.summaryValue} data-testid="theclimb-total-delivered">
|
||||
{schedule.totalDelivered}
|
||||
{schedule.totalDelivered.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.summaryStat}>
|
||||
<span className={styles.summaryLabel}>Total cost</span>
|
||||
<span className={styles.summaryValue} data-testid="theclimb-total-cost">
|
||||
{schedule.totalCost}
|
||||
{schedule.totalCost.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -43,7 +43,7 @@ export function ScheduleTimeline({ schedule }: ScheduleTimelineProps) {
|
||||
<tr data-testid={`theclimb-timeline-row-${index}`} key={`${flow.shaftId}-${flow.period}`}>
|
||||
<td>{flow.shaftId}</td>
|
||||
<td>{flow.period}</td>
|
||||
<td>{flow.peopleMoved}</td>
|
||||
<td>{flow.peopleMoved.toFixed(2)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@@ -63,8 +63,8 @@ export function ScheduleTimeline({ schedule }: ScheduleTimelineProps) {
|
||||
{schedule.demandOutcomes.map((outcome, index) => (
|
||||
<tr data-testid={`theclimb-demand-outcome-row-${index}`} key={outcome.demandId}>
|
||||
<td>{outcome.demandId}</td>
|
||||
<td>{outcome.delivered}</td>
|
||||
<td>{outcome.outstanding}</td>
|
||||
<td>{outcome.delivered.toFixed(2)}</td>
|
||||
<td>{outcome.outstanding.toFixed(2)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
||||
@@ -115,6 +115,23 @@ describe("DeviceMonitor (plan todo 18, QA failure path - uncorroborated)", () =>
|
||||
});
|
||||
});
|
||||
|
||||
describe("DeviceMonitor (display formatting - coherence audit)", () => {
|
||||
it("formats a fractional reported reading value to 2 decimals instead of echoing its raw precision", () => {
|
||||
const gate = createCorroborationGate({ windowMs: 5 * 60_000 });
|
||||
const controller = createWaterWatchController(gate);
|
||||
|
||||
render(<DeviceMonitorView controller={controller} />);
|
||||
|
||||
act(() => {
|
||||
controller.ingest({ sensorId: "sensor-A", channel: "pH", timestamp: T0, value: 7.123456789 });
|
||||
});
|
||||
|
||||
const feed = screen.getByTestId("device-monitor-feed-pH");
|
||||
expect(feed).toHaveTextContent((7.123456789).toFixed(2));
|
||||
expect(feed).not.toHaveTextContent("7.123456789");
|
||||
});
|
||||
});
|
||||
|
||||
describe("DeviceMonitor (backend sync wiring, plan todo 4)", () => {
|
||||
beforeEach(async () => {
|
||||
indexedDB.deleteDatabase(db.name);
|
||||
|
||||
@@ -97,7 +97,7 @@ export function DeviceMonitorView({ controller }: { controller: WaterWatchContro
|
||||
{channel.feed.map((reading) => (
|
||||
<li key={`${reading.sensorId}-${reading.timestamp}`} className={styles.feedRow}>
|
||||
<span className={styles.feedSensor}>{reading.sensorId}</span>
|
||||
<span className={styles.feedValue}>{reading.value}</span>
|
||||
<span className={styles.feedValue}>{reading.value.toFixed(2)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -72,6 +72,21 @@ describe("TransactionHistory signature verification", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("TransactionHistory (display formatting - coherence audit)", () => {
|
||||
it("formats a fractional issued amount to 2 decimals instead of echoing its raw precision", async () => {
|
||||
await init();
|
||||
const accountId = toAccountId(await getPublicKey());
|
||||
const stored = await append({ type: "wallet.issue", account: accountId, amount: 42.123456 });
|
||||
const [history] = walletHistoryFor([stored], accountId);
|
||||
|
||||
render(<TransactionHistory entries={[history]} />);
|
||||
|
||||
const row = screen.getByTestId("history-entry");
|
||||
expect(row).toHaveTextContent(`+${(42.123456).toFixed(2)}`);
|
||||
expect(row).not.toHaveTextContent("42.123456");
|
||||
});
|
||||
});
|
||||
|
||||
describe("TransactionHistory backend sync wiring (plan todo 3, mount-time pull - no transfer UI exists)", () => {
|
||||
it("calls trySyncWithBackend() on mount, without altering the empty-state render", async () => {
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"));
|
||||
|
||||
@@ -12,12 +12,12 @@ type VerificationStatus = "checking" | "verified" | "failed";
|
||||
|
||||
function describe(entry: WalletHistoryEntry): { label: string; signed: string; isCredit: boolean } {
|
||||
if (entry.kind === "issued") {
|
||||
return { label: "Issued", signed: `+${entry.amount}`, isCredit: true };
|
||||
return { label: "Issued", signed: `+${entry.amount.toFixed(2)}`, isCredit: true };
|
||||
}
|
||||
if (entry.kind === "received") {
|
||||
return { label: `From ${entry.counterparty}`, signed: `+${entry.amount}`, isCredit: true };
|
||||
return { label: `From ${entry.counterparty}`, signed: `+${entry.amount.toFixed(2)}`, isCredit: true };
|
||||
}
|
||||
return { label: `To ${entry.counterparty}`, signed: `-${entry.amount}`, isCredit: false };
|
||||
return { label: `To ${entry.counterparty}`, signed: `-${entry.amount.toFixed(2)}`, isCredit: false };
|
||||
}
|
||||
|
||||
function toHex(bytes: Uint8Array): string {
|
||||
|
||||
@@ -145,3 +145,57 @@ describe("WalletCard: send credits (resident-to-resident spend)", () => {
|
||||
expect((transfers[0]!.payload as { to: string }).to).toBe("bob");
|
||||
});
|
||||
});
|
||||
|
||||
describe("WalletCard (display formatting - coherence audit)", () => {
|
||||
it("formats a fractional wallet balance to 2 decimals instead of echoing its raw precision", async () => {
|
||||
await init();
|
||||
const accountId = toAccountId(await getPublicKey());
|
||||
|
||||
// A wallet.issue amount is just a number - nothing requires it to be a
|
||||
// whole number (see Farms' real LP/GDD forecast credits and Fair
|
||||
// Draw's prize issuance, both of which can carry real fractional
|
||||
// precision).
|
||||
await append({ type: "wallet.issue", account: accountId, amount: 123.456789 });
|
||||
|
||||
render(<WalletCard />);
|
||||
|
||||
await waitFor(() => {
|
||||
const text = screen.getByTestId("wallet-balance").textContent ?? "";
|
||||
expect(text).toMatch(/^\d+\.\d\d$/);
|
||||
expect(text).toBe((123.456789).toFixed(2));
|
||||
});
|
||||
});
|
||||
|
||||
it("formats the echoed send amount and remaining-balance status messages to 2 decimals", async () => {
|
||||
await init();
|
||||
const me = toAccountId(await getPublicKey());
|
||||
await append({ type: "wallet.issue", account: me, amount: 50.987654 });
|
||||
|
||||
render(<WalletCard />);
|
||||
await screen.findByTestId("wallet-send-submit");
|
||||
// The amount input has no `step="any"`, so a real browser blocks a
|
||||
// decimal value at the native submit-time constraint-validation gate
|
||||
// when triggered by a button click; `fireEvent.submit` on the form
|
||||
// dispatches the submit event directly, exactly like
|
||||
// ResourceTiles.test.tsx's own "echoed need amount" proving test does
|
||||
// for its structurally identical input.
|
||||
const form = screen.getByTestId("wallet-send-submit").closest("form")!;
|
||||
|
||||
fireEvent.change(screen.getByTestId("wallet-send-recipient"), { target: { value: "bob" } });
|
||||
fireEvent.change(screen.getByTestId("wallet-send-amount"), { target: { value: "999" } });
|
||||
fireEvent.submit(form);
|
||||
await waitFor(() => {
|
||||
const text = screen.getByTestId("wallet-send-status").textContent ?? "";
|
||||
expect(text).toContain((50.987654).toFixed(2));
|
||||
expect(text).not.toContain("50.987654");
|
||||
});
|
||||
|
||||
fireEvent.change(screen.getByTestId("wallet-send-amount"), { target: { value: "9.123456" } });
|
||||
fireEvent.submit(form);
|
||||
await waitFor(() => {
|
||||
const text = screen.getByTestId("wallet-send-status").textContent ?? "";
|
||||
expect(text).toContain((9.123456).toFixed(2));
|
||||
expect(text).not.toContain("9.123456");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -64,12 +64,12 @@ export function WalletCard({ compact = false }: WalletCardProps = {}) {
|
||||
return;
|
||||
}
|
||||
if (amount > spendable) {
|
||||
setSendStatus(`You only have ${spendable} credits to send.`);
|
||||
setSendStatus(`You only have ${spendable.toFixed(2)} credits to send.`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await postWalletTransfer(to, amount);
|
||||
setSendStatus(`Sent ${amount} credits.`);
|
||||
setSendStatus(`Sent ${amount.toFixed(2)} credits.`);
|
||||
setRecipient("");
|
||||
setAmountInput("");
|
||||
void trySyncWithBackend();
|
||||
@@ -87,7 +87,7 @@ export function WalletCard({ compact = false }: WalletCardProps = {}) {
|
||||
<div className={styles.headerText}>
|
||||
<div className={styles.label}>Balance</div>
|
||||
<div className={styles.balance} data-testid="wallet-balance">
|
||||
{accountId === undefined ? "--" : balance === undefined ? "No balance yet" : balance}
|
||||
{accountId === undefined ? "--" : balance === undefined ? "No balance yet" : balance.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user