SpoolFormModal.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. import { useState, useEffect, useMemo } from 'react';
  2. import { useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Loader2, Save, Beaker, Palette } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { InventorySpool, SlicerSetting, SpoolCatalogEntry, LocalPreset } from '../api/client';
  7. import { Button } from './Button';
  8. import { useToast } from '../contexts/ToastContext';
  9. import type { SpoolFormData, PrinterWithCalibrations, ColorPreset } from './spool-form/types';
  10. import { defaultFormData, validateForm } from './spool-form/types';
  11. import { buildFilamentOptions, extractBrandsFromPresets, findPresetOption, loadRecentColors, saveRecentColor } from './spool-form/utils';
  12. import { FilamentSection } from './spool-form/FilamentSection';
  13. import { ColorSection } from './spool-form/ColorSection';
  14. import { AdditionalSection } from './spool-form/AdditionalSection';
  15. import { PAProfileSection } from './spool-form/PAProfileSection';
  16. import { SpoolUsageHistory } from './SpoolUsageHistory';
  17. type TabId = 'filament' | 'pa-profile';
  18. interface SpoolFormModalProps {
  19. isOpen: boolean;
  20. onClose: () => void;
  21. spool?: InventorySpool | null;
  22. printersWithCalibrations?: PrinterWithCalibrations[];
  23. }
  24. export function SpoolFormModal({ isOpen, onClose, spool, printersWithCalibrations = [] }: SpoolFormModalProps) {
  25. const { t } = useTranslation();
  26. const queryClient = useQueryClient();
  27. const { showToast } = useToast();
  28. const isEditing = !!spool;
  29. // Form state
  30. const [formData, setFormData] = useState<SpoolFormData>(defaultFormData);
  31. const [errors, setErrors] = useState<Partial<Record<keyof SpoolFormData, string>>>({});
  32. const [activeTab, setActiveTab] = useState<TabId>('filament');
  33. const [weightTouched, setWeightTouched] = useState(false);
  34. // Cloud presets
  35. const [cloudAuthenticated, setCloudAuthenticated] = useState(false);
  36. const [loadingCloudPresets, setLoadingCloudPresets] = useState(false);
  37. const [cloudPresets, setCloudPresets] = useState<SlicerSetting[]>([]);
  38. const [presetInputValue, setPresetInputValue] = useState('');
  39. // Spool catalog
  40. const [spoolCatalog, setSpoolCatalog] = useState<SpoolCatalogEntry[]>([]);
  41. // Local presets (OrcaSlicer imports)
  42. const [localPresets, setLocalPresets] = useState<LocalPreset[]>([]);
  43. // Color catalog
  44. const [colorCatalog, setColorCatalog] = useState<{ manufacturer: string; color_name: string; hex_color: string; material: string | null }[]>([]);
  45. // Color state
  46. const [recentColors, setRecentColors] = useState<ColorPreset[]>([]);
  47. // PA Profile state
  48. const [fetchedCalibrations, setFetchedCalibrations] = useState<PrinterWithCalibrations[]>([]);
  49. const [selectedProfiles, setSelectedProfiles] = useState<Set<string>>(new Set());
  50. const [expandedPrinters, setExpandedPrinters] = useState<Set<string>>(new Set());
  51. // Use prop if provided, otherwise use self-fetched data
  52. const resolvedCalibrations = printersWithCalibrations.length > 0
  53. ? printersWithCalibrations
  54. : fetchedCalibrations;
  55. // Count selected PA profiles for tab badge
  56. const selectedProfileCount = useMemo(() => {
  57. return selectedProfiles.size;
  58. }, [selectedProfiles]);
  59. // Load recent colors on mount
  60. useEffect(() => {
  61. setRecentColors(loadRecentColors());
  62. }, []);
  63. // Fetch cloud presets and catalog when modal opens
  64. useEffect(() => {
  65. if (isOpen) {
  66. const fetchData = async () => {
  67. setLoadingCloudPresets(true);
  68. try {
  69. const status = await api.getCloudStatus();
  70. setCloudAuthenticated(status.is_authenticated);
  71. if (status.is_authenticated) {
  72. const presets = await api.getFilamentPresets();
  73. setCloudPresets(presets);
  74. }
  75. } catch (e) {
  76. console.error('Failed to fetch cloud presets:', e);
  77. setCloudAuthenticated(false);
  78. } finally {
  79. setLoadingCloudPresets(false);
  80. }
  81. };
  82. fetchData();
  83. api.getSpoolCatalog().then(setSpoolCatalog).catch(console.error);
  84. api.getColorCatalog().then(setColorCatalog).catch(console.error);
  85. api.getLocalPresets().then(r => setLocalPresets(r.filament)).catch(console.error);
  86. // Fetch printer calibrations if not provided via props
  87. if (printersWithCalibrations.length === 0) {
  88. (async () => {
  89. try {
  90. const printers = await api.getPrinters();
  91. const statuses = await Promise.all(
  92. printers.map(p => api.getPrinterStatus(p.id).catch(() => null)),
  93. );
  94. const results: PrinterWithCalibrations[] = [];
  95. for (let i = 0; i < printers.length; i++) {
  96. const printer = printers[i];
  97. const status = statuses[i];
  98. const connected = status?.connected ?? false;
  99. let calibrations: PrinterWithCalibrations['calibrations'] = [];
  100. if (connected) {
  101. try {
  102. const kRes = await api.getKProfiles(printer.id);
  103. calibrations = kRes.profiles.map(p => ({
  104. cali_idx: p.slot_id,
  105. filament_id: p.filament_id,
  106. setting_id: p.setting_id || '',
  107. name: p.name,
  108. k_value: parseFloat(p.k_value) || 0,
  109. n_coef: parseFloat(p.n_coef) || 0,
  110. extruder_id: p.extruder_id,
  111. nozzle_diameter: p.nozzle_diameter,
  112. }));
  113. } catch {
  114. // Printer may not support K-profiles
  115. }
  116. }
  117. results.push({ printer: { ...printer, connected }, calibrations });
  118. }
  119. setFetchedCalibrations(results);
  120. } catch (e) {
  121. console.error('Failed to fetch printer calibrations:', e);
  122. }
  123. })();
  124. }
  125. }
  126. }, [isOpen, printersWithCalibrations.length]);
  127. // Build filament options: cloud → local → fallback
  128. const filamentOptions = useMemo(
  129. () => buildFilamentOptions(cloudPresets, new Set(), localPresets),
  130. [cloudPresets, localPresets],
  131. );
  132. // Extract brands from presets
  133. const availableBrands = useMemo(
  134. () => extractBrandsFromPresets(cloudPresets, localPresets),
  135. [cloudPresets, localPresets],
  136. );
  137. // Find selected preset option
  138. const selectedPresetOption = useMemo(
  139. () => findPresetOption(formData.slicer_filament, filamentOptions),
  140. [formData.slicer_filament, filamentOptions],
  141. );
  142. // Reset form when modal opens/closes or spool changes
  143. useEffect(() => {
  144. if (isOpen) {
  145. if (spool) {
  146. setFormData({
  147. material: spool.material || '',
  148. subtype: spool.subtype || '',
  149. brand: spool.brand || '',
  150. color_name: spool.color_name || '',
  151. rgba: spool.rgba || '808080FF',
  152. label_weight: spool.label_weight || 1000,
  153. core_weight: spool.core_weight || 250,
  154. core_weight_catalog_id: spool.core_weight_catalog_id ?? null,
  155. weight_used: spool.weight_used || 0,
  156. slicer_filament: spool.slicer_filament || '',
  157. note: spool.note || '',
  158. });
  159. setPresetInputValue(spool.slicer_filament_name || spool.slicer_filament || '');
  160. // Load K-profiles for this spool
  161. if (spool.k_profiles && spool.k_profiles.length > 0) {
  162. const profileKeys = new Set<string>();
  163. for (const p of spool.k_profiles) {
  164. if (p.cali_idx !== null && p.cali_idx !== undefined) {
  165. profileKeys.add(`${p.printer_id}:${p.cali_idx}:${p.extruder ?? 'null'}`);
  166. }
  167. }
  168. setSelectedProfiles(profileKeys);
  169. } else {
  170. setSelectedProfiles(new Set());
  171. }
  172. } else {
  173. setFormData(defaultFormData);
  174. setPresetInputValue('');
  175. setSelectedProfiles(new Set());
  176. }
  177. setErrors({});
  178. setActiveTab('filament');
  179. setWeightTouched(false);
  180. }
  181. }, [isOpen, spool]);
  182. // Expand all printers in PA profile section when calibrations are available
  183. useEffect(() => {
  184. if (isOpen && resolvedCalibrations.length > 0) {
  185. setExpandedPrinters(new Set(resolvedCalibrations.map(p => String(p.printer.id))));
  186. }
  187. }, [isOpen, resolvedCalibrations]);
  188. // Update field helper
  189. const updateField = <K extends keyof SpoolFormData>(key: K, value: SpoolFormData[K]) => {
  190. setFormData(prev => ({ ...prev, [key]: value }));
  191. if (key === 'weight_used') setWeightTouched(true);
  192. if (errors[key]) {
  193. setErrors(prev => ({ ...prev, [key]: undefined }));
  194. }
  195. };
  196. // Handle color selection
  197. const handleColorUsed = (color: ColorPreset) => {
  198. setRecentColors(prev => saveRecentColor(color, prev));
  199. };
  200. // Mutations
  201. const createMutation = useMutation({
  202. mutationFn: (data: Record<string, unknown>) =>
  203. api.createSpool(data as Parameters<typeof api.createSpool>[0]),
  204. onSuccess: async (newSpool) => {
  205. // Save K-profiles if any selected
  206. if (selectedProfiles.size > 0 && newSpool?.id) {
  207. await saveKProfiles(newSpool.id);
  208. }
  209. await queryClient.invalidateQueries({ queryKey: ['inventory-spools'] });
  210. showToast(t('inventory.spoolCreated'), 'success');
  211. onClose();
  212. },
  213. onError: (error: Error) => {
  214. showToast(error.message, 'error');
  215. },
  216. });
  217. const updateMutation = useMutation({
  218. mutationFn: (data: Record<string, unknown>) =>
  219. api.updateSpool(spool!.id, data as Parameters<typeof api.updateSpool>[1]),
  220. onSuccess: async () => {
  221. // Save K-profiles
  222. if (spool?.id) {
  223. await saveKProfiles(spool.id);
  224. }
  225. await queryClient.invalidateQueries({ queryKey: ['inventory-spools'] });
  226. showToast(t('inventory.spoolUpdated'), 'success');
  227. onClose();
  228. },
  229. onError: (error: Error) => {
  230. showToast(error.message, 'error');
  231. },
  232. });
  233. // Save K-profiles for selected calibrations
  234. const saveKProfiles = async (spoolId: number) => {
  235. if (selectedProfiles.size === 0) {
  236. // Clear existing K-profiles
  237. try {
  238. await api.saveSpoolKProfiles(spoolId, []);
  239. } catch {
  240. // Ignore
  241. }
  242. return;
  243. }
  244. const profiles = [];
  245. for (const key of selectedProfiles) {
  246. const [printerIdStr, caliIdxStr, extruderStr] = key.split(':');
  247. const printerId = parseInt(printerIdStr);
  248. const caliIdx = parseInt(caliIdxStr);
  249. const extruder = extruderStr === 'null' ? 0 : parseInt(extruderStr);
  250. // Find the matching calibration
  251. const pc = resolvedCalibrations.find(p => p.printer.id === printerId);
  252. if (pc) {
  253. const cal = pc.calibrations.find(c => c.cali_idx === caliIdx);
  254. if (cal) {
  255. profiles.push({
  256. printer_id: printerId,
  257. extruder,
  258. nozzle_diameter: cal.nozzle_diameter || '0.4',
  259. k_value: cal.k_value,
  260. name: cal.name || null,
  261. cali_idx: cal.cali_idx,
  262. setting_id: cal.setting_id || null,
  263. });
  264. }
  265. }
  266. }
  267. if (profiles.length > 0) {
  268. try {
  269. await api.saveSpoolKProfiles(spoolId, profiles);
  270. } catch (e) {
  271. console.error('Failed to save K-profiles:', e);
  272. }
  273. }
  274. };
  275. // Close on Escape key
  276. useEffect(() => {
  277. if (!isOpen) return;
  278. const handleKeyDown = (e: KeyboardEvent) => {
  279. if (e.key === 'Escape') onClose();
  280. };
  281. document.addEventListener('keydown', handleKeyDown);
  282. return () => document.removeEventListener('keydown', handleKeyDown);
  283. }, [isOpen, onClose]);
  284. if (!isOpen) return null;
  285. const handleSubmit = () => {
  286. const validation = validateForm(formData);
  287. if (!validation.isValid) {
  288. setErrors(validation.errors);
  289. // Switch to filament tab if there are errors there
  290. if (validation.errors.slicer_filament || validation.errors.material) {
  291. setActiveTab('filament');
  292. }
  293. return;
  294. }
  295. // Find preset name from selected option
  296. const presetName = selectedPresetOption?.displayName || presetInputValue || null;
  297. const data: Record<string, unknown> = {
  298. material: formData.material,
  299. subtype: formData.subtype || null,
  300. brand: formData.brand || null,
  301. color_name: formData.color_name || null,
  302. rgba: formData.rgba || null,
  303. label_weight: formData.label_weight,
  304. core_weight: formData.core_weight,
  305. core_weight_catalog_id: formData.core_weight_catalog_id,
  306. slicer_filament: formData.slicer_filament || null,
  307. slicer_filament_name: presetName,
  308. nozzle_temp_min: null,
  309. nozzle_temp_max: null,
  310. note: formData.note || null,
  311. };
  312. // Only send weight_used when creating or when explicitly changed by the user.
  313. // This prevents stale cached values from overwriting usage-tracker data.
  314. if (!isEditing || weightTouched) {
  315. data.weight_used = formData.weight_used;
  316. }
  317. if (isEditing) {
  318. updateMutation.mutate(data);
  319. } else {
  320. createMutation.mutate(data);
  321. }
  322. };
  323. const isPending = createMutation.isPending || updateMutation.isPending;
  324. return (
  325. <div className="fixed inset-0 z-50 flex items-center justify-center">
  326. <div
  327. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  328. onClick={onClose}
  329. />
  330. <div className="relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col">
  331. {/* Header */}
  332. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0">
  333. <h2 className="text-lg font-semibold text-white">
  334. {isEditing ? t('inventory.editSpool') : t('inventory.addSpool')}
  335. </h2>
  336. <button
  337. onClick={onClose}
  338. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  339. >
  340. <X className="w-5 h-5" />
  341. </button>
  342. </div>
  343. {/* Tabs */}
  344. <div className="flex border-b border-bambu-dark-tertiary flex-shrink-0">
  345. <button
  346. onClick={() => setActiveTab('filament')}
  347. className={`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${
  348. activeTab === 'filament'
  349. ? 'text-bambu-green border-b-2 border-bambu-green'
  350. : 'text-bambu-gray hover:text-white'
  351. }`}
  352. >
  353. <Palette className="w-4 h-4" />
  354. {t('inventory.filamentInfoTab')}
  355. </button>
  356. <button
  357. onClick={() => setActiveTab('pa-profile')}
  358. className={`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${
  359. activeTab === 'pa-profile'
  360. ? 'text-bambu-green border-b-2 border-bambu-green'
  361. : 'text-bambu-gray hover:text-white'
  362. }`}
  363. >
  364. <Beaker className="w-4 h-4" />
  365. {t('inventory.paProfileTab')}
  366. {selectedProfileCount > 0 && (
  367. <span className="text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green">
  368. {selectedProfileCount}
  369. </span>
  370. )}
  371. </button>
  372. </div>
  373. {/* Content */}
  374. <div className="p-4 overflow-y-auto flex-1" style={{ scrollbarGutter: 'stable' }}>
  375. {activeTab === 'filament' ? (
  376. <div className="space-y-6">
  377. {/* Filament Info Section */}
  378. <div>
  379. <h3 className="text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3">
  380. {t('inventory.filamentInfo')}
  381. </h3>
  382. <FilamentSection
  383. formData={formData}
  384. updateField={updateField}
  385. cloudAuthenticated={cloudAuthenticated}
  386. loadingCloudPresets={loadingCloudPresets}
  387. presetInputValue={presetInputValue}
  388. setPresetInputValue={setPresetInputValue}
  389. selectedPresetOption={selectedPresetOption}
  390. filamentOptions={filamentOptions}
  391. availableBrands={availableBrands}
  392. />
  393. {errors.slicer_filament && (
  394. <p className="mt-1 text-xs text-red-400">{errors.slicer_filament}</p>
  395. )}
  396. {errors.material && (
  397. <p className="mt-1 text-xs text-red-400">{errors.material}</p>
  398. )}
  399. </div>
  400. {/* Color Section */}
  401. <div>
  402. <h3 className="text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3">
  403. {t('inventory.color')}
  404. </h3>
  405. <ColorSection
  406. formData={formData}
  407. updateField={updateField}
  408. recentColors={recentColors}
  409. onColorUsed={handleColorUsed}
  410. catalogColors={colorCatalog}
  411. />
  412. </div>
  413. {/* Additional Section */}
  414. <div>
  415. <h3 className="text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3">
  416. {t('inventory.additional')}
  417. </h3>
  418. <AdditionalSection
  419. formData={formData}
  420. updateField={updateField}
  421. spoolCatalog={spoolCatalog}
  422. />
  423. </div>
  424. {/* Usage History (only when editing) */}
  425. {isEditing && spool && (
  426. <div>
  427. <SpoolUsageHistory spoolId={spool.id} />
  428. </div>
  429. )}
  430. </div>
  431. ) : (
  432. <PAProfileSection
  433. formData={formData}
  434. updateField={updateField}
  435. printersWithCalibrations={resolvedCalibrations}
  436. selectedProfiles={selectedProfiles}
  437. setSelectedProfiles={setSelectedProfiles}
  438. expandedPrinters={expandedPrinters}
  439. setExpandedPrinters={setExpandedPrinters}
  440. />
  441. )}
  442. </div>
  443. {/* Footer */}
  444. <div className="flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0">
  445. <Button variant="secondary" onClick={onClose}>
  446. {t('common.cancel')}
  447. </Button>
  448. <Button
  449. onClick={handleSubmit}
  450. disabled={isPending}
  451. >
  452. {isPending ? (
  453. <>
  454. <Loader2 className="w-4 h-4 animate-spin" />
  455. {t('common.saving')}
  456. </>
  457. ) : (
  458. <>
  459. <Save className="w-4 h-4" />
  460. {isEditing ? t('common.save') : t('inventory.addSpool')}
  461. </>
  462. )}
  463. </Button>
  464. </div>
  465. </div>
  466. </div>
  467. );
  468. }