QrAssignTargetModal.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. import { useEffect, useMemo, useRef, useState } from 'react';
  2. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Loader2, QrCode, Cpu, MapPin, ArrowLeft } from 'lucide-react';
  5. import { api, ApiError, type AMSTray } from '../api/client';
  6. import { Button } from './Button';
  7. import { MaterialMismatchConfirm } from './MaterialMismatchConfirm';
  8. import { QrSpoolScanner } from './QrSpoolScanner';
  9. import { useToast } from '../contexts/ToastContext';
  10. import { useUiSettings } from '../hooks/useUiSettings';
  11. import { formatSlotLabel, getEmptySlotKind, rackExternalLabel } from '../utils/amsHelpers';
  12. import { externalSlotIndex, externalTrayId, trayLayoutOf } from '../utils/trayIds';
  13. import { findMaterialMismatch, type MaterialMismatch } from '../utils/assignMismatch';
  14. import { getSwatchStyle } from '../utils/colors';
  15. import { inventoryLocationsQueryKey, invalidateInventoryLocations } from '../utils/inventoryQueries';
  16. import { parseSpoolQr, scannedSpoolId, type AssignTarget } from '../utils/qrAssignTarget';
  17. type AmsTarget = Extract<AssignTarget, { kind: 'ams' }>;
  18. interface QrAssignTargetModalProps {
  19. isOpen: boolean;
  20. onClose: () => void;
  21. spoolmanMode?: boolean;
  22. }
  23. type SlotOption = {
  24. amsId: number;
  25. trayId: number;
  26. isHt: boolean;
  27. isExternal: boolean;
  28. label: string;
  29. /** What the printer reports in the slot, for its tile. */
  30. tray?: AMSTray;
  31. };
  32. /**
  33. * What a slot's tile says is in it, by the printer card's rules
  34. * (getEmptySlotKind): filament it reports, "?" for a spool it can't identify,
  35. * and Empty only where it says no spool is there. A missing tray_type alone is
  36. * not empty — a spool without RFID reads that way (#2527).
  37. */
  38. function SlotContents({ tray }: { tray?: AMSTray }) {
  39. const { t } = useTranslation();
  40. const kind = getEmptySlotKind(tray);
  41. if (kind === 'physical') return <span className="text-[10px] font-normal text-bambu-gray">{t('ams.slotEmpty')}</span>;
  42. if (kind === 'reset' || !tray) return <span className="text-xs font-normal text-bambu-gray">{t('ams.slotUnconfigured')}</span>;
  43. return (
  44. <span className="flex flex-col items-center gap-0.5 max-w-full">
  45. <span className="flex items-center gap-1 max-w-full">
  46. {tray.tray_color && (
  47. <span className="w-2.5 h-2.5 shrink-0 rounded-full border border-bambu-gray/50" style={getSwatchStyle(tray.tray_color)} />
  48. )}
  49. <span className="text-[10px] font-normal text-white truncate">{tray.tray_type}</span>
  50. </span>
  51. {/* Spaces keep the button's accessible name readable ("A1 PLA 80%"). */}
  52. {tray.remain >= 0 && <> <span className="text-[10px] font-normal text-bambu-gray">{tray.remain}%</span></>}
  53. </span>
  54. );
  55. }
  56. const TABS = [
  57. { key: 'ams' as const, Icon: Cpu, labelKey: 'inventory.qrAssign.tabAms' },
  58. { key: 'storage' as const, Icon: MapPin, labelKey: 'inventory.qrAssign.tabStorage' },
  59. ];
  60. function targetLocationLabel(target: AssignTarget): string {
  61. return target.kind === 'ams'
  62. ? target.printerName
  63. ? `${target.printerName} · ${target.label}`
  64. : target.label
  65. : target.locationName;
  66. }
  67. function externalLabel(t: (k: string) => string, vtCount: number, trayId: number, rack = false): string {
  68. // Match PrintersPage: Ext-n on a rack printer, Ext-L / Ext-R when two
  69. // external slots, "External" otherwise.
  70. if (rack) return rackExternalLabel(externalTrayId(trayId));
  71. if (vtCount > 1) return t(trayId === 0 ? 'printers.extL' : 'printers.extR');
  72. return t('printers.external');
  73. }
  74. export function QrAssignTargetModal({ isOpen, onClose, spoolmanMode = false }: QrAssignTargetModalProps) {
  75. const { t } = useTranslation();
  76. const { showToast } = useToast();
  77. const queryClient = useQueryClient();
  78. const [step, setStep] = useState<'target' | 'scan'>('target');
  79. const [tab, setTab] = useState<'ams' | 'storage'>('ams');
  80. const [pickedPrinterId, setPickedPrinterId] = useState<number | null>(null);
  81. const [selectedSlot, setSelectedSlot] = useState<SlotOption | null>(null);
  82. // Name is kept next to the id so the target survives a locations refetch that
  83. // hasn't landed yet (notably right after creating one inline).
  84. const [pickedLocation, setPickedLocation] = useState<{ id: number; name: string } | null>(null);
  85. const [newLocationName, setNewLocationName] = useState('');
  86. const [creatingLocation, setCreatingLocation] = useState(false);
  87. const [target, setTarget] = useState<AssignTarget | null>(null);
  88. const [error, setError] = useState<string | null>(null);
  89. // Looking the scanned spool up before an AMS assign, and a material mismatch
  90. // waiting on the confirm — as in the Assign Spool dialog.
  91. const [checking, setChecking] = useState(false);
  92. const [mismatch, setMismatch] = useState<{ spoolId: number; tg: AmsTarget; details: MaterialMismatch } | null>(null);
  93. // Synchronous in-flight guard: mutation.isPending only updates next render.
  94. const inFlightRef = useRef(false);
  95. // Counts the dialog's closings and openings: a spool lookup still running
  96. // when the dialog closed (Cancel, X, the backdrop) must not go on to assign
  97. // the spool.
  98. const openingRef = useRef(0);
  99. useEffect(() => {
  100. if (isOpen) {
  101. setStep('target');
  102. setSelectedSlot(null);
  103. setPickedLocation(null);
  104. setNewLocationName('');
  105. setCreatingLocation(false);
  106. setTarget(null);
  107. setError(null);
  108. setChecking(false);
  109. setMismatch(null);
  110. inFlightRef.current = false;
  111. }
  112. return () => {
  113. openingRef.current += 1;
  114. };
  115. }, [isOpen]);
  116. const { data: settings } = useUiSettings({ enabled: isOpen });
  117. const { data: printers, isLoading: printersLoading } = useQuery({
  118. queryKey: ['printers'],
  119. queryFn: () => api.getPrinters(),
  120. enabled: isOpen,
  121. });
  122. // Structured Locations are the canonical storage model, so the storage tab is
  123. // a picker over the same list the inventory Locations filter and LocationsModal
  124. // use — a QR assignment lands in `location_id`, not the legacy free-text field.
  125. const { data: locations = [], isLoading: locationsLoading } = useQuery({
  126. queryKey: inventoryLocationsQueryKey,
  127. queryFn: api.getLocations,
  128. enabled: isOpen && step === 'target',
  129. });
  130. const effectivePrinterId = pickedPrinterId ?? printers?.[0]?.id ?? null;
  131. const { data: status, isLoading: statusLoading } = useQuery({
  132. queryKey: ['printerStatus', effectivePrinterId],
  133. queryFn: () => api.getPrinterStatus(effectivePrinterId!),
  134. enabled: isOpen && step === 'target' && tab === 'ams' && effectivePrinterId !== null,
  135. });
  136. const slots = useMemo<SlotOption[]>(() => {
  137. if (!status) return [];
  138. const out: SlotOption[] = [];
  139. for (const ams of status.ams ?? []) {
  140. for (const tray of ams.tray ?? []) {
  141. out.push({
  142. amsId: ams.id,
  143. trayId: tray.id,
  144. isHt: ams.is_ams_ht,
  145. isExternal: false,
  146. label: formatSlotLabel(ams.id, tray.id, ams.is_ams_ht, false, ams.ams_type),
  147. tray,
  148. });
  149. }
  150. }
  151. // External (vt_tray) slots: backend keys them under ams_id 255 with
  152. // tray_id = id - 254 (mirrors PrintersPage; utils/trayIds externalSlotIndex).
  153. const externals = status.vt_tray ?? [];
  154. const rack = trayLayoutOf(status.ams, externals).rack;
  155. for (const vt of externals) {
  156. const trayId = externalSlotIndex(vt.id ?? 254);
  157. out.push({ amsId: 255, trayId, isHt: false, isExternal: true, label: externalLabel(t, externals.length, trayId, rack), tray: vt });
  158. }
  159. return out;
  160. }, [status, t]);
  161. const assignMutation = useMutation({
  162. mutationFn: async ({ spoolId, tg }: { spoolId: number; tg: AssignTarget }): Promise<{ pendingConfig: boolean }> => {
  163. if (tg.kind === 'ams') {
  164. // A spool lives in one slot at a time. `move` has the backend take it
  165. // out of its other slot(s) in the same transaction as the assign, so a
  166. // failure leaves it where it was rather than in no slot.
  167. if (spoolmanMode) {
  168. await api.assignSpoolmanSlot({ spoolman_spool_id: spoolId, printer_id: tg.printerId, ams_id: tg.amsId, tray_id: tg.trayId, move: true });
  169. return { pendingConfig: false };
  170. }
  171. const assignment = await api.assignSpool({ spool_id: spoolId, printer_id: tg.printerId, ams_id: tg.amsId, tray_id: tg.trayId, move: true });
  172. return { pendingConfig: !!assignment.pending_config };
  173. }
  174. if (spoolmanMode) {
  175. await api.updateSpoolmanInventorySpool(spoolId, { location_id: tg.locationId });
  176. } else {
  177. await api.updateSpool(spoolId, { location_id: tg.locationId });
  178. }
  179. return { pendingConfig: false };
  180. },
  181. onSuccess: ({ pendingConfig }, { tg }) => {
  182. // Intentionally do NOT clear inFlightRef here: the modal closes right
  183. // after, and leaving it set blocks any stale in-flight live-scan decode
  184. // from firing a second assignment in the brief window before unmount.
  185. // It's reset wholesale when the modal next opens (and in onError for retry).
  186. //
  187. // A slot that read empty at assign time is configured when the spool goes
  188. // in (#1680); "Assigned" would read as if the slot were set up already.
  189. showToast(
  190. pendingConfig
  191. ? t('inventory.assignPendingInsert')
  192. : t(tg.kind === 'ams' ? 'inventory.qrAssign.assignSuccess' : 'inventory.qrAssign.storageSuccess', { location: targetLocationLabel(tg) }),
  193. 'success',
  194. );
  195. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  196. queryClient.invalidateQueries({ queryKey: spoolmanMode ? ['spoolman-inventory-spools'] : ['inventory-spools'] });
  197. // Prefix match: the per-printer lists and the all-printers one.
  198. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  199. if (tg.kind === 'ams') {
  200. // #1414 parity: nudge the printer to republish so its card doesn't show
  201. // stale tray state until the next poll. Best-effort.
  202. api.refreshPrinterStatus(tg.printerId).catch(() => {});
  203. queryClient.invalidateQueries({ queryKey: ['printerStatus', tg.printerId] });
  204. // A Spoolman move clears the fallback tag linking the spool to its old slot.
  205. if (spoolmanMode) queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  206. } else {
  207. // The move changes per-location spool_count, which the Locations UI shows.
  208. invalidateInventoryLocations(queryClient);
  209. }
  210. onClose();
  211. },
  212. onError: (error: Error, { tg }) => {
  213. inFlightRef.current = false;
  214. // Said in the dialog, which stays open: a toast sits under its backdrop,
  215. // the SpoolBuddy kiosk shows none, and the scanner doesn't send a label
  216. // again while it stays in view.
  217. setError(`${t('inventory.qrAssign.assignFailed', { location: targetLocationLabel(tg) })}: ${error.message}`);
  218. },
  219. });
  220. if (!isOpen) return null;
  221. const printerName = printers?.find((p) => p.id === effectivePrinterId)?.name ?? '';
  222. const canStart = tab === 'ams' ? selectedSlot !== null && effectivePrinterId !== null : pickedLocation !== null;
  223. const isBusy = assignMutation.isPending || checking || mismatch !== null;
  224. // A freshly created location may not be in the fetched list yet, so make sure
  225. // the current pick is always offered.
  226. const locationOptions =
  227. pickedLocation && !locations.some((l) => l.id === pickedLocation.id)
  228. ? [...locations, pickedLocation]
  229. : locations;
  230. // Create-and-pick, so the user doesn't have to leave the scan flow to add a
  231. // shelf. Mirrors the spool form's inline location creation.
  232. const handleCreateLocation = async () => {
  233. const name = newLocationName.trim();
  234. if (!name || creatingLocation) return;
  235. setCreatingLocation(true);
  236. try {
  237. const created = await api.createLocation({ name });
  238. invalidateInventoryLocations(queryClient);
  239. setPickedLocation({ id: created.id, name: created.name });
  240. setNewLocationName('');
  241. } catch (err) {
  242. showToast(err instanceof Error ? err.message : t('locations.saveFailed'), 'error');
  243. } finally {
  244. setCreatingLocation(false);
  245. }
  246. };
  247. const handleStart = () => {
  248. let tg: AssignTarget;
  249. if (tab === 'ams') {
  250. if (!selectedSlot || effectivePrinterId === null) return;
  251. tg = {
  252. kind: 'ams',
  253. printerId: effectivePrinterId,
  254. printerName,
  255. amsId: selectedSlot.amsId,
  256. trayId: selectedSlot.trayId,
  257. isExternal: selectedSlot.isExternal,
  258. label: selectedSlot.label,
  259. filament: {
  260. type: selectedSlot.tray?.tray_type || '',
  261. profile: selectedSlot.tray?.tray_sub_brands || undefined,
  262. },
  263. };
  264. } else {
  265. if (!pickedLocation) return;
  266. tg = { kind: 'storage', locationId: pickedLocation.id, locationName: pickedLocation.name };
  267. }
  268. setTarget(tg);
  269. setError(null);
  270. setStep('scan');
  271. };
  272. // A built-in spool going into an AMS slot is looked up first, as the Assign
  273. // Spool dialog has it at hand: a missing or archived spool says so, and one
  274. // whose material doesn't fit the slot asks before it is assigned. Spoolman
  275. // spools go straight to the backend, which checks them, as in that dialog.
  276. const checkAndAssign = async (spoolId: number, tg: AmsTarget) => {
  277. const opening = openingRef.current;
  278. setChecking(true);
  279. try {
  280. const spool = await api.getSpool(spoolId);
  281. if (openingRef.current !== opening) return; // the dialog was closed meanwhile
  282. if (spool.archived_at) {
  283. setError(t('inventory.spoolIdArchived', { id: spoolId }));
  284. inFlightRef.current = false;
  285. return;
  286. }
  287. const details = settings?.disable_filament_warnings ? null : findMaterialMismatch(spool, tg.filament);
  288. if (details) {
  289. setMismatch({ spoolId, tg, details }); // still in flight until confirmed or cancelled
  290. return;
  291. }
  292. assignMutation.mutate({ spoolId, tg });
  293. } catch (err) {
  294. if (openingRef.current !== opening) return;
  295. setError(
  296. err instanceof ApiError && err.status === 404
  297. ? t('inventory.spoolIdNotFound', { id: spoolId })
  298. : err instanceof Error
  299. ? err.message
  300. : t('inventory.assignFailed'),
  301. );
  302. inFlightRef.current = false;
  303. } finally {
  304. setChecking(false);
  305. }
  306. };
  307. // Shared by the live scanner and the photo fallback: validate the decoded QR
  308. // and fire the assignment (guarded so one scan can't assign twice).
  309. const handleDecode = (text: string) => {
  310. if (inFlightRef.current || isBusy || !target) return;
  311. const scanned = parseSpoolQr(text);
  312. if (!scanned) {
  313. setError(t('inventory.qrAssign.invalidQr'));
  314. return;
  315. }
  316. const id = scannedSpoolId(scanned, spoolmanMode);
  317. if (id === null) {
  318. setError(t('inventory.qrAssign.spoolmanLabel'));
  319. return;
  320. }
  321. setError(null);
  322. inFlightRef.current = true;
  323. if (target.kind === 'ams' && !spoolmanMode) {
  324. void checkAndAssign(id, target);
  325. return;
  326. }
  327. assignMutation.mutate({ spoolId: id, tg: target });
  328. };
  329. const confirmMismatch = () => {
  330. if (!mismatch) return;
  331. setMismatch(null);
  332. assignMutation.mutate({ spoolId: mismatch.spoolId, tg: mismatch.tg });
  333. };
  334. // The scanner keeps this label from coming straight back; another label, a
  335. // photo or Retry starts over.
  336. const cancelMismatch = () => {
  337. setMismatch(null);
  338. inFlightRef.current = false;
  339. };
  340. return (
  341. <>
  342. <div className="fixed inset-0 z-[100] flex items-start sm:items-center justify-center p-4 overflow-y-auto">
  343. <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
  344. <div className="relative w-full max-w-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col my-auto">
  345. {/* Header */}
  346. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  347. <div className="flex items-center gap-2">
  348. <QrCode className="w-5 h-5 text-bambu-green" />
  349. <h2 className="text-lg font-semibold text-white">
  350. {step === 'target' ? t('inventory.qrAssign.title') : t('inventory.qrAssign.scanTitle')}
  351. </h2>
  352. </div>
  353. <button onClick={onClose} className="p-1 text-bambu-gray hover:text-white rounded transition-colors">
  354. <X className="w-5 h-5" />
  355. </button>
  356. </div>
  357. {/* Content */}
  358. <div className="p-4 space-y-4 overflow-y-auto">
  359. {step === 'target' ? (
  360. <>
  361. <p className="text-sm text-bambu-gray">{t('inventory.qrAssign.description')}</p>
  362. {/* Tabs */}
  363. <div className="flex gap-2">
  364. {TABS.map(({ key, Icon, labelKey }) => (
  365. <button
  366. key={key}
  367. onClick={() => setTab(key)}
  368. className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-lg text-sm font-medium border transition-colors ${
  369. tab === key
  370. ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
  371. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray'
  372. }`}
  373. >
  374. <Icon className="w-4 h-4" />
  375. {t(labelKey)}
  376. </button>
  377. ))}
  378. </div>
  379. {tab === 'ams' ? (
  380. <div className="space-y-3">
  381. <div>
  382. <label htmlFor="qr-printer-select" className="block text-xs font-medium text-bambu-gray uppercase tracking-wide mb-1">
  383. {t('inventory.qrAssign.printer')}
  384. </label>
  385. <select
  386. id="qr-printer-select"
  387. value={effectivePrinterId ?? ''}
  388. onChange={(e) => {
  389. setPickedPrinterId(Number(e.target.value));
  390. setSelectedSlot(null);
  391. }}
  392. disabled={printersLoading || !printers?.length}
  393. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  394. >
  395. {printers?.map((p) => (
  396. <option key={p.id} value={p.id}>
  397. {p.name}
  398. </option>
  399. ))}
  400. </select>
  401. </div>
  402. <div>
  403. <span className="block text-xs font-medium text-bambu-gray uppercase tracking-wide mb-1">
  404. {t('inventory.qrAssign.selectSlot')}
  405. </span>
  406. {statusLoading ? (
  407. <div className="flex justify-center py-6">
  408. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  409. </div>
  410. ) : slots.length > 0 ? (
  411. <div className="grid grid-cols-4 gap-2">
  412. {slots.map((slot) => {
  413. const isSel = selectedSlot?.amsId === slot.amsId && selectedSlot?.trayId === slot.trayId;
  414. return (
  415. <button
  416. key={`${slot.amsId}-${slot.trayId}`}
  417. onClick={() => setSelectedSlot(slot)}
  418. className={`aspect-square min-w-0 px-1 flex flex-col items-center justify-center gap-1 rounded-lg border text-sm font-semibold transition-colors ${
  419. isSel
  420. ? 'bg-bambu-green/20 border-bambu-green text-white'
  421. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray'
  422. }`}
  423. >
  424. <span>{slot.label}</span> <SlotContents tray={slot.tray} />
  425. </button>
  426. );
  427. })}
  428. </div>
  429. ) : (
  430. <p className="text-center py-6 text-sm text-bambu-gray">{t('inventory.qrAssign.noSlots')}</p>
  431. )}
  432. </div>
  433. </div>
  434. ) : (
  435. <div>
  436. <label htmlFor="qr-storage-select" className="block text-xs font-medium text-bambu-gray uppercase tracking-wide mb-1">
  437. {t('inventory.qrAssign.storageLabel')}
  438. </label>
  439. {locationsLoading ? (
  440. <div className="flex justify-center py-6">
  441. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  442. </div>
  443. ) : (
  444. <select
  445. id="qr-storage-select"
  446. value={pickedLocation?.id ?? ''}
  447. onChange={(e) => {
  448. const id = e.target.value ? Number(e.target.value) : null;
  449. const match = id === null ? null : locationOptions.find((l) => l.id === id);
  450. setPickedLocation(match ? { id: match.id, name: match.name } : null);
  451. }}
  452. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"
  453. >
  454. <option value="">{t('inventory.qrAssign.storagePick')}</option>
  455. {locationOptions.map((loc) => (
  456. <option key={loc.id} value={loc.id}>
  457. {loc.name}
  458. </option>
  459. ))}
  460. </select>
  461. )}
  462. {!locationsLoading && locationOptions.length === 0 && (
  463. <p className="mt-2 text-xs text-bambu-gray">{t('locations.empty')}</p>
  464. )}
  465. <div className="mt-2 flex gap-2">
  466. <input
  467. type="text"
  468. maxLength={255}
  469. value={newLocationName}
  470. onChange={(e) => setNewLocationName(e.target.value)}
  471. placeholder={t('locations.createPlaceholder')}
  472. className="flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"
  473. />
  474. <button
  475. type="button"
  476. onClick={handleCreateLocation}
  477. disabled={!newLocationName.trim() || creatingLocation}
  478. className="px-3 py-2 text-sm rounded-lg bg-bambu-dark-tertiary text-white hover:bg-bambu-gray-dark disabled:opacity-50"
  479. >
  480. {creatingLocation ? <Loader2 className="w-4 h-4 animate-spin" /> : t('locations.addShort')}
  481. </button>
  482. </div>
  483. </div>
  484. )}
  485. </>
  486. ) : (
  487. <QrSpoolScanner
  488. onDecode={handleDecode}
  489. busy={isBusy}
  490. error={error}
  491. targetLabel={target ? targetLocationLabel(target) : undefined}
  492. />
  493. )}
  494. </div>
  495. {/* Footer */}
  496. <div className="flex justify-between gap-2 p-4 border-t border-bambu-dark-tertiary">
  497. {step === 'scan' ? (
  498. <Button variant="secondary" onClick={() => setStep('target')} disabled={isBusy}>
  499. <ArrowLeft className="w-4 h-4" />
  500. {t('inventory.qrAssign.back')}
  501. </Button>
  502. ) : (
  503. <span />
  504. )}
  505. <div className="flex gap-2">
  506. <Button variant="secondary" onClick={onClose}>
  507. {t('common.cancel')}
  508. </Button>
  509. {step === 'target' && (
  510. <Button onClick={handleStart} disabled={!canStart}>
  511. <QrCode className="w-4 h-4" />
  512. {t('inventory.qrAssign.startScan')}
  513. </Button>
  514. )}
  515. </div>
  516. </div>
  517. </div>
  518. </div>
  519. {mismatch && (
  520. <MaterialMismatchConfirm
  521. mismatch={mismatch.details}
  522. location={targetLocationLabel(mismatch.tg)}
  523. onConfirm={confirmMismatch}
  524. onCancel={cancelMismatch}
  525. />
  526. )}
  527. </>
  528. );
  529. }