Refactors grantAward to accept an array of recipientUserIds, adds duplicate-award and eligibility checks per recipient, and returns a per-recipient result summary. GrantAwardDialog gains a third step showing grant results when some recipients fail. RecipientPicker is rewritten to support multi-select with chip-based selected state and a maxSelections cap.
289 lines
10 KiB
TypeScript
289 lines
10 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import type { Assignment, Media, Profile } from "@/payload-types";
|
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
import { Input } from "@/components/ui/input";
|
|
import { cn } from "@/lib/utils";
|
|
import { Loader2Icon, SearchIcon, XIcon } from "lucide-react";
|
|
|
|
export interface RecipientSelection {
|
|
id: number;
|
|
username: string;
|
|
displayName?: string | null;
|
|
profileId?: number;
|
|
}
|
|
|
|
interface RecipientPickerProps {
|
|
selectedUsers: RecipientSelection[];
|
|
onSelect: (user: RecipientSelection) => void;
|
|
onRemove: (id: number) => void;
|
|
maxSelections?: number;
|
|
disabled?: boolean;
|
|
}
|
|
|
|
interface SearchResult extends RecipientSelection {
|
|
rankName?: string | null;
|
|
insigniaUrl?: string | null;
|
|
assignmentLabel?: string | null;
|
|
}
|
|
|
|
function initialsOf(username: string): string {
|
|
return username.slice(0, 2).toUpperCase();
|
|
}
|
|
|
|
/**
|
|
* Searchable recipient picker. Queries the profiles REST API (users have no
|
|
* `profile` relationship, so searching /api/users would not surface rank
|
|
* data) and enriches each hit with the user's primary assignment.
|
|
*/
|
|
export function RecipientPicker({
|
|
selectedUsers,
|
|
onSelect,
|
|
onRemove,
|
|
maxSelections,
|
|
disabled = false,
|
|
}: RecipientPickerProps) {
|
|
const [query, setQuery] = useState("");
|
|
const [results, setResults] = useState<SearchResult[]>([]);
|
|
const [searching, setSearching] = useState(false);
|
|
const [open, setOpen] = useState(false);
|
|
const [activeIndex, setActiveIndex] = useState(0);
|
|
const wrapperRef = useRef<HTMLDivElement>(null);
|
|
const searchSeq = useRef(0);
|
|
|
|
// Debounced search with a sequence guard so stale responses are dropped.
|
|
useEffect(() => {
|
|
const trimmed = query.trim();
|
|
if (trimmed.length < 1) {
|
|
setResults([]);
|
|
setSearching(false);
|
|
return;
|
|
}
|
|
|
|
const seq = ++searchSeq.current;
|
|
setSearching(true);
|
|
const timer = setTimeout(async () => {
|
|
try {
|
|
const q = encodeURIComponent(trimmed);
|
|
const url = `/api/profiles?where[or][0][user.username][like]=${q}&where[or][1][user.displayName][like]=${q}&limit=10&depth=2`;
|
|
const res = await fetch(url, { cache: "no-store" });
|
|
if (!res.ok) throw new Error("Search failed");
|
|
const data = (await res.json()) as { docs?: unknown[] };
|
|
|
|
const mapped: SearchResult[] = [];
|
|
for (const doc of data.docs ?? []) {
|
|
const profile = doc as Profile;
|
|
const userDoc = profile.user;
|
|
if (typeof userDoc !== "object" || !userDoc) continue;
|
|
const rank = typeof profile.rank === "object" && profile.rank ? profile.rank : null;
|
|
mapped.push({
|
|
id: userDoc.id,
|
|
username: userDoc.username,
|
|
displayName: userDoc.displayName,
|
|
profileId: profile.id,
|
|
rankName: rank?.name ?? null,
|
|
insigniaUrl:
|
|
rank && typeof rank.insignia === "object" && rank.insignia
|
|
? (rank.insignia as Media).url
|
|
: null,
|
|
});
|
|
}
|
|
|
|
// Enrich with each user's primary assignment (best-effort).
|
|
const assignmentResults = await Promise.allSettled(
|
|
mapped.map((r) =>
|
|
fetch(`/api/assignments?where[members][equals]=${r.id}&limit=1&depth=0`, {
|
|
cache: "no-store",
|
|
})
|
|
.then((res) => (res.ok ? res.json() : null))
|
|
.then((json) => {
|
|
const doc = (json as { docs?: unknown[] } | null)?.docs?.[0];
|
|
if (!doc || typeof doc !== "object") return null;
|
|
const assignment = doc as Assignment;
|
|
return assignment.callsign ? `[${assignment.callsign}] ${assignment.name}` : assignment.name;
|
|
}),
|
|
),
|
|
);
|
|
assignmentResults.forEach((res, i) => {
|
|
if (res.status === "fulfilled" && res.value) mapped[i].assignmentLabel = res.value;
|
|
});
|
|
|
|
if (seq !== searchSeq.current) return;
|
|
setResults(mapped);
|
|
setActiveIndex(0);
|
|
} catch {
|
|
if (seq === searchSeq.current) {
|
|
setResults([]);
|
|
}
|
|
} finally {
|
|
if (seq === searchSeq.current) setSearching(false);
|
|
}
|
|
}, 300);
|
|
|
|
return () => clearTimeout(timer);
|
|
}, [query]);
|
|
|
|
// Close the dropdown on outside click.
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
function handlePointerDown(e: MouseEvent) {
|
|
if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
|
|
setOpen(false);
|
|
}
|
|
}
|
|
document.addEventListener("mousedown", handlePointerDown);
|
|
return () => document.removeEventListener("mousedown", handlePointerDown);
|
|
}, [open]);
|
|
|
|
function select(result: SearchResult) {
|
|
onSelect({
|
|
id: result.id,
|
|
username: result.username,
|
|
displayName: result.displayName,
|
|
profileId: result.profileId,
|
|
});
|
|
setQuery("");
|
|
setActiveIndex(0);
|
|
}
|
|
|
|
const atMax = maxSelections != null && selectedUsers.length >= maxSelections;
|
|
|
|
return (
|
|
<div ref={wrapperRef} className="flex flex-col gap-2">
|
|
{selectedUsers.length > 0 && (
|
|
<div className="flex flex-wrap gap-1.5">
|
|
{selectedUsers.map((u) => (
|
|
<span
|
|
key={u.id}
|
|
className="inline-flex items-center gap-1.5 rounded-full border bg-muted/40 py-1 pl-1 pr-1.5 text-sm"
|
|
>
|
|
<Avatar className="size-5">
|
|
<AvatarFallback className="text-[10px]">
|
|
{initialsOf(u.username)}
|
|
</AvatarFallback>
|
|
</Avatar>
|
|
<span className="max-w-[10rem] truncate font-medium">
|
|
{u.displayName || u.username}
|
|
</span>
|
|
<span className="truncate text-xs text-muted-foreground">@{u.username}</span>
|
|
<button
|
|
type="button"
|
|
aria-label={`Remove ${u.username}`}
|
|
disabled={disabled}
|
|
onClick={() => onRemove(u.id)}
|
|
className="rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
|
|
>
|
|
<XIcon className="size-3.5" />
|
|
</button>
|
|
</span>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
<div className="relative">
|
|
<SearchIcon className="absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
|
<Input
|
|
value={query}
|
|
disabled={disabled || atMax}
|
|
onChange={(e) => {
|
|
setQuery(e.target.value);
|
|
setOpen(true);
|
|
}}
|
|
onFocus={() => setOpen(true)}
|
|
onKeyDown={(e) => {
|
|
if (e.key === "Escape") {
|
|
setOpen(false);
|
|
return;
|
|
}
|
|
if (!open || results.length === 0) return;
|
|
if (e.key === "ArrowDown") {
|
|
e.preventDefault();
|
|
setActiveIndex((i) => Math.min(i + 1, results.length - 1));
|
|
} else if (e.key === "ArrowUp") {
|
|
e.preventDefault();
|
|
setActiveIndex((i) => Math.max(i - 1, 0));
|
|
} else if (e.key === "Enter") {
|
|
e.preventDefault();
|
|
const active = results[activeIndex];
|
|
if (active) select(active);
|
|
}
|
|
}}
|
|
placeholder={
|
|
atMax
|
|
? "Maximum recipients selected"
|
|
: "Search by username or display name..."
|
|
}
|
|
className="pl-8"
|
|
role="combobox"
|
|
aria-expanded={open}
|
|
aria-controls="recipient-picker-results"
|
|
/>
|
|
{open && query.trim().length > 0 && (
|
|
<div
|
|
id="recipient-picker-results"
|
|
role="listbox"
|
|
className="absolute z-50 mt-1 max-h-80 w-full overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md"
|
|
>
|
|
{searching ? (
|
|
<div className="flex items-center gap-2 px-3 py-3 text-sm text-muted-foreground">
|
|
<Loader2Icon className="size-4 animate-spin" />
|
|
Searching...
|
|
</div>
|
|
) : results.length === 0 ? (
|
|
<div className="px-3 py-3 text-sm text-muted-foreground">No users found.</div>
|
|
) : (
|
|
results.map((result, i) => {
|
|
const alreadySelected = selectedUsers.some((u) => u.id === result.id);
|
|
return (
|
|
<button
|
|
key={result.id}
|
|
type="button"
|
|
role="option"
|
|
aria-selected={i === activeIndex}
|
|
disabled={alreadySelected || atMax}
|
|
onMouseDown={(e) => e.preventDefault()}
|
|
onClick={() => select(result)}
|
|
onMouseEnter={() => setActiveIndex(i)}
|
|
className={cn(
|
|
"flex w-full items-center gap-3 px-3 py-2 text-left",
|
|
i === activeIndex && "bg-accent",
|
|
(alreadySelected || atMax) && "cursor-not-allowed opacity-50",
|
|
)}
|
|
>
|
|
<Avatar className="size-8">
|
|
{result.insigniaUrl ? (
|
|
<AvatarImage src={result.insigniaUrl} alt="" />
|
|
) : (
|
|
<AvatarFallback>{initialsOf(result.username)}</AvatarFallback>
|
|
)}
|
|
</Avatar>
|
|
<span className="flex min-w-0 flex-col">
|
|
<span className="truncate text-sm font-medium">
|
|
{result.displayName || result.username}
|
|
</span>
|
|
<span className="truncate text-xs text-muted-foreground">
|
|
@{result.username}
|
|
{result.rankName ? ` · ${result.rankName}` : ""}
|
|
</span>
|
|
</span>
|
|
{result.assignmentLabel && (
|
|
<span className="ml-auto shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">
|
|
{result.assignmentLabel}
|
|
</span>
|
|
)}
|
|
{alreadySelected && (
|
|
<span className="ml-auto shrink-0 text-xs text-muted-foreground">
|
|
Selected
|
|
</span>
|
|
)}
|
|
</button>
|
|
);
|
|
})
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|