useMultiPrinterFilamentMapping.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. preferLowest?: boolean,
  88. ): { exactMatches: number; typeOnlyMatches: number; missingTypes: number; totalSlots: number; status: PrinterMatchStatus } {
  89. if (!filamentReqs || filamentReqs.length === 0) {
  90. return { exactMatches: 0, typeOnlyMatches: 0, missingTypes: 0, totalSlots: 0, status: 'full' };
  91. }
  92. let exactMatches = 0;
  93. let typeOnlyMatches = 0;
  94. let missingTypes = 0;
  95. const usedTrayIds = new Set<number>(Object.values(manualMappings));
  96. for (const req of filamentReqs) {
  97. const slotId = req.slot_id || 0;
  98. // Check manual override first
  99. if (slotId > 0 && manualMappings[slotId] !== undefined) {
  100. const manualTrayId = manualMappings[slotId];
  101. const manualLoaded = loadedFilaments.find((f) => f.globalTrayId === manualTrayId);
  102. if (manualLoaded) {
  103. const typeMatch = manualLoaded.type?.toUpperCase() === req.type?.toUpperCase();
  104. const colorMatch =
  105. normalizeColorForCompare(manualLoaded.color) === normalizeColorForCompare(req.color) ||
  106. colorsAreSimilar(manualLoaded.color, req.color);
  107. if (typeMatch && colorMatch) {
  108. exactMatches++;
  109. } else if (typeMatch) {
  110. typeOnlyMatches++;
  111. } else {
  112. missingTypes++;
  113. }
  114. continue;
  115. }
  116. }
  117. // Auto-match with nozzle-aware filtering
  118. let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId));
  119. if (req.nozzle_id != null) {
  120. const nozzleFiltered = candidates.filter((f) => f.extruderId === req.nozzle_id);
  121. if (nozzleFiltered.length > 0) {
  122. candidates = nozzleFiltered;
  123. }
  124. }
  125. if (preferLowest) {
  126. candidates = [...candidates].sort((a, b) => {
  127. const ra = a.remain >= 0 ? a.remain : 101;
  128. const rb = b.remain >= 0 ? b.remain : 101;
  129. return ra - rb;
  130. });
  131. }
  132. const exactMatch = candidates.find(
  133. (f) =>
  134. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  135. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  136. );
  137. const similarMatch = exactMatch
  138. ? undefined
  139. : candidates.find(
  140. (f) =>
  141. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  142. colorsAreSimilar(f.color, req.color)
  143. );
  144. const typeOnlyMatch =
  145. exactMatch || similarMatch
  146. ? undefined
  147. : candidates.find(
  148. (f) => f.type?.toUpperCase() === req.type?.toUpperCase()
  149. );
  150. const loaded = exactMatch ?? similarMatch ?? typeOnlyMatch;
  151. if (loaded) {
  152. usedTrayIds.add(loaded.globalTrayId);
  153. }
  154. if (exactMatch || similarMatch) {
  155. exactMatches++;
  156. } else if (typeOnlyMatch) {
  157. typeOnlyMatches++;
  158. } else {
  159. missingTypes++;
  160. }
  161. }
  162. const totalSlots = filamentReqs.length;
  163. let status: PrinterMatchStatus = 'full';
  164. if (missingTypes > 0) {
  165. status = 'missing';
  166. } else if (typeOnlyMatches > 0) {
  167. status = 'partial';
  168. }
  169. return { exactMatches, typeOnlyMatches, missingTypes, totalSlots, status };
  170. }
  171. /**
  172. * Compute AMS mapping with manual overrides applied.
  173. */
  174. function computeMappingWithOverrides(
  175. filamentReqs: { filaments: FilamentRequirement[] } | undefined,
  176. printerStatus: PrinterStatus | undefined,
  177. manualMappings: Record<number, number>,
  178. preferLowest?: boolean,
  179. ): number[] | undefined {
  180. if (!filamentReqs?.filaments || filamentReqs.filaments.length === 0) return undefined;
  181. const loadedFilaments = buildLoadedFilaments(printerStatus);
  182. if (loadedFilaments.length === 0) return undefined;
  183. const usedTrayIds = new Set<number>(Object.values(manualMappings));
  184. const comparisons: { slot_id: number; globalTrayId: number }[] = [];
  185. for (const req of filamentReqs.filaments) {
  186. const slotId = req.slot_id || 0;
  187. // Check manual override first
  188. if (slotId > 0 && manualMappings[slotId] !== undefined) {
  189. comparisons.push({ slot_id: slotId, globalTrayId: manualMappings[slotId] });
  190. continue;
  191. }
  192. // Auto-match with nozzle-aware filtering
  193. let candidates = loadedFilaments.filter((f) => !usedTrayIds.has(f.globalTrayId));
  194. if (req.nozzle_id != null) {
  195. const nozzleFiltered = candidates.filter((f) => f.extruderId === req.nozzle_id);
  196. if (nozzleFiltered.length > 0) {
  197. candidates = nozzleFiltered;
  198. }
  199. }
  200. if (preferLowest) {
  201. candidates = [...candidates].sort((a, b) => {
  202. const ra = a.remain >= 0 ? a.remain : 101;
  203. const rb = b.remain >= 0 ? b.remain : 101;
  204. return ra - rb;
  205. });
  206. }
  207. const exactMatch = candidates.find(
  208. (f) =>
  209. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  210. normalizeColorForCompare(f.color) === normalizeColorForCompare(req.color)
  211. );
  212. const similarMatch = exactMatch
  213. ? undefined
  214. : candidates.find(
  215. (f) =>
  216. f.type?.toUpperCase() === req.type?.toUpperCase() &&
  217. colorsAreSimilar(f.color, req.color)
  218. );
  219. const typeOnlyMatch =
  220. exactMatch || similarMatch
  221. ? undefined
  222. : candidates.find(
  223. (f) => f.type?.toUpperCase() === req.type?.toUpperCase()
  224. );
  225. const loaded = exactMatch ?? similarMatch ?? typeOnlyMatch;
  226. if (loaded) {
  227. usedTrayIds.add(loaded.globalTrayId);
  228. }
  229. comparisons.push({ slot_id: slotId, globalTrayId: loaded?.globalTrayId ?? -1 });
  230. }
  231. const maxSlotId = Math.max(...comparisons.map((f) => f.slot_id || 0));
  232. if (maxSlotId <= 0) return undefined;
  233. const mapping = new Array(maxSlotId).fill(-1);
  234. comparisons.forEach((f) => {
  235. if (f.slot_id && f.slot_id > 0) {
  236. mapping[f.slot_id - 1] = f.globalTrayId;
  237. }
  238. });
  239. return mapping;
  240. }
  241. /**
  242. * Default per-printer config (use default mapping).
  243. */
  244. const DEFAULT_PRINTER_CONFIG: PerPrinterConfig = {
  245. useDefault: true,
  246. manualMappings: {},
  247. autoConfigured: false,
  248. };
  249. /**
  250. * Hook to manage filament mapping for multiple printers.
  251. * Fetches printer status for all selected printers and computes per-printer mappings.
  252. */
  253. export function useMultiPrinterFilamentMapping(
  254. selectedPrinterIds: number[],
  255. printers: Printer[] | undefined,
  256. filamentReqs: { filaments: FilamentRequirement[] } | undefined,
  257. defaultMappings: Record<number, number>,
  258. perPrinterConfigs: Record<number, PerPrinterConfig>,
  259. setPerPrinterConfigs: React.Dispatch<React.SetStateAction<Record<number, PerPrinterConfig>>>,
  260. preferLowest?: boolean,
  261. ): UseMultiPrinterFilamentMappingResult {
  262. // Fetch printer status for all selected printers in parallel
  263. const statusQueries = useQueries({
  264. queries: selectedPrinterIds.map((printerId) => ({
  265. queryKey: ['printer-status', printerId],
  266. queryFn: () => api.getPrinterStatus(printerId),
  267. enabled: selectedPrinterIds.length > 0,
  268. staleTime: 5000, // Consider data fresh for 5 seconds
  269. })),
  270. });
  271. // Build results for each printer
  272. const printerResults = useMemo((): PrinterMappingResult[] => {
  273. return selectedPrinterIds.map((printerId, index) => {
  274. const query = statusQueries[index];
  275. const printerStatus = query?.data;
  276. const printer = printers?.find((p) => p.id === printerId);
  277. const printerName = printer?.name || `Printer ${printerId}`;
  278. const loadedFilaments = buildLoadedFilaments(printerStatus);
  279. const config = perPrinterConfigs[printerId] || DEFAULT_PRINTER_CONFIG;
  280. // Compute auto mapping for this printer
  281. const autoMapping = computeAmsMapping(filamentReqs, printerStatus, preferLowest);
  282. // Determine which mappings to use:
  283. // If printer has override (useDefault=false), use its custom mappings
  284. // Otherwise use the default mappings
  285. const effectiveMappings = !config.useDefault
  286. ? config.manualMappings
  287. : defaultMappings;
  288. // Compute final mapping with overrides
  289. const finalMapping = computeMappingWithOverrides(filamentReqs, printerStatus, effectiveMappings, preferLowest);
  290. // Compute match details
  291. const matchDetails = computeMatchDetails(
  292. filamentReqs?.filaments,
  293. loadedFilaments,
  294. effectiveMappings,
  295. preferLowest,
  296. );
  297. return {
  298. printerId,
  299. printerName,
  300. status: printerStatus,
  301. isLoading: query?.isLoading ?? false,
  302. loadedFilaments,
  303. autoMapping,
  304. finalMapping,
  305. matchStatus: matchDetails.status,
  306. exactMatches: matchDetails.exactMatches,
  307. typeOnlyMatches: matchDetails.typeOnlyMatches,
  308. missingTypes: matchDetails.missingTypes,
  309. totalSlots: matchDetails.totalSlots,
  310. config,
  311. };
  312. });
  313. }, [selectedPrinterIds, statusQueries, printers, filamentReqs, perPrinterConfigs, defaultMappings, preferLowest]);
  314. const isLoading = statusQueries.some((q) => q.isLoading);
  315. // Update config for a specific printer
  316. const updatePrinterConfig = (printerId: number, updates: Partial<PerPrinterConfig>) => {
  317. setPerPrinterConfigs((prev) => ({
  318. ...prev,
  319. [printerId]: {
  320. ...(prev[printerId] || DEFAULT_PRINTER_CONFIG),
  321. ...updates,
  322. },
  323. }));
  324. };
  325. // Auto-configure a specific printer based on its loaded filaments
  326. const autoConfigurePrinter = (printerId: number) => {
  327. const result = printerResults.find((r) => r.printerId === printerId);
  328. if (!result || !result.status || !filamentReqs?.filaments) return;
  329. // Compute optimal mapping for this printer
  330. const autoMapping = computeAmsMapping(filamentReqs, result.status, preferLowest);
  331. if (!autoMapping) return;
  332. // Convert autoMapping array to manualMappings record
  333. const manualMappings: Record<number, number> = {};
  334. autoMapping.forEach((globalTrayId, index) => {
  335. if (globalTrayId !== -1) {
  336. manualMappings[index + 1] = globalTrayId;
  337. }
  338. });
  339. updatePrinterConfig(printerId, {
  340. useDefault: false,
  341. manualMappings,
  342. autoConfigured: true,
  343. });
  344. };
  345. // Auto-configure all printers
  346. const autoConfigureAll = () => {
  347. for (const printerId of selectedPrinterIds) {
  348. autoConfigurePrinter(printerId);
  349. }
  350. };
  351. // Get final mapping for a specific printer (for submission)
  352. const getFinalMapping = (printerId: number): number[] | undefined => {
  353. const result = printerResults.find((r) => r.printerId === printerId);
  354. return result?.finalMapping;
  355. };
  356. // Check if all printers have acceptable mappings (no missing types)
  357. const allPrintersReady = printerResults.every((r) => r.matchStatus !== 'missing');
  358. return {
  359. printerResults,
  360. isLoading,
  361. perPrinterConfigs,
  362. updatePrinterConfig,
  363. autoConfigureAll,
  364. autoConfigurePrinter,
  365. getFinalMapping,
  366. allPrintersReady,
  367. };
  368. }