Files
co-lite/solvway-admin-portal/app/components/members/MemberSearchCombobox.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

304 lines
13 KiB
TypeScript

"use client";
import { useEffect, useRef, useState } from "react";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/app/components/ui/command";
import { Popover, PopoverAnchor, PopoverContent } from "@/app/components/ui/popover";
import { Avatar, AvatarFallback } from "@/app/components/ui/avatar";
import { Badge } from "@/app/components/ui/badge";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { MEMBER_STATUS_LABEL_CODES } from "@/app/lib/memberLabels";
import { listMembers } from "@/app/lib/services/members";
import type { AdminMember, AdminMemberStatus } from "@/app/lib/types";
// Reusable member search combobox (add-network-member-search, Task 4). Wraps
// the combined `q` OR-search (memberCode/name/nickname/email) behind
// a debounced, keyboard-navigable dropdown. Three call sites (Task 5): the
// network root picker and both placement-correction fields, plus the members
// quick-search. Keep the prop surface minimal — only what those call sites
// need.
const MIN_QUERY_LENGTH = 3;
const DEBOUNCE_MS = 250;
const PAGE_SIZE = 8;
const STATUS_VARIANT: Record<AdminMemberStatus, "default" | "secondary" | "destructive"> = {
Y: "default",
N: "secondary",
P: "secondary",
F: "secondary",
E: "secondary",
R: "destructive",
S: "destructive",
T: "destructive",
};
function initialOf(member: AdminMember): string {
const source = member.name ?? member.memberCode;
return source ? source.trim().charAt(0).toUpperCase() : "?";
}
/** The single display string for a member, used both in the results dropdown
* and — once chosen — as the field's own value (see handleSelect below). */
function displayLabel(member: AdminMember): string {
return member.nickname
? `${member.name ?? member.memberCode} (${member.nickname})`
: (member.name ?? member.memberCode);
}
export interface MemberSearchComboboxProps {
/** Called with the full member record when a row is selected. */
onSelect: (member: AdminMember) => void;
placeholder?: string;
initialQuery?: string;
autoFocus?: boolean;
disabled?: boolean;
/**
* Accessible name for the field. cmdk's own CommandPrimitive.Input
* unconditionally regenerates its own `id` and `aria-labelledby` on the
* rendered <input> (they're set after the caller's props are spread in),
* so neither an `id` prop nor an `aria-labelledby` prop passed here could
* ever actually reach the DOM node — an external `<label htmlFor>` can
* never resolve through to this component, and `aria-labelledby` always
* wins over a same-element `aria-label` in accessible-name computation
* regardless. Internally this is wired via cmdk's own `label` Root prop
* (rendered as the text of its hidden `aria-labelledby` target) rather
* than an `aria-label` attribute on the input itself — see the `<Command
* label={ariaLabel}>` below. Pass the same text used in any neighbouring
* visible label.
*/
"aria-label"?: string;
}
export function MemberSearchCombobox({
onSelect,
placeholder,
initialQuery = "",
autoFocus,
disabled,
"aria-label": ariaLabel,
}: MemberSearchComboboxProps) {
const t = useT();
const [query, setQuery] = useState(initialQuery);
const [open, setOpen] = useState(false);
const [results, setResults] = useState<AdminMember[]>([]);
const [loading, setLoading] = useState(false);
const [searched, setSearched] = useState(false);
const requestIdRef = useRef(0);
// Tracks the last `initialQuery` value this component has already
// reflected, so the re-sync effect below only reacts to an actual change
// in the prop (not every render).
const lastSyncedInitialQueryRef = useRef(initialQuery);
// Set synchronously by handleSelect, before onSelect(member) runs. A
// caller that reacts to onSelect by updating its own state and re-passing
// it as `initialQuery` (e.g. the network root picker setting the `root`
// URL param to the just-selected member's code) would otherwise have that
// prop change immediately clobber the friendly "Name (nickname)" label
// handleSelect just wrote into `query` with the bare code. This flag lets
// the very next `initialQuery` change be attributed to that selection and
// skipped once, without disabling the re-sync for genuine external changes
// (e.g. a node's "Correct placement" inline action prefilling a different,
// separate field).
const justSelectedRef = useRef(false);
// Set alongside justSelectedRef by handleSelect, to the exact label string
// that same setQuery call just wrote into `query`. That setQuery call
// (populating the field with the chosen member's label) also changes
// `trimmed`, which would otherwise re-trigger this search effect below and
// fire one wasted listMembers request ~DEBOUNCE_MS after every selection —
// the popover is already closed by then, so it's invisible but wasteful.
//
// This is deliberately VALUE-based, not a bare boolean: a boolean flag
// assumes the effect is guaranteed to re-run once after being set, but if
// the selected member's label happens to be byte-identical to what the
// user had already typed (e.g. a member with no nickname, typed verbatim
// then clicked), `trimmed` never actually changes, React skips re-running
// the `[trimmed]`-keyed effect entirely, and a bare boolean would never get
// consumed — silently swallowing the *next* genuine search instead. Storing
// the value lets the effect only skip when the *current* `trimmed` still
// equals what was just selected; any later, different `trimmed` (including
// the effect run this same value eventually triggers once the query
// genuinely changes) clears it and searches normally.
const skipSearchForQueryRef = useRef<string | null>(null);
const trimmed = query.trim();
useEffect(() => {
if (skipSearchForQueryRef.current !== null) {
const skipValue = skipSearchForQueryRef.current;
skipSearchForQueryRef.current = null;
if (trimmed === skipValue) return;
}
// Below the floor: cancel any in-flight/pending request and show nothing
// but the hint — no request is issued.
if (trimmed.length < MIN_QUERY_LENGTH) {
requestIdRef.current += 1;
// eslint-disable-next-line react-hooks/set-state-in-effect -- clears the previous results when the query drops below the minimum length; no fetch is made.
setLoading(false);
setSearched(false);
setResults([]);
return;
}
const requestId = ++requestIdRef.current;
setLoading(true);
setSearched(false);
const timer = setTimeout(() => {
listMembers({ q: trimmed, pageSize: PAGE_SIZE })
.then((result) => {
// A newer query may have superseded this one while it was in
// flight — a slower, older response must never overwrite it.
if (requestIdRef.current !== requestId) return;
setResults(result.items);
setLoading(false);
setSearched(true);
})
.catch(() => {
if (requestIdRef.current !== requestId) return;
setResults([]);
setLoading(false);
setSearched(true);
});
}, DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [trimmed]);
// Re-syncs the visible value when `initialQuery` changes to a genuinely
// new value AFTER mount — e.g. a node's "Set as tree root" / "Correct
// placement" inline action (Task 10) sets the caller's state, which flows
// back down as a new `initialQuery`. Without this, the field's `query`
// state (seeded from `initialQuery` only once, at mount) never reflects a
// prop change, so the field can keep showing a stale, different member
// than the one the caller's state now actually targets.
//
// Guarded so it never fights the user: it only fires when `initialQuery`
// itself changes (not on every render, so it never touches `query` while
// the user is mid-typing), and it skips the one change immediately
// following this component's own `handleSelect` (see justSelectedRef
// above) so selecting a suggestion here is never immediately overwritten
// by the caller reflecting that same selection back down.
useEffect(() => {
if (initialQuery === lastSyncedInitialQueryRef.current) return;
lastSyncedInitialQueryRef.current = initialQuery;
if (justSelectedRef.current) {
justSelectedRef.current = false;
return;
}
setQuery(initialQuery ?? "");
}, [initialQuery]);
function handleValueChange(value: string) {
setQuery(value);
setOpen(true);
}
function handleSelect(member: AdminMember) {
justSelectedRef.current = true;
onSelect(member);
setOpen(false);
// Populate the field with the chosen member rather than leaving the
// partial text the user typed to find them. Setting `query` (not just
// display state) keeps it re-searchable — typing again replaces it.
const label = displayLabel(member);
skipSearchForQueryRef.current = label;
setQuery(label);
}
const belowFloor = trimmed.length < MIN_QUERY_LENGTH;
const noMatch = !belowFloor && !loading && searched && results.length === 0;
return (
<Popover open={open} onOpenChange={setOpen}>
{/* cmdk's Input unconditionally sets its own aria-labelledby pointing at
the Root's hidden <label cmdk-label> element — that always wins over
any aria-label placed directly on the input in accessible-name
computation, so the accessible name is wired via the Root's `label`
prop (rendered as that hidden label's text), not via CommandInput. */}
<Command shouldFilter={false} label={ariaLabel} className="overflow-visible bg-transparent">
<PopoverAnchor asChild>
{/* Render the field as a standard bordered Input box (matching
app/components/ui/input.tsx) rather than cmdk's default underline
row: full rounded border, the search icon sits inside on the left,
and focus-within mirrors the Input focus ring. The inner
[data-slot=command-input-wrapper] keeps the icon + input but loses
its own bottom border and fills this box. */}
<div className="flex h-9 w-full items-center rounded-md border border-input bg-transparent shadow-sm transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 dark:bg-input/30 [&_[data-slot=command-input-wrapper]]:h-full [&_[data-slot=command-input-wrapper]]:flex-1 [&_[data-slot=command-input-wrapper]]:border-b-0 [&_[data-slot=command-input]]:h-full [&_[data-slot=command-input]]:py-0 [&_[data-slot=command-input]]:outline-none">
{/* An empty box opens nothing on focus, so its hint never covers what sits below (e.g. the POS walk-in option); typing opens it. */}
<CommandInput
value={query}
onValueChange={handleValueChange}
onFocus={() => { if (query.trim()) setOpen(true); }}
placeholder={placeholder ?? t("MemberSearchPlaceholder")}
autoFocus={autoFocus}
disabled={disabled}
/>
</div>
</PopoverAnchor>
<PopoverContent
className="w-[var(--radix-popover-trigger-width)] p-0"
align="start"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<CommandList>
{belowFloor ? (
<div className="px-3 py-6 text-center text-sm text-muted-foreground">
{t("MemberSearchHint")}
</div>
) : loading ? (
<div className="px-3 py-6 text-center text-sm text-muted-foreground">
{t("MemberSearchLoading")}
</div>
) : noMatch ? (
<CommandEmpty>{t("MemberSearchNoMatch", { term: trimmed })}</CommandEmpty>
) : results.length > 0 ? (
<CommandGroup>
{results.map((member) => {
const statusCode = member.status;
const label = displayLabel(member);
return (
<CommandItem
key={member.memberCode}
value={member.memberCode}
onSelect={() => handleSelect(member)}
className="items-center gap-2"
>
<Avatar size="sm">
<AvatarFallback>{initialOf(member)}</AvatarFallback>
</Avatar>
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-sm font-medium">{label}</span>
<span className="truncate text-xs text-muted-foreground">
{member.memberCode}
{member.email ? ` · ${member.email}` : ""}
</span>
</div>
{statusCode ? (
<Badge variant={STATUS_VARIANT[statusCode]}>
{t(MEMBER_STATUS_LABEL_CODES[statusCode])}
</Badge>
) : null}
</CommandItem>
);
})}
{results.length === PAGE_SIZE ? (
<div className="px-3 py-1.5 text-xs text-muted-foreground">
{t("MemberSearchRefine")}
</div>
) : null}
</CommandGroup>
) : null}
</CommandList>
</PopoverContent>
</Command>
</Popover>
);
}