AssignSpoolModal.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. import { useEffect, useMemo, useState } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Loader2, Package, Search } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { InventorySpool, SpoolAssignment } from '../api/client';
  7. import { Button } from './Button';
  8. import { ConfirmModal } from './ConfirmModal';
  9. import { useToast } from '../contexts/ToastContext';
  10. import { filterSpoolsByQuery } from '../utils/inventorySearch';
  11. import { getSwatchStyle } from '../utils/colors';
  12. interface AssignSpoolModalProps {
  13. isOpen: boolean;
  14. onClose: () => void;
  15. printerId: number;
  16. amsId: number;
  17. trayId: number;
  18. trayInfo?: {
  19. type: string;
  20. material?: string;
  21. profile?: string;
  22. color: string;
  23. location: string;
  24. };
  25. spoolmanEnabled?: boolean;
  26. }
  27. export function AssignSpoolModal({ isOpen, onClose, printerId, amsId, trayId, trayInfo, spoolmanEnabled }: AssignSpoolModalProps) {
  28. const { t } = useTranslation();
  29. const queryClient = useQueryClient();
  30. const { showToast } = useToast();
  31. const [disableFiltering, setDisableFiltering] = useState(false);
  32. const [selectedSpoolId, setSelectedSpoolId] = useState<number | null>(null);
  33. const [selectedSpoolmanSpoolId, setSelectedSpoolmanSpoolId] = useState<number | null>(null);
  34. useEffect(() => {
  35. setSelectedSpoolId(null);
  36. setSelectedSpoolmanSpoolId(null);
  37. }, [disableFiltering]);
  38. const [searchFilter, setSearchFilter] = useState('');
  39. const [pendingAssignId, setPendingAssignId] = useState<number | null>(null);
  40. const [showMismatchConfirm, setShowMismatchConfirm] = useState(false);
  41. // Profile-only mismatch no longer triggers the popup — the backend's
  42. // `apply_spool_to_slot_via_mqtt` pushes the spool's slicer profile to the
  43. // AMS slot on every assign anyway, so warning the user about a profile
  44. // delta then "fixing" it during the same action was friction without
  45. // benefit (#1552). Material mismatch still warns because the firmware can
  46. // refuse a print when type doesn't match; combined material+profile
  47. // mismatches keep the profile detail in the same popup as the material
  48. // warning.
  49. const [mismatchDetails, setMismatchDetails] = useState<{
  50. type: 'material' | 'partial' | 'material_profile' | 'partial_profile';
  51. spoolMaterial: string;
  52. trayMaterial: string;
  53. spoolProfile?: string;
  54. trayProfile?: string;
  55. } | null>(null);
  56. useEffect(() => {
  57. if (isOpen) {
  58. setDisableFiltering(false);
  59. }
  60. }, [isOpen]);
  61. // Unique cache key — different consumers of `['inventory-spools']` call
  62. // `getSpools()` with different `includeArchived` arguments (InventoryPage:
  63. // true, SpoolBuddyDashboard / SpoolBuddyInventoryPage: false), but they
  64. // all share the same key. React Query treats them as one query and
  65. // serves whichever response landed first, so a SpoolBuddy component
  66. // priming the cache with the archived-excluded payload makes the picker
  67. // miss spools that *are* archived OR (more subtly) miss any spool that
  68. // wasn't yet present when SpoolBuddy ran its initial fetch. The picker
  69. // gets its own key + a fetch-everything call so this consumer is never
  70. // at the mercy of someone else's cache state. Archived spools are then
  71. // explicitly excluded client-side because the backend rejects archived
  72. // assignments with HTTP 400 anyway, so listing them would only let the
  73. // user click a button that fails.
  74. const { data: spools, isLoading } = useQuery({
  75. queryKey: ['inventory-spools', 'assign-modal'],
  76. queryFn: () => api.getSpools(true),
  77. enabled: isOpen && !spoolmanEnabled,
  78. });
  79. const { data: assignments } = useQuery({
  80. queryKey: ['spool-assignments'],
  81. queryFn: () => api.getAssignments(),
  82. enabled: isOpen,
  83. });
  84. const { data: settings } = useQuery({
  85. queryKey: ['settings'],
  86. queryFn: () => api.getSettings(),
  87. enabled: isOpen,
  88. });
  89. const { data: spoolmanSpools, isLoading: spoolmanLoading } = useQuery({
  90. queryKey: ['spoolman-inventory-spools', 'assign-modal'],
  91. queryFn: () => api.getSpoolmanInventorySpools(false),
  92. enabled: isOpen && !!spoolmanEnabled,
  93. });
  94. // Spoolman SlotAssignments across all printers — used to filter out spools
  95. // already bound to another slot. Without this filter the modal offers spools
  96. // that are already in use elsewhere (e.g. an h2d-1 slot's spool appearing
  97. // in the x1c-2 assign list), and assigning would silently steal it from
  98. // the other printer's slot.
  99. const { data: allSpoolmanAssignments } = useQuery({
  100. queryKey: ['spoolman-slot-assignments-all'],
  101. queryFn: () => api.getSpoolmanSlotAssignments(),
  102. enabled: isOpen && !!spoolmanEnabled,
  103. });
  104. // ids of spools already in some Spoolman slot — excluding the current slot
  105. // (so a user could in theory re-pick the same spool, though the modal is
  106. // typically only opened from empty slots).
  107. const assignedSpoolmanSpoolIds = useMemo(() => {
  108. if (!allSpoolmanAssignments) return new Set<number>();
  109. return new Set(
  110. allSpoolmanAssignments
  111. .filter(a => !(a.printer_id === printerId && a.ams_id === amsId && a.tray_id === trayId))
  112. .map(a => a.spoolman_spool_id),
  113. );
  114. }, [allSpoolmanAssignments, printerId, amsId, trayId]);
  115. // #1414: nudge the printer to republish its state after we assign a
  116. // spool. The backend assign-spool path already issues an MQTT command,
  117. // but firmware (especially A1 mini external slots and any non-RFID
  118. // assignment) doesn't always echo the new tray state back on its own,
  119. // so the printer card sits on stale data and the user has to press
  120. // Force-refresh to see the assignment. Calling /refresh-status forces
  121. // a pushall the way the Force-refresh button does. Failures are
  122. // intentionally swallowed — the assignment itself succeeded; if the
  123. // refresh is offline the next poll / websocket update will catch up.
  124. const nudgePrinterRepublish = () => {
  125. api.refreshPrinterStatus(printerId).catch(() => {});
  126. queryClient.invalidateQueries({ queryKey: ['printerStatus', printerId] });
  127. };
  128. const assignMutation = useMutation({
  129. mutationFn: (spoolId: number) =>
  130. api.assignSpool({ spool_id: spoolId, printer_id: printerId, ams_id: amsId, tray_id: trayId }),
  131. onSuccess: (newAssignment) => {
  132. // Immediately update cache so UI reflects the new assignment without waiting for refetch
  133. queryClient.setQueryData<SpoolAssignment[]>(['spool-assignments'], (old) => {
  134. const filtered = (old || []).filter(a =>
  135. !(a.printer_id === printerId && a.ams_id === amsId && a.tray_id === trayId)
  136. );
  137. filtered.push(newAssignment);
  138. return filtered;
  139. });
  140. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  141. nudgePrinterRepublish();
  142. // When the AMS slot was empty at assign time (tray_state ∈ {9, 10}), the
  143. // backend persists the assignment but deliberately skips the MQTT
  144. // `ams_filament_setting` push because Bambu firmware drops it silently
  145. // for empty slots. `on_ams_change` re-fires the configuration once a
  146. // spool is detected in the slot (#1680). The success-but-pending case
  147. // gets a distinct toast so the user understands the slot hasn't been
  148. // configured on the printer yet — saying "AMS slot configured" reads
  149. // as a lie in that state. Mirror of `spoolbuddy/AssignToAmsModal.tsx`,
  150. // which has handled this since the SpoolBuddy assign flow shipped.
  151. const toastKey = newAssignment.pending_config
  152. ? 'inventory.assignPendingInsert'
  153. : 'inventory.assignSuccess';
  154. showToast(t(toastKey), 'success');
  155. setShowMismatchConfirm(false);
  156. setPendingAssignId(null);
  157. setMismatchDetails(null);
  158. onClose();
  159. },
  160. onError: (error: Error) => {
  161. showToast(`${t('inventory.assignFailed')}: ${error.message}`, 'error');
  162. },
  163. });
  164. const assignSpoolmanMutation = useMutation({
  165. mutationFn: (spoolmanSpoolId: number) =>
  166. api.assignSpoolmanSlot({
  167. spoolman_spool_id: spoolmanSpoolId,
  168. printer_id: printerId,
  169. ams_id: amsId,
  170. tray_id: trayId,
  171. }),
  172. onSuccess: () => {
  173. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  174. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  175. nudgePrinterRepublish();
  176. showToast(t('inventory.assignSuccess'), 'success');
  177. onClose();
  178. },
  179. onError: (error: Error) => {
  180. showToast(`${t('inventory.assignFailed')}: ${error.message}`, 'error');
  181. },
  182. });
  183. // --- Material/profile mismatch logic ---
  184. const normalizeValue = (value: string | undefined | null) =>
  185. (value ?? '').trim().toUpperCase();
  186. const checkMaterialMatch = (
  187. spoolMaterial: string | undefined | null,
  188. trayMaterial: string | undefined | null
  189. ): 'exact' | 'partial' | 'none' => {
  190. const normalizedSpool = normalizeValue(spoolMaterial);
  191. const normalizedTray = normalizeValue(trayMaterial);
  192. if (!normalizedSpool || !normalizedTray) return 'none';
  193. if (normalizedSpool === normalizedTray) return 'exact';
  194. if (normalizedTray.includes(normalizedSpool) || normalizedSpool.includes(normalizedTray)) {
  195. return 'partial';
  196. }
  197. return 'none';
  198. };
  199. // Bambu Studio / OrcaSlicer profile names carry a printer/nozzle/variant qualifier after
  200. // `@` (e.g. "Devil Design PLA Basic @Bambu Lab H2D 0.4 nozzle (Custom)"), while the tray's
  201. // profile is typically the bare base name. Strip the qualifier before comparing so identical
  202. // base profiles don't trigger a mismatch warning (#1047).
  203. const stripProfileQualifier = (value: string) => value.split('@')[0].trim();
  204. const checkProfileMatch = (
  205. spoolProfile: string | undefined | null,
  206. trayProfile: string | undefined | null
  207. ): boolean => {
  208. const normalizedSpoolProfile = stripProfileQualifier(normalizeValue(spoolProfile));
  209. const normalizedTrayProfile = stripProfileQualifier(normalizeValue(trayProfile));
  210. if (!normalizedSpoolProfile || !normalizedTrayProfile) return false;
  211. return normalizedSpoolProfile === normalizedTrayProfile;
  212. };
  213. if (!isOpen) return null;
  214. // Filter out spools already assigned to other slots
  215. const assignedSpoolIds = new Set(
  216. (assignments || [])
  217. .filter(a => !(a.printer_id === printerId && a.ams_id === amsId && a.tray_id === trayId))
  218. .map(a => a.spool_id)
  219. );
  220. // Show every spool that isn't already taken by another slot — including
  221. // RFID-tagged Bambu Lab spools (#1133). The earlier "manual spools only"
  222. // gate (tag_uid && tray_uuid both null) blocked the workflow where a
  223. // user has a Bambu Lab spool in inventory but doesn't want to scan it
  224. // via SpoolBuddy NFC every time and just wants to pick it from the list.
  225. // External slots (amsId 254/255) have always been allowed to pick from
  226. // any spool because the slot itself has no RFID reader; that
  227. // distinction collapses now that AMS slots also accept any spool.
  228. //
  229. // The "Show all spools" toggle (disableFiltering) bypasses BOTH this
  230. // gate and the material/profile filter below, making it a real escape
  231. // hatch for cases where MQTT has auto-reassigned a spool to another
  232. // slot a fraction of a second after a manual unassign — without this,
  233. // the toggle's label is a lie ("Show all" but actually filters by
  234. // assignment). The backend's assign_spool route is upsert-per-
  235. // (printer, ams, tray), so picking a spool that's currently taken by
  236. // a different slot creates a second assignment row; that's a foot-gun
  237. // for normal flows but exactly the recovery path the toggle is for.
  238. const availableSpools = spools?.filter((spool: InventorySpool) =>
  239. !spool.archived_at &&
  240. (disableFiltering || !assignedSpoolIds.has(spool.id))
  241. );
  242. // Filtering logic with toggle: search filter always applies, AMS tray profile filter is optional.
  243. // Show a spool if EITHER the slicer profile matches exactly OR the material overlaps with the
  244. // tray's material (partial-match both directions — "PLA" spool accepts a "PLA Basic" slot and
  245. // vice versa). Manually-added inventory spools typically have no slicer_filament_name; gating
  246. // on strict profile equality alone hid them even when the material matched (#1047).
  247. let filteredSpools = availableSpools;
  248. if (!disableFiltering) {
  249. const trayProfile = stripProfileQualifier(normalizeValue(trayInfo?.profile));
  250. const trayMaterial = normalizeValue(trayInfo?.material || trayInfo?.type);
  251. if (trayProfile || trayMaterial) {
  252. filteredSpools = filteredSpools?.filter((spool: InventorySpool) => {
  253. const spoolProfile = stripProfileQualifier(normalizeValue(spool.slicer_filament_name || spool.slicer_filament));
  254. const spoolMaterial = normalizeValue(spool.material);
  255. if (trayProfile && spoolProfile && spoolProfile === trayProfile) return true;
  256. if (trayMaterial && spoolMaterial) {
  257. return (
  258. spoolMaterial === trayMaterial ||
  259. trayMaterial.includes(spoolMaterial) ||
  260. spoolMaterial.includes(trayMaterial)
  261. );
  262. }
  263. // Neither side has filterable info on whatever dimension remains — show it.
  264. return !spoolProfile && !spoolMaterial;
  265. });
  266. }
  267. }
  268. if (searchFilter && filteredSpools) {
  269. filteredSpools = filterSpoolsByQuery(filteredSpools, searchFilter);
  270. }
  271. const handleAssign = () => {
  272. if (selectedSpoolmanSpoolId !== null) {
  273. assignSpoolmanMutation.mutate(selectedSpoolmanSpoolId);
  274. return;
  275. }
  276. if (!selectedSpoolId) return;
  277. const selectedSpool = spools?.find((spool: InventorySpool) => spool.id === selectedSpoolId);
  278. if (!selectedSpool) {
  279. showToast(t('inventory.assignFailed'), 'error');
  280. return;
  281. }
  282. if (!settings?.disable_filament_warnings && trayInfo) {
  283. const trayMaterial = trayInfo.material || trayInfo.type;
  284. const materialMatchResult = checkMaterialMatch(selectedSpool.material, trayMaterial);
  285. const spoolProfile = selectedSpool.slicer_filament_name || selectedSpool.slicer_filament;
  286. const trayProfile = trayInfo.profile || trayInfo.type;
  287. const profileMatches = checkProfileMatch(spoolProfile, trayProfile);
  288. // Only material-bearing mismatches warn — profile-only deltas are
  289. // silently resolved by the backend's AMS reconfigure on every assign
  290. // (#1552).
  291. if (materialMatchResult !== 'exact') {
  292. let mismatchType: 'material' | 'partial' | 'material_profile' | 'partial_profile';
  293. if (materialMatchResult === 'none' && !profileMatches) {
  294. mismatchType = 'material_profile';
  295. } else if (materialMatchResult === 'partial' && !profileMatches) {
  296. mismatchType = 'partial_profile';
  297. } else if (materialMatchResult === 'none') {
  298. mismatchType = 'material';
  299. } else {
  300. mismatchType = 'partial';
  301. }
  302. setPendingAssignId(selectedSpoolId);
  303. setMismatchDetails({
  304. type: mismatchType,
  305. spoolMaterial: selectedSpool.material || '',
  306. trayMaterial: trayMaterial || '',
  307. spoolProfile: spoolProfile || undefined,
  308. trayProfile: trayProfile || undefined,
  309. });
  310. setShowMismatchConfirm(true);
  311. return;
  312. }
  313. }
  314. assignMutation.mutate(selectedSpoolId);
  315. };
  316. const handleConfirmMismatch = () => {
  317. if (!pendingAssignId) return;
  318. assignMutation.mutate(pendingAssignId);
  319. setShowMismatchConfirm(false);
  320. setPendingAssignId(null);
  321. };
  322. return (
  323. <>
  324. <div className="fixed inset-0 z-[100] flex items-start sm:items-center justify-center p-4 overflow-y-auto">
  325. <div
  326. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  327. onClick={onClose}
  328. />
  329. <div className="relative w-full max-w-2xl bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto">
  330. {/* Header */}
  331. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  332. <div className="flex items-center gap-2">
  333. <Package className="w-5 h-5 text-bambu-green" />
  334. <h2 className="text-lg font-semibold text-white">{t('inventory.assignSpool')}</h2>
  335. </div>
  336. <button
  337. onClick={onClose}
  338. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  339. >
  340. <X className="w-5 h-5" />
  341. </button>
  342. </div>
  343. {/* Content */}
  344. <div className="p-4 space-y-4 overflow-y-auto">
  345. {/* Tray info */}
  346. {trayInfo && (
  347. <div className="p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary">
  348. <p className="text-xs text-bambu-gray mb-1">{t('inventory.selectSpool')}:</p>
  349. <div className="flex items-center gap-2">
  350. {trayInfo.color && (
  351. <span
  352. className="w-4 h-4 rounded-full border border-black/20"
  353. style={{ backgroundColor: `#${trayInfo.color}` }}
  354. />
  355. )}
  356. <span className="text-white font-medium">{trayInfo.type || t('ams.emptySlot')}</span>
  357. <span className="text-bambu-gray">({trayInfo.location})</span>
  358. </div>
  359. </div>
  360. )}
  361. {/* Search filter */}
  362. <div className="relative">
  363. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  364. <input
  365. type="text"
  366. value={searchFilter}
  367. onChange={(e) => setSearchFilter(e.target.value)}
  368. placeholder={t('inventory.searchSpools')}
  369. className="w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"
  370. />
  371. </div>
  372. {/* Spool list */}
  373. <div className="space-y-3">
  374. {!spoolmanEnabled && (isLoading ? (
  375. <div className="flex justify-center py-8">
  376. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  377. </div>
  378. ) : filteredSpools && filteredSpools.length > 0 ? (
  379. <div className="max-h-96 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2">
  380. {filteredSpools.map((spool: InventorySpool) => (
  381. <button
  382. key={spool.id}
  383. onClick={() => { setSelectedSpoolId(spool.id); setSelectedSpoolmanSpoolId(null); }}
  384. title={spool.note || undefined}
  385. className={`p-2.5 rounded-lg border text-left transition-colors ${
  386. selectedSpoolId === spool.id
  387. ? 'bg-bambu-green/20 border-bambu-green'
  388. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  389. }`}
  390. >
  391. <p className="text-white text-sm font-medium truncate">
  392. {spool.brand ? `${spool.brand} ` : ''}{spool.material}{spool.subtype ? ` ${spool.subtype}` : ''}
  393. </p>
  394. <div className="flex items-center gap-1.5 mt-1">
  395. {spool.rgba && (
  396. <span
  397. className="w-3 h-3 rounded-full border border-black/20 flex-shrink-0"
  398. style={getSwatchStyle(spool.rgba)}
  399. />
  400. )}
  401. <span className="text-xs text-bambu-gray truncate">{spool.color_name || ''}</span>
  402. </div>
  403. {spool.label_weight && (
  404. <p className="text-xs text-bambu-gray mt-1">
  405. {Math.max(0, Math.round(spool.label_weight - spool.weight_used))} / {spool.label_weight}g
  406. </p>
  407. )}
  408. {spool.note && (
  409. <p className="text-[10px] text-bambu-gray/70 mt-1 truncate" title={spool.note}>
  410. {spool.note}
  411. </p>
  412. )}
  413. </button>
  414. ))}
  415. </div>
  416. ) : availableSpools && availableSpools.length === 0 ? (
  417. <div className="text-center py-8 text-bambu-gray">
  418. <p>{t('inventory.noAvailableSpools')}</p>
  419. {/* Diagnostic counter — when the picker is empty, having
  420. the raw fetch / filter counts visible makes a
  421. "spool I expected to see is missing" report
  422. immediately answerable: if `total fetched` is 0 the
  423. backend / cache returned nothing; if it's > 0 then
  424. the archived / assigned-elsewhere filter ate the
  425. spool and the toggle is the right escape hatch. */}
  426. {spools && (
  427. <p className="text-[10px] mt-2 opacity-60">
  428. {spools.length} fetched · {spools.filter(s => s.archived_at).length} archived ·{' '}
  429. {spools.filter(s => assignedSpoolIds.has(s.id)).length} assigned to other slots
  430. </p>
  431. )}
  432. </div>
  433. ) : (
  434. <div className="text-center py-8 text-bambu-gray">
  435. <p>{t('inventory.noSpoolsMatch')}</p>
  436. {availableSpools && (
  437. <p className="text-[10px] mt-2 opacity-60">
  438. {availableSpools.length} unassigned spools — {(availableSpools.length) - (filteredSpools?.length ?? 0)} filtered by tray match. Try "Show all spools".
  439. </p>
  440. )}
  441. </div>
  442. ))}
  443. {spoolmanEnabled && (
  444. <>
  445. {spoolmanLoading ? (
  446. <div className="flex justify-center py-4">
  447. <Loader2 className="w-5 h-5 text-bambu-green animate-spin" />
  448. </div>
  449. ) : spoolmanSpools && spoolmanSpools.filter(s => !s.archived_at && !assignedSpoolmanSpoolIds.has(s.id)).length > 0 ? (
  450. <>
  451. <p className="text-xs font-medium text-bambu-gray uppercase tracking-wide pt-1">
  452. {t('inventory.spoolmanSpools')}
  453. </p>
  454. <div className="max-h-64 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2">
  455. {filterSpoolsByQuery(spoolmanSpools.filter(s => !s.archived_at && !assignedSpoolmanSpoolIds.has(s.id)), searchFilter)
  456. .map((spool: InventorySpool) => (
  457. <button
  458. key={`spoolman-${spool.id}`}
  459. onClick={() => {
  460. setSelectedSpoolmanSpoolId(spool.id);
  461. setSelectedSpoolId(null);
  462. }}
  463. title={spool.note || undefined}
  464. className={`p-2.5 rounded-lg border text-left transition-colors ${
  465. selectedSpoolmanSpoolId === spool.id
  466. ? 'bg-bambu-green/20 border-bambu-green'
  467. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  468. }`}
  469. >
  470. <p className="text-white text-sm font-medium truncate">
  471. {spool.brand ? `${spool.brand} ` : ''}{spool.material}{spool.subtype ? ` ${spool.subtype}` : ''}
  472. </p>
  473. <div className="flex items-center gap-1.5 mt-1">
  474. {spool.rgba && (
  475. <span
  476. className="w-3 h-3 rounded-full border border-black/20 flex-shrink-0"
  477. style={getSwatchStyle(spool.rgba)}
  478. />
  479. )}
  480. <span className="text-xs text-bambu-gray truncate">{spool.color_name || ''}</span>
  481. </div>
  482. {spool.label_weight && (
  483. <p className="text-xs text-bambu-gray mt-1">
  484. {Math.max(0, Math.round(spool.label_weight - spool.weight_used))} / {spool.label_weight}g
  485. </p>
  486. )}
  487. {spool.note && (
  488. <p className="text-[10px] text-bambu-gray/70 mt-1 truncate" title={spool.note}>
  489. {spool.note}
  490. </p>
  491. )}
  492. </button>
  493. ))}
  494. </div>
  495. </>
  496. ) : null}
  497. </>
  498. )}
  499. </div>
  500. </div>
  501. {/* Footer with filtering toggle */}
  502. <div className="flex justify-between items-center p-4 border-t border-bambu-dark-tertiary">
  503. <div className="flex items-center gap-2">
  504. <input
  505. id="disable-filtering-toggle"
  506. type="checkbox"
  507. checked={disableFiltering}
  508. onChange={() => setDisableFiltering(v => !v)}
  509. className="accent-bambu-green w-4 h-4 rounded focus:ring-0 border-bambu-dark-tertiary"
  510. />
  511. <label htmlFor="disable-filtering-toggle" className="text-xs text-bambu-gray select-none cursor-pointer">
  512. {t('inventory.showAllSpools')}
  513. </label>
  514. </div>
  515. <div className="flex gap-2">
  516. <Button variant="secondary" onClick={onClose}>
  517. {t('common.cancel')}
  518. </Button>
  519. <Button
  520. onClick={handleAssign}
  521. disabled={(!selectedSpoolId && selectedSpoolmanSpoolId === null) || assignMutation.isPending || assignSpoolmanMutation.isPending}
  522. >
  523. {(assignMutation.isPending || assignSpoolmanMutation.isPending) ? (
  524. <>
  525. <Loader2 className="w-4 h-4 animate-spin" />
  526. {t('inventory.assigning')}
  527. </>
  528. ) : (
  529. <>
  530. <Package className="w-4 h-4" />
  531. {t('inventory.assignSpool')}
  532. </>
  533. )}
  534. </Button>
  535. </div>
  536. </div>
  537. {assignMutation.isError && (
  538. <div className="mx-4 mb-4 p-2 bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/50 rounded text-sm text-red-700 dark:text-red-400">
  539. {(assignMutation.error as Error).message}
  540. </div>
  541. )}
  542. </div>
  543. </div>
  544. {showMismatchConfirm && trayInfo && selectedSpoolId && mismatchDetails && (() => {
  545. let message = '';
  546. if (mismatchDetails.type === 'material') {
  547. message = t('inventory.assignMismatchMessage', {
  548. spoolMaterial: mismatchDetails.spoolMaterial,
  549. trayMaterial: mismatchDetails.trayMaterial,
  550. location: trayInfo.location,
  551. });
  552. } else if (mismatchDetails.type === 'partial') {
  553. message = t('inventory.assignPartialMismatchMessage', {
  554. spoolMaterial: mismatchDetails.spoolMaterial,
  555. trayMaterial: mismatchDetails.trayMaterial,
  556. location: trayInfo.location,
  557. });
  558. } else if (mismatchDetails.type === 'material_profile') {
  559. message = `${t('inventory.assignMismatchMessage', {
  560. spoolMaterial: mismatchDetails.spoolMaterial,
  561. trayMaterial: mismatchDetails.trayMaterial,
  562. location: trayInfo.location,
  563. })}\n\n${t('inventory.assignProfileMismatchMessage', {
  564. spoolProfile: mismatchDetails.spoolProfile || t('common.unknown'),
  565. trayProfile: mismatchDetails.trayProfile || t('common.unknown'),
  566. location: trayInfo.location,
  567. })}`;
  568. } else if (mismatchDetails.type === 'partial_profile') {
  569. message = `${t('inventory.assignPartialMismatchMessage', {
  570. spoolMaterial: mismatchDetails.spoolMaterial,
  571. trayMaterial: mismatchDetails.trayMaterial,
  572. location: trayInfo.location,
  573. })}\n\n${t('inventory.assignProfileMismatchMessage', {
  574. spoolProfile: mismatchDetails.spoolProfile || t('common.unknown'),
  575. trayProfile: mismatchDetails.trayProfile || t('common.unknown'),
  576. location: trayInfo.location,
  577. })}`;
  578. }
  579. // Always tell the user the AMS slot is going to be reconfigured —
  580. // the existing wording made "Assign Anyway" sound like the popup was
  581. // a no-op confirmation, when the backend in fact pushes the spool's
  582. // profile to the slot on every assign (#1552).
  583. message = `${message}\n\n${t('inventory.assignReconfigureNote')}`;
  584. return (
  585. <ConfirmModal
  586. title={t('inventory.assignMismatchTitle')}
  587. message={message}
  588. confirmText={t('inventory.assignMismatchConfirm')}
  589. variant="warning"
  590. // Sit above the AssignSpoolModal wrapper (z-[100], #1336) —
  591. // without this the mismatch dialog is hidden behind its parent.
  592. overlayZIndex="z-[110]"
  593. isLoading={assignMutation.isPending}
  594. onConfirm={handleConfirmMismatch}
  595. onCancel={() => {
  596. if (!assignMutation.isPending) {
  597. setShowMismatchConfirm(false);
  598. setPendingAssignId(null);
  599. setMismatchDetails(null);
  600. }
  601. }}
  602. />
  603. );
  604. })()}
  605. </>
  606. );
  607. }