AssignSpoolModal.tsx 31 KB

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