FilamentMapping.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import { useEffect, 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, effectivePreferLowest } 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. onEstimatedCostChange,
  21. budgetAvailable,
  22. quantity = 1,
  23. currencySymbol,
  24. defaultCostPerKg,
  25. defaultExpanded = false,
  26. forceColorMatch,
  27. onForceColorMatchChange,
  28. }: FilamentMappingProps & { defaultExpanded?: boolean }) {
  29. const { t } = useTranslation();
  30. const queryClient = useQueryClient();
  31. const [isRefreshing, setIsRefreshing] = useState(false);
  32. const [isExpanded, setIsExpanded] = useState(defaultExpanded);
  33. // Fetch printer status
  34. const { data: printerStatus } = useQuery({
  35. queryKey: ['printer-status', printerId],
  36. queryFn: () => api.getPrinterStatus(printerId),
  37. enabled: !!printerId,
  38. });
  39. const { data: assignments } = useQuery({
  40. queryKey: ['spool-assignments', printerId],
  41. queryFn: () => api.getAssignments(printerId),
  42. enabled: !!printerId,
  43. });
  44. // Settings + inventory map drive the same prefer-lowest + AMS-backup gate
  45. // the dispatcher uses (#1766). Without this, the per-slot dropdown's
  46. // auto-suggestion could disagree with what actually gets dispatched.
  47. const { data: settings } = useQuery({
  48. queryKey: ['settings'],
  49. queryFn: api.getSettings,
  50. });
  51. const { data: inventoryRemain } = useQuery({
  52. queryKey: ['printer-inventory-remain', printerId],
  53. queryFn: () => api.getInventoryRemain(printerId),
  54. enabled: !!printerId,
  55. staleTime: 30 * 1000,
  56. });
  57. const inventoryByTrayId = useMemo(() => {
  58. if (!inventoryRemain?.inventory_remain_g) return undefined;
  59. const map = new Map<number, number>();
  60. Object.entries(inventoryRemain.inventory_remain_g).forEach(([key, grams]) => {
  61. const gtid = Number(key);
  62. if (!Number.isNaN(gtid)) map.set(gtid, grams);
  63. });
  64. return map;
  65. }, [inventoryRemain]);
  66. const gatedPreferLowest = effectivePreferLowest(
  67. settings?.prefer_lowest_filament,
  68. printerStatus?.ams_filament_backup,
  69. );
  70. const { loadedFilaments, filamentComparison, hasTypeMismatch, hasColorMismatch } =
  71. useFilamentMapping(filamentReqs, printerStatus, manualMappings, gatedPreferLowest, inventoryByTrayId);
  72. // Per-slot sub-brand + material-disambiguated colour labels (#1718). Same
  73. // shared hook the model-mode FilamentOverride uses so both panels render
  74. // the same sliced-3MF identity. Falls back to the raw type / generic
  75. // colour bucket when the SKU is unknown or the by-material lookup hasn't
  76. // resolved — never blanks out the required row.
  77. const filamentLabels = useFilamentLabels(filamentReqs?.filaments);
  78. const trayCostMap = useMemo(() => {
  79. const map = new Map<number, number | null>();
  80. for (const assignment of assignments || []) {
  81. const isExternal = assignment.ams_id === 255;
  82. const globalTrayId = getGlobalTrayId(assignment.ams_id, assignment.tray_id, isExternal);
  83. map.set(globalTrayId, assignment.spool?.cost_per_kg ?? null);
  84. }
  85. return map;
  86. }, [assignments]);
  87. const trayRemainingWeightMap = useMemo(() => {
  88. const map = new Map<number, number | null>();
  89. for (const assignment of assignments || []) {
  90. const isExternal = assignment.ams_id === 255;
  91. const globalTrayId = getGlobalTrayId(assignment.ams_id, assignment.tray_id, isExternal);
  92. const spool = assignment.spool;
  93. if (!spool) {
  94. map.set(globalTrayId, null);
  95. continue;
  96. }
  97. map.set(globalTrayId, Math.max(0, Math.round((spool.label_weight ?? 0) - (spool.weight_used ?? 0))));
  98. }
  99. return map;
  100. }, [assignments]);
  101. const totalCost = useMemo(() => {
  102. let total = 0;
  103. for (const item of filamentComparison) {
  104. const trayId = item.loaded?.globalTrayId;
  105. if (trayId == null) continue;
  106. const assignedCost = trayCostMap.get(trayId) ?? null;
  107. const costPerKg = assignedCost ?? defaultCostPerKg;
  108. if (costPerKg > 0) {
  109. total += (item.used_grams / 1000) * costPerKg;
  110. }
  111. }
  112. return total;
  113. }, [filamentComparison, trayCostMap, defaultCostPerKg]);
  114. useEffect(() => {
  115. onEstimatedCostChange?.(totalCost > 0 ? totalCost : null);
  116. }, [onEstimatedCostChange, totalCost]);
  117. const hasAnyCost = useMemo(
  118. () => Array.from(trayCostMap.values()).some((v) => v != null && v > 0),
  119. [trayCostMap]
  120. );
  121. const budgetCheckCost = totalCost * Math.max(1, quantity);
  122. const isBudgetInsufficient = budgetAvailable != null && budgetCheckCost > budgetAvailable;
  123. const hasFilamentReqs = filamentReqs?.filaments && filamentReqs.filaments.length > 0;
  124. const isDualNozzle = filamentReqs?.filaments?.some((f) => f.nozzle_id != null) ?? false;
  125. // Filament Track Switch: when installed, AMS-to-extruder mapping is dynamic
  126. // (any slot can be routed to either extruder), so the per-nozzle dropdown
  127. // filter is suppressed. fila_switch.in_slots[track] = currently fed slot,
  128. // fila_switch.out_extruders[track] = extruder that track terminates at. See #1162.
  129. const ftsInstalled = printerStatus?.fila_switch?.installed === true;
  130. const ftsExtruderForSlot = (globalTrayId: number): number | null => {
  131. const fs = printerStatus?.fila_switch;
  132. if (!fs?.installed) return null;
  133. const track = fs.in_slots.indexOf(globalTrayId);
  134. if (track < 0) return null;
  135. return fs.out_extruders[track] ?? null;
  136. };
  137. // Don't render if no filament requirements
  138. if (!hasFilamentReqs) {
  139. return null;
  140. }
  141. // Don't render until we have printer status to do the comparison
  142. if (!printerStatus) {
  143. return null;
  144. }
  145. // Determine status indicator color
  146. const statusColor = hasTypeMismatch
  147. ? '#f97316' // orange
  148. : hasColorMismatch
  149. ? '#facc15' // yellow
  150. : '#00ae42'; // green
  151. const handleSlotChange = (slotId: number, value: string) => {
  152. if (slotId > 0) {
  153. if (value === '') {
  154. // Clear manual override
  155. const next = { ...manualMappings };
  156. delete next[slotId];
  157. onManualMappingChange(next);
  158. } else {
  159. onManualMappingChange({
  160. ...manualMappings,
  161. [slotId]: parseInt(value, 10),
  162. });
  163. }
  164. }
  165. };
  166. const handleRefresh = async () => {
  167. setIsRefreshing(true);
  168. try {
  169. // Request fresh data from printer via MQTT pushall command
  170. await api.refreshPrinterStatus(printerId);
  171. // Wait a moment for printer to respond, then refetch
  172. await new Promise((r) => setTimeout(r, 500));
  173. await queryClient.refetchQueries({ queryKey: ['printer-status', printerId] });
  174. } finally {
  175. setIsRefreshing(false);
  176. }
  177. };
  178. return (
  179. <div className="mb-4">
  180. <button
  181. type="button"
  182. onClick={() => setIsExpanded(!isExpanded)}
  183. className="flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full"
  184. >
  185. <Circle className="w-4 h-4" fill={statusColor} stroke="none" />
  186. <span>{t('printModal.filamentMapping')}</span>
  187. {hasTypeMismatch ? (
  188. <span className="text-xs text-orange-400">(Type not found)</span>
  189. ) : hasColorMismatch ? (
  190. <span className="text-xs text-yellow-400">(Color mismatch)</span>
  191. ) : (
  192. <span className="text-xs text-bambu-green">(Ready)</span>
  193. )}
  194. {isExpanded ? (
  195. <ChevronUp className="w-4 h-4 ml-auto" />
  196. ) : (
  197. <ChevronDown className="w-4 h-4 ml-auto" />
  198. )}
  199. </button>
  200. {isExpanded && (
  201. <div className="mt-2 bg-bambu-dark rounded-lg p-3 space-y-2">
  202. <div className="flex items-center justify-between mb-2">
  203. <span className="text-xs text-bambu-gray">Click to change slot assignment</span>
  204. <button
  205. type="button"
  206. onClick={handleRefresh}
  207. 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"
  208. disabled={isRefreshing}
  209. >
  210. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  211. <span>Re-read</span>
  212. </button>
  213. </div>
  214. {filamentComparison.map((item, idx) => {
  215. // #1717: surface the same per-slot force-color-match checkbox here
  216. // that FilamentOverride exposes for model-mode dispatch. The
  217. // scheduler honors the flag in both modes; only the UI was missing.
  218. const slotId = item.slot_id ?? 0;
  219. const canForceMatch = slotId > 0 && onForceColorMatchChange != null;
  220. // #1718: same sub-brand + colour resolution as FilamentOverride.
  221. // Indexing is safe because ``useFilamentLabels`` mirrors the input
  222. // array shape; defensive fallback covers the empty-reqs render
  223. // path that shouldn't reach here anyway.
  224. const { resolvedName, colorLabel } = filamentLabels[idx] ?? { resolvedName: item.type, colorLabel: getColorName(item.color) };
  225. return (
  226. <div key={idx} className="space-y-1">
  227. <div
  228. className="grid items-center gap-2 text-xs"
  229. style={{ gridTemplateColumns: '16px minmax(70px, 1fr) auto 2fr 16px' }}
  230. >
  231. {/* Required color */}
  232. <span title={`Required: ${resolvedName} - ${colorLabel}`}>
  233. <Circle className="w-3 h-3" fill={item.color} stroke={item.color} />
  234. </span>
  235. {/* Required type + grams + nozzle badge */}
  236. <span className="text-white truncate flex items-center gap-1">
  237. {isDualNozzle && item.nozzle_id != null && (
  238. <span
  239. 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"
  240. title={item.nozzle_id === 1 ? t('printModal.leftNozzleTooltip') : t('printModal.rightNozzleTooltip')}
  241. >
  242. {item.nozzle_id === 1 ? t('printModal.leftNozzle') : t('printModal.rightNozzle')}
  243. </span>
  244. )}
  245. {resolvedName} <span className="text-bambu-gray">({item.used_grams}g)</span>
  246. </span>
  247. {/* Arrow */}
  248. <span className="text-bambu-gray">→</span>
  249. {/* Slot selector dropdown */}
  250. <select
  251. value={item.loaded?.globalTrayId ?? ''}
  252. onChange={(e) => handleSlotChange(slotId, e.target.value)}
  253. 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 ${
  254. item.status === 'match'
  255. ? 'border-bambu-green/50 text-bambu-green'
  256. : item.status === 'type_only'
  257. ? 'border-yellow-400/50 text-yellow-400'
  258. : 'border-orange-400/50 text-orange-400'
  259. } ${item.isManual ? 'ring-1 ring-blue-400/50' : ''}`}
  260. title={item.isManual ? 'Manually selected' : 'Auto-matched'}
  261. >
  262. <option value="" className="bg-bambu-dark text-bambu-gray">
  263. -- Select slot --
  264. </option>
  265. {/*
  266. #1722: every loaded slot is offered for every filament row,
  267. regardless of which extruder the slot is wired to. Before this
  268. change a slot was only listed when its extruder matched the
  269. filament's slicer-assigned nozzle (item.nozzle_id), which
  270. locked users out of cross-extruder picks even when they'd
  271. intentionally loaded the required filament into the "other"
  272. AMS. The L/R badge on the filament row still tells the user
  273. what the slicer planned; the dropdown now trusts the user to
  274. pick based on their physical setup. Printer firmware accepts
  275. or rejects the ams_mapping at start-print — failure is loud,
  276. not silent.
  277. */}
  278. {loadedFilaments.map((f) => {
  279. const remainingWeight = trayRemainingWeightMap.get(f.globalTrayId);
  280. const remainingLabel = remainingWeight != null
  281. ? t('printModal.slotRemainingShort', {
  282. grams: remainingWeight,
  283. defaultValue: ` - ${remainingWeight}g left`,
  284. })
  285. : '';
  286. // FTS routing badge: if this slot is currently fed into an FTS
  287. // track, show the destination extruder. Idle (not-loaded) slots
  288. // get no badge — they can be routed to either extruder on demand.
  289. const ftsTargetExtruder = ftsInstalled
  290. ? ftsExtruderForSlot(f.globalTrayId)
  291. : null;
  292. const ftsBadge =
  293. ftsTargetExtruder == null
  294. ? ''
  295. : ` [${ftsTargetExtruder === 1 ? t('printModal.leftNozzle') : t('printModal.rightNozzle')}]`;
  296. return (
  297. <option key={f.globalTrayId} value={f.globalTrayId} className="bg-bambu-dark text-white">
  298. {f.label}: {f.traySubBrands || f.type} ({f.colorName}){remainingLabel}{ftsBadge}
  299. </option>
  300. );
  301. })}
  302. </select>
  303. {/* Status icon */}
  304. {item.status === 'match' ? (
  305. <Check className="w-3 h-3 text-bambu-green" />
  306. ) : item.status === 'type_only' ? (
  307. <span title="Same type, different color">
  308. <AlertTriangle className="w-3 h-3 text-yellow-400" />
  309. </span>
  310. ) : (
  311. <span title="Filament type not loaded">
  312. <AlertTriangle className="w-3 h-3 text-orange-400" />
  313. </span>
  314. )}
  315. </div>
  316. {/* Force Color Match checkbox — matches FilamentOverride's layout. */}
  317. {canForceMatch && (
  318. <label className="inline-flex items-center gap-1.5 text-xs text-bambu-gray cursor-pointer select-none pl-5">
  319. <input
  320. type="checkbox"
  321. checked={forceColorMatch?.[slotId] ?? false}
  322. onChange={(e) => onForceColorMatchChange(slotId, e.target.checked)}
  323. className="accent-bambu-green w-3 h-3"
  324. />
  325. <Palette className="w-3 h-3" />
  326. {t('printModal.forceColorMatch')}
  327. </label>
  328. )}
  329. </div>
  330. );
  331. })}
  332. <div className="text-xs text-bambu-gray">
  333. {t('printModal.totalCost')}{' '}
  334. <span className="text-white">
  335. {totalCost > 0 || hasAnyCost ? `${currencySymbol}${totalCost.toFixed(2)}` : 'N/A'}
  336. </span>
  337. {quantity > 1 && totalCost > 0 && (
  338. <span className="ml-2">
  339. {t('printModal.totalCostForQuantity', 'total: {{cost}}', {
  340. cost: `${currencySymbol}${budgetCheckCost.toFixed(2)}`,
  341. })}
  342. </span>
  343. )}
  344. </div>
  345. {isBudgetInsufficient && (
  346. <p className="text-xs text-red-400 mt-2">
  347. {t('printModal.insufficientBudget', 'Insufficient budget for this cost center.')}
  348. </p>
  349. )}
  350. {hasTypeMismatch && (
  351. <p className="text-xs text-orange-400 mt-2">Required filament type not found in printer.</p>
  352. )}
  353. </div>
  354. )}
  355. </div>
  356. );
  357. }