Reports frontend — spec-driven generate form, sliceable viewer, dimension bars (#16)
# 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>
This commit is contained in:
@@ -5,7 +5,12 @@ export { useAppContext } from "./src/context/AppContext";
|
||||
export { useResource } from "./src/context/useResource";
|
||||
export { ListCellRenderer, DetailFieldRenderer, applyDisplayFormat } from "./src/components/fields";
|
||||
export { FormFieldRenderer } from "./src/components/fields/FormFieldRenderer";
|
||||
export { MultiEnumField } from "./src/components/fields/renderers/MultiEnumField";
|
||||
export { extractFields } from "./src/transformers/field-config";
|
||||
export { useFkFieldOptions } from "./src/hooks/useFkFieldOptions";
|
||||
export type { FkOption } from "./src/hooks/useFkFieldOptions";
|
||||
export { CurrencyField, formatCurrency } from "./src/components/fields/renderers/CurrencyField";
|
||||
export { FkMultiSelectField } from "./src/components/fields/renderers/FkMultiSelectField";
|
||||
export { SseStreamView } from "./src/components/SseStreamView";
|
||||
export { SseConnectionStatus } from "./src/components/SseConnectionStatus";
|
||||
export { getApi } from "./src/hooks/useApi";
|
||||
|
||||
@@ -6,6 +6,7 @@ import { NumberField } from "./renderers/NumberField";
|
||||
import { DateField } from "./renderers/DateField";
|
||||
import { BooleanField } from "./renderers/BooleanField";
|
||||
import { EnumField } from "./renderers/EnumField";
|
||||
import { MultiEnumField } from "./renderers/MultiEnumField";
|
||||
import { FkSelectField } from "./renderers/FkSelectField";
|
||||
import { FkMultiSelectField } from "./renderers/FkMultiSelectField";
|
||||
import { FileUploadField } from "./renderers/FileUploadField";
|
||||
@@ -81,6 +82,17 @@ export function FormFieldRenderer({ field, value, onChange, error, fkOptions, fk
|
||||
);
|
||||
}
|
||||
|
||||
if (field.isArray && field.enumValues) {
|
||||
return (
|
||||
<MultiEnumField
|
||||
field={field}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
error={error}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (field.enumValues) {
|
||||
return (
|
||||
<EnumField
|
||||
|
||||
@@ -3,4 +3,5 @@ export { ListCellRenderer } from "./ListCellRenderer";
|
||||
export { DetailFieldRenderer } from "./DetailFieldRenderer";
|
||||
export { applyDisplayFormat } from "./utils";
|
||||
export { JsonField } from "./renderers/JsonField";
|
||||
export { MultiEnumField } from "./renderers/MultiEnumField";
|
||||
export { CurrencyField, formatCurrency } from "./renderers/CurrencyField";
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import React from "react";
|
||||
import { Autocomplete, TextField, Chip, Box } from "@mui/material";
|
||||
import DoneIcon from "@mui/icons-material/Done";
|
||||
import type { FieldConfig } from "../../../types";
|
||||
|
||||
interface Props {
|
||||
field: FieldConfig;
|
||||
value: any;
|
||||
onChange: (value: any[]) => void;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function MultiEnumField({ field, value, onChange, error }: Props) {
|
||||
const selected: string[] = Array.isArray(value) ? value : [];
|
||||
|
||||
return (
|
||||
<Autocomplete
|
||||
multiple
|
||||
disableCloseOnSelect
|
||||
size="small"
|
||||
options={field.enumValues ?? []}
|
||||
value={selected}
|
||||
onChange={(_, newVal) => onChange(newVal)}
|
||||
renderOption={(props, option, { selected: isSelected }) => {
|
||||
const { key, ...rest } = props as any;
|
||||
return (
|
||||
<li key={key} {...rest}>
|
||||
{isSelected ? (
|
||||
<DoneIcon sx={{ fontSize: 14, mr: 1, color: "primary.main" }} />
|
||||
) : (
|
||||
<Box sx={{ width: 22, mr: 1 }} />
|
||||
)}
|
||||
{option}
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
renderTags={(tagValue, getTagProps) =>
|
||||
tagValue.map((tag, index) => {
|
||||
const { key, ...tagProps } = getTagProps({ index });
|
||||
return <Chip key={key} {...tagProps} label={tag} size="small" />;
|
||||
})
|
||||
}
|
||||
renderInput={(params) => (
|
||||
<TextField
|
||||
{...params}
|
||||
label={field.label}
|
||||
placeholder={field.description || undefined}
|
||||
error={!!error}
|
||||
helperText={error || field.description || undefined}
|
||||
size="small"
|
||||
/>
|
||||
)}
|
||||
sx={{
|
||||
"& .MuiAutocomplete-popupIndicator, & .MuiAutocomplete-clearIndicator": { width: 20, height: 20, fontSize: 16 },
|
||||
}}
|
||||
disabled={field.readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,24 @@ import axios, { AxiosInstance } from "axios";
|
||||
let apiClient: AxiosInstance | null = null;
|
||||
let _onUnauthorized: (() => void) | undefined;
|
||||
|
||||
function serializeParams(params: Record<string, any>): string {
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(params ?? {})) {
|
||||
if (value === undefined || value === null) continue;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) searchParams.append(key, String(item));
|
||||
} else if (typeof value === "object") {
|
||||
for (const [nestedKey, nestedValue] of Object.entries(value)) {
|
||||
if (nestedValue === undefined || nestedValue === null) continue;
|
||||
searchParams.append(`${key}[${nestedKey}]`, String(nestedValue));
|
||||
}
|
||||
} else {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
}
|
||||
return searchParams.toString();
|
||||
}
|
||||
|
||||
export function initApi(baseUrl: string, getToken?: () => string | null, onUnauthorized?: () => void): AxiosInstance {
|
||||
if (apiClient && apiClient.defaults.baseURL === baseUrl) {
|
||||
_onUnauthorized = onUnauthorized;
|
||||
@@ -14,6 +32,7 @@ export function initApi(baseUrl: string, getToken?: () => string | null, onUnaut
|
||||
apiClient = axios.create({
|
||||
baseURL: baseUrl,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
paramsSerializer: serializeParams,
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
|
||||
82
react-openapi/src/hooks/useFkFieldOptions.ts
Normal file
82
react-openapi/src/hooks/useFkFieldOptions.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
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 };
|
||||
}
|
||||
@@ -136,7 +136,10 @@ export function extractFields(schemaName: string, schema: any, schemas: Record<s
|
||||
sortable: prop["x-sortable"] ?? false,
|
||||
readOnly: prop.readOnly ?? false,
|
||||
required: requiredFields.includes(name),
|
||||
enumValues: prop.enum,
|
||||
// Lift enum constraints from array items so arrays-of-enum can render
|
||||
// as multi-selects (e.g. ReportQuery.granularities).
|
||||
enumValues: prop.enum ?? (prop.type === "array" ? prop.items?.enum : undefined),
|
||||
defaultValue: prop.default,
|
||||
fk: prop["x-fk"],
|
||||
uiType: prop["x-ui-type"],
|
||||
uploadUrl: prop["x-upload-url"],
|
||||
|
||||
@@ -85,6 +85,8 @@ export interface ResourceConfig {
|
||||
export interface FKFieldConfig {
|
||||
resource: string;
|
||||
prefetch: boolean;
|
||||
/** Target property used as the wire value (defaults to the target's primary key). */
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export interface OneOfOption {
|
||||
@@ -106,6 +108,8 @@ export interface FieldConfig {
|
||||
readOnly: boolean;
|
||||
required: boolean;
|
||||
enumValues?: string[];
|
||||
/** Schema-level `default` used to seed create-form state. */
|
||||
defaultValue?: any;
|
||||
fk?: FKFieldConfig;
|
||||
uiType?: string;
|
||||
uploadUrl?: string;
|
||||
|
||||
@@ -29,7 +29,9 @@ export async function sanitizePayload(
|
||||
|
||||
const val = result[key];
|
||||
|
||||
if (field.fk) {
|
||||
// FK fields whose wire value is a plain target property (fk.value, e.g.
|
||||
// account names) are already in wire format — no id→object resolution.
|
||||
if (field.fk && !field.fk.value) {
|
||||
if (val == null || val === "") {
|
||||
result[key] = null;
|
||||
} else if (resolveFk) {
|
||||
|
||||
Reference in New Issue
Block a user