SpoolFormModal.tsx 57 KB

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