frontend: make AI proposal cards editable and de-densify them

The single proposal card crammed every proposed record into comma-joined
summary lines — an inventory import became an unreadable wall of text.
Render inventory/invoice records as a compact scrollable item list, and
add an Edit button (single card + per-row in the batch review) that opens
a per-kind edit dialog so the clinician can adjust the data — whole record
or individual items — before it is committed.

New RecordEditDialog is schema-driven (EDIT_SCHEMAS) per action kind,
including add/remove rows for invoice line items and inventory items.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Khalid Abdi
2026-06-18 19:51:24 +03:00
parent a06c8c739b
commit 9a913147fb
4 changed files with 507 additions and 19 deletions
+132 -15
View File
@@ -6,6 +6,7 @@ import {
CalendarPlus,
Check,
ClipboardList,
Pencil,
Pill,
Receipt,
X,
@@ -13,9 +14,10 @@ import {
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { RecordEditDialog } from "@/components/chat/record-edit-dialog";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import type { ActionPreviewData } from "@/lib/ai-chat";
import type { ActionPreviewData, ActionPreviewKind } from "@/lib/ai-chat";
import { type AppointmentInput, createAppointment } from "@/lib/appointments";
import {
createInvoice,
@@ -110,20 +112,123 @@ export async function commitAction(data: ActionPreviewData): Promise<void> {
}
}
// A structured, de-densified view of a proposed record. Inventory and invoice
// records carry an item array — rendered as a compact scrollable list (one row
// per item) rather than a single comma-joined wall of text; everything else
// uses the per-kind summary lines.
export function RecordSummary({
kind,
record,
}: {
kind: ActionPreviewKind;
record: Record<string, unknown>;
}) {
const { t } = useTranslation();
if (kind === "inventory") {
const items = (record.items as InventoryInput[] | undefined) ?? [];
return (
<div className="flex flex-col gap-2">
<p className="text-muted-foreground text-xs">
{t("chat.actionCard.itemCount", { count: items.length })}
</p>
<ul className="max-h-48 divide-y divide-border overflow-y-auto rounded-lg border bg-card/30">
{items.map((it, i) => (
<li
className="flex items-center gap-2 px-3 py-1.5 text-sm"
key={`${it.name}-${i}`}
>
<span className="min-w-0 flex-1 truncate text-foreground">
{it.name}
{it.strength ? (
<span className="text-muted-foreground"> · {it.strength}</span>
) : null}
</span>
{it.stockQuantity != null ? (
<span className="shrink-0 tabular-nums text-muted-foreground">
×{it.stockQuantity}
</span>
) : null}
</li>
))}
</ul>
</div>
);
}
if (kind === "invoice") {
const items = (record.lineItems as InvoiceLineItem[] | undefined) ?? [];
const total = items.reduce((s, li) => s + li.quantity * li.unitPrice, 0);
return (
<div className="flex flex-col gap-2">
{record.name ? (
<p className="font-medium text-foreground text-sm">
{String(record.name)}
</p>
) : null}
<ul className="max-h-48 divide-y divide-border overflow-y-auto rounded-lg border bg-card/30">
{items.map((li, i) => (
<li
className="flex items-center gap-2 px-3 py-1.5 text-sm"
key={`${li.description}-${i}`}
>
<span className="min-w-0 flex-1 truncate text-foreground">
{li.description}
<span className="text-muted-foreground"> ×{li.quantity}</span>
</span>
<span className="shrink-0 tabular-nums text-muted-foreground">
{formatMoney(li.quantity * li.unitPrice)}
</span>
</li>
))}
</ul>
<p className="flex items-center justify-between text-sm">
<span className="text-muted-foreground">
{t("chat.actionCard.total")}
</span>
<span className="font-medium tabular-nums text-foreground">
{formatMoney(total)}
</span>
</p>
</div>
);
}
const lines = summarize({ kind, record } as ActionPreviewData);
return (
<div className="space-y-0.5 text-sm">
{lines.map((line, i) => (
<p
className={
i === 0 ? "font-medium text-foreground" : "text-muted-foreground"
}
key={line + i}
>
{line}
</p>
))}
</div>
);
}
// The human approval gate for an agent-proposed add. The agent drafts the record
// (dry run, nothing written); the clinician reviews it here and must approve
// before it is committed via the matching RBAC-gated create endpoint.
// (dry run, nothing written); the clinician reviews it here, may edit it, and
// must approve before it is committed via the matching RBAC-gated create endpoint.
export function ActionPreviewCard({ data }: { data: ActionPreviewData }) {
const { t } = useTranslation();
const [status, setStatus] = useState<Status>("pending");
// Editable working copy of the proposed record (edits commit, not the draft).
const [record, setRecord] = useState<Record<string, unknown>>(
data.record as Record<string, unknown>,
);
const [editOpen, setEditOpen] = useState(false);
const Icon = ICONS[data.kind];
const hasIssues = (data.issues?.length ?? 0) > 0;
const lines = summarize(data);
const approve = async () => {
setStatus("committing");
try {
await commitAction(data);
await commitAction({ ...data, record });
setStatus("done");
notify.success(
t("chat.actionCard.addedTitle"),
@@ -138,6 +243,8 @@ export function ActionPreviewCard({ data }: { data: ActionPreviewData }) {
}
};
const editable = status === "pending";
return (
<Card className="w-full gap-3 p-4">
<div className="flex items-center gap-2">
@@ -145,18 +252,20 @@ export function ActionPreviewCard({ data }: { data: ActionPreviewData }) {
<span className="font-medium text-sm">
{t(`chat.actionCard.title.${data.kind}`)}
</span>
{editable ? (
<Button
className="ml-auto"
onClick={() => setEditOpen(true)}
size="sm"
variant="ghost"
>
<Pencil className="size-3.5" />
{t("chat.actionCard.editButton")}
</Button>
) : null}
</div>
<div className="space-y-0.5 text-sm">
{lines.map((line, i) => (
<p
className={i === 0 ? "font-medium text-foreground" : "text-muted-foreground"}
key={line + i}
>
{line}
</p>
))}
</div>
<RecordSummary kind={data.kind} record={record} />
{hasIssues ? (
<ul className="space-y-1 rounded-lg bg-muted/50 p-3 text-muted-foreground text-xs">
@@ -200,6 +309,14 @@ export function ActionPreviewCard({ data }: { data: ActionPreviewData }) {
</Button>
</div>
)}
<RecordEditDialog
kind={data.kind}
onOpenChange={setEditOpen}
onSave={setRecord}
open={editOpen}
record={record}
/>
</Card>
);
}
@@ -1,6 +1,6 @@
"use client";
import { AlertTriangle, Check, Sparkles, X } from "lucide-react";
import { AlertTriangle, Check, Pencil, Sparkles, X } from "lucide-react";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -9,6 +9,7 @@ import {
commitAction,
summarize,
} from "@/components/chat/action-preview-card";
import { RecordEditDialog } from "@/components/chat/record-edit-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -39,6 +40,16 @@ export function BatchActionPreviewCard({ items }: { items: ActionPreviewData[] }
const [result, setResult] = useState<{ added: number; failed: number } | null>(
null,
);
// Per-row edits, keyed by token. The committed record is the edit if present,
// otherwise the agent's original proposal.
const [edits, setEdits] = useState<Record<string, Record<string, unknown>>>(
{},
);
// The row currently open in the edit dialog.
const [editing, setEditing] = useState<ActionPreviewData | null>(null);
const recordFor = (it: ActionPreviewData) =>
edits[it.token] ?? (it.record as Record<string, unknown>);
const kept = useMemo(
() => items.filter((it) => !removed.has(it.token)),
@@ -54,7 +65,7 @@ export function BatchActionPreviewCard({ items }: { items: ActionPreviewData[] }
// Sequential so server-side patient de-dup (by name) sees prior creates.
for (const it of kept) {
try {
await commitAction(it);
await commitAction({ ...it, record: recordFor(it) });
added += 1;
} catch {
failed += 1;
@@ -137,10 +148,11 @@ export function BatchActionPreviewCard({ items }: { items: ActionPreviewData[] }
</p>
) : (
kept.map((it) => {
const lines = summarize(it);
const record = it.record as Record<string, unknown>;
const record = recordFor(it);
const lines = summarize({ ...it, record });
const newPatient =
it.kind === "appointment" && !record.fileNumber;
const edited = it.token in edits;
return (
<div
className="flex items-start gap-2 rounded-xl border bg-card/30 p-3"
@@ -159,6 +171,12 @@ export function BatchActionPreviewCard({ items }: { items: ActionPreviewData[] }
{line}
</span>
))}
{edited ? (
<span className="mt-1 inline-flex items-center gap-1 text-[11px] text-muted-foreground">
<Pencil className="size-3" />
{t("chat.actionCard.batch.edited")}
</span>
) : null}
{newPatient ? (
<span className="mt-1 inline-flex items-center gap-1 text-[11px] text-muted-foreground">
<Sparkles className="size-3" />
@@ -172,6 +190,15 @@ export function BatchActionPreviewCard({ items }: { items: ActionPreviewData[] }
</span>
) : null}
</div>
<Button
aria-label={t("chat.actionCard.editButton")}
className="shrink-0"
onClick={() => setEditing({ ...it, record })}
size="icon"
variant="ghost"
>
<Pencil className="size-4" />
</Button>
<Button
aria-label={t("chat.actionCard.batch.remove")}
className="shrink-0"
@@ -205,6 +232,20 @@ export function BatchActionPreviewCard({ items }: { items: ActionPreviewData[] }
</DialogFooter>
</DialogPopup>
</Dialog>
{editing ? (
<RecordEditDialog
kind={editing.kind}
onOpenChange={(o) => {
if (!o) setEditing(null);
}}
onSave={(record) =>
setEdits((prev) => ({ ...prev, [editing.token]: record }))
}
open={editing !== null}
record={editing.record as Record<string, unknown>}
/>
) : null}
</Card>
);
}
@@ -0,0 +1,295 @@
"use client";
// Lets a clinician edit an AI-proposed record before it is committed. Driven by
// a small per-kind schema (EDIT_SCHEMAS) so every action kind — appointment,
// task, prescription, invoice, inventory — gets the right fields, including
// array fields (invoice line items, inventory items) edited as add/remove rows.
import { Plus, X } from "lucide-react";
import { type ReactNode, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import type { ActionPreviewKind } from "@/lib/ai-chat";
import { cn } from "@/lib/utils";
type FieldType = "text" | "number" | "select";
type FieldDef = {
key: string;
labelKey: string;
type?: FieldType;
// For select fields: option values + an i18n key prefix resolved as `${prefix}.${value}`.
options?: { value: string; labelPrefix: string }[];
};
type ListDef = {
key: string;
labelKey: string;
itemFields: FieldDef[];
blank: Record<string, unknown>;
};
type KindSchema = { fields: FieldDef[]; list?: ListDef };
const controlClass =
"h-9 w-full rounded-3xl border border-transparent bg-input/50 px-3 text-sm text-foreground outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30";
const PRIORITY_OPTIONS = [
{ value: "high", labelPrefix: "tasks.priority" },
{ value: "medium", labelPrefix: "tasks.priority" },
{ value: "low", labelPrefix: "tasks.priority" },
];
export const EDIT_SCHEMAS: Record<ActionPreviewKind, KindSchema> = {
appointment: {
fields: [
{ key: "name", labelKey: "chat.actionCard.fields.name" },
{ key: "date", labelKey: "chat.actionCard.fields.date" },
{ key: "time", labelKey: "chat.actionCard.fields.time" },
{ key: "type", labelKey: "chat.actionCard.fields.type" },
{ key: "provider", labelKey: "chat.actionCard.fields.provider" },
],
},
task: {
fields: [
{ key: "title", labelKey: "chat.actionCard.fields.title" },
{ key: "assignee", labelKey: "chat.actionCard.fields.assignee" },
{ key: "due", labelKey: "chat.actionCard.fields.due" },
{
key: "priority",
labelKey: "chat.actionCard.fields.priority",
type: "select",
options: PRIORITY_OPTIONS,
},
{ key: "patient", labelKey: "chat.actionCard.fields.patient" },
],
},
prescription: {
fields: [
{ key: "medication", labelKey: "chat.actionCard.fields.medication" },
{ key: "dose", labelKey: "chat.actionCard.fields.dose" },
{ key: "frequency", labelKey: "chat.actionCard.fields.frequency" },
{ key: "duration", labelKey: "chat.actionCard.fields.duration" },
{ key: "name", labelKey: "chat.actionCard.fields.name" },
],
},
invoice: {
fields: [{ key: "name", labelKey: "chat.actionCard.fields.name" }],
list: {
key: "lineItems",
labelKey: "chat.actionCard.fields.lineItems",
itemFields: [
{ key: "description", labelKey: "chat.actionCard.fields.description" },
{
key: "quantity",
labelKey: "chat.actionCard.fields.quantity",
type: "number",
},
{
key: "unitPrice",
labelKey: "chat.actionCard.fields.unitPrice",
type: "number",
},
],
blank: { description: "", quantity: 1, unitPrice: 0 },
},
},
inventory: {
fields: [],
list: {
key: "items",
labelKey: "chat.actionCard.fields.items",
itemFields: [
{ key: "name", labelKey: "chat.actionCard.fields.itemName" },
{ key: "strength", labelKey: "chat.actionCard.fields.strength" },
{
key: "stockQuantity",
labelKey: "chat.actionCard.fields.stockQuantity",
type: "number",
},
],
blank: { name: "", strength: "", stockQuantity: 0 },
},
},
};
type Rec = Record<string, unknown>;
function FieldInput({
field,
value,
onChange,
}: {
field: FieldDef;
value: unknown;
onChange: (value: unknown) => void;
}) {
const { t } = useTranslation();
if (field.type === "select" && field.options) {
return (
<select
aria-label={t(field.labelKey)}
className={controlClass}
onChange={(e) => onChange(e.target.value)}
value={String(value ?? "")}
>
{field.options.map((o) => (
<option key={o.value} value={o.value}>
{t(`${o.labelPrefix}.${o.value}`)}
</option>
))}
</select>
);
}
return (
<Input
aria-label={t(field.labelKey)}
inputMode={field.type === "number" ? "numeric" : undefined}
onChange={(e) =>
onChange(
field.type === "number"
? e.target.value === ""
? ""
: Number(e.target.value)
: e.target.value,
)
}
value={value === null || value === undefined ? "" : String(value)}
/>
);
}
function Labelled({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="flex flex-col gap-1.5">
<span className="text-muted-foreground text-xs">{label}</span>
{children}
</label>
);
}
export function RecordEditDialog({
kind,
record,
open,
onOpenChange,
onSave,
}: {
kind: ActionPreviewKind;
record: Rec;
open: boolean;
onOpenChange: (open: boolean) => void;
onSave: (record: Rec) => void;
}) {
const { t } = useTranslation();
const schema = EDIT_SCHEMAS[kind];
const [draft, setDraft] = useState<Rec>(record);
// Re-seed the draft whenever a fresh record is opened for editing.
useEffect(() => {
if (open) setDraft(record);
}, [open, record]);
const setField = (key: string, value: unknown) =>
setDraft((d) => ({ ...d, [key]: value }));
const list = schema.list;
const listRows = (list ? (draft[list.key] as Rec[] | undefined) : undefined) ?? [];
const setRows = (rows: Rec[]) => list && setField(list.key, rows);
const save = () => {
onSave(draft);
onOpenChange(false);
};
return (
<Dialog onOpenChange={onOpenChange} open={open}>
<DialogPopup className="max-h-[85dvh] sm:max-w-lg">
<DialogHeader>
<DialogTitle>{t("chat.actionCard.edit.title")}</DialogTitle>
</DialogHeader>
<DialogPanel className="no-scrollbar flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto">
{schema.fields.map((field) => (
<Labelled key={field.key} label={t(field.labelKey)}>
<FieldInput
field={field}
onChange={(v) => setField(field.key, v)}
value={draft[field.key]}
/>
</Labelled>
))}
{list && (
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{t(list.labelKey)}
</span>
<Button
onClick={() => setRows([...listRows, { ...list.blank }])}
size="sm"
type="button"
variant="ghost"
>
<Plus className="size-4" />
{t("chat.actionCard.edit.addRow")}
</Button>
</div>
{listRows.map((row, index) => (
<div className="flex items-center gap-2" key={index}>
{list.itemFields.map((field) => (
<FieldInput
field={field}
key={field.key}
onChange={(v) =>
setRows(
listRows.map((r, i) =>
i === index ? { ...r, [field.key]: v } : r,
),
)
}
value={row[field.key]}
/>
))}
<button
aria-label={t("chat.actionCard.edit.removeRow")}
className={cn(
"shrink-0 text-muted-foreground transition-colors hover:text-foreground",
)}
onClick={() =>
setRows(listRows.filter((_, i) => i !== index))
}
type="button"
>
<X className="size-4" />
</button>
</div>
))}
</div>
)}
</DialogPanel>
<DialogFooter>
<DialogClose render={<Button type="button" variant="outline" />}>
{t("chat.actionCard.edit.cancel")}
</DialogClose>
<Button onClick={save} type="button">
{t("chat.actionCard.edit.save")}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
@@ -970,6 +970,40 @@
"inventory": "Inventory updated."
},
"inventoryItems": "{{count}} item(s)",
"itemCount": "{{count}} item(s)",
"total": "Total",
"editButton": "Edit",
"edit": {
"title": "Edit proposed record",
"save": "Save changes",
"cancel": "Cancel",
"addRow": "Add",
"removeRow": "Remove row"
},
"fields": {
"name": "Patient name",
"date": "Date",
"time": "Time",
"type": "Type",
"provider": "Provider",
"title": "Title",
"assignee": "Assignee",
"due": "Due",
"priority": "Priority",
"patient": "Patient",
"medication": "Medication",
"dose": "Dose",
"frequency": "Frequency",
"duration": "Duration",
"lineItems": "Line items",
"description": "Description",
"quantity": "Qty",
"unitPrice": "Unit price",
"items": "Items",
"itemName": "Name",
"strength": "Strength",
"stockQuantity": "Quantity"
},
"approve": "Add",
"adding": "Adding…",
"discard": "Discard",
@@ -987,6 +1021,7 @@
"adding": "Adding…",
"discardAll": "Discard all",
"newPatient": "New patient will be created",
"edited": "Edited",
"remove": "Remove",
"done": "Added {{added}} of {{total}}.",
"failedCount": "{{count}} failed",