FilamentMapping.tsx 17 KB

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