AssignSpoolModal.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import { useEffect, 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. interface AssignSpoolModalProps {
  11. isOpen: boolean;
  12. onClose: () => void;
  13. printerId: number;
  14. amsId: number;
  15. trayId: number;
  16. trayInfo?: {
  17. type: string;
  18. material?: string;
  19. profile?: string;
  20. color: string;
  21. location: string;
  22. };
  23. }
  24. export function AssignSpoolModal({ isOpen, onClose, printerId, amsId, trayId, trayInfo }: AssignSpoolModalProps) {
  25. const { t } = useTranslation();
  26. const queryClient = useQueryClient();
  27. const { showToast } = useToast();
  28. const [disableFiltering, setDisableFiltering] = useState(false);
  29. const [selectedSpoolId, setSelectedSpoolId] = useState<number | null>(null);
  30. useEffect(() => {
  31. setSelectedSpoolId(null);
  32. }, [disableFiltering]);
  33. const [searchFilter, setSearchFilter] = useState('');
  34. const [pendingAssignId, setPendingAssignId] = useState<number | null>(null);
  35. const [showMismatchConfirm, setShowMismatchConfirm] = useState(false);
  36. const [mismatchDetails, setMismatchDetails] = useState<{
  37. type: 'material' | 'partial' | 'profile' | 'material_profile' | 'partial_profile';
  38. spoolMaterial: string;
  39. trayMaterial: string;
  40. spoolProfile?: string;
  41. trayProfile?: string;
  42. } | null>(null);
  43. useEffect(() => {
  44. if (isOpen) {
  45. setDisableFiltering(false);
  46. }
  47. }, [isOpen]);
  48. const { data: spools, isLoading } = useQuery({
  49. queryKey: ['inventory-spools'],
  50. queryFn: () => api.getSpools(),
  51. enabled: isOpen,
  52. });
  53. const { data: assignments } = useQuery({
  54. queryKey: ['spool-assignments'],
  55. queryFn: () => api.getAssignments(),
  56. enabled: isOpen,
  57. });
  58. const { data: settings } = useQuery({
  59. queryKey: ['settings'],
  60. queryFn: () => api.getSettings(),
  61. enabled: isOpen,
  62. });
  63. const assignMutation = useMutation({
  64. mutationFn: (spoolId: number) =>
  65. api.assignSpool({ spool_id: spoolId, printer_id: printerId, ams_id: amsId, tray_id: trayId }),
  66. onSuccess: (newAssignment) => {
  67. // Immediately update cache so UI reflects the new assignment without waiting for refetch
  68. queryClient.setQueryData<SpoolAssignment[]>(['spool-assignments'], (old) => {
  69. const filtered = (old || []).filter(a =>
  70. !(a.printer_id === printerId && a.ams_id === amsId && a.tray_id === trayId)
  71. );
  72. filtered.push(newAssignment);
  73. return filtered;
  74. });
  75. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  76. showToast(t('inventory.assignSuccess'), 'success');
  77. setShowMismatchConfirm(false);
  78. setPendingAssignId(null);
  79. setMismatchDetails(null);
  80. onClose();
  81. },
  82. onError: (error: Error) => {
  83. showToast(`${t('inventory.assignFailed')}: ${error.message}`, 'error');
  84. },
  85. });
  86. // --- Material/profile mismatch logic ---
  87. const normalizeValue = (value: string | undefined | null) =>
  88. (value ?? '').trim().toUpperCase();
  89. const checkMaterialMatch = (
  90. spoolMaterial: string | undefined | null,
  91. trayMaterial: string | undefined | null
  92. ): 'exact' | 'partial' | 'none' => {
  93. const normalizedSpool = normalizeValue(spoolMaterial);
  94. const normalizedTray = normalizeValue(trayMaterial);
  95. if (!normalizedSpool || !normalizedTray) return 'none';
  96. if (normalizedSpool === normalizedTray) return 'exact';
  97. if (normalizedTray.includes(normalizedSpool) || normalizedSpool.includes(normalizedTray)) {
  98. return 'partial';
  99. }
  100. return 'none';
  101. };
  102. const checkProfileMatch = (
  103. spoolProfile: string | undefined | null,
  104. trayProfile: string | undefined | null
  105. ): boolean => {
  106. const normalizedSpoolProfile = normalizeValue(spoolProfile);
  107. const normalizedTrayProfile = normalizeValue(trayProfile);
  108. if (!normalizedSpoolProfile || !normalizedTrayProfile) return false;
  109. return normalizedSpoolProfile === normalizedTrayProfile;
  110. };
  111. if (!isOpen) return null;
  112. // Filter out spools already assigned to other slots
  113. const assignedSpoolIds = new Set(
  114. (assignments || [])
  115. .filter(a => !(a.printer_id === printerId && a.ams_id === amsId && a.tray_id === trayId))
  116. .map(a => a.spool_id)
  117. );
  118. // External slots (amsId 254 or 255) have no RFID reader, so show all spools.
  119. // AMS slots only show manual spools (no tag_uid or tray_uuid).
  120. const isExternalSlot = amsId === 254 || amsId === 255;
  121. const manualSpools = spools?.filter((spool: InventorySpool) =>
  122. !assignedSpoolIds.has(spool.id) && (isExternalSlot || (!spool.tag_uid && !spool.tray_uuid))
  123. );
  124. // Filtering logic with toggle: search filter always applies, AMS tray profile filter is optional
  125. let filteredSpools = manualSpools;
  126. if (!disableFiltering) {
  127. if (trayInfo?.profile || trayInfo?.type) {
  128. const trayProfile = normalizeValue(trayInfo.profile || trayInfo.type);
  129. filteredSpools = filteredSpools?.filter((spool: InventorySpool) => {
  130. const spoolProfile = normalizeValue(spool.slicer_filament_name || spool.slicer_filament);
  131. return trayProfile && spoolProfile && spoolProfile === trayProfile;
  132. });
  133. }
  134. }
  135. if (searchFilter && filteredSpools) {
  136. const q = searchFilter.toLowerCase();
  137. filteredSpools = filteredSpools.filter((spool: InventorySpool) => {
  138. return (
  139. spool.material.toLowerCase().includes(q) ||
  140. (spool.brand?.toLowerCase().includes(q) ?? false) ||
  141. (spool.color_name?.toLowerCase().includes(q) ?? false) ||
  142. (spool.subtype?.toLowerCase().includes(q) ?? false)
  143. );
  144. });
  145. }
  146. const handleAssign = () => {
  147. if (!selectedSpoolId) return;
  148. const selectedSpool = spools?.find((spool: InventorySpool) => spool.id === selectedSpoolId);
  149. if (!selectedSpool) {
  150. showToast(t('inventory.assignFailed'), 'error');
  151. return;
  152. }
  153. if (!settings?.disable_filament_warnings && trayInfo) {
  154. const trayMaterial = trayInfo.material || trayInfo.type;
  155. const materialMatchResult = checkMaterialMatch(selectedSpool.material, trayMaterial);
  156. const spoolProfile = selectedSpool.slicer_filament_name || selectedSpool.slicer_filament;
  157. const trayProfile = trayInfo.profile || trayInfo.type;
  158. const profileMatches = checkProfileMatch(spoolProfile, trayProfile);
  159. // Always evaluate both checks; if both fail, show a combined warning.
  160. if (materialMatchResult !== 'exact' || !profileMatches) {
  161. let mismatchType: 'material' | 'partial' | 'profile' | 'material_profile' | 'partial_profile' = 'profile';
  162. if (materialMatchResult === 'none' && !profileMatches) {
  163. mismatchType = 'material_profile';
  164. } else if (materialMatchResult === 'partial' && !profileMatches) {
  165. mismatchType = 'partial_profile';
  166. } else if (materialMatchResult === 'none') {
  167. mismatchType = 'material';
  168. } else if (materialMatchResult === 'partial') {
  169. mismatchType = 'partial';
  170. }
  171. setPendingAssignId(selectedSpoolId);
  172. setMismatchDetails({
  173. type: mismatchType,
  174. spoolMaterial: selectedSpool.material || '',
  175. trayMaterial: trayMaterial || '',
  176. spoolProfile: spoolProfile || undefined,
  177. trayProfile: trayProfile || undefined,
  178. });
  179. setShowMismatchConfirm(true);
  180. return;
  181. }
  182. }
  183. assignMutation.mutate(selectedSpoolId);
  184. };
  185. const handleConfirmMismatch = () => {
  186. if (!pendingAssignId) return;
  187. assignMutation.mutate(pendingAssignId);
  188. setShowMismatchConfirm(false);
  189. setPendingAssignId(null);
  190. };
  191. return (
  192. <>
  193. <div className="fixed inset-0 z-50 flex items-start sm:items-center justify-center p-4 overflow-y-auto">
  194. <div
  195. className="absolute inset-0 bg-black/60 backdrop-blur-sm"
  196. onClick={onClose}
  197. />
  198. <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">
  199. {/* Header */}
  200. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  201. <div className="flex items-center gap-2">
  202. <Package className="w-5 h-5 text-bambu-green" />
  203. <h2 className="text-lg font-semibold text-white">{t('inventory.assignSpool')}</h2>
  204. </div>
  205. <button
  206. onClick={onClose}
  207. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  208. >
  209. <X className="w-5 h-5" />
  210. </button>
  211. </div>
  212. {/* Content */}
  213. <div className="p-4 space-y-4 overflow-y-auto">
  214. {/* Tray info */}
  215. {trayInfo && (
  216. <div className="p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary">
  217. <p className="text-xs text-bambu-gray mb-1">{t('inventory.selectSpool')}:</p>
  218. <div className="flex items-center gap-2">
  219. {trayInfo.color && (
  220. <span
  221. className="w-4 h-4 rounded-full border border-black/20"
  222. style={{ backgroundColor: `#${trayInfo.color}` }}
  223. />
  224. )}
  225. <span className="text-white font-medium">{trayInfo.type || t('ams.emptySlot')}</span>
  226. <span className="text-bambu-gray">({trayInfo.location})</span>
  227. </div>
  228. </div>
  229. )}
  230. {/* Search filter */}
  231. <div className="relative">
  232. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  233. <input
  234. type="text"
  235. value={searchFilter}
  236. onChange={(e) => setSearchFilter(e.target.value)}
  237. placeholder={t('inventory.searchSpools')}
  238. 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"
  239. />
  240. </div>
  241. {/* Spool list */}
  242. <div>
  243. {isLoading ? (
  244. <div className="flex justify-center py-8">
  245. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  246. </div>
  247. ) : filteredSpools && filteredSpools.length > 0 ? (
  248. <div className="max-h-96 overflow-y-auto grid grid-cols-2 sm:grid-cols-3 gap-2">
  249. {filteredSpools.map((spool: InventorySpool) => (
  250. <button
  251. key={spool.id}
  252. onClick={() => setSelectedSpoolId(spool.id)}
  253. title={spool.note || undefined}
  254. className={`p-2.5 rounded-lg border text-left transition-colors ${
  255. selectedSpoolId === spool.id
  256. ? 'bg-bambu-green/20 border-bambu-green'
  257. : 'bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray'
  258. }`}
  259. >
  260. <p className="text-white text-sm font-medium truncate">
  261. {spool.brand ? `${spool.brand} ` : ''}{spool.material}{spool.subtype ? ` ${spool.subtype}` : ''}
  262. </p>
  263. <div className="flex items-center gap-1.5 mt-1">
  264. {spool.rgba && (
  265. <span
  266. className="w-3 h-3 rounded-full border border-black/20 flex-shrink-0"
  267. style={{ backgroundColor: `#${spool.rgba.substring(0, 6)}` }}
  268. />
  269. )}
  270. <span className="text-xs text-bambu-gray truncate">{spool.color_name || ''}</span>
  271. </div>
  272. {spool.label_weight && (
  273. <p className="text-xs text-bambu-gray mt-1">
  274. {Math.max(0, Math.round(spool.label_weight - spool.weight_used))} / {spool.label_weight}g
  275. </p>
  276. )}
  277. </button>
  278. ))}
  279. </div>
  280. ) : manualSpools && manualSpools.length === 0 ? (
  281. <div className="text-center py-8 text-bambu-gray">
  282. <p>{t('inventory.noManualSpools')}</p>
  283. </div>
  284. ) : (
  285. <div className="text-center py-8 text-bambu-gray">
  286. <p>{t('inventory.noSpoolsMatch')}</p>
  287. </div>
  288. )}
  289. </div>
  290. </div>
  291. {/* Footer with filtering toggle */}
  292. <div className="flex justify-between items-center p-4 border-t border-bambu-dark-tertiary">
  293. <div className="flex items-center gap-2">
  294. <input
  295. id="disable-filtering-toggle"
  296. type="checkbox"
  297. checked={disableFiltering}
  298. onChange={() => setDisableFiltering(v => !v)}
  299. className="accent-bambu-green w-4 h-4 rounded focus:ring-0 border-bambu-dark-tertiary"
  300. />
  301. <label htmlFor="disable-filtering-toggle" className="text-xs text-bambu-gray select-none cursor-pointer">
  302. {t('inventory.showAllSpools')}
  303. </label>
  304. </div>
  305. <div className="flex gap-2">
  306. <Button variant="secondary" onClick={onClose}>
  307. {t('common.cancel')}
  308. </Button>
  309. <Button
  310. onClick={handleAssign}
  311. disabled={!selectedSpoolId || assignMutation.isPending}
  312. >
  313. {assignMutation.isPending ? (
  314. <>
  315. <Loader2 className="w-4 h-4 animate-spin" />
  316. {t('inventory.assigning')}
  317. </>
  318. ) : (
  319. <>
  320. <Package className="w-4 h-4" />
  321. {t('inventory.assignSpool')}
  322. </>
  323. )}
  324. </Button>
  325. </div>
  326. </div>
  327. {assignMutation.isError && (
  328. <div className="mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400">
  329. {(assignMutation.error as Error).message}
  330. </div>
  331. )}
  332. </div>
  333. </div>
  334. {showMismatchConfirm && trayInfo && selectedSpoolId && mismatchDetails && (() => {
  335. let message = '';
  336. if (mismatchDetails.type === 'material') {
  337. message = t('inventory.assignMismatchMessage', {
  338. spoolMaterial: mismatchDetails.spoolMaterial,
  339. trayMaterial: mismatchDetails.trayMaterial,
  340. location: trayInfo.location,
  341. });
  342. } else if (mismatchDetails.type === 'partial') {
  343. message = t('inventory.assignPartialMismatchMessage', {
  344. spoolMaterial: mismatchDetails.spoolMaterial,
  345. trayMaterial: mismatchDetails.trayMaterial,
  346. location: trayInfo.location,
  347. });
  348. } else if (mismatchDetails.type === 'material_profile') {
  349. message = `${t('inventory.assignMismatchMessage', {
  350. spoolMaterial: mismatchDetails.spoolMaterial,
  351. trayMaterial: mismatchDetails.trayMaterial,
  352. location: trayInfo.location,
  353. })}\n\n${t('inventory.assignProfileMismatchMessage', {
  354. spoolProfile: mismatchDetails.spoolProfile || t('common.unknown'),
  355. trayProfile: mismatchDetails.trayProfile || t('common.unknown'),
  356. location: trayInfo.location,
  357. })}`;
  358. } else if (mismatchDetails.type === 'partial_profile') {
  359. message = `${t('inventory.assignPartialMismatchMessage', {
  360. spoolMaterial: mismatchDetails.spoolMaterial,
  361. trayMaterial: mismatchDetails.trayMaterial,
  362. location: trayInfo.location,
  363. })}\n\n${t('inventory.assignProfileMismatchMessage', {
  364. spoolProfile: mismatchDetails.spoolProfile || t('common.unknown'),
  365. trayProfile: mismatchDetails.trayProfile || t('common.unknown'),
  366. location: trayInfo.location,
  367. })}`;
  368. } else if (mismatchDetails.type === 'profile') {
  369. message = t('inventory.assignProfileMismatchMessage', {
  370. spoolProfile: mismatchDetails.spoolProfile || t('common.unknown'),
  371. trayProfile: mismatchDetails.trayProfile || t('common.unknown'),
  372. location: trayInfo.location,
  373. });
  374. }
  375. return (
  376. <ConfirmModal
  377. title={t('inventory.assignMismatchTitle')}
  378. message={message}
  379. confirmText={t('inventory.assignMismatchConfirm')}
  380. variant="warning"
  381. isLoading={assignMutation.isPending}
  382. onConfirm={handleConfirmMismatch}
  383. onCancel={() => {
  384. if (!assignMutation.isPending) {
  385. setShowMismatchConfirm(false);
  386. setPendingAssignId(null);
  387. setMismatchDetails(null);
  388. }
  389. }}
  390. />
  391. );
  392. })()}
  393. </>
  394. );
  395. }