LocationsModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import { useState, useEffect, useCallback } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { MapPin, Plus, Loader2, Pencil, Trash2, X } from 'lucide-react';
  5. import { api, type StorageLocation } from '../api/client';
  6. import { Button } from './Button';
  7. import { ConfirmModal } from './ConfirmModal';
  8. import { useToast } from '../contexts/ToastContext';
  9. import { inventoryLocationsQueryKey, invalidateInventoryLocations } from '../utils/inventoryQueries';
  10. interface LocationsModalProps {
  11. open: boolean;
  12. onClose: () => void;
  13. // Optional even with startCreating: a caller that just wants the inline
  14. // "create a location" dialog without picking one afterward can omit it.
  15. // The save always closes the modal regardless of whether this is set.
  16. onPickLocation?: (locationId: number) => void;
  17. startCreating?: boolean;
  18. }
  19. export function LocationsModal({ open, onClose, onPickLocation, startCreating }: LocationsModalProps) {
  20. const { t } = useTranslation();
  21. const queryClient = useQueryClient();
  22. const { showToast } = useToast();
  23. const [editorOpen, setEditorOpen] = useState(false);
  24. const [editing, setEditing] = useState<StorageLocation | null>(null);
  25. const [name, setName] = useState('');
  26. const [deleteTarget, setDeleteTarget] = useState<StorageLocation | null>(null);
  27. const { data: locations = [], isLoading } = useQuery({
  28. queryKey: inventoryLocationsQueryKey,
  29. queryFn: api.getLocations,
  30. enabled: open,
  31. });
  32. const { data: locationSensors = [] } = useQuery({
  33. queryKey: ['locationHaSensors'],
  34. queryFn: () => api.getLocationHASensors(),
  35. enabled: open,
  36. });
  37. const sensorCountByLocation = locationSensors.reduce<Record<number, number>>((acc, sensor) => {
  38. acc[sensor.location_id] = (acc[sensor.location_id] ?? 0) + 1;
  39. return acc;
  40. }, {});
  41. const invalidate = () => {
  42. invalidateInventoryLocations(queryClient);
  43. queryClient.invalidateQueries({ queryKey: ['inventory-spools'] });
  44. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  45. queryClient.invalidateQueries({ queryKey: ['locationHaSensors'] });
  46. queryClient.invalidateQueries({ queryKey: ['locationHaSensorReadings'] });
  47. };
  48. const saveMutation = useMutation({
  49. mutationFn: async () => {
  50. const trimmed = name.trim();
  51. if (!trimmed) throw new Error(t('locations.nameRequired'));
  52. if (editing) {
  53. return api.updateLocation(editing.id, { name: trimmed });
  54. }
  55. return api.createLocation({ name: trimmed });
  56. },
  57. onSuccess: (saved) => {
  58. showToast(t(editing ? 'locations.updated' : 'locations.created'), 'success');
  59. invalidate();
  60. // startCreating mode has no location-list view to fall back to (see the
  61. // render branch below and closeEditor's own unconditional onClose), so
  62. // a save here must always close — with or without onPickLocation, which
  63. // is optional by design for a caller that only wants location
  64. // management, not a picker. Gating this on onPickLocation being set
  65. // used to leave editorOpen false with open still true: nothing left to
  66. // render, but the caller never told to close.
  67. if (!editing && startCreating) {
  68. onPickLocation?.(saved.id);
  69. onClose();
  70. return;
  71. }
  72. setEditorOpen(false);
  73. setEditing(null);
  74. setName('');
  75. },
  76. onError: (err: Error) => {
  77. showToast(err.message || t('locations.saveFailed'), 'error');
  78. },
  79. });
  80. const deleteMutation = useMutation({
  81. mutationFn: (id: number) => api.deleteLocation(id),
  82. onSuccess: () => {
  83. showToast(t('locations.deleted'), 'success');
  84. setDeleteTarget(null);
  85. invalidate();
  86. },
  87. onError: (err: Error) => {
  88. showToast(err.message || t('locations.deleteFailed'), 'error');
  89. },
  90. });
  91. const openCreate = () => {
  92. setEditing(null);
  93. setName('');
  94. setEditorOpen(true);
  95. };
  96. useEffect(() => {
  97. if (open && startCreating) {
  98. setEditing(null);
  99. setName('');
  100. setEditorOpen(true);
  101. }
  102. }, [open, startCreating]);
  103. const openEdit = (location: StorageLocation) => {
  104. setEditing(location);
  105. setName(location.name);
  106. setEditorOpen(true);
  107. };
  108. const closeEditor = useCallback(() => {
  109. if (saveMutation.isPending) return;
  110. if (startCreating) {
  111. onClose();
  112. return;
  113. }
  114. setEditorOpen(false);
  115. setEditing(null);
  116. setName('');
  117. }, [saveMutation.isPending, startCreating, onClose]);
  118. // Esc closes the inner editor first; if it's closed, Esc closes the outer
  119. // modal — but only when neither save nor delete is mid-flight, so a stray
  120. // keypress during a network round-trip doesn't drop the user back into the
  121. // inventory page with an orphaned spinner.
  122. useEffect(() => {
  123. if (!open) return;
  124. const handleKeyDown = (e: KeyboardEvent) => {
  125. if (e.key !== 'Escape') return;
  126. if (saveMutation.isPending || deleteMutation.isPending) return;
  127. if (editorOpen) {
  128. closeEditor();
  129. } else if (!deleteTarget) {
  130. onClose();
  131. }
  132. };
  133. document.addEventListener('keydown', handleKeyDown);
  134. return () => document.removeEventListener('keydown', handleKeyDown);
  135. }, [open, editorOpen, deleteTarget, saveMutation.isPending, deleteMutation.isPending, closeEditor, onClose]);
  136. const handleSave = (e: React.FormEvent) => {
  137. e.preventDefault();
  138. saveMutation.mutate();
  139. };
  140. if (!open) return null;
  141. const modalTitleId = 'locations-modal-title';
  142. const editorTitleId = 'location-editor-title';
  143. const editorForm = (
  144. <form onSubmit={handleSave}>
  145. <label className="block text-sm font-medium text-bambu-gray mb-1" htmlFor="location-name">
  146. {t('locations.name')}
  147. </label>
  148. <input
  149. id="location-name"
  150. type="text"
  151. maxLength={255}
  152. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green mb-4"
  153. placeholder={t('locations.createPlaceholder')}
  154. value={name}
  155. onChange={(e) => setName(e.target.value)}
  156. autoFocus
  157. />
  158. <div className="flex justify-end gap-2">
  159. <Button type="button" variant="secondary" onClick={closeEditor}>
  160. {t('common.cancel')}
  161. </Button>
  162. <Button type="submit" disabled={saveMutation.isPending || !name.trim()}>
  163. {saveMutation.isPending && <Loader2 className="w-4 h-4 animate-spin" />}
  164. {t('common.save')}
  165. </Button>
  166. </div>
  167. </form>
  168. );
  169. if (startCreating) {
  170. return editorOpen ? (
  171. <div className="fixed inset-0 z-50 flex items-center justify-center">
  172. <div className="absolute inset-0 bg-black/60" onClick={closeEditor} />
  173. <div
  174. className="relative w-full max-w-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-6 shadow-2xl"
  175. role="dialog"
  176. aria-modal="true"
  177. aria-labelledby={editorTitleId}
  178. >
  179. <h3 id={editorTitleId} className="text-lg font-semibold text-white mb-4">
  180. {t('locations.add')}
  181. </h3>
  182. {editorForm}
  183. </div>
  184. </div>
  185. ) : null;
  186. }
  187. return (
  188. <div className="fixed inset-0 z-50 flex items-center justify-center">
  189. <div
  190. className="absolute inset-0 bg-black/60"
  191. onClick={() => {
  192. if (saveMutation.isPending || deleteMutation.isPending) return;
  193. onClose();
  194. }}
  195. />
  196. <div
  197. className="relative w-full max-w-2xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col"
  198. role="dialog"
  199. aria-modal="true"
  200. aria-labelledby={modalTitleId}
  201. >
  202. <div className="flex items-center justify-between gap-4 px-6 py-4 border-b border-bambu-dark-tertiary">
  203. <div>
  204. <h2 id={modalTitleId} className="text-lg font-semibold text-white flex items-center gap-2">
  205. <MapPin className="w-5 h-5 text-bambu-green" />
  206. {t('locations.title')}
  207. </h2>
  208. <p className="text-bambu-gray text-sm mt-0.5">{t('locations.subtitle')}</p>
  209. </div>
  210. <div className="flex items-center gap-2">
  211. <Button onClick={openCreate}>
  212. <Plus className="w-4 h-4" />
  213. {t('locations.add')}
  214. </Button>
  215. <button
  216. type="button"
  217. className="p-1.5 text-bambu-gray hover:text-white rounded"
  218. onClick={onClose}
  219. aria-label={t('common.close')}
  220. >
  221. <X className="w-5 h-5" />
  222. </button>
  223. </div>
  224. </div>
  225. <div className="overflow-y-auto">
  226. {isLoading ? (
  227. <div className="flex items-center justify-center py-16 text-bambu-gray">
  228. <Loader2 className="w-6 h-6 animate-spin mr-2" />
  229. {t('common.loading')}
  230. </div>
  231. ) : locations.length === 0 ? (
  232. <div className="py-16 text-center text-bambu-gray">{t('locations.empty')}</div>
  233. ) : (
  234. <table className="w-full text-sm table-fixed">
  235. <thead>
  236. <tr className="border-b border-bambu-dark-tertiary text-left text-bambu-gray">
  237. <th className="px-4 py-3 font-medium">{t('locations.name')}</th>
  238. <th className="px-2 py-3 font-medium text-right w-24">{t('locations.sensors')}</th>
  239. <th className="pl-[28px] pr-4 py-3 font-medium text-right w-28">{t('locations.spools')}</th>
  240. <th className="px-4 py-3 font-medium text-right w-32">{t('common.actions')}</th>
  241. </tr>
  242. </thead>
  243. <tbody>
  244. {locations.map((loc) => (
  245. <tr
  246. key={loc.id}
  247. className="border-b border-bambu-dark-tertiary/60 hover:bg-bambu-dark-tertiary/30 cursor-pointer"
  248. onClick={() => {
  249. if (onPickLocation) {
  250. onPickLocation(loc.id);
  251. onClose();
  252. }
  253. }}
  254. >
  255. <td className="px-4 py-3 text-white font-medium truncate">{loc.name}</td>
  256. <td className="px-2 py-3 text-right text-bambu-gray">{sensorCountByLocation[loc.id] ?? 0}</td>
  257. <td className="pl-[28px] pr-4 py-3 text-right text-bambu-gray">{loc.spool_count}</td>
  258. <td className="px-4 py-3 text-right" onClick={(e) => e.stopPropagation()}>
  259. <div className="flex items-center justify-end gap-1">
  260. <button
  261. type="button"
  262. className="p-1.5 text-bambu-gray hover:text-bambu-green rounded"
  263. onClick={() => openEdit(loc)}
  264. title={t('common.edit')}
  265. aria-label={t('locations.editAria', { name: loc.name, defaultValue: `Edit ${loc.name}` })}
  266. >
  267. <Pencil className="w-4 h-4" />
  268. </button>
  269. <button
  270. type="button"
  271. className="p-1.5 text-bambu-gray hover:text-red-600 dark:hover:text-red-400 rounded disabled:opacity-40"
  272. disabled={loc.spool_count > 0}
  273. onClick={() => setDeleteTarget(loc)}
  274. title={loc.spool_count > 0 ? t('locations.deleteBlocked') : t('common.delete')}
  275. aria-label={t('locations.deleteAria', { name: loc.name, defaultValue: `Delete ${loc.name}` })}
  276. >
  277. <Trash2 className="w-4 h-4" />
  278. </button>
  279. </div>
  280. </td>
  281. </tr>
  282. ))}
  283. </tbody>
  284. </table>
  285. )}
  286. </div>
  287. </div>
  288. {editorOpen && (
  289. <div className="fixed inset-0 z-[60] flex items-center justify-center">
  290. <div className="absolute inset-0 bg-black/60" onClick={closeEditor} />
  291. <div
  292. className="relative w-full max-w-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-6 shadow-2xl"
  293. role="dialog"
  294. aria-modal="true"
  295. aria-labelledby={editorTitleId}
  296. >
  297. <h3 id={editorTitleId} className="text-lg font-semibold text-white mb-4">
  298. {editing ? t('locations.edit') : t('locations.add')}
  299. </h3>
  300. {editorForm}
  301. </div>
  302. </div>
  303. )}
  304. {deleteTarget && (
  305. <ConfirmModal
  306. title={t('locations.confirmDelete', { name: deleteTarget.name })}
  307. message={
  308. sensorCountByLocation[deleteTarget.id]
  309. ? t('locations.confirmDeleteMessageWithSensors')
  310. : t('locations.confirmDeleteMessage')
  311. }
  312. confirmText={t('common.delete')}
  313. variant="danger"
  314. isLoading={deleteMutation.isPending}
  315. onConfirm={() => deleteMutation.mutate(deleteTarget.id)}
  316. onCancel={() => setDeleteTarget(null)}
  317. />
  318. )}
  319. </div>
  320. );
  321. }