useMultiPrinterFilamentMapping.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import { useMemo } from 'react';
  2. import { useQueries } from '@tanstack/react-query';
  3. import { api } from '../api/client';
  4. import type { PrinterStatus, Printer } from '../api/client';
  5. import {
  6. buildLoadedFilaments,
  7. computeAmsMapping,
  8. type LoadedFilament,
  9. type FilamentRequirement,
  10. } from './useFilamentMapping';
  11. import {
  12. normalizeColorForCompare,
  13. colorsAreSimilar,
  14. } from '../utils/amsHelpers';
  15. /**
  16. * Match status for a single printer's filament configuration.
  17. */
  18. export type PrinterMatchStatus = 'full' | 'partial' | 'missing';
  19. /**
  20. * Per-printer configuration for AMS mapping.
  21. */
  22. export interface PerPrinterConfig {
  23. /** Whether this printer uses the default mapping or has custom config */
  24. useDefault: boolean;
  25. /** Manual slot overrides for this printer (slot_id -> globalTrayId) */
  26. manualMappings: Record<number, number>;
  27. /** Whether this mapping was auto-configured */
  28. autoConfigured: boolean;
  29. }
  30. /**
  31. * Result of filament mapping for a single printer.
  32. */
  33. export interface PrinterMappingResult {
  34. printerId: number;
  35. printerName: string;
  36. /** Printer status data */
  37. status: PrinterStatus | undefined;
  38. /** Whether status is still loading */
  39. isLoading: boolean;
  40. /** List of loaded filaments in this printer */
  41. loadedFilaments: LoadedFilament[];
  42. /** Auto-computed AMS mapping for this printer */
  43. autoMapping: number[] | undefined;
  44. /** Final AMS mapping (considering manual overrides) */
  45. finalMapping: number[] | undefined;
  46. /** Match status: full (all exact), partial (some mismatches), missing (type not found) */
  47. matchStatus: PrinterMatchStatus;
  48. /** Number of slots with exact match (type + color) */
  49. exactMatches: number;
  50. /** Number of slots with type-only match */
  51. typeOnlyMatches: number;
  52. /** Number of slots with missing type */
  53. missingTypes: number;
  54. /** Total required slots */
  55. totalSlots: number;
  56. /** Per-printer config */
  57. config: PerPrinterConfig;
  58. }
  59. /**
  60. * Result of the useMultiPrinterFilamentMapping hook.
  61. */
  62. export interface UseMultiPrinterFilamentMappingResult {
  63. /** Results for each selected printer */
  64. printerResults: PrinterMappingResult[];
  65. /** Whether any printer data is still loading */
  66. isLoading: boolean;
  67. /** Per-printer configurations */
  68. perPrinterConfigs: Record<number, PerPrinterConfig>;
  69. /** Update config for a specific printer */
  70. updatePrinterConfig: (printerId: number, config: Partial<PerPrinterConfig>) => void;
  71. /** Auto-configure all printers based on their loaded filaments */
  72. autoConfigureAll: () => void;
  73. /** Auto-configure a specific printer */
  74. autoConfigurePrinter: (printerId: number) => void;
  75. /** Get final mapping for a specific printer (for submission) */
  76. getFinalMapping: (printerId: number) => number[] | undefined;
  77. /** Check if all printers have acceptable mappings */
  78. allPrintersReady: boolean;
  79. }
  80. /**
  81. * Compute match details for a printer given filament requirements and loaded filaments.
  82. */
  83. function computeMatchDetails(
  84. filamentReqs: FilamentRequirement[] | undefined,
  85. loadedFilaments: LoadedFilament[],
  86. manualMappings: Record<number, number>
  87. ): { exactMatches: number; typeOnlyMatches: number; missingTypes: number; totalSlots: number; status: PrinterMatchStatus } {
  88. if (!filamentReqs || filamentReqs.length === 0) {
  89. return { exactMatches: 0, typeOnlyMatches: 0, missingTypes: 0, totalSlots: 0, status: 'full' };
  90. }
  91. let exactMatches = 0;
  92. let typeOnlyMatches = 0;
  93. let missingTypes = 0;
  94. const usedTrayIds = new Set<number>(Object.values(manualMappings));
  95. for (const req of filamentReqs) {
  96. const slotId = req.slot_id || 0;
  97. // Check manual override first
  98. if (slotId > 0 && manualMappings[slotId] !== undefined) {
  99. const manualTrayId = manualMappings[slotId];
  100. const manualLoaded = loadedFilaments.find((f) => f.globalTrayId === manualTrayId);
  101. if (manualLoaded) {
  102. const typeMatch = manualLoaded.type?.toUpperCase() === req.type?.toUpperCase();
  103. const colorMatch =
  104. normalizeColorForCompare(manualLoaded.color) === normalizeColorForCompare(req.color) ||
  105. colorsAreSimilar(manualLoaded.color, req.color);
  106. if (typeMatch && colorMatch) {
  107. exactMatches++;
  108. } else if (typeMatch) {
  109. typeOnlyMatches++;
  110. } else {
  111. missingTypes++;
  112. }
  113. continue;
  114. }
  115. }
  116. // Auto-match with nozzle-aware filtering
  117. let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId));
  118. if (req.nozzle_id != null) {
  119. const nozzleFiltered = candidates.filter((f) => f.extruderId === req.nozzle_id);
  120. if (nozzleFiltered.length > 0) {
  121. candidates = nozzleFiltered;
  122. }
  123. }
  124. const exactMatch = candidates.find(
  125. (f) =>
  126. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  127. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  128. );
  129. const similarMatch = exactMatch
  130. ? undefined
  131. : candidates.find(
  132. (f) =>
  133. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  134. colorsAreSimilar(f.color, req.color)
  135. );
  136. const typeOnlyMatch =
  137. exactMatch || similarMatch
  138. ? undefined
  139. : candidates.find(
  140. (f) => f.type?.toUpperCase() === req.type?.toUpperCase()
  141. );
  142. const loaded = exactMatch ?? similarMatch ?? typeOnlyMatch;
  143. if (loaded) {
  144. usedTrayIds.add(loaded.globalTrayId);
  145. }
  146. if (exactMatch || similarMatch) {
  147. exactMatches++;
  148. } else if (typeOnlyMatch) {
  149. typeOnlyMatches++;
  150. } else {
  151. missingTypes++;
  152. }
  153. }
  154. const totalSlots = filamentReqs.length;
  155. let status: PrinterMatchStatus = 'full';
  156. if (missingTypes > 0) {
  157. status = 'missing';
  158. } else if (typeOnlyMatches > 0) {
  159. status = 'partial';
  160. }
  161. return { exactMatches, typeOnlyMatches, missingTypes, totalSlots, status };
  162. }
  163. /**
  164. * Compute AMS mapping with manual overrides applied.
  165. */
  166. function computeMappingWithOverrides(
  167. filamentReqs: { filaments: FilamentRequirement[] } | undefined,
  168. printerStatus: PrinterStatus | undefined,
  169. manualMappings: Record<number, number>
  170. ): number[] | undefined {
  171. if (!filamentReqs?.filaments || filamentReqs.filaments.length === 0) return undefined;
  172. const loadedFilaments = buildLoadedFilaments(printerStatus);
  173. if (loadedFilaments.length === 0) return undefined;
  174. const usedTrayIds = new Set<number>(Object.values(manualMappings));
  175. const comparisons: { slot_id: number; globalTrayId: number }[] = [];
  176. for (const req of filamentReqs.filaments) {
  177. const slotId = req.slot_id || 0;
  178. // Check manual override first
  179. if (slotId > 0 && manualMappings[slotId] !== undefined) {
  180. comparisons.push({ slot_id: slotId, globalTrayId: manualMappings[slotId] });
  181. continue;
  182. }
  183. // Auto-match with nozzle-aware filtering
  184. let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId));
  185. if (req.nozzle_id != null) {
  186. const nozzleFiltered = candidates.filter((f) => f.extruderId === req.nozzle_id);
  187. if (nozzleFiltered.length > 0) {
  188. candidates = nozzleFiltered;
  189. }
  190. }
  191. const exactMatch = candidates.find(
  192. (f) =>
  193. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  194. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  195. );
  196. const similarMatch = exactMatch
  197. ? undefined
  198. : candidates.find(
  199. (f) =>
  200. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  201. colorsAreSimilar(f.color, req.color)
  202. );
  203. const typeOnlyMatch =
  204. exactMatch || similarMatch
  205. ? undefined
  206. : candidates.find(
  207. (f) => f.type?.toUpperCase() === req.type?.toUpperCase()
  208. );
  209. const loaded = exactMatch ?? similarMatch ?? typeOnlyMatch;
  210. if (loaded) {
  211. usedTrayIds.add(loaded.globalTrayId);
  212. }
  213. comparisons.push({ slot_id: slotId, globalTrayId: loaded?.globalTrayId ?? -1 });
  214. }
  215. const maxSlotId = Math.max(...comparisons.map((f) => f.slot_id || 0));
  216. if (maxSlotId <= 0) return undefined;
  217. const mapping = new Array(maxSlotId).fill(-1);
  218. comparisons.forEach((f) => {
  219. if (f.slot_id && f.slot_id > 0) {
  220. mapping[f.slot_id - 1] = f.globalTrayId;
  221. }
  222. });
  223. return mapping;
  224. }
  225. /**
  226. * Default per-printer config (use default mapping).
  227. */
  228. const DEFAULT_PRINTER_CONFIG: PerPrinterConfig = {
  229. useDefault: true,
  230. manualMappings: {},
  231. autoConfigured: false,
  232. };
  233. /**
  234. * Hook to manage filament mapping for multiple printers.
  235. * Fetches printer status for all selected printers and computes per-printer mappings.
  236. */
  237. export function useMultiPrinterFilamentMapping(
  238. selectedPrinterIds: number[],
  239. printers: Printer[] | undefined,
  240. filamentReqs: { filaments: FilamentRequirement[] } | undefined,
  241. defaultMappings: Record<number, number>,
  242. perPrinterConfigs: Record<number, PerPrinterConfig>,
  243. setPerPrinterConfigs: React.Dispatch<React.SetStateAction<Record<number, PerPrinterConfig>>>
  244. ): UseMultiPrinterFilamentMappingResult {
  245. // Fetch printer status for all selected printers in parallel
  246. const statusQueries = useQueries({
  247. queries: selectedPrinterIds.map((printerId) => ({
  248. queryKey: ['printer-status', printerId],
  249. queryFn: () => api.getPrinterStatus(printerId),
  250. enabled: selectedPrinterIds.length > 0,
  251. staleTime: 5000, // Consider data fresh for 5 seconds
  252. })),
  253. });
  254. // Build results for each printer
  255. const printerResults = useMemo((): PrinterMappingResult[] => {
  256. return selectedPrinterIds.map((printerId, index) => {
  257. const query = statusQueries[index];
  258. const printerStatus = query?.data;
  259. const printer = printers?.find((p) => p.id === printerId);
  260. const printerName = printer?.name || `Printer ${printerId}`;
  261. const loadedFilaments = buildLoadedFilaments(printerStatus);
  262. const config = perPrinterConfigs[printerId] || DEFAULT_PRINTER_CONFIG;
  263. // Compute auto mapping for this printer
  264. const autoMapping = computeAmsMapping(filamentReqs, printerStatus);
  265. // Determine which mappings to use:
  266. // If printer has override (useDefault=false), use its custom mappings
  267. // Otherwise use the default mappings
  268. const effectiveMappings = !config.useDefault
  269. ? config.manualMappings
  270. : defaultMappings;
  271. // Compute final mapping with overrides
  272. const finalMapping = computeMappingWithOverrides(filamentReqs, printerStatus, effectiveMappings);
  273. // Compute match details
  274. const matchDetails = computeMatchDetails(
  275. filamentReqs?.filaments,
  276. loadedFilaments,
  277. effectiveMappings
  278. );
  279. return {
  280. printerId,
  281. printerName,
  282. status: printerStatus,
  283. isLoading: query?.isLoading ?? false,
  284. loadedFilaments,
  285. autoMapping,
  286. finalMapping,
  287. matchStatus: matchDetails.status,
  288. exactMatches: matchDetails.exactMatches,
  289. typeOnlyMatches: matchDetails.typeOnlyMatches,
  290. missingTypes: matchDetails.missingTypes,
  291. totalSlots: matchDetails.totalSlots,
  292. config,
  293. };
  294. });
  295. }, [selectedPrinterIds, statusQueries, printers, filamentReqs, perPrinterConfigs, defaultMappings]);
  296. const isLoading = statusQueries.some((q) => q.isLoading);
  297. // Update config for a specific printer
  298. const updatePrinterConfig = (printerId: number, updates: Partial<PerPrinterConfig>) => {
  299. setPerPrinterConfigs((prev) => ({
  300. ...prev,
  301. [printerId]: {
  302. ...(prev[printerId] || DEFAULT_PRINTER_CONFIG),
  303. ...updates,
  304. },
  305. }));
  306. };
  307. // Auto-configure a specific printer based on its loaded filaments
  308. const autoConfigurePrinter = (printerId: number) => {
  309. const result = printerResults.find((r) => r.printerId === printerId);
  310. if (!result || !result.status || !filamentReqs?.filaments) return;
  311. // Compute optimal mapping for this printer
  312. const autoMapping = computeAmsMapping(filamentReqs, result.status);
  313. if (!autoMapping) return;
  314. // Convert autoMapping array to manualMappings record
  315. const manualMappings: Record<number, number> = {};
  316. autoMapping.forEach((globalTrayId, index) => {
  317. if (globalTrayId !== -1) {
  318. manualMappings[index + 1] = globalTrayId;
  319. }
  320. });
  321. updatePrinterConfig(printerId, {
  322. useDefault: false,
  323. manualMappings,
  324. autoConfigured: true,
  325. });
  326. };
  327. // Auto-configure all printers
  328. const autoConfigureAll = () => {
  329. for (const printerId of selectedPrinterIds) {
  330. autoConfigurePrinter(printerId);
  331. }
  332. };
  333. // Get final mapping for a specific printer (for submission)
  334. const getFinalMapping = (printerId: number): number[] | undefined => {
  335. const result = printerResults.find((r) => r.printerId === printerId);
  336. return result?.finalMapping;
  337. };
  338. // Check if all printers have acceptable mappings (no missing types)
  339. const allPrintersReady = printerResults.every((r) => r.matchStatus !== 'missing');
  340. return {
  341. printerResults,
  342. isLoading,
  343. perPrinterConfigs,
  344. updatePrinterConfig,
  345. autoConfigureAll,
  346. autoConfigurePrinter,
  347. getFinalMapping,
  348. allPrintersReady,
  349. };
  350. }