SpoolmanSettings.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import { useState, useEffect } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { Loader2, Check, X, RefreshCw, Link2, Link2Off, Database, ChevronDown, Info, AlertTriangle } from 'lucide-react';
  4. import { api } from '../api/client';
  5. import type { SpoolmanSyncResult, Printer } from '../api/client';
  6. import { Card, CardContent, CardHeader } from './Card';
  7. import { Button } from './Button';
  8. interface SpoolmanSettingsData {
  9. spoolman_enabled: string;
  10. spoolman_url: string;
  11. spoolman_sync_mode: string;
  12. }
  13. async function getSpoolmanSettings(): Promise<SpoolmanSettingsData> {
  14. const response = await fetch('/api/v1/settings/spoolman');
  15. if (!response.ok) {
  16. throw new Error('Failed to load Spoolman settings');
  17. }
  18. return response.json();
  19. }
  20. async function updateSpoolmanSettings(data: Partial<SpoolmanSettingsData>): Promise<SpoolmanSettingsData> {
  21. const response = await fetch('/api/v1/settings/spoolman', {
  22. method: 'PUT',
  23. headers: { 'Content-Type': 'application/json' },
  24. body: JSON.stringify(data),
  25. });
  26. if (!response.ok) {
  27. throw new Error('Failed to save Spoolman settings');
  28. }
  29. return response.json();
  30. }
  31. export function SpoolmanSettings() {
  32. const queryClient = useQueryClient();
  33. const [localEnabled, setLocalEnabled] = useState(false);
  34. const [localUrl, setLocalUrl] = useState('');
  35. const [localSyncMode, setLocalSyncMode] = useState('auto');
  36. const [showSaved, setShowSaved] = useState(false);
  37. const [selectedPrinterId, setSelectedPrinterId] = useState<number | 'all'>('all');
  38. const [isInitialized, setIsInitialized] = useState(false);
  39. const [showAllSkipped, setShowAllSkipped] = useState(false);
  40. // Fetch Spoolman settings
  41. const { data: settings, isLoading: settingsLoading } = useQuery({
  42. queryKey: ['spoolman-settings'],
  43. queryFn: getSpoolmanSettings,
  44. });
  45. // Fetch Spoolman status
  46. const { data: status, isLoading: statusLoading, refetch: refetchStatus } = useQuery({
  47. queryKey: ['spoolman-status'],
  48. queryFn: api.getSpoolmanStatus,
  49. refetchInterval: 30000, // Refresh every 30 seconds
  50. });
  51. // Fetch printers for the dropdown
  52. const { data: printers } = useQuery({
  53. queryKey: ['printers'],
  54. queryFn: api.getPrinters,
  55. });
  56. // Initialize local state from settings
  57. useEffect(() => {
  58. if (settings) {
  59. setLocalEnabled(settings.spoolman_enabled === 'true');
  60. setLocalUrl(settings.spoolman_url || '');
  61. setLocalSyncMode(settings.spoolman_sync_mode || 'auto');
  62. setIsInitialized(true);
  63. }
  64. }, [settings]);
  65. // Auto-save when settings change (after initial load)
  66. useEffect(() => {
  67. if (!isInitialized || !settings) return;
  68. const hasChanges =
  69. (settings.spoolman_enabled === 'true') !== localEnabled ||
  70. (settings.spoolman_url || '') !== localUrl ||
  71. (settings.spoolman_sync_mode || 'auto') !== localSyncMode;
  72. if (hasChanges) {
  73. const timeoutId = setTimeout(() => {
  74. saveMutation.mutate();
  75. }, 500);
  76. return () => clearTimeout(timeoutId);
  77. }
  78. }, [localEnabled, localUrl, localSyncMode, isInitialized]);
  79. // Save mutation
  80. const saveMutation = useMutation({
  81. mutationFn: () =>
  82. updateSpoolmanSettings({
  83. spoolman_enabled: localEnabled ? 'true' : 'false',
  84. spoolman_url: localUrl,
  85. spoolman_sync_mode: localSyncMode,
  86. }),
  87. onSuccess: () => {
  88. queryClient.invalidateQueries({ queryKey: ['spoolman-settings'] });
  89. queryClient.invalidateQueries({ queryKey: ['spoolman-status'] });
  90. setShowSaved(true);
  91. setTimeout(() => setShowSaved(false), 2000);
  92. },
  93. });
  94. // Connect mutation
  95. const connectMutation = useMutation({
  96. mutationFn: api.connectSpoolman,
  97. onSuccess: () => {
  98. refetchStatus();
  99. },
  100. });
  101. // Disconnect mutation
  102. const disconnectMutation = useMutation({
  103. mutationFn: api.disconnectSpoolman,
  104. onSuccess: () => {
  105. refetchStatus();
  106. },
  107. });
  108. // Sync all mutation
  109. const syncAllMutation = useMutation({
  110. mutationFn: api.syncAllPrintersAms,
  111. onSuccess: (data: SpoolmanSyncResult) => {
  112. if (data.success) {
  113. // Show success message
  114. }
  115. },
  116. });
  117. // Sync single printer mutation
  118. const syncPrinterMutation = useMutation({
  119. mutationFn: (printerId: number) => api.syncPrinterAms(printerId),
  120. onSuccess: (data: SpoolmanSyncResult) => {
  121. if (data.success) {
  122. // Show success message
  123. }
  124. },
  125. });
  126. // Helper to handle sync based on selection
  127. const handleSync = () => {
  128. if (selectedPrinterId === 'all') {
  129. syncAllMutation.mutate();
  130. } else {
  131. syncPrinterMutation.mutate(selectedPrinterId);
  132. }
  133. };
  134. // Combine mutation states
  135. const isSyncing = syncAllMutation.isPending || syncPrinterMutation.isPending;
  136. const syncResult = selectedPrinterId === 'all' ? syncAllMutation.data : syncPrinterMutation.data;
  137. const syncSuccess = selectedPrinterId === 'all' ? syncAllMutation.isSuccess : syncPrinterMutation.isSuccess;
  138. if (settingsLoading) {
  139. return (
  140. <Card>
  141. <CardHeader>
  142. <div className="flex items-center gap-2">
  143. <Database className="w-5 h-5 text-bambu-green" />
  144. <h2 className="text-lg font-semibold text-white">Spoolman Integration</h2>
  145. </div>
  146. </CardHeader>
  147. <CardContent>
  148. <div className="flex justify-center py-8">
  149. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  150. </div>
  151. </CardContent>
  152. </Card>
  153. );
  154. }
  155. return (
  156. <Card>
  157. <CardHeader>
  158. <div className="flex items-center justify-between">
  159. <div className="flex items-center gap-2">
  160. <Database className="w-5 h-5 text-bambu-green" />
  161. <h2 className="text-lg font-semibold text-white">Spoolman Integration</h2>
  162. </div>
  163. {saveMutation.isPending && (
  164. <Loader2 className="w-4 h-4 text-bambu-green animate-spin" />
  165. )}
  166. {showSaved && (
  167. <Check className="w-4 h-4 text-bambu-green" />
  168. )}
  169. </div>
  170. </CardHeader>
  171. <CardContent className="space-y-4">
  172. <p className="text-sm text-bambu-gray">
  173. Connect to Spoolman for filament inventory tracking. AMS data will sync automatically.
  174. </p>
  175. {/* Info banner about sync requirements */}
  176. <div className="p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg">
  177. <div className="flex gap-2">
  178. <Info className="w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5" />
  179. <div className="text-xs text-blue-300">
  180. <p className="font-medium mb-1">How Sync Works</p>
  181. <ul className="list-disc list-inside space-y-0.5 text-blue-300/80">
  182. <li>Only official Bambu Lab spools with RFID are synced</li>
  183. <li>New spools are auto-created in Spoolman on first sync</li>
  184. <li>Non-Bambu Lab spools (third-party, refilled) are skipped</li>
  185. </ul>
  186. <p className="font-medium mt-2 mb-1">Linking Existing Spools</p>
  187. <p className="text-blue-300/80">
  188. To link existing Spoolman spools to your AMS, hover over an AMS slot and click "Link to Spoolman".
  189. </p>
  190. </div>
  191. </div>
  192. </div>
  193. {/* Enable toggle */}
  194. <div className="flex items-center justify-between">
  195. <div>
  196. <p className="text-white">Enable Spoolman</p>
  197. <p className="text-sm text-bambu-gray">
  198. Sync filament data with Spoolman server
  199. </p>
  200. </div>
  201. <label className="relative inline-flex items-center cursor-pointer">
  202. <input
  203. type="checkbox"
  204. checked={localEnabled}
  205. onChange={(e) => setLocalEnabled(e.target.checked)}
  206. className="sr-only peer"
  207. />
  208. <div className="w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"></div>
  209. </label>
  210. </div>
  211. {/* URL input */}
  212. <div>
  213. <label className="block text-sm text-bambu-gray mb-1">
  214. Spoolman URL
  215. </label>
  216. <input
  217. type="text"
  218. placeholder="http://192.168.1.100:7912"
  219. value={localUrl}
  220. onChange={(e) => setLocalUrl(e.target.value)}
  221. disabled={!localEnabled}
  222. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none disabled:opacity-50"
  223. />
  224. <p className="text-xs text-bambu-gray mt-1">
  225. URL of your Spoolman server (e.g., http://localhost:7912)
  226. </p>
  227. </div>
  228. {/* Sync mode */}
  229. <div>
  230. <label className="block text-sm text-bambu-gray mb-1">
  231. Sync Mode
  232. </label>
  233. <select
  234. value={localSyncMode}
  235. onChange={(e) => setLocalSyncMode(e.target.value)}
  236. disabled={!localEnabled}
  237. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none disabled:opacity-50"
  238. >
  239. <option value="auto">Automatic</option>
  240. <option value="manual">Manual Only</option>
  241. </select>
  242. <p className="text-xs text-bambu-gray mt-1">
  243. {localSyncMode === 'auto'
  244. ? 'AMS data syncs automatically when changes are detected'
  245. : 'Only sync when manually triggered'}
  246. </p>
  247. </div>
  248. {/* Connection status */}
  249. {localEnabled && (
  250. <div className="pt-2 border-t border-bambu-dark-tertiary">
  251. <div className="flex items-center justify-between mb-3">
  252. <div className="flex items-center gap-2">
  253. <span className="text-sm text-bambu-gray">Status:</span>
  254. {statusLoading ? (
  255. <Loader2 className="w-4 h-4 text-bambu-gray animate-spin" />
  256. ) : status?.connected ? (
  257. <span className="flex items-center gap-1 text-sm text-green-500">
  258. <Check className="w-4 h-4" />
  259. Connected
  260. </span>
  261. ) : (
  262. <span className="flex items-center gap-1 text-sm text-red-500">
  263. <X className="w-4 h-4" />
  264. Disconnected
  265. </span>
  266. )}
  267. </div>
  268. <div className="flex gap-2">
  269. {status?.connected ? (
  270. <Button
  271. variant="secondary"
  272. size="sm"
  273. onClick={() => disconnectMutation.mutate()}
  274. disabled={disconnectMutation.isPending}
  275. >
  276. {disconnectMutation.isPending ? (
  277. <Loader2 className="w-4 h-4 animate-spin" />
  278. ) : (
  279. <Link2Off className="w-4 h-4" />
  280. )}
  281. Disconnect
  282. </Button>
  283. ) : (
  284. <Button
  285. size="sm"
  286. onClick={() => connectMutation.mutate()}
  287. disabled={connectMutation.isPending || !localUrl}
  288. >
  289. {connectMutation.isPending ? (
  290. <Loader2 className="w-4 h-4 animate-spin" />
  291. ) : (
  292. <Link2 className="w-4 h-4" />
  293. )}
  294. Connect
  295. </Button>
  296. )}
  297. </div>
  298. </div>
  299. {/* Error display */}
  300. {connectMutation.isError && (
  301. <div className="mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400">
  302. {(connectMutation.error as Error).message}
  303. </div>
  304. )}
  305. {/* Manual sync section */}
  306. {status?.connected && (
  307. <div className="space-y-3">
  308. <div>
  309. <p className="text-sm text-white">Sync AMS Data</p>
  310. <p className="text-xs text-bambu-gray">
  311. Manually sync printer AMS data to Spoolman
  312. </p>
  313. </div>
  314. <div className="flex items-center gap-2">
  315. {/* Printer selector */}
  316. <div className="relative flex-1">
  317. <select
  318. value={selectedPrinterId}
  319. onChange={(e) => setSelectedPrinterId(e.target.value === 'all' ? 'all' : Number(e.target.value))}
  320. className="w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer"
  321. >
  322. <option value="all">All Printers</option>
  323. {printers?.map((printer: Printer) => (
  324. <option key={printer.id} value={printer.id}>
  325. {printer.name}
  326. </option>
  327. ))}
  328. </select>
  329. <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none" />
  330. </div>
  331. {/* Sync button */}
  332. <Button
  333. variant="secondary"
  334. size="sm"
  335. onClick={handleSync}
  336. disabled={isSyncing}
  337. >
  338. {isSyncing ? (
  339. <Loader2 className="w-4 h-4 animate-spin" />
  340. ) : (
  341. <RefreshCw className="w-4 h-4" />
  342. )}
  343. Sync
  344. </Button>
  345. </div>
  346. </div>
  347. )}
  348. {/* Sync result */}
  349. {syncSuccess && syncResult && (
  350. <div className="mt-3 space-y-2">
  351. {/* Main result */}
  352. <div
  353. className={`p-2 rounded text-sm ${
  354. syncResult.success
  355. ? 'bg-green-500/20 border border-green-500/50 text-green-400'
  356. : 'bg-yellow-500/20 border border-yellow-500/50 text-yellow-400'
  357. }`}
  358. >
  359. {syncResult.success
  360. ? `Synced ${syncResult.synced_count} spool${syncResult.synced_count !== 1 ? 's' : ''} successfully`
  361. : `Synced ${syncResult.synced_count} spool${syncResult.synced_count !== 1 ? 's' : ''} with ${syncResult.errors.length} error${syncResult.errors.length !== 1 ? 's' : ''}`}
  362. </div>
  363. {/* Skipped spools */}
  364. {syncResult.skipped_count > 0 && (
  365. <div className="p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm">
  366. <div className="flex items-center justify-between text-amber-400 mb-1">
  367. <div className="flex items-center gap-1.5">
  368. <AlertTriangle className="w-3.5 h-3.5" />
  369. <span className="font-medium">
  370. {syncResult.skipped_count} spool{syncResult.skipped_count !== 1 ? 's' : ''} skipped
  371. </span>
  372. </div>
  373. {syncResult.skipped_count > 5 && (
  374. <button
  375. onClick={() => setShowAllSkipped(!showAllSkipped)}
  376. className="text-xs text-amber-400 hover:text-amber-300 underline"
  377. >
  378. {showAllSkipped ? 'Show less' : 'Show all'}
  379. </button>
  380. )}
  381. </div>
  382. <ul className="text-xs text-amber-300/80 space-y-0.5">
  383. {(showAllSkipped ? syncResult.skipped : syncResult.skipped.slice(0, 5)).map((s, i) => (
  384. <li key={i} className="flex items-center gap-2">
  385. {s.color && (
  386. <span
  387. className="w-3 h-3 rounded-full border border-white/20"
  388. style={{ backgroundColor: `#${s.color}` }}
  389. />
  390. )}
  391. <span>{s.location}</span>
  392. <span className="text-amber-300/60">- {s.reason}</span>
  393. </li>
  394. ))}
  395. {!showAllSkipped && syncResult.skipped_count > 5 && (
  396. <li className="text-amber-300/60 italic">
  397. ...and {syncResult.skipped_count - 5} more
  398. </li>
  399. )}
  400. </ul>
  401. </div>
  402. )}
  403. {/* Errors */}
  404. {syncResult.errors.length > 0 && (
  405. <div className="p-2 bg-red-500/10 border border-red-500/30 rounded text-sm">
  406. <div className="text-red-400 font-medium mb-1">Errors:</div>
  407. <ul className="text-xs text-red-300/80 space-y-0.5">
  408. {syncResult.errors.map((err, i) => (
  409. <li key={i}>{err}</li>
  410. ))}
  411. </ul>
  412. </div>
  413. )}
  414. </div>
  415. )}
  416. </div>
  417. )}
  418. </CardContent>
  419. </Card>
  420. );
  421. }