SpoolmanSettings.tsx 20 KB

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