Fetch-request source types, glass-pane create page, date formatting (#18)

# MR: Fetch-request source types, glass-pane create page, date formatting

**Branch:** `xlsx-statement-support` → `main`
**Commits:** 1af0a6b231869d (6 commits)

## Summary

Three related strands of UI work on the fetch-request flow, plus library-level improvements in `react-openapi`:

1. **Source types** — the create form now offers Pdf / Xlsx / Csv / Email sources (spec-driven); legacy generic `file` is no longer offered for new fetch requests, and a per-request `trust_fallback` (`amount` | `balance`) can be set at creation.
2. **Create page redesign** — the flat single-column form is now two equal-height frosted "glass" panes over a subtle brand-indigo gradient backdrop: *Source & Account* (account/bank above the expanding source field) and *Window & Policy* (start/end/pipeline/trusted). Recent fetch-request rows share the same glass recipe.
3. **Date formatting** — all dates/datetimes across lists, details and display-format templates render as `"24 Aug 2026"` / `"24 Aug 2026, 09:07"` instead of raw ISO strings; datetime fields can opt into editing as a plain date picker while storing midnight.

## Changes

### react-openapi (library)
- **`src/utils/datetime.ts` (new)** — zero-dep `formatDate` / `formatDateTime` (en-IN via `Intl`). Only ISO-shaped strings are rewritten; DD-MM-YYYY expense strings and non-dates pass through untouched. Exported from the package index.
- Display wiring: `ListCellRenderer` catch-all + inline-dialog cells, `InlineRefField`, and `applyDisplayFormat` template interpolation (ISO-shaped values auto-format).
- **`x-edit-as` mechanism**: new `FieldConfig.editAs`; `DateField` renders a `date-time` field with `x-edit-as: date` as a plain date input, normalizes inbound values to `YYYY-MM-DD`, and submits `T00:00:00`. Routing sites unchanged.

### App
- `fetch-requests.models.ts`: `SourceType` gains `"csv"`, new `CsvSource`, create-side union drops `FileSource`.
- `FetchRequestCreate.tsx`: two-pane grid layout (explicit field partitioning, grid stretch for equal heights), fixed backdrop layer, local `GlassPanel` helper, list rows restyled; `created_at` pinned right before row actions.
- `ReportList.tsx`: generated date right-aligned before action buttons; outer row no longer wraps.
- `ReportViewer.tsx`: header timestamp formatted via exported `formatDateTime`.

## Verification

- `tsc -b` clean at every commit.
- Formatter behavior spot-checked: `2026-08-24T09:07:25.168000` → `24 Aug 2026, 09:07`; `01-05-2026` unchanged; `Z`-suffixed UTC converts to local wall time.

## Deploy notes

- Pairs with the khata-app MR (same branch name): backend supplies the Source oneOf (pdf/xlsx/csv/email), `trust_fallback`, and `x-edit-as` annotations consumed here.
- No dependency changes; no API changes client-side beyond honoring existing spec extensions.

Reviewed-on: #18
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
This commit is contained in:
2026-08-24 20:28:18 +00:00
committed by aetos
parent 9377460e79
commit 2dd7f64f2b
13 changed files with 280 additions and 89 deletions

View File

@@ -17,5 +17,6 @@ export { getApi } from "./src/hooks/useApi";
export { useItemSse } from "./src/hooks/useItemSse";
export { sanitizePayload } from "./src/utils/sanitize-payload";
export type { FkResolver } from "./src/utils/sanitize-payload";
export { formatDate, formatDateTime } from "./src/utils/datetime";
export type { FilterComponentProps } from "./src/context/useResource";
export type { SpecConfiguration, ResourceConfig, FieldConfig, FKFieldConfig, ResourceRelationship, ProfileOperation, ProfileComponents, AuthConfig } from "./src/types";

View File

@@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom";
import { Box, Typography, Chip, Avatar, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
import type { FieldConfig } from "../../types";
import { applyDisplayFormat, resolveMediaUrl } from "./utils";
import { formatByFieldFormat } from "../../utils/datetime";
import { InlineRefField } from "./renderers/InlineRefField";
import { CurrencyField } from "./renderers/CurrencyField";
import { extractFields } from "../../transformers/field-config";
@@ -57,7 +58,7 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
{sf.label}
</Typography>
<Typography variant="body2">
{fv == null ? "—" : typeof fv === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(fv, sf.inlineDisplayFormat) : JSON.stringify(fv)) : String(fv)}
{fv == null ? "—" : typeof fv === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(fv, sf.inlineDisplayFormat) : JSON.stringify(fv)) : formatByFieldFormat(fv, sf.format)}
</Typography>
</Box>
</Grid>
@@ -153,5 +154,5 @@ export function ListCellRenderer({ field, value, displayFormat, basePath }: List
return <Typography variant="body2">{applyDisplayFormat(value, displayFormat ?? "")}</Typography>;
}
return <Typography variant="body2">{String(value)}</Typography>;
return <Typography variant="body2">{formatByFieldFormat(value, field.format)}</Typography>;
}

