Invoices: make the machine picker searchable
Booking a line meant scrolling a native <select> of 44 machines, where two dozen near-identical "CASE TLB" entries sit next to each other. A native select cannot be filtered, so finding TLB07 meant scrolling past most of the list. Replaced with a combobox that filters as you type, on the code, the name or the category, and says how many of 44 machines matched. Still behaves like a select rather than a text box: opening it, Up/Down to move, Enter to choose, Escape to cancel, and a "Not booked" entry to clear. The list stays grouped by category so the codes read the way the plant register does, and every row is a 44px target with the list scrolling within its own box, so it stays usable on a phone. It is an ARIA combobox — aria-expanded, aria-autocomplete, aria-controls — and the highlighted row scrolls into view as you arrow through it. Booking behaviour is unchanged: still posts on selection, still rolls the display back if the save fails, still refreshes on success. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
293276ccce
commit
d471dc2d88
3 changed files with 260 additions and 109 deletions
|
|
@ -1,105 +0,0 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useMemo } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, AlertCircle } from "lucide-react";
|
||||
|
||||
type AssetOption = { id: string; code: string; name: string; category: string };
|
||||
|
||||
// Books one invoice line to a plant item from the register.
|
||||
//
|
||||
// Saves immediately on change — there is no separate "save" button to miss on a phone.
|
||||
// On success it refreshes the router so the server-rendered header, banner and totals
|
||||
// re-read from PocketBase rather than showing stale booking state.
|
||||
export function BookingSelect({
|
||||
lineId,
|
||||
value,
|
||||
assets,
|
||||
}: {
|
||||
lineId: string;
|
||||
value: string;
|
||||
assets: AssetOption[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [current, setCurrent] = useState(value);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 44 plant items flat in one dropdown is unusable — group them by category.
|
||||
const groups = useMemo(() => {
|
||||
const byCategory = new Map<string, AssetOption[]>();
|
||||
for (const a of assets) {
|
||||
const key = a.category || "Other";
|
||||
if (!byCategory.has(key)) byCategory.set(key, []);
|
||||
byCategory.get(key)!.push(a);
|
||||
}
|
||||
return Array.from(byCategory.entries())
|
||||
.map(([category, items]) => ({ category, items: items.sort((x, y) => x.code.localeCompare(y.code)) }))
|
||||
.sort((a, b) => a.category.localeCompare(b.category));
|
||||
}, [assets]);
|
||||
|
||||
async function book(assetId: string) {
|
||||
const previous = current;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
setCurrent(assetId); // optimistic
|
||||
try {
|
||||
const res = await fetch(`/api/invoice-lines/${lineId}/book`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ assetId }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({ ok: false, error: "Unexpected response" }));
|
||||
if (!data.ok) {
|
||||
setCurrent(previous); // roll back so the UI never claims a booking that failed
|
||||
setError(data.error || "Booking failed");
|
||||
} else {
|
||||
router.refresh(); // re-read server-rendered banner/totals
|
||||
}
|
||||
} catch {
|
||||
setCurrent(previous);
|
||||
setError("Could not reach the server");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="sr-only" htmlFor={`book-${lineId}`}>
|
||||
Book this line to a plant item
|
||||
</label>
|
||||
<select
|
||||
id={`book-${lineId}`}
|
||||
value={current}
|
||||
disabled={saving}
|
||||
onChange={(e) => book(e.target.value)}
|
||||
className={`min-h-[44px] w-full rounded-lg border px-2 text-sm transition focus:outline-none focus:border-[#30638E] disabled:opacity-60 ${
|
||||
current
|
||||
? "border-[#00798C]/30 bg-[#00798C]/5 text-[#003D5B] dark:text-white"
|
||||
: "border-[#D1495B]/40 bg-[#D1495B]/5 text-[#D1495B]"
|
||||
}`}
|
||||
>
|
||||
<option value="">— Not booked —</option>
|
||||
{groups.map((g) => (
|
||||
<optgroup key={g.category} label={g.category}>
|
||||
{g.items.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.code} · {a.name}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</select>
|
||||
{saving && <Loader2 className="w-4 h-4 animate-spin text-[#00798C] shrink-0" aria-label="Saving" />}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="flex items-start gap-1 text-sm text-[#D1495B] mt-1">
|
||||
<AlertCircle className="w-3.5 h-3.5 mt-0.5 shrink-0" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import type { Asset, BookedLine, Invoice } from "@/lib/data";
|
||||
import { ZAR2 } from "@/lib/utils";
|
||||
import { AlertTriangle, CheckCircle2 } from "lucide-react";
|
||||
import { BookingSelect } from "@/components/BookingSelect";
|
||||
import { MachineCombobox } from "@/components/MachineCombobox";
|
||||
import { ScrollFade } from "@/components/ScrollFade";
|
||||
import { SiteBookingSelect, SiteBookingLegend } from "@/components/SiteBookingSelect";
|
||||
import { InvoiceUploader, AttachedDocument } from "@/components/InvoiceUploader";
|
||||
|
|
@ -223,9 +223,9 @@ function TotalRow({ label, value, strong }: { label: string; value: number; stro
|
|||
}
|
||||
|
||||
export function InvoiceTable({ lines, assets }: { lines: BookedLine[]; assets: Asset[] }) {
|
||||
const options = assets
|
||||
const machines = assets
|
||||
.filter((a) => a.is_active !== false)
|
||||
.map((a) => ({ id: a.id, code: a.code || "", name: a.name, category: a.category }));
|
||||
.map((a) => ({ id: a.id, code: a.code || "", name: a.name, category: a.category || "Other" }));
|
||||
|
||||
return (
|
||||
// Rule 1 + 4: the table scrolls inside its own container, so the page itself never
|
||||
|
|
@ -284,7 +284,7 @@ export function InvoiceTable({ lines, assets }: { lines: BookedLine[]; assets: A
|
|||
<td className="py-3 px-3">
|
||||
<div className="flex flex-col sm:flex-row gap-2 sm:items-start">
|
||||
<div className="min-w-[180px]">
|
||||
<BookingSelect lineId={l.id} value={l.booked_asset || ""} assets={options} />
|
||||
<MachineCombobox lineId={l.id} value={l.booked_asset || ""} machines={machines} />
|
||||
</div>
|
||||
{(!l.isBooked || l.booked_site) && (
|
||||
<SiteBookingSelect lineId={l.id} value={l.booked_site || ""} />
|
||||
|
|
|
|||
256
components/MachineCombobox.tsx
Normal file
256
components/MachineCombobox.tsx
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
"use client";
|
||||
|
||||
import { useState, useRef, useEffect, useMemo } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Loader2, AlertCircle, ChevronDown, Check, Search, X } from "lucide-react";
|
||||
|
||||
type Machine = { id: string; code: string; name: string; category: string };
|
||||
|
||||
// A searchable replacement for the native <select> of 44 machines.
|
||||
//
|
||||
// A native select cannot be filtered, so finding "TLB07" meant scrolling a list that
|
||||
// repeats two dozen near-identical "CASE TLB" entries. This filters as you type, on
|
||||
// either the code or the name, and still behaves like a select: opening it, arrowing,
|
||||
// Enter to choose, Escape to cancel, and a clear option.
|
||||
//
|
||||
// Keyboard and touch are both first-class — arrows move the highlighted row, the list
|
||||
// scrolls, and every row is a 44px target so it is usable on a phone.
|
||||
export function MachineCombobox({
|
||||
lineId,
|
||||
value,
|
||||
machines,
|
||||
}: {
|
||||
lineId: string;
|
||||
value: string;
|
||||
machines: Machine[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [query, setQuery] = useState("");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [highlight, setHighlight] = useState(0);
|
||||
const boxRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const listRef = useRef<HTMLUListElement>(null);
|
||||
|
||||
const selected = machines.find((m) => m.id === value) || null;
|
||||
|
||||
// Flattened, filtered list — the flat order is what the keyboard walks.
|
||||
const groups = useMemo(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
const hit = (m: Machine) =>
|
||||
!q || m.code.toLowerCase().includes(q) || m.name.toLowerCase().includes(q) || m.category.toLowerCase().includes(q);
|
||||
const matched = machines.filter(hit);
|
||||
const byCategory = new Map<string, Machine[]>();
|
||||
for (const m of matched) {
|
||||
if (!byCategory.has(m.category)) byCategory.set(m.category, []);
|
||||
byCategory.get(m.category)!.push(m);
|
||||
}
|
||||
return {
|
||||
list: Array.from(byCategory.entries())
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.map(([category, items]) => ({
|
||||
category,
|
||||
items: items.sort((a, b) => a.code.localeCompare(b.code)),
|
||||
})),
|
||||
flat: Array.from(byCategory.values())
|
||||
.flat()
|
||||
.sort((a, b) => a.code.localeCompare(b.code)),
|
||||
};
|
||||
}, [machines, query]);
|
||||
|
||||
// Click away closes.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: MouseEvent) => {
|
||||
if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
document.addEventListener("mousedown", onDown);
|
||||
return () => document.removeEventListener("mousedown", onDown);
|
||||
}, [open]);
|
||||
|
||||
// Keep the highlighted row inside the results after each keystroke.
|
||||
useEffect(() => {
|
||||
setHighlight((h) => Math.min(h, Math.max(0, groups.flat.length - 1)));
|
||||
}, [groups.flat.length]);
|
||||
|
||||
// Scroll the highlighted row into view.
|
||||
useEffect(() => {
|
||||
if (!open || !listRef.current) return;
|
||||
const el = listRef.current.querySelector<HTMLElement>(`[data-idx="${highlight}"]`);
|
||||
el?.scrollIntoView({ block: "nearest" });
|
||||
}, [highlight, open]);
|
||||
|
||||
async function book(id: string) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch(`/api/invoice-lines/${lineId}/book`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ assetId: id }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({ ok: false, error: "Unexpected response" }));
|
||||
if (!data.ok) setError(data.error || "Could not book it");
|
||||
else {
|
||||
setOpen(false);
|
||||
setQuery("");
|
||||
router.refresh();
|
||||
}
|
||||
} catch {
|
||||
setError("Could not reach the server");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function onKeyDown(e: React.KeyboardEvent) {
|
||||
if (e.key === "Escape") {
|
||||
setOpen(false);
|
||||
setQuery("");
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
const pick = groups.flat[highlight];
|
||||
if (pick) book(pick.id);
|
||||
return;
|
||||
}
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
if (!open) {
|
||||
setOpen(true);
|
||||
return;
|
||||
}
|
||||
const n = groups.flat.length;
|
||||
if (!n) return;
|
||||
setHighlight((h) => (e.key === "ArrowDown" ? (h + 1) % n : (h - 1 + n) % n));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={boxRef} className="relative min-w-[200px]">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-autocomplete="list"
|
||||
aria-controls={`machine-list-${lineId}`}
|
||||
value={open ? query : selected ? `${selected.code} · ${selected.name}` : ""}
|
||||
placeholder="Search machines…"
|
||||
onFocus={() => setOpen(true)}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setOpen(true);
|
||||
setHighlight(0);
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
className={`min-h-[44px] w-full pl-8 pr-8 rounded-lg border text-sm transition focus:outline-none focus:border-[#30638E] ${
|
||||
selected
|
||||
? "border-[#00798C]/30 bg-[#00798C]/5 text-[#003D5B] dark:text-white font-medium"
|
||||
: "border-[#D1495B]/40 bg-[#D1495B]/5 text-[#D1495B]"
|
||||
}`}
|
||||
/>
|
||||
{busy ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin text-[#00798C] absolute right-2.5 top-1/2 -translate-y-1/2" />
|
||||
) : (
|
||||
<ChevronDown
|
||||
className={`w-4 h-4 absolute right-2.5 top-1/2 -translate-y-1/2 text-gray-400 transition-transform pointer-events-none ${
|
||||
open ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{selected && !busy && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => book("")}
|
||||
aria-label="Clear the machine booking"
|
||||
className="grid place-items-center w-11 h-11 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-white/5 transition shrink-0"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{open && (
|
||||
<div className="absolute z-30 left-0 top-full mt-1 w-full min-w-[280px] max-w-[340px] rounded-xl bg-white dark:bg-[#1a222b] border border-gray-200 dark:border-white/10 shadow-xl overflow-hidden">
|
||||
<div className="px-3 py-2 text-xs text-gray-500 dark:text-gray-400 border-b border-gray-100 dark:border-white/5">
|
||||
{groups.flat.length} of {machines.length} machines
|
||||
{!selected && " · type a code or name to narrow it"}
|
||||
</div>
|
||||
|
||||
{value && (
|
||||
<ul>
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => book("")}
|
||||
className="w-full min-h-[44px] px-3 py-2 text-left text-sm text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 flex items-center gap-2"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
Not booked
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{groups.flat.length === 0 ? (
|
||||
<p className="px-3 py-4 text-sm text-gray-500 dark:text-gray-400">
|
||||
No machine matches “{query}”.
|
||||
</p>
|
||||
) : (
|
||||
<ul ref={listRef} id={`machine-list-${lineId}`} className="max-h-64 overflow-y-auto py-1">
|
||||
{groups.list.map((g) => (
|
||||
<li key={g.category}>
|
||||
<div className="px-3 pt-2 pb-1 text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500">
|
||||
{g.category}
|
||||
</div>
|
||||
<ul>
|
||||
{g.items.map((m) => {
|
||||
const idx = groups.flat.indexOf(m);
|
||||
const isSel = m.id === value;
|
||||
return (
|
||||
<li key={m.id}>
|
||||
<button
|
||||
type="button"
|
||||
data-idx={idx}
|
||||
onMouseEnter={() => setHighlight(idx)}
|
||||
onClick={() => book(m.id)}
|
||||
className={`w-full min-h-[44px] px-3 py-2 text-left text-sm flex items-center gap-2 transition ${
|
||||
idx === highlight
|
||||
? "bg-[#00798C]/10 text-[#003D5B] dark:text-white"
|
||||
: "text-gray-600 dark:text-gray-300"
|
||||
}`}
|
||||
>
|
||||
<span className="font-mono text-xs font-semibold text-[#00798C] w-16 shrink-0">
|
||||
{m.code || "—"}
|
||||
</span>
|
||||
<span className="truncate">{m.name}</span>
|
||||
{isSel && <Check className="w-4 h-4 text-[#00798C] ml-auto shrink-0" />}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="mt-1 flex items-start gap-1 text-sm text-[#D1495B]">
|
||||
<AlertCircle className="w-3.5 h-3.5 mt-0.5 shrink-0" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue