GroupEditPage.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import { useState, useMemo } from 'react';
  2. import { Link, useParams, useNavigate } from 'react-router-dom';
  3. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import { useTranslation } from 'react-i18next';
  5. import { ArrowLeft, Save, Loader2, Search, Check, Minus, Shield, AlertTriangle, Printer as PrinterIcon } from 'lucide-react';
  6. import { api } from '../api/client';
  7. import type { GroupCreate, GroupUpdate, Permission, PermissionCategory } from '../api/client';
  8. import { Button } from '../components/Button';
  9. import { Card } from '../components/Card';
  10. import { useToast } from '../contexts/ToastContext';
  11. export function GroupEditPage() {
  12. const { id } = useParams<{ id: string }>();
  13. const navigate = useNavigate();
  14. const queryClient = useQueryClient();
  15. const { t } = useTranslation();
  16. const { showToast } = useToast();
  17. const isEditing = Boolean(id);
  18. const [name, setName] = useState('');
  19. const [description, setDescription] = useState('');
  20. const [permissions, setPermissions] = useState<Permission[]>([]);
  21. const [search, setSearch] = useState('');
  22. const [initialized, setInitialized] = useState(false);
  23. const { data: groupData, isLoading: groupLoading } = useQuery({
  24. queryKey: ['group', id],
  25. queryFn: () => api.getGroup(Number(id)),
  26. enabled: isEditing,
  27. });
  28. const { data: permissionsData, isLoading: permissionsLoading } = useQuery({
  29. queryKey: ['permissions'],
  30. queryFn: () => api.getPermissions(),
  31. });
  32. // Initialize form from fetched group data (once)
  33. if (isEditing && groupData && !initialized) {
  34. setName(groupData.name);
  35. setDescription(groupData.description || '');
  36. setPermissions(groupData.permissions);
  37. setInitialized(true);
  38. }
  39. const createMutation = useMutation({
  40. mutationFn: (data: GroupCreate) => api.createGroup(data),
  41. onSuccess: () => {
  42. queryClient.invalidateQueries({ queryKey: ['groups'] });
  43. queryClient.invalidateQueries({ queryKey: ['group'] });
  44. showToast(t('groups.toast.created'));
  45. navigate('/settings?tab=users');
  46. },
  47. onError: (error: Error) => {
  48. showToast(error.message, 'error');
  49. },
  50. });
  51. const updateMutation = useMutation({
  52. mutationFn: (data: GroupUpdate) => api.updateGroup(Number(id), data),
  53. onSuccess: (updatedGroup) => {
  54. queryClient.invalidateQueries({ queryKey: ['groups'] });
  55. // Prime the single-group detail cache with the PATCH response body so
  56. // reopening the editor within the 60s default staleTime shows the
  57. // newly-saved permissions instead of the stale pre-update snapshot
  58. // (#1083). setQueryData alone is enough — we intentionally do NOT also
  59. // invalidate ['group', id] because that would trigger an immediate
  60. // background refetch that could race with / overwrite this primed value
  61. // in test environments where the GET handler is a static mock; in
  62. // production the server's GET would match this payload anyway.
  63. if (updatedGroup) {
  64. queryClient.setQueryData(['group', id], updatedGroup);
  65. }
  66. showToast(t('groups.toast.updated'));
  67. navigate('/settings?tab=users');
  68. },
  69. onError: (error: Error) => {
  70. showToast(error.message, 'error');
  71. },
  72. });
  73. const isSaving = createMutation.isPending || updateMutation.isPending;
  74. // Administrators see every printer regardless
  75. const isAdministrators = isEditing && groupData?.is_system === true && groupData.name === 'Administrators';
  76. const handleSave = () => {
  77. if (!name.trim()) {
  78. showToast(t('groups.toast.enterGroupName'), 'error');
  79. return;
  80. }
  81. if (isEditing) {
  82. // System groups refuse any permissions payload, so only send it when it
  83. // changed -- otherwise their description couldn't be saved at all.
  84. const permissionsChanged =
  85. !groupData ||
  86. permissions.length !== groupData.permissions.length ||
  87. permissions.some((p) => !groupData.permissions.includes(p));
  88. updateMutation.mutate({
  89. name: name !== groupData?.name ? name : undefined,
  90. description,
  91. permissions: groupData?.is_system && !permissionsChanged ? undefined : permissions,
  92. });
  93. } else {
  94. createMutation.mutate({
  95. name,
  96. description: description || undefined,
  97. permissions,
  98. });
  99. }
  100. };
  101. const togglePermission = (perm: Permission) => {
  102. setPermissions((prev) =>
  103. prev.includes(perm) ? prev.filter((p) => p !== perm) : [...prev, perm]
  104. );
  105. };
  106. const toggleCategoryPermissions = (category: PermissionCategory, checked: boolean) => {
  107. const categoryPerms = category.permissions.map((p) => p.value);
  108. setPermissions((prev) => {
  109. const otherPerms = prev.filter((p) => !categoryPerms.includes(p));
  110. return checked ? [...otherPerms, ...categoryPerms] : otherPerms;
  111. });
  112. };
  113. const isCategoryFullySelected = (category: PermissionCategory) =>
  114. category.permissions.every((p) => permissions.includes(p.value));
  115. const isCategoryPartiallySelected = (category: PermissionCategory) => {
  116. const count = category.permissions.filter((p) => permissions.includes(p.value)).length;
  117. return count > 0 && count < category.permissions.length;
  118. };
  119. const selectAll = () => {
  120. if (permissionsData) {
  121. setPermissions(permissionsData.all_permissions);
  122. }
  123. };
  124. const clearAll = () => {
  125. setPermissions([]);
  126. };
  127. const searchLower = search.toLowerCase();
  128. const filteredCategories = useMemo(() => {
  129. if (!permissionsData) return [];
  130. if (!searchLower) return permissionsData.categories;
  131. return permissionsData.categories
  132. .map((cat) => ({
  133. ...cat,
  134. permissions: cat.permissions.filter((p) =>
  135. p.label.toLowerCase().includes(searchLower)
  136. ),
  137. }))
  138. .filter((cat) => cat.permissions.length > 0);
  139. }, [permissionsData, searchLower]);
  140. const totalPermissions = permissionsData?.all_permissions.length ?? 0;
  141. if (groupLoading || permissionsLoading) {
  142. return (
  143. <div className="flex items-center justify-center py-16">
  144. <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
  145. </div>
  146. );
  147. }
  148. return (
  149. <div className="space-y-6 max-w-5xl mx-auto">
  150. {/* Header */}
  151. <div className="flex items-center gap-3">
  152. <button
  153. onClick={() => navigate('/settings?tab=users')}
  154. className="p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors"
  155. >
  156. <ArrowLeft className="w-5 h-5" />
  157. </button>
  158. <h1 className="text-xl font-bold text-white">
  159. {isEditing ? t('groups.editor.title') : t('groups.editor.createTitle')}
  160. </h1>
  161. </div>
  162. {/* System group warning */}
  163. {isEditing && groupData?.is_system && (
  164. <div className="flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/20 text-yellow-700 dark:text-yellow-400 text-sm">
  165. <AlertTriangle className="w-4 h-4 shrink-0" />
  166. {t('groups.form.systemGroupWarning')}
  167. </div>
  168. )}
  169. {/* Name + Description */}
  170. <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
  171. <div>
  172. <label className="block text-sm font-medium text-white mb-2">{t('groups.form.groupName')}</label>
  173. <input
  174. type="text"
  175. value={name}
  176. onChange={(e) => setName(e.target.value)}
  177. disabled={isEditing && groupData?.is_system}
  178. className="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50"
  179. placeholder={t('groups.form.groupNamePlaceholder')}
  180. />
  181. </div>
  182. <div>
  183. <label className="block text-sm font-medium text-white mb-2">{t('groups.form.description')}</label>
  184. <input
  185. type="text"
  186. value={description}
  187. onChange={(e) => setDescription(e.target.value)}
  188. className="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"
  189. placeholder={t('groups.form.descriptionPlaceholder')}
  190. />
  191. </div>
  192. </div>
  193. {/* Printer access (#1727) is managed on its own page */}
  194. <Card>
  195. <div className="p-4 flex flex-wrap items-center justify-between gap-3">
  196. <div className="flex items-center gap-2 min-w-0">
  197. <PrinterIcon className="w-4 h-4 text-bambu-gray shrink-0" />
  198. <span className="text-white font-medium text-sm">{t('groups.editor.printerAccess')}</span>
  199. <span className="text-sm text-bambu-gray">
  200. {isAdministrators
  201. ? t('groups.editor.adminsSeeAllPrinters')
  202. : !isEditing
  203. ? t('groups.editor.printerAccessAfterCreate')
  204. : groupData?.restrict_printers
  205. ? t('groups.editor.printerAccessLimited', {
  206. printers: groupData.printer_ids.length,
  207. locations: groupData.locations?.length ?? 0,
  208. })
  209. : t('groups.editor.printerAccessOpen')}
  210. </span>
  211. </div>
  212. {isEditing && !isAdministrators && (
  213. <Link
  214. to={`/settings?tab=users&sub=printer-access&group=${id}`}
  215. className="text-sm text-bambu-green hover:underline shrink-0"
  216. >
  217. {t('groups.editor.managePrinterAccess')}
  218. </Link>
  219. )}
  220. </div>
  221. </Card>
  222. {/* Toolbar */}
  223. <div className="flex items-center justify-between flex-wrap gap-3">
  224. <div className="flex items-center gap-3">
  225. <span className="text-sm text-bambu-gray">
  226. {t('groups.editor.permissionsSelected', { count: permissions.length })} / {totalPermissions}
  227. </span>
  228. <Button size="sm" variant="ghost" onClick={selectAll}>
  229. {t('groups.editor.selectAll')}
  230. </Button>
  231. <Button size="sm" variant="ghost" onClick={clearAll}>
  232. {t('groups.editor.clearAll')}
  233. </Button>
  234. </div>
  235. <div className="relative">
  236. <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray" />
  237. <input
  238. type="text"
  239. value={search}
  240. onChange={(e) => setSearch(e.target.value)}
  241. placeholder={t('groups.editor.search')}
  242. className="pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"
  243. />
  244. </div>
  245. </div>
  246. {/* Permission grid */}
  247. {filteredCategories.length === 0 ? (
  248. <div className="text-center py-12 text-bambu-gray">
  249. {t('groups.editor.noResults')}
  250. </div>
  251. ) : (
  252. <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
  253. {filteredCategories.map((category) => {
  254. // Use the full (unfiltered) category for selection logic
  255. const fullCategory = permissionsData!.categories.find((c) => c.name === category.name)!;
  256. const selectedCount = fullCategory.permissions.filter((p) => permissions.includes(p.value)).length;
  257. const totalCount = fullCategory.permissions.length;
  258. const fullySelected = isCategoryFullySelected(fullCategory);
  259. const partiallySelected = isCategoryPartiallySelected(fullCategory);
  260. return (
  261. <Card key={category.name}>
  262. <div className="sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl">
  263. <div className="flex items-center gap-3">
  264. <button
  265. type="button"
  266. onClick={() => toggleCategoryPermissions(fullCategory, !fullySelected)}
  267. className={`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${
  268. fullySelected
  269. ? 'bg-bambu-green border-bambu-green'
  270. : partiallySelected
  271. ? 'bg-bambu-green/50 border-bambu-green'
  272. : 'border-bambu-gray hover:border-white'
  273. }`}
  274. >
  275. {fullySelected && <Check className="w-3 h-3 text-white" />}
  276. {partiallySelected && !fullySelected && <Minus className="w-3 h-3 text-white" />}
  277. </button>
  278. <Shield className="w-4 h-4 text-bambu-gray shrink-0" />
  279. <span className="text-white font-medium text-sm">{category.name}</span>
  280. </div>
  281. <span className="text-xs text-bambu-gray tabular-nums">
  282. {selectedCount}/{totalCount}
  283. </span>
  284. </div>
  285. <div className="p-3 space-y-1">
  286. {category.permissions.map((perm) => (
  287. <label
  288. key={perm.value}
  289. className="flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer"
  290. >
  291. <input
  292. type="checkbox"
  293. checked={permissions.includes(perm.value)}
  294. onChange={() => togglePermission(perm.value)}
  295. className="w-4 h-4 shrink-0 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"
  296. />
  297. <span className="flex flex-col">
  298. <span className="text-sm text-bambu-gray">{perm.label}</span>
  299. {perm.value === 'websocket:connect' && (
  300. <span className="text-xs text-bambu-gray/60">
  301. {t('groups.editor.websocketHint')}
  302. </span>
  303. )}
  304. </span>
  305. </label>
  306. ))}
  307. </div>
  308. </Card>
  309. );
  310. })}
  311. </div>
  312. )}
  313. {/* Spacer for fixed bottom bar */}
  314. <div className="h-16" />
  315. {/* Fixed bottom bar */}
  316. <div className="fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3">
  317. <Button variant="secondary" onClick={() => navigate('/settings?tab=users')}>
  318. {t('common.cancel')}
  319. </Button>
  320. <Button onClick={handleSave} disabled={isSaving || !name.trim()}>
  321. {isSaving ? (
  322. <>
  323. <Loader2 className="w-4 h-4 animate-spin" />
  324. {t('common.saving')}
  325. </>
  326. ) : (
  327. <>
  328. <Save className="w-4 h-4" />
  329. {t('common.save')}
  330. </>
  331. )}
  332. </Button>
  333. </div>
  334. </div>
  335. );
  336. }