View File

@@ -10,11 +10,26 @@ interface Props {
}
export function DateField({ field, value, onChange, error }: Props) {
const inputType = field.format === "date" ? "date" : "datetime-local";
// `x-edit-as: date` renders a date-time field as a plain date picker;
// the picked day is submitted as midnight so the stored type is intact.
const editAsDate = field.format === "date" || field.editAs === "date";
const normalized = field.format === "date-time" && typeof value === "string"
? value.replace(/\.\d+Z$/, "").replace(/Z$/, "")
: value;
const inputType = editAsDate ? "date" : "datetime-local";
const normalized = (() => {
if (field.format !== "date-time" || typeof value !== "string") return value;
if (editAsDate) return value.slice(0, 10);
return value.replace(/\.\d+Z$/, "").replace(/Z$/, "");
})();
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const v = e.target.value;
if (editAsDate && field.format === "date-time" && /^\d{4}-\d{2}-\d{2}$/.test(v)) {
onChange(`${v}T00:00:00`);
} else {
onChange(v);
}
};
return (
<TextField
@@ -22,7 +37,7 @@ export function DateField({ field, value, onChange, error }: Props) {
label={field.label}
type={inputType}
value={normalized ?? ""}
onChange={(e) => onChange(e.target.value)}
onChange={handleChange}
error={!!error}
helperText={error || field.description || undefined}
placeholder={field.description || undefined}

View File

@@ -2,6 +2,7 @@ import React, { useState } from "react";
import { Box, Typography, Chip, Dialog, DialogTitle, DialogContent, DialogActions, Button, Grid } from "@mui/material";
import type { FieldConfig } from "../../../types";
import { applyDisplayFormat } from "../utils";
import { formatByFieldFormat } from "../../../utils/datetime";
import { extractFields } from "../../../transformers/field-config";
import { useAppContext } from "../../../context/AppContext";
@@ -68,7 +69,7 @@ export function InlineRefField({ field, value }: Props) {
<Typography variant="caption" color="text.secondary" fontWeight={600} sx={{ mb: 0.25, display: "block" }}>
{sf.label}
</Typography>
<Typography variant="body2">{value?.[sf.name] == null ? "—" : typeof value[sf.name] === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(value[sf.name], sf.inlineDisplayFormat) : JSON.stringify(value[sf.name])) : String(value[sf.name])}</Typography>
<Typography variant="body2">{value?.[sf.name] == null ? "—" : typeof value[sf.name] === "object" ? (sf.inlineDisplayFormat ? applyDisplayFormat(value[sf.name], sf.inlineDisplayFormat) : JSON.stringify(value[sf.name])) : formatByFieldFormat(value[sf.name], sf.format)}</Typography>
</Box>
</Grid>
))}

