# MR: Reports frontend — spec-driven generate form, sliceable viewer, dimension bars
**Branch:** `cached-reporting` → **Target:** `main`
## Summary
Reports UI rebuilt to treat the backend OpenAPI spec as the source of truth: the
generate-report form renders generically from `ReportQuery`, and the viewer displays
API-computed metrics verbatim instead of recomputing them client-side.
## Changes
### react-openapi (library)
- `MultiEnumField` renderer for array-of-enum fields; dispatch branch in
`FormFieldRenderer`
- `useFkFieldOptions` hook + `FKFieldConfig.value` (FK options keyed by a non-PK
field — accounts resolve by `name`)
- `FieldConfig.defaultValue` seeding in `extractFields`; enum lift for
`items.enum` arrays; sanitize-payload bypasses FK resolution when `fk.value` is set
### Reports page
- **GenerateReportPanel**: rewritten (~275 → ~110 lines) — fields extracted from the
served `ReportQuery` schema (labels, order, defaults, multi-enum, account picker);
server-side validation only
- **ReportViewer**:
- Period groups built from cube buckets keyed by canonical `period_id`; buckets
merged per period (disjoint slices), txn ids deduped
- Cards/bars/metric strips read `metrics` verbatim (outflows/inflows/sum/count/
avg/min/max/cadence/frequency); Net = one subtraction at render
- Dimension-switchable bar strip (Period / Payees / Tags): segmented pill control
with sliding indicator; pills disabled when the report has ≤1 distinct value;
top-10 bars in a fixed view paged by chevrons (hidden scrollbar)
- Active dim requests the full distribution via `payee=*` / `tags=*` when its own
filter is unselected; explicit selections always slice normally
- **TransactionList**: shared component with optional `groups` prop (API periods +
metrics) used by the viewer; Expense page keeps the client-side fallback path;
group strip shows Sum · Avg · Min · Max · Cadence (or Frequency /day when
cadence < 1)
### Fixes
- Strict DD-MM-YYYY parsing (`parseOccurredAt`) in period merges and date ordering —
`new Date()` mis-read dates as MM-DD-YYYY and corrupted merged cadence
(Aug Zomato: 12.89 days displayed vs 0.76 actual)
- Bar widths magnitude-based so all-outflow slices render at proper width
Reviewed-on: #16
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
83 lines
2.8 KiB
TypeScript
83 lines
2.8 KiB
TypeScript
import { useCallback, useEffect, useState } from "react";
|
|
import type { FieldConfig, FKFieldConfig } from "../types";
|
|
import { useAppContext } from "../context/AppContext";
|
|
import { getApi } from "./useApi";
|
|
|
|
export interface FkOption {
|
|
value: any;
|
|
label: string;
|
|
}
|
|
|
|
function applyFormat(obj: any, format: string): string {
|
|
if (!obj || typeof obj !== "object") return String(obj ?? "");
|
|
return format.replace(/\{(\w+)\}/g, (_, key) => String(obj[key] ?? ""));
|
|
}
|
|
|
|
/**
|
|
* Loads select options for FK-annotated fields of a field set.
|
|
* Option values bind to `fk.value` when set (e.g. account names),
|
|
* otherwise to the target resource's primary key.
|
|
*/
|
|
export function useFkFieldOptions(fields: FieldConfig[]) {
|
|
const { resources } = useAppContext();
|
|
const [fkOptions, setFkOptions] = useState<Record<string, FkOption[]>>({});
|
|
const [fkLoading, setFkLoading] = useState<Record<string, boolean>>({});
|
|
|
|
const loadFkOptions = useCallback(
|
|
async (fieldName: string, fk: FKFieldConfig) => {
|
|
setFkLoading((prev) => ({ ...prev, [fieldName]: true }));
|
|
try {
|
|
const targetRes = resources.find((r) => r.name === fk.resource);
|
|
if (!targetRes) return;
|
|
|
|
const api = getApi();
|
|
const params: Record<string, any> = {};
|
|
if (targetRes.pagination) params.limit = 0;
|
|
const res = await api.get(targetRes.path, { params });
|
|
|
|
let items: any[];
|
|
if (targetRes.pagination) {
|
|
if (!res.data || typeof res.data !== "object" || !Array.isArray(res.data.items)) {
|
|
throw new Error(`Expected paginated response from ${targetRes.path}`);
|
|
}
|
|
items = res.data.items;
|
|
} else {
|
|
if (!Array.isArray(res.data)) {
|
|
throw new Error(`Expected array response from ${targetRes.path}`);
|
|
}
|
|
items = res.data;
|
|
}
|
|
|
|
const opts: FkOption[] = items.map((item: any) => ({
|
|
value: item[fk.value ?? targetRes.primaryKey],
|
|
label: applyFormat(item, targetRes.displayFormat),
|
|
}));
|
|
setFkOptions((prev) => ({ ...prev, [fieldName]: opts }));
|
|
} catch {
|
|
// leave options empty; the field renders without suggestions
|
|
} finally {
|
|
setFkLoading((prev) => ({ ...prev, [fieldName]: false }));
|
|
}
|
|
},
|
|
[resources]
|
|
);
|
|
|
|
useEffect(() => {
|
|
fields.forEach((f) => {
|
|
if (f.fk?.prefetch) loadFkOptions(f.name, f.fk);
|
|
});
|
|
}, [fields, loadFkOptions]);
|
|
|
|
const loadFkOnOpen = useCallback(
|
|
(fieldName: string) => {
|
|
const field = fields.find((f) => f.name === fieldName);
|
|
if (field?.fk && !field.fk.prefetch && !fkOptions[fieldName]) {
|
|
loadFkOptions(fieldName, field.fk);
|
|
}
|
|
},
|
|
[fields, fkOptions, loadFkOptions]
|
|
);
|
|
|
|
return { fkOptions, fkLoading, loadFkOnOpen };
|
|
}
|