SpoolFormModal.tsx 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. import { useState, useEffect, useMemo } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Loader2, Save, Beaker, Palette, Zap, Tag, Unlink } from 'lucide-react';
  5. import { api, ApiError } from '../api/client';
  6. import type { InventorySpool, SlicerSetting, SpoolCatalogEntry, LocalPreset, BuiltinFilament, SpoolmanBulkCreateResult, SpoolFilamentPresetInput, SpoolKProfileInput, SpoolmanFilamentEntry } from '../api/client';
  7. import { Button } from './Button';
  8. import { useToast } from '../contexts/ToastContext';
  9. import type {
  10. CalibrationProfile,
  11. ColorPreset,
  12. PresetChoice,
  13. PrinterWithCalibrations,
  14. SpoolFormData,
  15. SpoolFormMode,
  16. } from './spool-form/types';
  17. import { defaultFormData, validateForm, SPOOLMAN_LINKED_FIELDS } from './spool-form/types';
  18. import { buildFilamentOptions, extractBrandsFromPresets, fetchPrinterCalibrations, findPresetOption, hotendKey, loadRecentColors, pairedOptions, parsePresetKey, parsePresetName, presetKey, saveRecentColor, withCurrentValue } from './spool-form/utils';
  19. import { MATERIALS } from './spool-form/constants';
  20. import { FilamentSection } from './spool-form/FilamentSection';
  21. import { ColorSection } from './spool-form/ColorSection';
  22. import { AdditionalSection } from './spool-form/AdditionalSection';
  23. import { SpoolmanFilamentPicker } from './spool-form/SpoolmanFilamentPicker';
  24. import { PrinterProfilesSection } from './spool-form/PrinterProfilesSection';
  25. import { normaliseFlow } from '../utils/nozzleFlow';
  26. import { SpoolUsageHistory } from './SpoolUsageHistory';
  27. import {
  28. invalidateInventoryLocations,
  29. invalidateSpoolAndLocationQueries,
  30. } from '../utils/inventoryQueries';
  31. type TabId = 'filament' | 'appearance' | 'printers';
  32. const CLEAR_TAG_PAYLOAD = { tag_uid: null, tray_uuid: null, tag_type: null, data_origin: null };
  33. export type { SpoolFormMode };
  34. interface SpoolFormModalProps {
  35. isOpen: boolean;
  36. onClose: () => void;
  37. spool?: InventorySpool | null;
  38. mode: SpoolFormMode;
  39. printersWithCalibrations?: PrinterWithCalibrations[];
  40. currencySymbol: string;
  41. onSpoolsCreated?: (spools: InventorySpool[]) => void;
  42. /** When true, CRUD operations target the Spoolman inventory proxy endpoints. */
  43. spoolmanMode?: boolean;
  44. /** Query key to invalidate after mutations (differs for Spoolman vs local). */
  45. spoolsQueryKey?: string[];
  46. }
  47. export function SpoolFormModal({
  48. isOpen,
  49. onClose,
  50. spool,
  51. mode,
  52. printersWithCalibrations = [],
  53. currencySymbol,
  54. onSpoolsCreated,
  55. spoolmanMode = false,
  56. spoolsQueryKey = ['inventory-spools'],
  57. }: SpoolFormModalProps) {
  58. const { t } = useTranslation();
  59. const queryClient = useQueryClient();
  60. const { showToast } = useToast();
  61. const refreshSpoolQueries = () =>
  62. invalidateSpoolAndLocationQueries(queryClient, spoolsQueryKey);
  63. const isEditing = mode === 'edit';
  64. const isCopying = mode === 'copy';
  65. // Form state
  66. const [formData, setFormData] = useState<SpoolFormData>(defaultFormData);
  67. const [errors, setErrors] = useState<Partial<Record<keyof SpoolFormData, string>>>({});
  68. const [activeTab, setActiveTab] = useState<TabId>('filament');
  69. const [weightTouched, setWeightTouched] = useState(false);
  70. const [locationIdTouched, setLocationIdTouched] = useState(false);
  71. const [quickAdd, setQuickAdd] = useState(false);
  72. const [quantity, setQuantity] = useState(1);
  73. // Cloud presets
  74. const [cloudAuthenticated, setCloudAuthenticated] = useState(false);
  75. const [loadingCloudPresets, setLoadingCloudPresets] = useState(false);
  76. const [cloudPresets, setCloudPresets] = useState<SlicerSetting[]>([]);
  77. const [orcaSettingIds, setOrcaSettingIds] = useState<Set<string>>(new Set());
  78. const [presetInputValue, setPresetInputValue] = useState('');
  79. // Spool catalog
  80. const [spoolCatalog, setSpoolCatalog] = useState<SpoolCatalogEntry[]>([]);
  81. const [storageLocations, setStorageLocations] = useState<{ id: number; name: string }[]>([]);
  82. // Local presets (OrcaSlicer imports)
  83. const [localPresets, setLocalPresets] = useState<LocalPreset[]>([]);
  84. // Built-in filaments (static fallback)
  85. const [builtinFilaments, setBuiltinFilaments] = useState<BuiltinFilament[]>([]);
  86. // Color catalog
  87. const [colorCatalog, setColorCatalog] = useState<{
  88. manufacturer: string;
  89. color_name: string;
  90. hex_color: string;
  91. material: string | null;
  92. // #1340: gradient + effect carried from the catalog entry through to the
  93. // color picker so they're applied alongside hex + name on selection.
  94. extra_colors?: string | null;
  95. effect_type?: string | null;
  96. }[]>([]);
  97. // Color state
  98. const [recentColors, setRecentColors] = useState<ColorPreset[]>([]);
  99. // PA Profile state
  100. const [fetchedCalibrations, setFetchedCalibrations] = useState<PrinterWithCalibrations[]>([]);
  101. // Whether the calibration fetch above is still running. Without it the
  102. // Printers tab renders its "no printers configured" empty state while the
  103. // printers are still being asked -- which reads as a wrong answer rather
  104. // than as a wait, and the fetch is several round trips per machine.
  105. const [loadingCalibrations, setLoadingCalibrations] = useState(false);
  106. // One K profile per hotend, keyed `printerId:extruder:diameter`. A Map rather
  107. // than a Set of composite keys because the Printers tab presents each hotend
  108. // as a single-choice dropdown -- the shape makes "two profiles for one
  109. // hotend" unrepresentable instead of relying on eviction logic to prevent it.
  110. const [selectedProfiles, setSelectedProfiles] = useState<Map<string, CalibrationProfile>>(new Map());
  111. // Per-printer-model preset overrides, keyed by `presetKey(model, diameter)`.
  112. // Only the models the user has actually overridden are present; an absent
  113. // entry means "inherit this spool's own preset", which is exactly what the
  114. // backend cascade does with a missing row.
  115. const [modelPresets, setModelPresets] = useState<Map<string, PresetChoice>>(new Map());
  116. const [selectedGroupId, setSelectedGroupId] = useState<string>('');
  117. // Use prop if provided, otherwise use self-fetched data
  118. const resolvedCalibrations = printersWithCalibrations.length > 0
  119. ? printersWithCalibrations
  120. : fetchedCalibrations;
  121. // Tab badge: everything the user has configured under Printers, K profiles
  122. // and preset overrides alike, since both live on that tab now.
  123. const selectedProfileCount = selectedProfiles.size + modelPresets.size;
  124. // Fetch Spoolman filament catalog when in Spoolman mode
  125. // retry:false — Spoolman may be intentionally disabled (400); don't flood the server
  126. const { data: spoolmanFilaments = [], isLoading: isLoadingFilaments, error: filamentsError } = useQuery<SpoolmanFilamentEntry[], Error>({
  127. queryKey: ['spoolman-inventory-filaments'],
  128. queryFn: () => api.getSpoolmanInventoryFilaments(),
  129. enabled: spoolmanMode && isOpen,
  130. staleTime: 60_000,
  131. retry: false,
  132. });
  133. // Load recent colors on mount
  134. useEffect(() => {
  135. setRecentColors(loadRecentColors());
  136. }, []);
  137. // Fetch cloud presets and catalog when modal opens. Fetches Bambu Cloud
  138. // and Orca Cloud in parallel; merges Orca filaments into ``cloudPresets``
  139. // since ``OrcaProfileMeta`` is structurally identical to ``SlicerSetting``
  140. // (same fields, same semantics). ``cloudAuthenticated`` flips on if either
  141. // cloud is connected — the UI only uses it to gate "no cloud" hints.
  142. useEffect(() => {
  143. // ``cancelled`` gates every state setter so a fetch that resolves AFTER
  144. // the modal closes / unmounts can't fire setState on a torn-down
  145. // component. Without this guard the parallel Promise.allSettled chain
  146. // can still hit ``setLoadingCloudPresets(false)`` in its ``finally``
  147. // after vitest has dismantled the JSDOM window — surfaced as an
  148. // "Unhandled Rejection: window is not defined" in CI runs.
  149. let cancelled = false;
  150. if (isOpen) {
  151. const fetchData = async () => {
  152. setLoadingCloudPresets(true);
  153. try {
  154. const [bambuResult, orcaResult] = await Promise.allSettled([
  155. (async () => {
  156. const status = await api.getCloudStatus();
  157. if (!status.is_authenticated) return { connected: false, presets: [] as SlicerSetting[] };
  158. const presets = await api.getFilamentPresets();
  159. return { connected: true, presets };
  160. })(),
  161. (async () => {
  162. const status = await api.orcaCloudStatus();
  163. if (!status.connected) return { connected: false, presets: [] as SlicerSetting[] };
  164. const list = await api.orcaCloudListProfiles();
  165. // OrcaProfileMeta is structurally identical to SlicerSetting.
  166. return { connected: true, presets: list.filament as unknown as SlicerSetting[] };
  167. })(),
  168. ]);
  169. if (cancelled) return;
  170. const bambuConnected = bambuResult.status === 'fulfilled' && bambuResult.value.connected;
  171. const orcaConnected = orcaResult.status === 'fulfilled' && orcaResult.value.connected;
  172. const bambuPresets = bambuResult.status === 'fulfilled' ? bambuResult.value.presets : [];
  173. const orcaPresets = orcaResult.status === 'fulfilled' ? orcaResult.value.presets : [];
  174. setCloudAuthenticated(bambuConnected || orcaConnected);
  175. setCloudPresets([...bambuPresets, ...orcaPresets]);
  176. // The two clouds are merged into one list, so remember which ids came
  177. // from Orca -- it is the only way the origin badge can tell them
  178. // apart afterwards.
  179. setOrcaSettingIds(new Set(orcaPresets.map(p => p.setting_id)));
  180. } catch (e) {
  181. if (cancelled) return;
  182. console.error('Failed to fetch cloud presets:', e);
  183. setCloudAuthenticated(false);
  184. } finally {
  185. if (!cancelled) setLoadingCloudPresets(false);
  186. }
  187. };
  188. fetchData();
  189. if (!spoolmanMode) {
  190. api.getSpoolCatalog().then(setSpoolCatalog).catch(console.error);
  191. }
  192. api.getColorCatalog().then(setColorCatalog).catch(console.error);
  193. api.getLocalPresets().then(r => setLocalPresets(r.filament)).catch(console.error);
  194. api.getBuiltinFilaments().then(setBuiltinFilaments).catch(console.error);
  195. api.getLocations().then((locs) => setStorageLocations(locs.map((l) => ({ id: l.id, name: l.name })))).catch(console.error);
  196. // Fetch printer calibrations if not provided via props
  197. if (printersWithCalibrations.length === 0) {
  198. (async () => {
  199. setLoadingCalibrations(true);
  200. try {
  201. const printers = await api.getPrinters();
  202. const statuses = await Promise.all(
  203. printers.map(p => api.getPrinterStatus(p.id).catch(() => null)),
  204. );
  205. // Printers in parallel, diameters within a printer in series.
  206. // Separate machines are separate MQTT connections and do not
  207. // interfere; it is one printer's own firmware that drops a
  208. // concurrent burst of calibration requests (see
  209. // fetchPrinterCalibrations). Walking the fleet one machine at a
  210. // time made the whole tab wait for the sum of every printer.
  211. const results = await Promise.all(
  212. printers.map(async (printer, i) => {
  213. const status = statuses[i];
  214. const connected = status?.connected ?? false;
  215. let calibrations: PrinterWithCalibrations['calibrations'] = [];
  216. if (connected) {
  217. // Across every nozzle size, so a profile for a size that is
  218. // not currently fitted is still offered (#2618 fetched only
  219. // the fitted ones).
  220. calibrations = await fetchPrinterCalibrations(printer.id, status);
  221. }
  222. // Keep the reported nozzle hardware: the Printers tab lists a
  223. // model's installed diameters from it. Read as a set of
  224. // diameters only -- never indexed by extruder.
  225. return { printer: { ...printer, connected }, calibrations, nozzles: status?.nozzles };
  226. }),
  227. );
  228. if (!cancelled) setFetchedCalibrations(results);
  229. } catch (e) {
  230. console.error('Failed to fetch printer calibrations:', e);
  231. } finally {
  232. if (!cancelled) setLoadingCalibrations(false);
  233. }
  234. })();
  235. }
  236. }
  237. // The effect intentionally depends only on `isOpen` (and the prop-side
  238. // calibration count) — re-running on every spoolmanMode toggle would
  239. // race the in-flight async fetches with unmount/teardown and emit
  240. // "test environment was torn down" errors in vitest. spoolmanMode only
  241. // gates a single fetch (getSpoolCatalog) which is cheap enough to skip
  242. // when the modal opens in Spoolman mode.
  243. return () => {
  244. cancelled = true;
  245. };
  246. // eslint-disable-next-line react-hooks/exhaustive-deps
  247. }, [isOpen, printersWithCalibrations.length]);
  248. // Build filament options: cloud → local → fallback
  249. const filamentOptions = useMemo(
  250. () => buildFilamentOptions(cloudPresets, new Set(), localPresets, builtinFilaments, orcaSettingIds),
  251. [cloudPresets, localPresets, builtinFilaments, orcaSettingIds],
  252. );
  253. // Extract brands from presets
  254. const baseAvailableBrands = useMemo(() => {
  255. const presetBrands = extractBrandsFromPresets(cloudPresets, localPresets);
  256. const catalogBrands = colorCatalog
  257. .map(entry => entry.manufacturer?.trim())
  258. .filter((brand): brand is string => !!brand);
  259. const brandSet = new Set<string>([...presetBrands, ...catalogBrands]);
  260. return Array.from(brandSet).sort((a, b) => a.localeCompare(b));
  261. }, [cloudPresets, localPresets, colorCatalog]);
  262. const baseAvailableMaterials = useMemo(() => {
  263. const catalogMaterials = colorCatalog
  264. .map(entry => entry.material?.trim())
  265. .filter((material): material is string => !!material);
  266. const materialSet = new Set<string>([...MATERIALS, ...catalogMaterials]);
  267. return Array.from(materialSet).sort((a, b) => a.localeCompare(b));
  268. }, [colorCatalog]);
  269. const brandMaterialPairs = useMemo(() => {
  270. const pairs: Array<{ brand: string; material: string }> = [];
  271. for (const entry of colorCatalog) {
  272. const brand = entry.manufacturer?.trim();
  273. const material = entry.material?.trim();
  274. if (brand && material) pairs.push({ brand, material });
  275. }
  276. for (const preset of cloudPresets) {
  277. const parsed = parsePresetName(preset.name);
  278. if (parsed.brand && parsed.material) {
  279. pairs.push({ brand: parsed.brand, material: parsed.material });
  280. }
  281. }
  282. for (const preset of localPresets) {
  283. const parsed = parsePresetName(preset.name);
  284. const brand = preset.filament_vendor?.trim() || parsed.brand;
  285. const material = parsed.material;
  286. if (brand && material) {
  287. pairs.push({ brand, material });
  288. }
  289. }
  290. return pairs;
  291. }, [cloudPresets, colorCatalog, localPresets]);
  292. const brandToMaterials = useMemo(() => {
  293. const map = new Map<string, Set<string>>();
  294. for (const pair of brandMaterialPairs) {
  295. const brandKey = pair.brand.toLowerCase();
  296. const materialKey = pair.material.toLowerCase();
  297. if (!map.has(brandKey)) map.set(brandKey, new Set());
  298. map.get(brandKey)!.add(materialKey);
  299. }
  300. return map;
  301. }, [brandMaterialPairs]);
  302. const materialToBrands = useMemo(() => {
  303. const map = new Map<string, Set<string>>();
  304. for (const pair of brandMaterialPairs) {
  305. const brandKey = pair.brand.toLowerCase();
  306. const materialKey = pair.material.toLowerCase();
  307. if (!map.has(materialKey)) map.set(materialKey, new Set());
  308. map.get(materialKey)!.add(brandKey);
  309. }
  310. return map;
  311. }, [brandMaterialPairs]);
  312. // #1905: the brand and material dropdowns used to be filtered down to the
  313. // pairs seen in the color catalog / slicer presets, which hid perfectly valid
  314. // combinations — "Elegoo" exists (as a PLA brand) but vanished from the list
  315. // once ASA was selected, making the entry look impossible. Both lists now
  316. // always offer everything we know about, plus whatever the spool already has
  317. // stored (a custom brand saved earlier was missing from its own dropdown).
  318. // The pairing knowledge survives as `suggestedBrands`/`suggestedMaterials`,
  319. // which the dropdowns sort to the top instead of filtering by.
  320. const availableBrands = useMemo(
  321. () => withCurrentValue(baseAvailableBrands, formData.brand),
  322. [baseAvailableBrands, formData.brand],
  323. );
  324. const availableMaterials = useMemo(
  325. () => withCurrentValue(baseAvailableMaterials, formData.material),
  326. [baseAvailableMaterials, formData.material],
  327. );
  328. const suggestedBrands = useMemo(
  329. () => pairedOptions(availableBrands, formData.material, materialToBrands),
  330. [availableBrands, formData.material, materialToBrands],
  331. );
  332. const suggestedMaterials = useMemo(
  333. () => pairedOptions(availableMaterials, formData.brand, brandToMaterials),
  334. [availableMaterials, formData.brand, brandToMaterials],
  335. );
  336. // Find selected preset option
  337. const selectedPresetOption = useMemo(
  338. () => findPresetOption(formData.slicer_filament, filamentOptions),
  339. [formData.slicer_filament, filamentOptions],
  340. );
  341. // Reset form when modal opens/closes or spool changes
  342. useEffect(() => {
  343. if (isOpen) {
  344. if (spool) {
  345. // Legacy rows may carry a malformed rgba (e.g. the 7-char 'FFFFFFF'
  346. // from #1055 before the create/update pattern was enforced). The
  347. // backend SpoolUpdate schema rejects non-8-char hex on PATCH, so
  348. // re-submitting a malformed value would 422 every edit on that spool
  349. // — even edits that don't touch color. Normalize on load: any value
  350. // that isn't exactly 8 hex chars falls back to the default, so the
  351. // user can save unrelated fields (weight, material, note) without
  352. // first being forced to fix a color they may not even be aware is
  353. // broken. Saving also purges the bad value from the DB.
  354. const validRgba = spool.rgba && /^[0-9A-Fa-f]{8}$/.test(spool.rgba) ? spool.rgba : '808080FF';
  355. setFormData({
  356. material: spool.material || '',
  357. subtype: spool.subtype || '',
  358. brand: spool.brand || '',
  359. // #1319: leave color_name blank when the backend reports it was
  360. // synthesised from subtype — otherwise the form would round-trip
  361. // the synth value to Spoolman on save as if the user had set it,
  362. // which is what produced the "color reverts to subtype" symptom.
  363. color_name: spool.color_name_is_synthesized ? '' : (spool.color_name || ''),
  364. rgba: validRgba,
  365. extra_colors: spool.extra_colors || '',
  366. effect_type: spool.effect_type || '',
  367. label_weight: spool.label_weight || 1000,
  368. core_weight: spool.core_weight || 250,
  369. core_weight_catalog_id: spool.core_weight_catalog_id ?? null,
  370. weight_used: isCopying ? 0 : spool.weight_used || 0,
  371. slicer_filament: spool.slicer_filament || '',
  372. note: spool.note || '',
  373. cost_per_kg: spool.cost_per_kg ?? null,
  374. category: spool.category || '',
  375. low_stock_threshold_pct: spool.low_stock_threshold_pct ?? null,
  376. location_id: spool.location_id ?? null,
  377. spoolman_filament_id: null,
  378. });
  379. setPresetInputValue(spool.slicer_filament_name || spool.slicer_filament || '');
  380. // Load K-profiles for this spool. The stored row carries everything
  381. // the picker needs to show the selection before the printer answers,
  382. // so an offline printer still renders what was chosen for it.
  383. if (spool.k_profiles && spool.k_profiles.length > 0) {
  384. const chosen = new Map<string, CalibrationProfile>();
  385. for (const p of spool.k_profiles) {
  386. if (p.cali_idx === null || p.cali_idx === undefined) continue;
  387. const diameter = (p.nozzle_diameter || '').trim() || '0.4';
  388. const extruder = p.extruder ?? 0;
  389. chosen.set(hotendKey(p.printer_id, extruder, diameter), {
  390. cali_idx: p.cali_idx,
  391. filament_id: '',
  392. setting_id: p.setting_id || '',
  393. name: p.name || '',
  394. k_value: p.k_value,
  395. n_coef: 0,
  396. extruder_id: extruder,
  397. nozzle_diameter: diameter,
  398. // Stored as the bare flow code; the picker re-derives its label
  399. // from the same field it reads off a live profile.
  400. nozzle_id: p.nozzle_type || '',
  401. });
  402. }
  403. setSelectedProfiles(chosen);
  404. } else {
  405. setSelectedProfiles(new Map());
  406. }
  407. } else {
  408. setFormData(defaultFormData);
  409. setPresetInputValue('');
  410. setSelectedProfiles(new Map());
  411. }
  412. // Reset on every open, not just the create path (#1905). The modal keeps
  413. // its state while closed, and the Quick Add toggle only renders in create
  414. // mode — so quick-adding a spool and then opening Edit left the edit form
  415. // stuck in quick-add layout (no preset field, no PA-profile tab) with no
  416. // control to switch back.
  417. setQuickAdd(false);
  418. setQuantity(1);
  419. setErrors({});
  420. setActiveTab('filament');
  421. setSelectedGroupId('');
  422. // Cleared on every open, both branches: the modal keeps its state while
  423. // closed, so editing spool B after spool A would otherwise show (and
  424. // save) A's per-model overrides on B. Refilled by the fetch below.
  425. setModelPresets(new Map());
  426. setWeightTouched(false);
  427. setLocationIdTouched(false);
  428. }
  429. }, [isOpen, spool, mode, isCopying]);
  430. // Load this spool's per-printer-model preset overrides. Fetched rather than
  431. // read off the spool: they are deliberately not embedded in the spool
  432. // response, which the inventory list returns once per spool the user owns.
  433. // Copying a spool copies its overrides -- they describe the filament on the
  434. // spool, which is what a copy has too.
  435. useEffect(() => {
  436. if (!isOpen || !spool) return;
  437. let cancelled = false;
  438. const load = spoolmanMode ? api.getSpoolmanFilamentPresets : api.getSpoolFilamentPresets;
  439. load(spool.id)
  440. .then(rows => {
  441. if (cancelled) return;
  442. const next = new Map<string, PresetChoice>();
  443. for (const row of rows) {
  444. next.set(presetKey(row.printer_model, row.nozzle_diameter || ''), {
  445. code: row.slicer_filament || '',
  446. name: row.slicer_filament_name || '',
  447. });
  448. }
  449. setModelPresets(next);
  450. })
  451. .catch(e => {
  452. // Non-fatal: the tab still works, it just starts with nothing
  453. // overridden. Saving from that state WOULD clear the stored rows, so
  454. // say so rather than letting the user save over what they cannot see.
  455. if (cancelled) return;
  456. console.error('Failed to load filament preset overrides:', e);
  457. showToast(t('inventory.filamentPresetsLoadFailed'), 'warning');
  458. });
  459. return () => {
  460. cancelled = true;
  461. };
  462. // eslint-disable-next-line react-hooks/exhaustive-deps
  463. }, [isOpen, spool?.id, spoolmanMode]);
  464. // Legacy rows may have storage_location text but no location_id yet — link when catalog loads.
  465. useEffect(() => {
  466. if (!isOpen || !spool || locationIdTouched || formData.location_id != null) return;
  467. const legacy = spool.storage_location?.trim();
  468. if (!legacy || storageLocations.length === 0) return;
  469. const match = storageLocations.find((l) => l.name.toLowerCase() === legacy.toLowerCase());
  470. if (match) {
  471. setFormData((prev) => (prev.location_id === match.id ? prev : { ...prev, location_id: match.id }));
  472. }
  473. }, [isOpen, spool, storageLocations, formData.location_id, locationIdTouched]);
  474. // Update field helper
  475. const updateField = <K extends keyof SpoolFormData>(key: K, value: SpoolFormData[K]) => {
  476. const isLinkedField = SPOOLMAN_LINKED_FIELDS.has(key);
  477. if (spoolmanMode && isLinkedField && formData.spoolman_filament_id !== null) {
  478. showToast(t('inventory.spoolmanFilamentUnlinked'), 'info');
  479. }
  480. setFormData(prev => ({
  481. ...prev,
  482. [key]: value,
  483. ...(spoolmanMode && isLinkedField && prev.spoolman_filament_id !== null
  484. ? { spoolman_filament_id: null }
  485. : {}),
  486. }));
  487. if (key === 'weight_used') setWeightTouched(true);
  488. if (key === 'location_id') setLocationIdTouched(true);
  489. if (errors[key]) {
  490. setErrors(prev => ({ ...prev, [key]: undefined }));
  491. }
  492. };
  493. // Prefill form from a Spoolman filament catalog entry
  494. // subtype extraction mirrors _spoolman_helpers.py logic
  495. const handleFilamentSelect = (filament: SpoolmanFilamentEntry) => {
  496. const material = filament.material || '';
  497. const name = filament.name || '';
  498. const subtype = material && name.startsWith(material) ? name.slice(material.length).trim() : name;
  499. const rawHex = (filament.color_hex ?? '').replace('#', '').toUpperCase();
  500. // Guard against short/malformed hex values — 6 chars (RRGGBB), or 8 when the
  501. // filament is translucent and carries its own alpha (#2912). Rejecting 8 here
  502. // prefilled a clear filament picked from the Spoolman catalogue as 808080FF.
  503. const colorHex = /^[0-9A-F]{6}(?:[0-9A-F]{2})?$/.test(rawHex) ? rawHex : '808080';
  504. const prefillRgba = colorHex.length === 8 ? colorHex : `${colorHex}FF`;
  505. setFormData(prev => ({
  506. ...prev,
  507. spoolman_filament_id: filament.id,
  508. material,
  509. subtype,
  510. brand: filament.vendor?.name || '',
  511. rgba: prefillRgba,
  512. color_name: filament.color_name || '',
  513. label_weight: filament.weight ?? prev.label_weight,
  514. }));
  515. showToast(t('inventory.spoolmanFilamentSelected'), 'success');
  516. };
  517. // Handle color selection
  518. const handleColorUsed = (color: ColorPreset) => {
  519. setRecentColors(prev => saveRecentColor(color, prev));
  520. };
  521. // Mutations – dispatch to Spoolman proxy or local inventory based on mode
  522. const createMutation = useMutation({
  523. mutationFn: (data: Record<string, unknown>) =>
  524. spoolmanMode
  525. ? api.createSpoolmanInventorySpool(data as Parameters<typeof api.createSpoolmanInventorySpool>[0])
  526. : api.createSpool(data as Parameters<typeof api.createSpool>[0]),
  527. onSuccess: async (newSpool) => {
  528. if (newSpool?.id) {
  529. const ok = await savePrinterProfiles(newSpool.id);
  530. if (!ok) return;
  531. }
  532. await refreshSpoolQueries();
  533. if (onSpoolsCreated) onSpoolsCreated([newSpool]);
  534. showToast(t('inventory.spoolCreated'), 'success');
  535. onClose();
  536. },
  537. onError: (error: Error) => {
  538. if (error instanceof ApiError && error.status === 503) {
  539. showToast(t('inventory.spoolmanUnreachable'), 'error');
  540. } else {
  541. showToast(t('inventory.saveFailed'), 'error');
  542. }
  543. },
  544. });
  545. const bulkCreateMutation = useMutation<
  546. SpoolmanBulkCreateResult | InventorySpool[],
  547. Error,
  548. { data: Record<string, unknown>; qty: number }
  549. >({
  550. mutationFn: ({ data, qty }) =>
  551. spoolmanMode
  552. ? api.bulkCreateSpoolmanInventorySpools(data as Parameters<typeof api.bulkCreateSpoolmanInventorySpools>[0], qty)
  553. : api.bulkCreateSpools(data as Parameters<typeof api.bulkCreateSpools>[0], qty),
  554. onSuccess: async (result) => {
  555. // Spoolman bulk-create returns SpoolmanBulkCreateResult (207); local returns InventorySpool[].
  556. // Cast via unknown to satisfy strict TypeScript — the runtime shape is guaranteed by
  557. // the duck-type check ('created' in result) before any property access.
  558. const spoolmanResult = (spoolmanMode && 'created' in result)
  559. ? (result as unknown as SpoolmanBulkCreateResult)
  560. : null;
  561. const createdSpools: InventorySpool[] = spoolmanResult
  562. ? spoolmanResult.created
  563. : (result as InventorySpool[]);
  564. // Bulk create: every copy gets the same profiles and overrides. Skipped
  565. // entirely when the user configured neither, so a plain bulk add does
  566. // not fire two writes per spool.
  567. if (selectedProfiles.size > 0 || modelPresets.size > 0) {
  568. for (const s of createdSpools) {
  569. await savePrinterProfiles(s.id);
  570. }
  571. }
  572. await refreshSpoolQueries();
  573. if (onSpoolsCreated) onSpoolsCreated(createdSpools);
  574. if (spoolmanResult && spoolmanResult.failed_count > 0) {
  575. showToast(
  576. t('inventory.spoolsPartiallyCreated', {
  577. created: createdSpools.length,
  578. total: spoolmanResult.requested_count,
  579. }),
  580. 'warning',
  581. );
  582. } else {
  583. showToast(t('inventory.spoolsCreated', { count: createdSpools.length }), 'success');
  584. }
  585. onClose();
  586. },
  587. onError: (error: Error) => {
  588. if (error instanceof ApiError && error.status === 503) {
  589. showToast(t('inventory.spoolmanUnreachable'), 'error');
  590. } else {
  591. showToast(t('inventory.saveFailed'), 'error');
  592. }
  593. },
  594. });
  595. const updateMutation = useMutation({
  596. mutationFn: (data: Record<string, unknown>) =>
  597. spoolmanMode
  598. ? api.updateSpoolmanInventorySpool(spool!.id, data as Parameters<typeof api.updateSpoolmanInventorySpool>[1])
  599. : api.updateSpool(spool!.id, data as Parameters<typeof api.updateSpool>[1]),
  600. onSuccess: async () => {
  601. if (spool?.id) {
  602. const ok = await savePrinterProfiles(spool.id);
  603. if (!ok) return;
  604. }
  605. await refreshSpoolQueries();
  606. showToast(t('inventory.spoolUpdated'), 'success');
  607. onClose();
  608. },
  609. onError: (error: Error) => {
  610. if (error instanceof ApiError && error.status === 503) {
  611. showToast(t('inventory.spoolmanUnreachable'), 'error');
  612. } else {
  613. showToast(t('inventory.saveFailed'), 'error');
  614. }
  615. },
  616. });
  617. const deleteTagMutation = useMutation({
  618. mutationFn: () => {
  619. if (spoolmanMode) {
  620. return api.updateSpoolmanInventorySpool(spool!.id, CLEAR_TAG_PAYLOAD as Parameters<typeof api.updateSpoolmanInventorySpool>[1]);
  621. }
  622. return api.updateSpool(spool!.id, CLEAR_TAG_PAYLOAD as Parameters<typeof api.updateSpool>[1]);
  623. },
  624. onSuccess: async () => {
  625. await refreshSpoolQueries();
  626. showToast(t('inventory.rfidCleared', 'RFID tag cleared'), 'success');
  627. onClose();
  628. },
  629. onError: (error: Error) => {
  630. if (error instanceof ApiError && error.status === 503) {
  631. showToast(t('inventory.spoolmanUnreachable'), 'error');
  632. } else {
  633. showToast(t('inventory.tagClearFailed'), 'error');
  634. }
  635. },
  636. });
  637. // Fetch assignment for this spool (to show Unassign button). In Spoolman mode
  638. // the slot assignment lives in the spoolman_slot_assignments table keyed by
  639. // spoolman_spool_id, not in the legacy spool_assignments table — #1336 was the
  640. // resulting "Unassign button is always disabled" report.
  641. const { data: assignments } = useQuery({
  642. queryKey: ['spool-assignments'],
  643. queryFn: () => api.getAssignments(),
  644. enabled: isOpen && isEditing && !spoolmanMode,
  645. });
  646. const { data: spoolmanSlotAssignments } = useQuery({
  647. queryKey: ['spoolman-slot-assignments-all'],
  648. queryFn: () => api.getSpoolmanSlotAssignments(),
  649. enabled: isOpen && isEditing && spoolmanMode,
  650. });
  651. const spoolAssignment = (() => {
  652. if (!spool) return undefined;
  653. if (spoolmanMode) {
  654. return spoolmanSlotAssignments?.find(a => a.spoolman_spool_id === spool.id);
  655. }
  656. return assignments?.find(a => a.spool_id === spool.id);
  657. })();
  658. // Read inventory + settings caches (already populated by InventoryPage) to
  659. // drive the category autocomplete and low-stock-threshold placeholder. #729
  660. const { data: allSpools } = useQuery({
  661. queryKey: ['inventory-spools'],
  662. queryFn: () => api.getSpools(true),
  663. enabled: isOpen,
  664. });
  665. const { data: settingsForForm } = useQuery({
  666. queryKey: ['settings'],
  667. queryFn: api.getSettings,
  668. enabled: isOpen,
  669. });
  670. // Backend Bambu printer-model registry, so the Printers tab can read the
  671. // model out of a preset name and offer each model only its own presets. The
  672. // same query key and staleTime the Configure AMS Slot modal uses -- the
  673. // registry only changes across backend releases, so this is a cache hit
  674. // whenever that modal has been opened.
  675. const { data: printerModelsData } = useQuery({
  676. queryKey: ['slicerPrinterModels'],
  677. queryFn: api.getSlicerPrinterModels,
  678. enabled: isOpen,
  679. staleTime: Infinity,
  680. });
  681. const availableCategories = (() => {
  682. const set = new Set<string>();
  683. for (const s of allSpools ?? []) {
  684. const c = s.category?.trim();
  685. if (c) set.add(c);
  686. }
  687. return Array.from(set).sort((a, b) => a.localeCompare(b));
  688. })();
  689. const globalLowStockThreshold = settingsForForm?.low_stock_threshold ?? 20;
  690. const unassignMutation = useMutation({
  691. mutationFn: async () => {
  692. if (!spoolAssignment) throw new Error('No assignment');
  693. if (spoolmanMode) {
  694. if (!spool) throw new Error('No spool');
  695. await api.unassignSpoolmanSlot(spool.id);
  696. return;
  697. }
  698. await api.unassignSpool(spoolAssignment.printer_id, spoolAssignment.ams_id, spoolAssignment.tray_id);
  699. },
  700. onSuccess: async () => {
  701. if (spoolmanMode) {
  702. await queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments-all'] });
  703. await queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  704. } else {
  705. await queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  706. }
  707. showToast(t('inventory.unassignSuccess', 'Spool unassigned'), 'success');
  708. onClose();
  709. },
  710. onError: (error: Error) => {
  711. showToast(error.message, 'error');
  712. },
  713. });
  714. // Save everything the Printers tab holds: one K profile per hotend and the
  715. // per-printer-model preset overrides. Returns false if either write failed,
  716. // which keeps the modal open so the user does not lose what they picked.
  717. const savePrinterProfiles = async (spoolId: number): Promise<boolean> => {
  718. const saveKApi = spoolmanMode ? api.saveSpoolmanKProfiles : api.saveSpoolKProfiles;
  719. const savePresetApi = spoolmanMode ? api.saveSpoolmanFilamentPresets : api.saveSpoolFilamentPresets;
  720. // The selection Map is keyed by hotend and holds the calibration itself,
  721. // so nothing has to be resolved back out of the printer's live list. That
  722. // also fixes a real defect in the old key-based lookup: it matched a
  723. // calibration by cali_idx alone, and cali_idx is numbered PER NOZZLE --
  724. // on a dual-nozzle printer it could resolve the other hotend's entry and
  725. // persist that entry's K value and diameter.
  726. const profiles: SpoolKProfileInput[] = [];
  727. for (const [key, cal] of selectedProfiles) {
  728. const [printerIdStr, extruderStr, diameter] = key.split(':');
  729. profiles.push({
  730. printer_id: parseInt(printerIdStr),
  731. extruder: parseInt(extruderStr),
  732. nozzle_diameter: diameter || '0.4',
  733. // The flow the profile was measured on, when the printer declares one.
  734. // Null where it does not (an X1C declares none on any profile), which
  735. // the backend reads as "applies to whatever is fitted" -- the same rule
  736. // that keeps every profile stored before this working.
  737. nozzle_type: normaliseFlow(cal.nozzle_id),
  738. k_value: cal.k_value,
  739. name: cal.name || null,
  740. cali_idx: cal.cali_idx,
  741. setting_id: cal.setting_id || null,
  742. });
  743. }
  744. const presets: SpoolFilamentPresetInput[] = [];
  745. for (const [key, choice] of modelPresets) {
  746. const { model, diameter } = parsePresetKey(key);
  747. if (!model) continue;
  748. presets.push({
  749. printer_model: model,
  750. nozzle_diameter: diameter,
  751. slicer_filament: choice.code || null,
  752. slicer_filament_name: choice.name || null,
  753. });
  754. }
  755. // Both are full replacements, so both run even when empty -- that is how
  756. // the user clears the last profile or the last override.
  757. try {
  758. await saveKApi(spoolId, profiles);
  759. } catch (e) {
  760. console.error('Failed to save K-profiles:', e);
  761. showToast(t('inventory.kProfileSaveFailed'), 'warning');
  762. return false;
  763. }
  764. try {
  765. await savePresetApi(spoolId, presets);
  766. } catch (e) {
  767. console.error('Failed to save filament preset overrides:', e);
  768. showToast(t('inventory.filamentPresetSaveFailed'), 'warning');
  769. return false;
  770. }
  771. return true;
  772. };
  773. // Close on Escape key
  774. useEffect(() => {
  775. if (!isOpen) return;
  776. const handleKeyDown = (e: KeyboardEvent) => {
  777. if (e.key === 'Escape') onClose();
  778. };
  779. document.addEventListener('keydown', handleKeyDown);
  780. return () => document.removeEventListener('keydown', handleKeyDown);
  781. }, [isOpen, onClose]);
  782. if (!isOpen) return null;
  783. const handleSubmit = () => {
  784. const validation = validateForm(formData, quickAdd, spoolmanMode, mode);
  785. if (!validation.isValid) {
  786. setErrors(validation.errors);
  787. if (validation.errors.slicer_filament || validation.errors.material || validation.errors.brand || validation.errors.subtype) {
  788. setActiveTab('filament');
  789. }
  790. return;
  791. }
  792. // Find preset name from selected option
  793. const presetName = selectedPresetOption?.displayName || presetInputValue || null;
  794. const data: Record<string, unknown> = {
  795. material: formData.material || null,
  796. subtype: formData.subtype || null,
  797. brand: formData.brand || null,
  798. color_name: formData.color_name || null,
  799. rgba: formData.rgba || null,
  800. extra_colors: formData.extra_colors || null,
  801. effect_type: formData.effect_type || null,
  802. label_weight: formData.label_weight,
  803. ...(spoolmanMode ? {} : { core_weight: formData.core_weight, core_weight_catalog_id: formData.core_weight_catalog_id }),
  804. slicer_filament: formData.slicer_filament || null,
  805. slicer_filament_name: presetName,
  806. nozzle_temp_min: null,
  807. nozzle_temp_max: null,
  808. note: formData.note || null,
  809. cost_per_kg: formData.cost_per_kg,
  810. category: formData.category.trim() || null,
  811. low_stock_threshold_pct: formData.low_stock_threshold_pct,
  812. ...(spoolmanMode ? { spoolman_filament_id: formData.spoolman_filament_id } : {}),
  813. };
  814. // Only send weight_used when creating or when explicitly changed by the user.
  815. // This prevents stale cached values from overwriting usage-tracker data.
  816. if (!isEditing || weightTouched) {
  817. data.weight_used = formData.weight_used;
  818. }
  819. // Only send location_id when creating or when explicitly changed by the user.
  820. // Backend derives storage_location; omitting on untouched edit avoids stale overwrites.
  821. if (!isEditing || locationIdTouched) {
  822. data.location_id = formData.location_id;
  823. }
  824. if (isEditing) {
  825. updateMutation.mutate(data);
  826. } else if (quantity > 1) {
  827. bulkCreateMutation.mutate({ data, qty: quantity });
  828. } else {
  829. createMutation.mutate(data);
  830. }
  831. };
  832. const isPending = createMutation.isPending || bulkCreateMutation.isPending || updateMutation.isPending || deleteTagMutation.isPending || unassignMutation.isPending;
  833. return (
  834. <div className="fixed inset-0 z-50 flex items-center justify-center">
  835. <div
  836. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  837. onClick={onClose}
  838. />
  839. {/* Wider than the old max-w-xl: the Printers tab is a model list beside
  840. a detail pane holding a preset row per nozzle size and a hotend-by-
  841. size grid, which needs room for both. Held constant across tabs
  842. rather than sized per tab -- a modal that resizes as you switch tabs
  843. reads as a layout bug. */}
  844. <div className="relative w-full max-w-5xl mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col">
  845. {/* Header */}
  846. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0">
  847. <h2 className="text-lg font-semibold text-white flex items-baseline gap-2">
  848. {isEditing ? t('inventory.editSpool') : isCopying ? t('inventory.copySpool') : t('inventory.addSpool')}
  849. {isEditing && spool && (
  850. <span className="text-sm font-mono text-bambu-gray">#{spool.id}</span>
  851. )}
  852. </h2>
  853. <button
  854. onClick={onClose}
  855. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  856. >
  857. <X className="w-5 h-5" />
  858. </button>
  859. </div>
  860. {/* Quick Add toggle — only in create mode (not edit, not copy).
  861. In copy mode the modal title is the singular "Copy Spool", so the
  862. quantity-driven bulkCreateMutation path would silently produce N
  863. copies under a misleading title — keep this toggle out of that
  864. mode entirely. */}
  865. {mode === 'create' && (
  866. <div className="flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0">
  867. <div className="flex items-center gap-2">
  868. <Zap className="w-4 h-4 text-amber-600 dark:text-amber-400" />
  869. <span className="text-sm text-white">{t('inventory.quickAdd')}</span>
  870. </div>
  871. <button
  872. type="button"
  873. onClick={() => {
  874. setQuickAdd(!quickAdd);
  875. if (!quickAdd) setActiveTab('filament');
  876. }}
  877. className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
  878. quickAdd ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  879. }`}
  880. >
  881. <span
  882. className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${
  883. quickAdd ? 'translate-x-4' : 'translate-x-0.5'
  884. }`}
  885. />
  886. </button>
  887. </div>
  888. )}
  889. {/* Tabs */}
  890. <div className="flex border-b border-bambu-dark-tertiary flex-shrink-0">
  891. <button
  892. onClick={() => setActiveTab('filament')}
  893. className={`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${
  894. activeTab === 'filament'
  895. ? 'text-bambu-green border-b-2 border-bambu-green'
  896. : 'text-bambu-gray hover:text-white'
  897. }`}
  898. >
  899. <Beaker className="w-4 h-4" />
  900. {t('inventory.filamentInfoTab')}
  901. </button>
  902. {!quickAdd && (
  903. <button
  904. onClick={() => setActiveTab('appearance')}
  905. className={`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${
  906. activeTab === 'appearance'
  907. ? 'text-bambu-green border-b-2 border-bambu-green'
  908. : 'text-bambu-gray hover:text-white'
  909. }`}
  910. >
  911. <Palette className="w-4 h-4" />
  912. {t('inventory.colorAndCostTab')}
  913. </button>
  914. )}
  915. {!quickAdd && (
  916. <button
  917. onClick={() => setActiveTab('printers')}
  918. className={`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${
  919. activeTab === 'printers'
  920. ? 'text-bambu-green border-b-2 border-bambu-green'
  921. : 'text-bambu-gray hover:text-white'
  922. }`}
  923. >
  924. <Zap className="w-4 h-4" />
  925. {t('inventory.printersTab')}
  926. {selectedProfileCount > 0 && (
  927. <span className="text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green">
  928. {selectedProfileCount}
  929. </span>
  930. )}
  931. </button>
  932. )}
  933. </div>
  934. {/* Content */}
  935. <div className="p-4 overflow-y-auto flex-1" style={{ scrollbarGutter: 'stable' }}>
  936. {activeTab === 'filament' ? (
  937. <div className="space-y-6">
  938. {/* Spoolman Filament Catalog Picker — only when creating a spool in Spoolman mode */}
  939. {spoolmanMode && !isEditing && (
  940. <div>
  941. {filamentsError ? (
  942. <p className="text-sm text-red-700 dark:text-red-400 px-1">{t('inventory.spoolmanCatalogLoadFailed')}</p>
  943. ) : (
  944. <SpoolmanFilamentPicker
  945. filaments={spoolmanFilaments}
  946. isLoading={isLoadingFilaments}
  947. selectedId={formData.spoolman_filament_id}
  948. onSelect={handleFilamentSelect}
  949. />
  950. )}
  951. </div>
  952. )}
  953. {/* Filament Info Section */}
  954. <div>
  955. <h3 className="text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3">
  956. {t('inventory.filamentInfo')}
  957. </h3>
  958. <FilamentSection
  959. formData={formData}
  960. updateField={updateField}
  961. cloudAuthenticated={cloudAuthenticated}
  962. loadingCloudPresets={loadingCloudPresets}
  963. presetInputValue={presetInputValue}
  964. setPresetInputValue={setPresetInputValue}
  965. selectedPresetOption={selectedPresetOption}
  966. filamentOptions={filamentOptions}
  967. availableBrands={availableBrands}
  968. availableMaterials={availableMaterials}
  969. suggestedBrands={suggestedBrands}
  970. suggestedMaterials={suggestedMaterials}
  971. quickAdd={quickAdd}
  972. detailsRequired={!quickAdd && !spoolmanMode && mode === 'create'}
  973. quantity={quantity}
  974. onQuantityChange={setQuantity}
  975. errors={errors}
  976. />
  977. </div>
  978. </div>
  979. ) : activeTab === 'appearance' ? (
  980. <div className="space-y-6">
  981. {/* Color Section */}
  982. <div>
  983. <h3 className="text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3">
  984. {t('inventory.color')}
  985. </h3>
  986. <ColorSection
  987. formData={formData}
  988. updateField={updateField}
  989. recentColors={recentColors}
  990. onColorUsed={handleColorUsed}
  991. catalogColors={colorCatalog}
  992. />
  993. </div>
  994. {/* Additional Section */}
  995. <div>
  996. <h3 className="text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3">
  997. {t('inventory.additional')}
  998. </h3>
  999. <AdditionalSection
  1000. formData={formData}
  1001. updateField={updateField}
  1002. spoolCatalog={spoolCatalog}
  1003. currencySymbol={currencySymbol}
  1004. availableCategories={availableCategories}
  1005. availableLocations={storageLocations}
  1006. onCreateLocation={async (name) => {
  1007. try {
  1008. const created = await api.createLocation({ name });
  1009. setStorageLocations((prev) => [...prev, { id: created.id, name: created.name }].sort((a, b) => a.name.localeCompare(b.name)));
  1010. await invalidateInventoryLocations(queryClient);
  1011. return { id: created.id, name: created.name };
  1012. } catch (e) {
  1013. // Surface the backend's actual error so the user can
  1014. // distinguish 409 duplicate / 400 validation / 500 from
  1015. // a generic "save failed" message.
  1016. console.error(e);
  1017. const message = e instanceof Error ? e.message : t('locations.saveFailed');
  1018. showToast(message || t('locations.saveFailed'), 'error');
  1019. return null;
  1020. }
  1021. }}
  1022. globalLowStockThreshold={globalLowStockThreshold}
  1023. spoolmanMode={spoolmanMode}
  1024. />
  1025. </div>
  1026. {/* Usage History (only when editing internal inventory; Spoolman tracks its own) */}
  1027. {isEditing && spool && !spoolmanMode && (
  1028. <div>
  1029. <SpoolUsageHistory spoolId={spool.id} />
  1030. </div>
  1031. )}
  1032. </div>
  1033. ) : (
  1034. <PrinterProfilesSection
  1035. formData={formData}
  1036. printersWithCalibrations={resolvedCalibrations}
  1037. filamentOptions={filamentOptions}
  1038. modelPresets={modelPresets}
  1039. setModelPresets={setModelPresets}
  1040. selectedProfiles={selectedProfiles}
  1041. setSelectedProfiles={setSelectedProfiles}
  1042. selectedGroupId={selectedGroupId}
  1043. setSelectedGroupId={setSelectedGroupId}
  1044. printerModels={printerModelsData}
  1045. isLoading={loadingCalibrations}
  1046. />
  1047. )}
  1048. </div>
  1049. {/* Footer */}
  1050. <div className="flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0">
  1051. {isEditing && (
  1052. <div className="flex gap-2 mr-auto">
  1053. <Button
  1054. variant="secondary"
  1055. onClick={() => deleteTagMutation.mutate()}
  1056. disabled={isPending || !spool?.tag_uid}
  1057. >
  1058. <Tag className="w-4 h-4" />
  1059. {t('inventory.clearRfid', 'Clear RFID Tag')}
  1060. </Button>
  1061. <Button
  1062. variant="secondary"
  1063. onClick={() => unassignMutation.mutate()}
  1064. disabled={isPending || !spoolAssignment}
  1065. >
  1066. <Unlink className="w-4 h-4" />
  1067. {t('inventory.unassignSpool', 'Unassign')}
  1068. </Button>
  1069. </div>
  1070. )}
  1071. <div className="flex gap-2 ml-auto">
  1072. <Button variant="secondary" onClick={onClose}>
  1073. {t('common.cancel')}
  1074. </Button>
  1075. <Button
  1076. onClick={handleSubmit}
  1077. disabled={isPending}
  1078. >
  1079. {isPending ? (
  1080. <>
  1081. <Loader2 className="w-4 h-4 animate-spin" />
  1082. {t('common.saving')}
  1083. </>
  1084. ) : (
  1085. <>
  1086. <Save className="w-4 h-4" />
  1087. {isEditing ? t('common.save') : isCopying ? t('inventory.copySpool') : t('inventory.addSpool')}
  1088. </>
  1089. )}
  1090. </Button>
  1091. </div>
  1092. </div>
  1093. </div>
  1094. </div>
  1095. );
  1096. }