AssignSpoolModal.tsx 15 KB

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