FilamentMapping.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import { useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useQuery, useQueryClient } from '@tanstack/react-query';
  4. import { Circle, Check, AlertTriangle, RefreshCw, ChevronDown, ChevronUp, Palette } from 'lucide-react';
  5. import { api } from '../../api/client';
  6. import { useFilamentMapping } from '../../hooks/useFilamentMapping';
  7. import { getGlobalTrayId } from '../../utils/amsHelpers';
  8. import { getColorName } from '../../utils/colors';
  9. import { useFilamentLabels } from './useFilamentLabels';
  10. import type { FilamentMappingProps } from './types';
  11. /**
  12. * Filament mapping UI for comparing required filaments with loaded AMS slots.
  13. * Shows auto-matched and manually overridden slot assignments.
  14. */
  15. export function FilamentMapping({
  16. printerId,
  17. filamentReqs,
  18. manualMappings,
  19. onManualMappingChange,
  20. currencySymbol,
  21. defaultCostPerKg,
  22. defaultExpanded = false,
  23. forceColorMatch,
  24. onForceColorMatchChange,
  25. }: FilamentMappingProps & { defaultExpanded?: boolean }) {
  26. const { t } = useTranslation();
  27. const queryClient = useQueryClient();
  28. const [isRefreshing, setIsRefreshing] = useState(false);
  29. const [isExpanded, setIsExpanded] = useState(defaultExpanded);
  30. // Fetch printer status
  31. const { data: printerStatus } = useQuery({
  32. queryKey: ['printer-status', printerId],
  33. queryFn: () => api.getPrinterStatus(printerId),
  34. enabled: !!printerId,
  35. });
  36. const { data: assignments } = useQuery({
  37. queryKey: ['spool-assignments', printerId],
  38. queryFn: () => api.getAssignments(printerId),
  39. enabled: !!printerId,
  40. });
  41. const { loadedFilaments, filamentComparison, hasTypeMismatch, hasColorMismatch } =
  42. useFilamentMapping(filamentReqs, printerStatus, manualMappings);
  43. // Per-slot sub-brand + material-disambiguated colour labels (#1718). Same
  44. // shared hook the model-mode FilamentOverride uses so both panels render
  45. // the same sliced-3MF identity. Falls back to the raw type / generic
  46. // colour bucket when the SKU is unknown or the by-material lookup hasn't
  47. // resolved — never blanks out the required row.
  48. const filamentLabels = useFilamentLabels(filamentReqs?.filaments);
  49. const trayCostMap = useMemo(() => {
  50. const map = new Map<number, number | null>();
  51. for (const assignment of assignments || []) {
  52. const isExternal = assignment.ams_id === 255;
  53. const globalTrayId = getGlobalTrayId(assignment.ams_id, assignment.tray_id, isExternal);
  54. map.set(globalTrayId, assignment.spool?.cost_per_kg ?? null);
  55. }
  56. return map;
  57. }, [assignments]);
  58. const trayRemainingWeightMap = useMemo(() => {
  59. const map = new Map<number, number | null>();
  60. for (const assignment of assignments || []) {
  61. const isExternal = assignment.ams_id === 255;
  62. const globalTrayId = getGlobalTrayId(assignment.ams_id, assignment.tray_id, isExternal);
  63. const spool = assignment.spool;
  64. if (!spool) {
  65. map.set(globalTrayId, null);
  66. continue;
  67. }
  68. map.set(globalTrayId, Math.max(0, Math.round((spool.label_weight ?? 0) - (spool.weight_used ?? 0))));
  69. }
  70. return map;
  71. }, [assignments]);
  72. const totalCost = useMemo(() => {
  73. let total = 0;
  74. for (const item of filamentComparison) {
  75. const trayId = item.loaded?.globalTrayId;
  76. if (trayId == null) continue;
  77. const assignedCost = trayCostMap.get(trayId) ?? null;
  78. const costPerKg = assignedCost ?? defaultCostPerKg;
  79. if (costPerKg > 0) {
  80. total += (item.used_grams / 1000) * costPerKg;
  81. }
  82. }
  83. return total;
  84. }, [filamentComparison, trayCostMap, defaultCostPerKg]);
  85. const hasAnyCost = useMemo(
  86. () => Array.from(trayCostMap.values()).some((v) => v != null && v > 0),
  87. [trayCostMap]
  88. );
  89. const hasFilamentReqs = filamentReqs?.filaments && filamentReqs.filaments.length > 0;
  90. const isDualNozzle = filamentReqs?.filaments?.some((f) => f.nozzle_id != null) ?? false;
  91. // Filament Track Switch: when installed, AMS-to-extruder mapping is dynamic
  92. // (any slot can be routed to either extruder), so the per-nozzle dropdown
  93. // filter is suppressed. fila_switch.in_slots[track] = currently fed slot,
  94. // fila_switch.out_extruders[track] = extruder that track terminates at. See #1162.
  95. const ftsInstalled = printerStatus?.fila_switch?.installed === true;
  96. const ftsExtruderForSlot = (globalTrayId: number): number | null => {
  97. const fs = printerStatus?.fila_switch;
  98. if (!fs?.installed) return null;
  99. const track = fs.in_slots.indexOf(globalTrayId);
  100. if (track < 0) return null;
  101. return fs.out_extruders[track] ?? null;
  102. };
  103. // Don't render if no filament requirements
  104. if (!hasFilamentReqs) {
  105. return null;
  106. }
  107. // Don't render until we have printer status to do the comparison
  108. if (!printerStatus) {
  109. return null;
  110. }
  111. // Determine status indicator color
  112. const statusColor = hasTypeMismatch
  113. ? '#f97316' // orange
  114. : hasColorMismatch
  115. ? '#facc15' // yellow
  116. : '#00ae42'; // green
  117. const handleSlotChange = (slotId: number, value: string) => {
  118. if (slotId > 0) {
  119. if (value === '') {
  120. // Clear manual override
  121. const next = { ...manualMappings };
  122. delete next[slotId];
  123. onManualMappingChange(next);
  124. } else {
  125. onManualMappingChange({
  126. ...manualMappings,
  127. [slotId]: parseInt(value, 10),
  128. });
  129. }
  130. }
  131. };
  132. const handleRefresh = async () => {
  133. setIsRefreshing(true);
  134. try {
  135. // Request fresh data from printer via MQTT pushall command
  136. await api.refreshPrinterStatus(printerId);
  137. // Wait a moment for printer to respond, then refetch
  138. await new Promise((r) => setTimeout(r, 500));
  139. await queryClient.refetchQueries({ queryKey: ['printer-status', printerId] });
  140. } finally {
  141. setIsRefreshing(false);
  142. }
  143. };
  144. return (
  145. <div className="mb-4">
  146. <button
  147. type="button"
  148. onClick={() => setIsExpanded(!isExpanded)}
  149. className="flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full"
  150. >
  151. <Circle className="w-4 h-4" fill={statusColor} stroke="none" />
  152. <span>{t('printModal.filamentMapping')}</span>
  153. {hasTypeMismatch ? (
  154. <span className="text-xs text-orange-400">(Type not found)</span>
  155. ) : hasColorMismatch ? (
  156. <span className="text-xs text-yellow-400">(Color mismatch)</span>
  157. ) : (
  158. <span className="text-xs text-bambu-green">(Ready)</span>
  159. )}
  160. {isExpanded ? (
  161. <ChevronUp className="w-4 h-4 ml-auto" />
  162. ) : (
  163. <ChevronDown className="w-4 h-4 ml-auto" />
  164. )}
  165. </button>
  166. {isExpanded && (
  167. <div className="mt-2 bg-bambu-dark rounded-lg p-3 space-y-2">
  168. <div className="flex items-center justify-between mb-2">
  169. <span className="text-xs text-bambu-gray">Click to change slot assignment</span>
  170. <button
  171. type="button"
  172. onClick={handleRefresh}
  173. className="flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white"
  174. disabled={isRefreshing}
  175. >
  176. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  177. <span>Re-read</span>
  178. </button>
  179. </div>
  180. {filamentComparison.map((item, idx) => {
  181. // #1717: surface the same per-slot force-color-match checkbox here
  182. // that FilamentOverride exposes for model-mode dispatch. The
  183. // scheduler honors the flag in both modes; only the UI was missing.
  184. const slotId = item.slot_id ?? 0;
  185. const canForceMatch = slotId > 0 && onForceColorMatchChange != null;
  186. // #1718: same sub-brand + colour resolution as FilamentOverride.
  187. // Indexing is safe because ``useFilamentLabels`` mirrors the input
  188. // array shape; defensive fallback covers the empty-reqs render
  189. // path that shouldn't reach here anyway.
  190. const { resolvedName, colorLabel } = filamentLabels[idx] ?? { resolvedName: item.type, colorLabel: getColorName(item.color) };
  191. return (
  192. <div key={idx} className="space-y-1">
  193. <div
  194. className="grid items-center gap-2 text-xs"
  195. style={{ gridTemplateColumns: '16px minmax(70px, 1fr) auto 2fr 16px' }}
  196. >
  197. {/* Required color */}
  198. <span title={`Required: ${resolvedName} - ${colorLabel}`}>
  199. <Circle className="w-3 h-3" fill={item.color} stroke={item.color} />
  200. </span>
  201. {/* Required type + grams + nozzle badge */}
  202. <span className="text-white truncate flex items-center gap-1">
  203. {isDualNozzle && item.nozzle_id != null && (
  204. <span
  205. className="inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0"
  206. title={item.nozzle_id === 1 ? t('printModal.leftNozzleTooltip') : t('printModal.rightNozzleTooltip')}
  207. >
  208. {item.nozzle_id === 1 ? t('printModal.leftNozzle') : t('printModal.rightNozzle')}
  209. </span>
  210. )}
  211. {resolvedName} <span className="text-bambu-gray">({item.used_grams}g)</span>
  212. </span>
  213. {/* Arrow */}
  214. <span className="text-bambu-gray">→</span>
  215. {/* Slot selector dropdown */}
  216. <select
  217. value={item.loaded?.globalTrayId ?? ''}
  218. onChange={(e) => handleSlotChange(slotId, e.target.value)}
  219. className={`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${
  220. item.status === 'match'
  221. ? 'border-bambu-green/50 text-bambu-green'
  222. : item.status === 'type_only'
  223. ? 'border-yellow-400/50 text-yellow-400'
  224. : 'border-orange-400/50 text-orange-400'
  225. } ${item.isManual ? 'ring-1 ring-blue-400/50' : ''}`}
  226. title={item.isManual ? 'Manually selected' : 'Auto-matched'}
  227. >
  228. <option value="" className="bg-bambu-dark text-bambu-gray">
  229. -- Select slot --
  230. </option>
  231. {loadedFilaments
  232. .filter(
  233. (f) =>
  234. item.nozzle_id == null ||
  235. ftsInstalled ||
  236. f.extruderId === item.nozzle_id,
  237. )
  238. .map((f) => {
  239. const remainingWeight = trayRemainingWeightMap.get(f.globalTrayId);
  240. const remainingLabel = remainingWeight != null
  241. ? t('printModal.slotRemainingShort', {
  242. grams: remainingWeight,
  243. defaultValue: ` - ${remainingWeight}g left`,
  244. })
  245. : '';
  246. // FTS routing badge: if this slot is currently fed into an FTS
  247. // track, show the destination extruder. Idle (not-loaded) slots
  248. // get no badge — they can be routed to either extruder on demand.
  249. const ftsTargetExtruder = ftsInstalled
  250. ? ftsExtruderForSlot(f.globalTrayId)
  251. : null;
  252. const ftsBadge =
  253. ftsTargetExtruder == null
  254. ? ''
  255. : ` [${ftsTargetExtruder === 1 ? t('printModal.leftNozzle') : t('printModal.rightNozzle')}]`;
  256. return (
  257. <option key={f.globalTrayId} value={f.globalTrayId} className="bg-bambu-dark text-white">
  258. {f.label}: {f.traySubBrands || f.type} ({f.colorName}){remainingLabel}{ftsBadge}
  259. </option>
  260. );
  261. })}
  262. </select>
  263. {/* Status icon */}
  264. {item.status === 'match' ? (
  265. <Check className="w-3 h-3 text-bambu-green" />
  266. ) : item.status === 'type_only' ? (
  267. <span title="Same type, different color">
  268. <AlertTriangle className="w-3 h-3 text-yellow-400" />
  269. </span>
  270. ) : (
  271. <span title="Filament type not loaded">
  272. <AlertTriangle className="w-3 h-3 text-orange-400" />
  273. </span>
  274. )}
  275. </div>
  276. {/* Force Color Match checkbox — matches FilamentOverride's layout. */}
  277. {canForceMatch && (
  278. <label className="inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5">
  279. <input
  280. type="checkbox"
  281. checked={forceColorMatch?.[slotId] ?? false}
  282. onChange={(e) => onForceColorMatchChange(slotId, e.target.checked)}
  283. className="accent-bambu-green w-3 h-3"
  284. />
  285. <Palette className="w-3 h-3" />
  286. {t('printModal.forceColorMatch')}
  287. </label>
  288. )}
  289. </div>
  290. );
  291. })}
  292. <div className="text-xs text-bambu-gray">
  293. {t('printModal.totalCost')}{' '}
  294. <span className="text-white">
  295. {totalCost > 0 || hasAnyCost ? `${currencySymbol}${totalCost.toFixed(2)}` : 'N/A'}
  296. </span>
  297. </div>
  298. {hasTypeMismatch && (
  299. <p className="text-xs text-orange-400 mt-2">Required filament type not found in printer.</p>
  300. )}
  301. </div>
  302. )}
  303. </div>
  304. );
  305. }