SearchCommand.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. "use client";
  2. import { useCallback, useEffect, useRef, useState } from "react";
  3. import { useRouter } from "next/navigation";
  4. import {
  5. CommandDialog,
  6. CommandInput,
  7. CommandList,
  8. CommandEmpty,
  9. CommandGroup,
  10. CommandItem,
  11. } from "@/components/ui/command";
  12. import { Bell, Car, ClipboardCheck, FileText, Package, Settings, Users, Wrench } from "lucide-react";
  13. import { globalSearch, getRecentCustomers } from "@/features/search/Actions/searchActions";
  14. interface SearchResult {
  15. vehicles: {
  16. id: string;
  17. make: string;
  18. model: string;
  19. year: number;
  20. licensePlate: string | null;
  21. }[];
  22. customers: {
  23. id: string;
  24. name: string;
  25. email: string | null;
  26. phone: string | null;
  27. company: string | null;
  28. vehicles: {
  29. id: string;
  30. make: string;
  31. model: string;
  32. year: number;
  33. licensePlate: string | null;
  34. }[];
  35. }[];
  36. services: {
  37. id: string;
  38. title: string;
  39. invoiceNumber: string | null;
  40. vehicle: {
  41. id: string;
  42. make: string;
  43. model: string;
  44. year: number;
  45. licensePlate: string | null;
  46. };
  47. }[];
  48. parts: {
  49. id: string;
  50. name: string;
  51. partNumber: string | null;
  52. quantity: number;
  53. }[];
  54. quotes: {
  55. id: string;
  56. title: string;
  57. quoteNumber: string | null;
  58. status: string;
  59. }[];
  60. reminders: {
  61. id: string;
  62. title: string;
  63. dueDate: Date | null;
  64. isCompleted: boolean;
  65. vehicle: {
  66. id: string;
  67. make: string;
  68. model: string;
  69. year: number;
  70. licensePlate: string | null;
  71. };
  72. }[];
  73. inspections: {
  74. id: string;
  75. status: string;
  76. createdAt: Date;
  77. template: { name: string };
  78. vehicle: {
  79. id: string;
  80. make: string;
  81. model: string;
  82. year: number;
  83. licensePlate: string | null;
  84. };
  85. }[];
  86. }
  87. const SEARCHABLE_SETTINGS = [
  88. { label: "Company", description: "Company, business, branding, logo", href: "/settings/company", keywords: ["company", "business", "branding", "logo", "name", "address"] },
  89. { label: "Account", description: "Account, profile, password", href: "/settings/account", keywords: ["account", "profile", "password", "email", "2fa"] },
  90. { label: "Team", description: "Team members and roles", href: "/settings/team", keywords: ["team", "members", "roles", "invite"] },
  91. { label: "Invoice", description: "Invoice layout and prefix", href: "/settings/invoice", keywords: ["invoice", "layout", "prefix", "footer", "due"] },
  92. { label: "Templates", description: "Invoice & quote template styling", href: "/settings/templates", keywords: ["template", "styling", "colors", "font", "header", "quote"] },
  93. { label: "Payment", description: "Payment and bank settings", href: "/settings/payment", keywords: ["payment", "bank", "vipps", "stripe", "terms"] },
  94. { label: "Currency", description: "Currency, tax, and VAT", href: "/settings/currency", keywords: ["currency", "tax", "vat", "unit"] },
  95. { label: "Custom Fields", description: "Custom fields configuration", href: "/settings/custom-fields", keywords: ["custom fields", "fields"] },
  96. { label: "Email", description: "Email and SMTP settings", href: "/settings/email", keywords: ["email", "mail", "smtp", "sending"] },
  97. { label: "Workshop", description: "Workshop and labor settings", href: "/settings/workshop", keywords: ["workshop", "technician", "labor", "hours"] },
  98. { label: "Appearance", description: "Theme and date settings", href: "/settings/appearance", keywords: ["appearance", "theme", "dark", "light", "date", "timezone"] },
  99. { label: "Data", description: "Data export and backup", href: "/settings/data", keywords: ["data", "export", "import", "backup"] },
  100. { label: "About", description: "Version and info", href: "/settings/about", keywords: ["about", "version", "info"] },
  101. ];
  102. function useDebounce<T>(value: T, delay: number): T {
  103. const [debounced, setDebounced] = useState(value);
  104. useEffect(() => {
  105. const timer = setTimeout(() => setDebounced(value), delay);
  106. return () => clearTimeout(timer);
  107. }, [value, delay]);
  108. return debounced;
  109. }
  110. type RecentCustomer = {
  111. id: string;
  112. name: string;
  113. email: string | null;
  114. phone: string | null;
  115. company: string | null;
  116. };
  117. function filterSettings(query: string) {
  118. const q = query.toLowerCase();
  119. return SEARCHABLE_SETTINGS.filter(
  120. (s) =>
  121. s.label.toLowerCase().includes(q) ||
  122. s.description.toLowerCase().includes(q) ||
  123. s.keywords.some((k) => k.toLowerCase().includes(q))
  124. );
  125. }
  126. export function SearchCommand() {
  127. const router = useRouter();
  128. const [open, setOpen] = useState(false);
  129. const [query, setQuery] = useState("");
  130. const [results, setResults] = useState<SearchResult>({ vehicles: [], customers: [], services: [], parts: [], quotes: [], reminders: [], inspections: [] });
  131. const [loading, setLoading] = useState(false);
  132. const [recentCustomers, setRecentCustomers] = useState<RecentCustomer[]>([]);
  133. const recentFetchedRef = useRef(false);
  134. const debouncedQuery = useDebounce(query, 300);
  135. useEffect(() => {
  136. const down = (e: KeyboardEvent) => {
  137. if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
  138. e.preventDefault();
  139. setOpen((prev) => !prev);
  140. }
  141. };
  142. document.addEventListener("keydown", down);
  143. return () => document.removeEventListener("keydown", down);
  144. }, []);
  145. // Fetch recent customers when dialog opens
  146. useEffect(() => {
  147. if (open && !recentFetchedRef.current) {
  148. recentFetchedRef.current = true;
  149. getRecentCustomers().then((res) => {
  150. if (res.success && res.data) {
  151. setRecentCustomers(res.data);
  152. }
  153. });
  154. }
  155. if (!open) {
  156. recentFetchedRef.current = false;
  157. }
  158. }, [open]);
  159. useEffect(() => {
  160. if (!debouncedQuery || debouncedQuery.length < 2) {
  161. // eslint-disable-next-line react-hooks/set-state-in-effect -- clearing results on query change is intentional
  162. setResults({ vehicles: [], customers: [], services: [], parts: [], quotes: [], reminders: [], inspections: [] });
  163. setLoading(false);
  164. return;
  165. }
  166. let cancelled = false;
  167. setLoading(true);
  168. globalSearch(debouncedQuery).then((res) => {
  169. if (cancelled) return;
  170. if (res.success && res.data) {
  171. setResults(res.data);
  172. }
  173. setLoading(false);
  174. });
  175. return () => {
  176. cancelled = true;
  177. };
  178. }, [debouncedQuery]);
  179. const handleSelect = useCallback(
  180. (path: string) => {
  181. setOpen(false);
  182. setQuery("");
  183. router.push(path);
  184. },
  185. [router]
  186. );
  187. const hasQuery = debouncedQuery.length >= 2;
  188. const hasResults = results.vehicles.length > 0 || results.customers.length > 0 || results.services.length > 0 || results.parts.length > 0 || results.quotes.length > 0 || results.reminders.length > 0 || results.inspections.length > 0;
  189. const matchedSettings = hasQuery ? filterSettings(debouncedQuery) : SEARCHABLE_SETTINGS;
  190. const showDefault = !hasQuery;
  191. return (
  192. <CommandDialog
  193. open={open}
  194. onOpenChange={setOpen}
  195. title="Search"
  196. description="Search for vehicles, customers, services, and settings"
  197. >
  198. <CommandInput
  199. placeholder="Search by name, plate, phone, VIN, invoice..."
  200. value={query}
  201. onValueChange={setQuery}
  202. />
  203. <CommandList>
  204. {!loading && hasQuery && !hasResults && matchedSettings.length === 0 && (
  205. <CommandEmpty>No results found.</CommandEmpty>
  206. )}
  207. {/* Default view: recent customers + all settings */}
  208. {showDefault && recentCustomers.length > 0 && (
  209. <CommandGroup heading="Recent Customers">
  210. {recentCustomers.map((c) => (
  211. <CommandItem
  212. key={c.id}
  213. value={`${c.name} ${c.email || ""} ${c.company || ""}`}
  214. onSelect={() => handleSelect(`/customers/${c.id}`)}
  215. >
  216. <Users className="mr-2 h-4 w-4 text-muted-foreground" />
  217. <div className="flex flex-col">
  218. <span>{c.name}</span>
  219. <span className="text-xs text-muted-foreground">
  220. {[c.company, c.email, c.phone].filter(Boolean).join(" · ")}
  221. </span>
  222. </div>
  223. </CommandItem>
  224. ))}
  225. </CommandGroup>
  226. )}
  227. {/* Search results: grouped by entity type — kept visible while loading to avoid flicker */}
  228. {hasQuery && (
  229. <>
  230. {results.customers.length > 0 && (
  231. <CommandGroup heading="Customers">
  232. {results.customers.map((c) => (
  233. <div key={c.id}>
  234. <CommandItem
  235. value={`${c.name} ${c.email || ""} ${c.company || ""}`}
  236. onSelect={() => handleSelect(`/customers/${c.id}`)}
  237. >
  238. <Users className="mr-2 h-4 w-4 text-muted-foreground" />
  239. <div className="flex flex-col">
  240. <span>{c.name}</span>
  241. <span className="text-xs text-muted-foreground">
  242. {[c.company, c.email, c.phone].filter(Boolean).join(" · ")}
  243. </span>
  244. </div>
  245. </CommandItem>
  246. {c.vehicles.map((v) => (
  247. <CommandItem
  248. key={v.id}
  249. value={`${c.name} ${v.year} ${v.make} ${v.model} ${v.licensePlate || ""}`}
  250. onSelect={() => handleSelect(`/vehicles/${v.id}`)}
  251. className="pl-10"
  252. >
  253. <Car className="mr-2 h-3.5 w-3.5 text-muted-foreground" />
  254. <span className="text-sm">
  255. {v.year} {v.make} {v.model}
  256. </span>
  257. {v.licensePlate && (
  258. <span className="ml-2 font-mono text-xs text-muted-foreground">
  259. {v.licensePlate}
  260. </span>
  261. )}
  262. </CommandItem>
  263. ))}
  264. </div>
  265. ))}
  266. </CommandGroup>
  267. )}
  268. {results.vehicles.length > 0 && (
  269. <CommandGroup heading="Vehicles">
  270. {results.vehicles.map((v) => (
  271. <CommandItem
  272. key={v.id}
  273. value={`${v.year} ${v.make} ${v.model} ${v.licensePlate || ""}`}
  274. onSelect={() => handleSelect(`/vehicles/${v.id}`)}
  275. >
  276. <Car className="mr-2 h-4 w-4 text-muted-foreground" />
  277. <span>
  278. {v.year} {v.make} {v.model}
  279. </span>
  280. {v.licensePlate && (
  281. <span className="ml-2 font-mono text-xs text-muted-foreground">
  282. {v.licensePlate}
  283. </span>
  284. )}
  285. </CommandItem>
  286. ))}
  287. </CommandGroup>
  288. )}
  289. {results.services.length > 0 && (
  290. <CommandGroup heading="Services">
  291. {results.services.map((s) => (
  292. <CommandItem
  293. key={s.id}
  294. value={`${s.title} ${s.invoiceNumber || ""} ${s.vehicle.make} ${s.vehicle.model}`}
  295. onSelect={() => handleSelect(`/vehicles/${s.vehicle.id}/service/${s.id}`)}
  296. >
  297. <Wrench className="mr-2 h-4 w-4 text-muted-foreground" />
  298. <div className="flex flex-col">
  299. <span>{s.title}</span>
  300. <span className="text-xs text-muted-foreground">
  301. {[
  302. s.invoiceNumber,
  303. `${s.vehicle.year} ${s.vehicle.make} ${s.vehicle.model}`,
  304. s.vehicle.licensePlate,
  305. ].filter(Boolean).join(" · ")}
  306. </span>
  307. </div>
  308. </CommandItem>
  309. ))}
  310. </CommandGroup>
  311. )}
  312. {results.quotes.length > 0 && (
  313. <CommandGroup heading="Quotes">
  314. {results.quotes.map((q) => (
  315. <CommandItem
  316. key={q.id}
  317. value={`${q.title} ${q.quoteNumber || ""}`}
  318. onSelect={() => handleSelect(`/quotes/${q.id}`)}
  319. >
  320. <FileText className="mr-2 h-4 w-4 text-muted-foreground" />
  321. <div className="flex flex-col">
  322. <span>{q.title}</span>
  323. <span className="text-xs text-muted-foreground">
  324. {[q.quoteNumber, q.status].filter(Boolean).join(" · ")}
  325. </span>
  326. </div>
  327. </CommandItem>
  328. ))}
  329. </CommandGroup>
  330. )}
  331. {results.parts.length > 0 && (
  332. <CommandGroup heading="Parts">
  333. {results.parts.map((p) => (
  334. <CommandItem
  335. key={p.id}
  336. value={`${p.name} ${p.partNumber || ""}`}
  337. onSelect={() => handleSelect("/inventory")}
  338. >
  339. <Package className="mr-2 h-4 w-4 text-muted-foreground" />
  340. <div className="flex flex-col">
  341. <span>{p.name}</span>
  342. <span className="text-xs text-muted-foreground">
  343. {[p.partNumber, `${p.quantity} in stock`].filter(Boolean).join(" · ")}
  344. </span>
  345. </div>
  346. </CommandItem>
  347. ))}
  348. </CommandGroup>
  349. )}
  350. {results.reminders.length > 0 && (
  351. <CommandGroup heading="Reminders">
  352. {results.reminders.map((r) => (
  353. <CommandItem
  354. key={r.id}
  355. value={`${r.title} ${r.vehicle.make} ${r.vehicle.model} ${r.vehicle.licensePlate || ""}`}
  356. onSelect={() => handleSelect(`/vehicles/${r.vehicle.id}?tab=reminders`)}
  357. >
  358. <Bell className="mr-2 h-4 w-4 text-muted-foreground" />
  359. <div className="flex flex-col">
  360. <span>{r.title}{r.isCompleted && <span className="ml-1.5 text-muted-foreground line-through">(done)</span>}</span>
  361. <span className="text-xs text-muted-foreground">
  362. {`${r.vehicle.year} ${r.vehicle.make} ${r.vehicle.model}`}
  363. {r.vehicle.licensePlate && ` · ${r.vehicle.licensePlate}`}
  364. </span>
  365. </div>
  366. </CommandItem>
  367. ))}
  368. </CommandGroup>
  369. )}
  370. {results.inspections.length > 0 && (
  371. <CommandGroup heading="Inspections">
  372. {results.inspections.map((insp) => (
  373. <CommandItem
  374. key={insp.id}
  375. value={`${insp.template.name} ${insp.vehicle.make} ${insp.vehicle.model} ${insp.vehicle.licensePlate || ""}`}
  376. onSelect={() => handleSelect(`/inspections/${insp.id}`)}
  377. >
  378. <ClipboardCheck className="mr-2 h-4 w-4 text-muted-foreground" />
  379. <div className="flex flex-col">
  380. <span>{insp.template.name}</span>
  381. <span className="text-xs text-muted-foreground">
  382. {`${insp.vehicle.year} ${insp.vehicle.make} ${insp.vehicle.model}`}
  383. {insp.vehicle.licensePlate && ` · ${insp.vehicle.licensePlate}`}
  384. {` · ${insp.status}`}
  385. </span>
  386. </div>
  387. </CommandItem>
  388. ))}
  389. </CommandGroup>
  390. )}
  391. </>
  392. )}
  393. {/* Settings group: shown in both default and search views */}
  394. {matchedSettings.length > 0 && (
  395. <CommandGroup heading="Settings">
  396. {matchedSettings.map((s) => (
  397. <CommandItem
  398. key={s.href}
  399. value={`${s.label} ${s.keywords.join(" ")}`}
  400. onSelect={() => handleSelect(s.href)}
  401. >
  402. <Settings className="mr-2 h-4 w-4 text-muted-foreground" />
  403. <div className="flex flex-col">
  404. <span>{s.label}</span>
  405. <span className="text-xs text-muted-foreground">
  406. {s.description}
  407. </span>
  408. </div>
  409. </CommandItem>
  410. ))}
  411. </CommandGroup>
  412. )}
  413. </CommandList>
  414. <div className="border-t px-3 py-2">
  415. <span className="text-xs text-muted-foreground">
  416. <kbd className="pointer-events-none inline-flex h-5 items-center rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground">ESC</kbd>
  417. <span className="ml-1.5">to close</span>
  418. </span>
  419. </div>
  420. </CommandDialog>
  421. );
  422. }