View File

@@ -1,3 +1,5 @@
import { formatIsoLike } from "../../utils/datetime";
function getNested(obj: any, path: string): any {
return path.split(".").reduce((o, k) => o?.[k], obj);
}
@@ -6,7 +8,7 @@ export function applyDisplayFormat(item: any, format: string): string {
if (!item || typeof item !== "object") return String(item ?? "");
return format.replace(/\{([\w.]+)\}/g, (_, key) => {
const val = getNested(item, key);
return val != null ? String(val) : "";
return val != null ? formatIsoLike(val) : "";
});
}

View File

@@ -64,6 +64,7 @@ function extractOneOfOptions(schema: any, schemas: Record<string, any>, discrimi
description: prop["x-description"] ?? "",
type: prop.type ?? "string",
format: prop.format,
editAs: prop["x-edit-as"],
order: prop["x-order"] ?? Infinity,
hidden: prop["x-hidden"] ?? {},
filterable: prop["x-filterable"] ?? false,
@@ -130,6 +131,7 @@ export function extractFields(schemaName: string, schema: any, schemas: Record<s
description: prop["x-description"] ?? "",
type: isRef && refSchema ? "object" : isOneOf ? "object" : (prop.type ?? "string"),
format: prop.format,
editAs: prop["x-edit-as"],
order: prop["x-order"] ?? Infinity,
hidden: prop["x-hidden"] ?? {},
filterable: prop["x-filterable"] ?? false,

View File

@@ -101,6 +101,8 @@ export interface FieldConfig {
description: string;
type: string;
format?: string;
/** `x-edit-as: date` — edit a `date-time` field with a plain date input; submits midnight. */
editAs?: string;
order: number;
hidden: { form?: boolean; list?: boolean; detail?: boolean };
filterable: boolean;

View File

@@ -0,0 +1,63 @@
/**
* Zero-dependency date/time display helpers.
*
* Only ISO-shaped strings ("2026-08-24", "2026-08-24T09:07:25[.f][Z]") are
* reformatted; anything else (DD-MM-YYYY expense strings, free text) passes
* through untouched. Naive strings without a zone are parsed as clock time
* so the displayed wall time matches what the backend stored.
*/
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
function parseIso(value: any): Date | null {
if (typeof value !== "string") return null;
if (!ISO_DATE.test(value) && !ISO_DATETIME.test(value)) return null;
const d = new Date(value);
return isNaN(d.getTime()) ? null : d;
}
const DATE_FMT = new Intl.DateTimeFormat("en-IN", { day: "numeric", month: "short", year: "numeric" });
const DATETIME_FMT = new Intl.DateTimeFormat("en-IN", {
day: "numeric",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
function fallback(value: any): string {
return typeof value === "string" ? value : value != null ? String(value) : "";
}
/** "2026-08-24" -> "24 Aug 2026"; non-ISO values pass through. */
export function formatDate(value: any): string {
const d = parseIso(value);
return d ? DATE_FMT.format(d) : fallback(value);
}
/** "2026-08-24T09:07:25" -> "24 Aug 2026, 09:07"; non-ISO values pass through. */
export function formatDateTime(value: any): string {
const d = parseIso(value);
return d ? DATETIME_FMT.format(d) : fallback(value);
}
/** Route by OpenAPI field format ("date" | "date-time"); other formats render plainly. */
export function formatByFieldFormat(value: any, format?: string): string {
if (format === "date") return formatDate(value);
if (format === "date-time") return formatDateTime(value);
return fallback(value);
}
/**
* Metadata-free variant for display-format templates ({key} interpolation):
* reformats a scalar only when it happens to be ISO-shaped.
*/
export function formatIsoLike(value: any): string {
if (typeof value === "string") {
if (ISO_DATETIME.test(value)) return formatDateTime(value);
if (ISO_DATE.test(value)) return formatDate(value);
}
return fallback(value);
}