index.tsx 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
  2. import { AlertCircle, AlertTriangle, Layers, Loader2, Pencil, Printer, ThumbsUp, X } from 'lucide-react';
  3. import { useEffect, useMemo, useRef, useState } from 'react';
  4. import { useTranslation } from 'react-i18next';
  5. import type { CostCenterSummary, PrintQueueItemCreate, PrintQueueItemUpdate, SlotMaterial } from '../../api/client';
  6. import { api } from '../../api/client';
  7. import { useAuth } from '../../contexts/AuthContext';
  8. import { Card, CardContent } from '../Card';
  9. import { Button } from '../Button';
  10. import { ConfirmModal } from '../ConfirmModal';
  11. import { useToast } from '../../contexts/ToastContext';
  12. import {
  13. buildAmsMapping,
  14. buildFilamentComparison,
  15. buildLoadedFilaments,
  16. useFilamentMapping,
  17. } from '../../hooks/useFilamentMapping';
  18. import { useMultiPrinterFilamentMapping, type PerPrinterConfig } from '../../hooks/useMultiPrinterFilamentMapping';
  19. import { getColorName } from '../../utils/colors';
  20. import { productLineOf, useFilamentNameByIdx } from './useFilamentLabels';
  21. import { isGcodeCompatible, isPrinterCurrentlyDispatchable } from '../../utils/printer';
  22. import { getCurrencySymbol } from '../../utils/currency';
  23. import { getBedTypeInfo } from '../../utils/bedType';
  24. import { toDateTimeLocalValue, parseUTCDate } from '../../utils/date';
  25. import { isPlaceholderDate, effectivePreferLowest, filamentTypesCompatible } from '../../utils/amsHelpers';
  26. import { resolveSlicerAmsMapping } from './archiveAmsMapping';
  27. import { FilamentMapping } from './FilamentMapping';
  28. import { FilamentOverride } from './FilamentOverride';
  29. import { PlateSelector } from './PlateSelector';
  30. import { PrinterSelector } from './PrinterSelector';
  31. import { PrintOptionsPanel } from './PrintOptions';
  32. import { ScheduleOptionsPanel } from './ScheduleOptions';
  33. import { VariantCandidates, type VariantCandidate } from './VariantCandidates';
  34. import { MultiFileModeToggle } from './MultiFileModeToggle';
  35. import {
  36. commonModel,
  37. defaultMultiFileMode,
  38. duplicateModel,
  39. filesIncompatibleWith,
  40. filesNotSlicedFor,
  41. type MultiFileMode,
  42. } from './multiFile';
  43. import { fileHasQueuedPair, queueSeparateJobs, runAsapTail } from './separateJobs';
  44. import { CostCenterSelect } from './CostCenterSelect';
  45. import type {
  46. AssignmentMode,
  47. FilamentReqsData,
  48. PrintModalProps,
  49. PrintOptions,
  50. ScheduleOptions,
  51. ScheduleType,
  52. } from './types';
  53. import { DEFAULT_PRINT_OPTIONS, DEFAULT_SCHEDULE_OPTIONS } from './types';
  54. import { NumberInput } from '../NumberInput';
  55. import { hasGcodeSnippets, useUiSettings } from '../../hooks/useUiSettings';
  56. /** Same filament: type ignoring case, colour as RRGGBB ignoring `#`, case and alpha. */
  57. function isSameFilament(a: { type: string; color: string }, b: { type: string; color: string }): boolean {
  58. const hex = (c: string) => (c || '').replace('#', '').toLowerCase().slice(0, 6);
  59. return (a.type || '').toUpperCase() === (b.type || '').toUpperCase() && hex(a.color) === hex(b.color);
  60. }
  61. /**
  62. * The filament list as the tray matcher should see it: each overridden slot
  63. * asks for the override's type and colour, not the 3MF's (#3133). Mirrors the
  64. * scheduler's `_apply_filament_overrides` for a manual override — the 3MF's
  65. * `tray_info_idx` names the replaced spool's SKU, so it is dropped and matching
  66. * falls back to type + colour. An entry naming the slot's own filament is no
  67. * swap — a virtual printer's force-colour entries are exactly that — so the
  68. * slot keeps its idx and with it the PLA-variant pin (#2650). Slots with no
  69. * override pass through unchanged.
  70. */
  71. function withFilamentOverrides(
  72. reqs: FilamentReqsData | undefined,
  73. overrides: Record<number, { type: string; color: string }>,
  74. ): FilamentReqsData | undefined {
  75. const isSwap = (f: FilamentReqsData['filaments'][number]) => {
  76. const override = overrides[f.slot_id];
  77. return !!override && !isSameFilament(override, f);
  78. };
  79. if (!reqs?.filaments || !reqs.filaments.some(isSwap)) return reqs;
  80. return {
  81. ...reqs,
  82. filaments: reqs.filaments.map((f) =>
  83. isSwap(f) ? { ...f, type: overrides[f.slot_id].type, color: overrides[f.slot_id].color, tray_info_idx: '' } : f,
  84. ),
  85. };
  86. }
  87. /**
  88. * Unified PrintModal component that handles queue item creation and editing.
  89. * - 'create': Create a print queue item from an archive or library file
  90. * - 'edit-queue-item': Edit existing queue item
  91. *
  92. * Both archiveId and libraryFileId are supported. Library files are archived at
  93. * print start time by the scheduler, not when queued.
  94. */
  95. export function PrintModal({
  96. mode,
  97. archiveId,
  98. libraryFileId,
  99. archiveName,
  100. queueItem,
  101. initialSelectedPrinterIds,
  102. preselectPlateId,
  103. onClose,
  104. onSuccess,
  105. projectId,
  106. cleanupLibraryAfterDispatch,
  107. variantFiles,
  108. separateJobsAllowed,
  109. resumeSeparateJobs,
  110. onSeparateJobsProgress,
  111. }: PrintModalProps) {
  112. const { t } = useTranslation();
  113. const queryClient = useQueryClient();
  114. const { showToast } = useToast();
  115. const { hasPermission, hasAnyPermission, user } = useAuth();
  116. // Their jobs wait for someone to start them (#1620); the server enforces it,
  117. // this keeps the request and the dialog honest about it.
  118. const needsReview = !hasAnyPermission('queue:start_unreviewed', 'queue:update_all');
  119. // Determine if we're printing a library file
  120. const isLibraryFile = !!libraryFileId && !archiveId;
  121. const isEditing = mode === 'edit-queue-item';
  122. // The rest of a separate-jobs run closed after a refusal (#3471 review).
  123. const resumed = mode === 'create' && !!separateJobsAllowed && !!resumeSeparateJobs && (variantFiles?.length ?? 0) > 0;
  124. // What that run was submitted with: the reopened dialog starts from it, so
  125. // a quick Print finishes the run the way it began (#3471 review).
  126. const resumedSettings = resumed ? resumeSeparateJobs!.settings : undefined;
  127. // Several sliced files at once. One file is not a choice, so a single-entry
  128. // list behaves exactly like an ordinary print, unless it is the last file of
  129. // a resumed run: one printer may already have it, and only the separate-jobs
  130. // path knows to skip that pair.
  131. const isMultiFile = mode === 'create' && ((variantFiles?.length ?? 0) > 1 || resumed);
  132. // What those files become (#3462): one job with a candidate per file (#671),
  133. // or one queue item per file. Only a selection made in the File Manager may
  134. // be split into separate jobs; a version group is the same job sliced for
  135. // different printers, so without `separateJobsAllowed` it stays alternatives
  136. // and the dialog behaves exactly as before.
  137. const [multiFileMode, setMultiFileMode] = useState<MultiFileMode>(() =>
  138. resumed ? 'separate' : separateJobsAllowed && isMultiFile ? defaultMultiFileMode(variantFiles!) : 'alternatives',
  139. );
  140. // Cross-model alternatives (#671).
  141. const isCrossModel = isMultiFile && multiFileMode === 'alternatives';
  142. const isSeparateJobs = isMultiFile && multiFileMode === 'separate';
  143. // Set once separate jobs were partly queued and the rest is still listed.
  144. // The rest is the remainder of those jobs, so the mode is no longer offered:
  145. // as alternatives it could be a job of one candidate, or one whose filament
  146. // panel describes a file that has already been queued and left the list.
  147. const [partlyQueued, setPartlyQueued] = useState(resumed);
  148. // File and printer pairs earlier submits of a partly queued run got into the
  149. // queue. The next submit skips them, so a file one printer took and another
  150. // refused is not queued on the first printer again.
  151. const [queuedPairs, setQueuedPairs] = useState<ReadonlySet<string>>(
  152. () => new Set(resumed ? resumeSeparateJobs!.queuedPairs : []),
  153. );
  154. // ASAP positions the run has taken so far. The backend moves everything at
  155. // or below an inserted position down, so a second submit that restarted at 1
  156. // would put the rest ahead of what is already queued.
  157. const [asapPositionsTaken, setAsapPositionsTaken] = useState(resumed ? resumeSeparateJobs!.asapInserted : 0);
  158. // The run's own queue items and batches, to find where its ASAP items end
  159. // in the queue as it is at the next submit.
  160. const [runItemIds, setRunItemIds] = useState<number[]>(() => (resumed ? resumeSeparateJobs!.queuedItemIds ?? [] : []));
  161. const [runBatchIds, setRunBatchIds] = useState<number[]>(() => (resumed ? resumeSeparateJobs!.queuedBatchIds ?? [] : []));
  162. const showModeToggle = isMultiFile && !!separateJobsAllowed && !partlyQueued;
  163. // Editing an already-queued cross-model item. The candidates are shown so the
  164. // dialog doesn't misrepresent the job as a plain "Any H2D" — which is what it
  165. // did before, offering a printer picker whose Save would have left a row with
  166. // both variants and a printer_id. They are not editable here: changing the
  167. // set after queueing needs a variant-level API that doesn't exist, and the
  168. // backend refuses the printer/model change either way.
  169. const editingVariants: VariantCandidate[] =
  170. mode === 'edit-queue-item' && (queueItem?.variants?.length ?? 0) > 1
  171. ? queueItem!.variants!.map((v) => ({
  172. id: v.library_file_id,
  173. filename: v.filename,
  174. sliced_for_model: v.target_model,
  175. }))
  176. : [];
  177. const hasEditingVariants = editingVariants.length > 0;
  178. const [candidates, setCandidates] = useState<VariantCandidate[]>(variantFiles ?? []);
  179. const [candidatePlates, setCandidatePlates] = useState<Record<number, number | null>>(
  180. () => resumedSettings?.plateByFile ?? {},
  181. );
  182. // Whether every listed file's plates are known and chosen (#3471 review).
  183. // Before that a quick Print would send plate_id null: the whole file's time
  184. // and cost, and plate 1 printing.
  185. const [candidatePlatesReady, setCandidatePlatesReady] = useState(false);
  186. type FilamentWarningItem = {
  187. printerId: number;
  188. printerName: string;
  189. slotLabel: string;
  190. requiredGrams: number;
  191. remainingGrams: number;
  192. /** True when AMS Filament Backup pooled more than one spool for this slot;
  193. * `requiredGrams` / `remainingGrams` are then the pooled totals. */
  194. pooled?: boolean;
  195. };
  196. // Multiple printer selection (used for all modes now)
  197. const [selectedPrinters, setSelectedPrinters] = useState<number[]>(() => {
  198. // Initialize with the queue item's printer if editing
  199. if (mode === 'edit-queue-item' && queueItem?.printer_id) {
  200. return [queueItem.printer_id];
  201. }
  202. if (initialSelectedPrinterIds?.length) {
  203. return initialSelectedPrinterIds;
  204. }
  205. if (resumedSettings) return resumedSettings.printerIds;
  206. return [];
  207. });
  208. // Multi-select plates: create mode users can pick a subset of plates
  209. const [selectedPlates, setSelectedPlates] = useState<Set<number>>(() => {
  210. if (mode === 'edit-queue-item' && queueItem?.plate_id != null) {
  211. return new Set([queueItem.plate_id]);
  212. }
  213. // Several files choose their plates in the candidate list, in either mode.
  214. if (mode === 'create' && !isMultiFile && preselectPlateId != null) {
  215. return new Set([preselectPlateId]);
  216. }
  217. return new Set();
  218. });
  219. // Derived single-plate value for filament queries and single-select contexts
  220. const selectedPlate = selectedPlates.size === 1 ? [...selectedPlates][0] : null;
  221. // Quantity — number of copies (creates a batch if > 1)
  222. const [quantity, setQuantity] = useState(() => resumedSettings?.quantity ?? 1);
  223. // Per-plate quantities for multi-plate files (#342). Keyed by plate index;
  224. // a plate with no entry means one run. Only used in create mode on a
  225. // multi-plate file, where it replaces the single global Quantity field.
  226. const [plateQuantities, setPlateQuantities] = useState<Record<number, number>>({});
  227. const [printOptions, setPrintOptions] = useState<PrintOptions>(() => {
  228. if (mode === 'edit-queue-item' && queueItem) {
  229. return {
  230. bed_levelling: queueItem.bed_levelling ?? DEFAULT_PRINT_OPTIONS.bed_levelling,
  231. flow_cali: queueItem.flow_cali ?? DEFAULT_PRINT_OPTIONS.flow_cali,
  232. vibration_cali: queueItem.vibration_cali ?? DEFAULT_PRINT_OPTIONS.vibration_cali,
  233. layer_inspect: queueItem.layer_inspect ?? DEFAULT_PRINT_OPTIONS.layer_inspect,
  234. timelapse: queueItem.timelapse ?? DEFAULT_PRINT_OPTIONS.timelapse,
  235. nozzle_offset_cali: queueItem.nozzle_offset_cali ?? DEFAULT_PRINT_OPTIONS.nozzle_offset_cali,
  236. confirm_outcome: queueItem.confirm_outcome ?? DEFAULT_PRINT_OPTIONS.confirm_outcome,
  237. preheat_override: queueItem.preheat_override ?? DEFAULT_PRINT_OPTIONS.preheat_override,
  238. preheat_chamber_target_override: queueItem.preheat_chamber_target_override ?? DEFAULT_PRINT_OPTIONS.preheat_chamber_target_override,
  239. };
  240. }
  241. return resumedSettings?.printOptions ?? DEFAULT_PRINT_OPTIONS;
  242. });
  243. const [scheduleOptions, setScheduleOptions] = useState<ScheduleOptions>(() => {
  244. if (mode === 'edit-queue-item' && queueItem) {
  245. let scheduleType: ScheduleType = 'queue';
  246. if (queueItem.scheduled_time && !isPlaceholderDate(queueItem.scheduled_time)) {
  247. scheduleType = 'scheduled';
  248. }
  249. let scheduledTime = '';
  250. if (queueItem.scheduled_time && !isPlaceholderDate(queueItem.scheduled_time)) {
  251. const date = parseUTCDate(queueItem.scheduled_time) ?? new Date();
  252. // Use toDateTimeLocalValue to convert UTC to local time for datetime-local input
  253. scheduledTime = toDateTimeLocalValue(date);
  254. }
  255. return {
  256. scheduleType,
  257. scheduledTime,
  258. requireManualStart: queueItem.manual_start,
  259. requirePreviousSuccess: queueItem.require_previous_success,
  260. autoOffAfter: queueItem.auto_off_after,
  261. gcodeInjection: queueItem.gcode_injection ?? false,
  262. staggerEnabled: false,
  263. staggerGroupSize: DEFAULT_SCHEDULE_OPTIONS.staggerGroupSize,
  264. staggerIntervalMinutes: DEFAULT_SCHEDULE_OPTIONS.staggerIntervalMinutes,
  265. };
  266. }
  267. return resumedSettings?.scheduleOptions ?? DEFAULT_SCHEDULE_OPTIONS;
  268. });
  269. // Manual slot overrides: slot_id (1-indexed) -> globalTrayId (default mapping for single printer or all printers)
  270. const [manualMappings, setManualMappings] = useState<Record<number, number>>(() => {
  271. if (mode === 'edit-queue-item' && queueItem?.ams_mapping && Array.isArray(queueItem.ams_mapping)) {
  272. const mappings: Record<number, number> = {};
  273. queueItem.ams_mapping.forEach((globalTrayId, idx) => {
  274. if (globalTrayId !== -1) {
  275. mappings[idx + 1] = globalTrayId;
  276. }
  277. });
  278. return mappings;
  279. }
  280. return {};
  281. });
  282. // The printer `manualMappings` were resolved against (#2799). Its entries are
  283. // global tray IDs, which mean nothing on any other machine, so they follow
  284. // this one printer instead of every selected one. Seeded when editing an
  285. // existing item, whose stored mapping belongs to the printer it is queued on.
  286. const [sharedMappingPrinterId, setSharedMappingPrinterId] = useState<number | null>(() =>
  287. mode === 'edit-queue-item' ? queueItem?.printer_id ?? null : null,
  288. );
  289. // Per-printer override configs (for multi-printer selection)
  290. const [perPrinterConfigs, setPerPrinterConfigs] = useState<Record<number, PerPrinterConfig>>({});
  291. // Assignment mode: 'printer' (specific) or 'model' (any of model)
  292. const [assignmentMode, setAssignmentMode] = useState<AssignmentMode>(() => {
  293. // Cross-model alternatives are model-based by definition — naming one
  294. // printer would defeat the point of offering the other file.
  295. if (isCrossModel) {
  296. return 'model';
  297. }
  298. // Initialize from queue item if editing with target_model
  299. if (mode === 'edit-queue-item' && queueItem?.target_model) {
  300. return 'model';
  301. }
  302. return resumedSettings?.assignmentMode ?? 'printer';
  303. });
  304. // Target model for model-based assignment
  305. const [targetModel, setTargetModel] = useState<string | null>(() => {
  306. if (mode === 'edit-queue-item' && queueItem?.target_model) {
  307. return queueItem.target_model;
  308. }
  309. return resumedSettings?.targetModel ?? null;
  310. });
  311. // Target location for model-based assignment (optional filter)
  312. const [targetLocation, setTargetLocation] = useState<string | null>(() => {
  313. if (mode === 'edit-queue-item' && queueItem?.target_location) {
  314. return queueItem.target_location;
  315. }
  316. return resumedSettings?.targetLocation ?? null;
  317. });
  318. const [selectedCostCenterId, setSelectedCostCenterId] = useState<number | null>(() =>
  319. mode === 'edit-queue-item' ? queueItem?.cost_center_id ?? null : resumedSettings?.costCenterId ?? null
  320. );
  321. const [estimatedCost, setEstimatedCost] = useState<number | null>(queueItem?.estimated_cost ?? null);
  322. const [estimatedCostsByPlate, setEstimatedCostsByPlate] = useState<Record<number, number | null>>({});
  323. // Filament overrides for model-based assignment: slot_id -> {type, color}
  324. const [filamentOverrides, setFilamentOverrides] = useState<Record<number, { type: string; color: string }>>(() => {
  325. if (mode === 'edit-queue-item' && queueItem?.filament_overrides) {
  326. const overrides: Record<number, { type: string; color: string }> = {};
  327. for (const o of queueItem.filament_overrides) {
  328. overrides[o.slot_id] = { type: o.type, color: o.color };
  329. }
  330. return overrides;
  331. }
  332. return {};
  333. });
  334. // Per-slot force color match flags. Default is false (opt-in).
  335. const [forceColorMatch, setForceColorMatch] = useState<Record<number, boolean>>(() => {
  336. if (mode === 'edit-queue-item' && queueItem?.filament_overrides) {
  337. const flags: Record<number, boolean> = {};
  338. for (const o of queueItem.filament_overrides) {
  339. flags[o.slot_id] = o.force_color_match === true;
  340. }
  341. return flags;
  342. }
  343. return {};
  344. });
  345. // Track initial values for clearing mappings on change (edit mode only)
  346. const [initialPrinterIds] = useState(() => (mode === 'edit-queue-item' && queueItem?.printer_id ? [queueItem.printer_id] : []));
  347. const [initialPlateId] = useState(() => (mode === 'edit-queue-item' && queueItem ? queueItem.plate_id : null));
  348. // Submission state for multi-printer
  349. const [isSubmitting, setIsSubmitting] = useState(false);
  350. const [submitProgress, setSubmitProgress] = useState({ current: 0, total: 0 });
  351. const [filamentWarningItems, setFilamentWarningItems] = useState<FilamentWarningItem[] | null>(null);
  352. // Track which printers have had the "Expand custom mapping by default" setting applied
  353. // This ensures the setting only affects initial state, not preventing unchecking
  354. const [initialExpandApplied, setInitialExpandApplied] = useState<Set<number>>(new Set());
  355. // Printer counts and effective printer for filament mapping
  356. const effectivePrinterCount = selectedPrinters.length;
  357. // For filament mapping, use first selected printer (mapping applies to all)
  358. const effectivePrinterId = selectedPrinters.length > 0 ? selectedPrinters[0] : null;
  359. // Queries
  360. const { data: settings } = useUiSettings();
  361. // Sync print option defaults from settings once available
  362. const printDefaultsApplied = useRef(false);
  363. useEffect(() => {
  364. // A resumed run keeps the options it was submitted with.
  365. if (!settings || printDefaultsApplied.current || mode === 'edit-queue-item' || resumedSettings) return;
  366. printDefaultsApplied.current = true;
  367. setPrintOptions({
  368. bed_levelling: settings.default_bed_levelling ?? DEFAULT_PRINT_OPTIONS.bed_levelling,
  369. flow_cali: settings.default_flow_cali ?? DEFAULT_PRINT_OPTIONS.flow_cali,
  370. vibration_cali: settings.default_vibration_cali ?? DEFAULT_PRINT_OPTIONS.vibration_cali,
  371. layer_inspect: settings.default_layer_inspect ?? DEFAULT_PRINT_OPTIONS.layer_inspect,
  372. timelapse: settings.default_timelapse ?? DEFAULT_PRINT_OPTIONS.timelapse,
  373. nozzle_offset_cali: settings.default_nozzle_offset_cali ?? DEFAULT_PRINT_OPTIONS.nozzle_offset_cali,
  374. confirm_outcome: settings.default_confirm_outcome ?? DEFAULT_PRINT_OPTIONS.confirm_outcome,
  375. preheat_override: DEFAULT_PRINT_OPTIONS.preheat_override,
  376. preheat_chamber_target_override: DEFAULT_PRINT_OPTIONS.preheat_chamber_target_override,
  377. });
  378. }, [settings, mode, resumedSettings]);
  379. // Sync stagger defaults from settings once available
  380. const staggerDefaultsApplied = useRef(false);
  381. useEffect(() => {
  382. if (!settings || staggerDefaultsApplied.current || mode === 'edit-queue-item' || resumedSettings) return;
  383. staggerDefaultsApplied.current = true;
  384. setScheduleOptions((prev) => ({
  385. ...prev,
  386. staggerGroupSize: settings.stagger_group_size ?? prev.staggerGroupSize,
  387. staggerIntervalMinutes: settings.stagger_interval_minutes ?? prev.staggerIntervalMinutes,
  388. }));
  389. }, [settings, mode, resumedSettings]);
  390. const currencySymbol = getCurrencySymbol(settings?.currency || 'USD');
  391. const defaultCostPerKg = settings?.default_filament_cost ?? 0;
  392. const billingEnabled = settings?.billing_enabled === true;
  393. const { data: printers, isLoading: loadingPrinters } = useQuery({
  394. queryKey: ['printers'],
  395. queryFn: api.getPrinters,
  396. });
  397. const { data: myCostCenters, isLoading: loadingCostCenters } = useQuery({
  398. queryKey: ['finance', 'cost-centers', 'mine'],
  399. queryFn: api.getMyCostCenters,
  400. enabled: !!user && billingEnabled,
  401. });
  402. const printableCostCenters = useMemo(
  403. () => (myCostCenters || []).filter((center: CostCenterSummary) => center.can_print && center.is_active),
  404. [myCostCenters],
  405. );
  406. const selectedCostCenter = useMemo(
  407. () => printableCostCenters.find((center) => center.id === selectedCostCenterId) ?? null,
  408. [printableCostCenters, selectedCostCenterId],
  409. );
  410. useEffect(() => {
  411. if (printableCostCenters.length === 0) return;
  412. if (selectedCostCenterId != null && printableCostCenters.some((center) => center.id === selectedCostCenterId)) {
  413. return;
  414. }
  415. const preferredPrivate = printableCostCenters.find((center) => center.is_private);
  416. setSelectedCostCenterId(preferredPrivate?.id ?? printableCostCenters[0].id);
  417. }, [printableCostCenters, selectedCostCenterId]);
  418. // Fetch per-printer Map<globalTrayId, gramsRemaining> via the dedicated
  419. // backend endpoint (#1766). Server-side mirrors `_build_inventory_remain_overrides`
  420. // so internal and Spoolman modes both work uniformly, VT/external slots are
  421. // excluded, and negative grams are clamped — single source of truth between
  422. // the client-side preview and dispatch-time picks.
  423. const inventoryRemainQueries = useQueries({
  424. queries: selectedPrinters.map((printerId) => ({
  425. queryKey: ['printer-inventory-remain', printerId],
  426. queryFn: () => api.getInventoryRemain(printerId),
  427. staleTime: 30 * 1000,
  428. // Same key, same reason as FilamentMapping's copy — see the note there.
  429. // Concurrent mounts dedupe, so opening the dialog costs one fetch per
  430. // printer however many plate panels are on screen.
  431. refetchOnMount: 'always',
  432. enabled: selectedPrinters.length > 0,
  433. })),
  434. });
  435. const inventoryByTrayIdPerPrinter = useMemo(() => {
  436. const result = new Map<number, Map<number, number>>();
  437. selectedPrinters.forEach((printerId, idx) => {
  438. const data = inventoryRemainQueries[idx]?.data?.inventory_remain_g;
  439. if (!data) return;
  440. const printerMap = new Map<number, number>();
  441. Object.entries(data).forEach(([key, grams]) => {
  442. const gtid = Number(key);
  443. if (!Number.isNaN(gtid)) printerMap.set(gtid, grams);
  444. });
  445. result.set(printerId, printerMap);
  446. });
  447. return result;
  448. }, [selectedPrinters, inventoryRemainQueries]);
  449. // Same endpoint, the other half of its payload: every inventory-bound slot on
  450. // the printer with the backend's material identity and extruder side. The
  451. // pre-flight filament check groups on these instead of resolving spools
  452. // itself, which is what makes it agree with the dispatcher and work in
  453. // Spoolman mode (where the modal has no assignment rows of its own).
  454. const slotMaterialsPerPrinter = useMemo(() => {
  455. const result = new Map<number, Map<number, SlotMaterial>>();
  456. selectedPrinters.forEach((printerId, idx) => {
  457. const slots = inventoryRemainQueries[idx]?.data?.slot_materials;
  458. if (!slots) return;
  459. const printerMap = new Map<number, SlotMaterial>();
  460. slots.forEach((slot) => printerMap.set(slot.global_tray_id, slot));
  461. result.set(printerId, printerMap);
  462. });
  463. return result;
  464. }, [selectedPrinters, inventoryRemainQueries]);
  465. // Fetch archive details to get sliced_for_model
  466. const { data: archiveDetails, isError: archiveDetailsFailed } = useQuery({
  467. queryKey: ['archive', archiveId],
  468. queryFn: () => api.getArchive(archiveId!),
  469. enabled: !!archiveId && !isLibraryFile,
  470. });
  471. // Fetch library file details to get sliced_for_model
  472. const { data: libraryFileDetails, isError: libraryFileDetailsFailed } = useQuery({
  473. queryKey: ['library-file', libraryFileId],
  474. queryFn: () => api.getLibraryFile(libraryFileId!),
  475. enabled: isLibraryFile && !!libraryFileId,
  476. });
  477. // Get sliced_for_model from archive or library file
  478. const slicedForModel = archiveDetails?.sliced_for_model || libraryFileDetails?.sliced_for_model || null;
  479. // Until the file's details are in, the model it was sliced for is unknown.
  480. const sourceDetailsPending =
  481. (!!archiveId && !isLibraryFile && !archiveDetails && !archiveDetailsFailed) ||
  482. (isLibraryFile && !libraryFileDetails && !libraryFileDetailsFailed);
  483. // The model the printer picker filters on, pre-selects and offers as "Any X".
  484. // Separate jobs print every listed file, not just the first one the dialog
  485. // was opened with (which may already be queued and gone from the list after
  486. // a refusal), so they offer the model all of them share, or none.
  487. const selectorModel = isSeparateJobs ? commonModel(candidates) : slicedForModel;
  488. // The model gate (#2578) per file: each separate job runs its own file, and
  489. // the backend refuses each one sliced for an incompatible model. A file that
  490. // names no model passes, as a single file does.
  491. const separateJobsIncompatible = useMemo(
  492. () => (isSeparateJobs && assignmentMode === 'model' ? filesIncompatibleWith(candidates, targetModel) : []),
  493. [isSeparateJobs, assignmentMode, candidates, targetModel],
  494. );
  495. // Each mode starts from the assignment it is built on, as when the dialog
  496. // opens in it: the alternatives job is model-based with no printer chosen
  497. // (#671), separate jobs start at the printer picker. Nothing picked for one
  498. // mode rides along unseen into the other; the alternatives request always
  499. // carries target_location, and no control in that mode shows it.
  500. const handleMultiFileModeChange = (next: MultiFileMode) => {
  501. if (next === multiFileMode) return;
  502. // Not while the files are being queued: a refusal mid-run hides the
  503. // toggle, and the rest would then be queued in a mode nobody chose for it.
  504. // The toggle is disabled meanwhile; this keeps the mode in step with it.
  505. if (isSubmitting) return;
  506. // Two files for one model can't be alternatives; the toggle disables the
  507. // choice, and this keeps the mode from ever disagreeing with it.
  508. if (next === 'alternatives' && duplicateModel(candidates) != null) return;
  509. setMultiFileMode(next);
  510. setAssignmentMode(next === 'alternatives' ? 'model' : 'printer');
  511. setTargetModel(null);
  512. setTargetLocation(null);
  513. if (next === 'alternatives') setSelectedPrinters([]);
  514. };
  515. // The archive's own saved AMS-slot pick from the slicer (see the "Save AMS
  516. // mapping" virtual-printer setting) — undefined for library files or
  517. // archives that predate the feature / had it off at print time, and
  518. // deliberately undefined unless the selected printer is the one the mapping
  519. // was resolved against. See `resolveArchiveSlicerAmsMapping`.
  520. // While editing a virtual printer's queue job, the pick the job keeps (it
  521. // has no archive until it prints). See `resolveSlicerAmsMapping`.
  522. const editedQueueItem = isEditing ? queueItem : undefined;
  523. const archiveSlicerAmsMapping = useMemo(
  524. () =>
  525. resolveSlicerAmsMapping({
  526. queueItem: editedQueueItem,
  527. isLibraryFile,
  528. archiveExtraData: archiveDetails?.extra_data,
  529. printerId: effectivePrinterId,
  530. }),
  531. [editedQueueItem, isLibraryFile, archiveDetails?.extra_data, effectivePrinterId],
  532. );
  533. // Fetch plates for archives
  534. const { data: archivePlatesData, isError: archivePlatesError } = useQuery({
  535. queryKey: ['archive-plates', archiveId],
  536. queryFn: () => api.getArchivePlates(archiveId!),
  537. enabled: !!archiveId && !isLibraryFile,
  538. retry: false,
  539. });
  540. // Fetch plates for library files
  541. const { data: libraryPlatesData } = useQuery({
  542. queryKey: ['library-file-plates', libraryFileId],
  543. queryFn: () => api.getLibraryFilePlates(libraryFileId!),
  544. enabled: isLibraryFile && !!libraryFileId,
  545. });
  546. // Combine plates data from either source
  547. const platesData = isLibraryFile ? libraryPlatesData : archivePlatesData;
  548. // Fetch filament requirements for archives
  549. const { data: archiveFilamentReqs, isError: archiveFilamentReqsError } = useQuery({
  550. queryKey: ['archive-filaments', archiveId, selectedPlate],
  551. queryFn: () => api.getArchiveFilamentRequirements(archiveId!, selectedPlate ?? undefined),
  552. enabled: !!archiveId && !isLibraryFile && (selectedPlate !== null || !platesData?.is_multi_plate),
  553. retry: false,
  554. });
  555. // Fetch filament requirements for library files (with plate support)
  556. const { data: libraryFilamentReqs } = useQuery({
  557. queryKey: ['library-file-filaments', libraryFileId, selectedPlate],
  558. queryFn: () => api.getLibraryFileFilamentRequirements(libraryFileId!, selectedPlate ?? undefined),
  559. enabled: isLibraryFile && !!libraryFileId && (selectedPlate !== null || !platesData?.is_multi_plate),
  560. });
  561. // Track if archive data couldn't be loaded (archive deleted or file missing)
  562. const archiveDataMissing = !isLibraryFile && (archivePlatesError || archiveFilamentReqsError);
  563. // Combine filament requirements from either source
  564. const effectiveFilamentReqs = isLibraryFile ? libraryFilamentReqs : archiveFilamentReqs;
  565. // What the tray matching works from. An override chosen in model mode stays
  566. // in force when the job is moved to a specific printer (#3133), so that
  567. // printer's trays are matched against the requested filament rather than the
  568. // one the 3MF was sliced with. The override panel keeps the original list —
  569. // it shows "sliced brown, print Bone White".
  570. const mappingFilamentReqs = useMemo(
  571. () => withFilamentOverrides(effectiveFilamentReqs, filamentOverrides),
  572. [effectiveFilamentReqs, filamentOverrides],
  573. );
  574. // Fetch available filaments for model-based assignment (for filament override UI)
  575. // Preset id -> name, to store a colour name within its product line (SN-C9)
  576. const filamentNameByIdx = useFilamentNameByIdx();
  577. const { data: availableFilaments } = useQuery({
  578. queryKey: ['available-filaments', targetModel, targetLocation],
  579. queryFn: () => api.getAvailableFilaments(targetModel!, targetLocation ?? undefined),
  580. enabled: assignmentMode === 'model' && !!targetModel,
  581. });
  582. // A cross-model job (#671) has no single target model, so the query above is
  583. // disabled and the override UI would silently vanish — leaving less control
  584. // than the ordinary "Any X1C" flow offers. Ask each candidate's model instead
  585. // and offer the union: the job can land on any of them, so anything loaded on
  586. // any of them is a legitimate choice. Picking one only some models have is
  587. // allowed and meaningful — it narrows which candidates can match.
  588. const candidateModels = useMemo(
  589. () => Array.from(new Set(candidates.map((c) => c.sliced_for_model).filter((m): m is string => !!m))),
  590. [candidates],
  591. );
  592. const candidateFilamentQueries = useQueries({
  593. queries: isCrossModel
  594. ? candidateModels.map((model) => ({
  595. queryKey: ['available-filaments', model, targetLocation],
  596. queryFn: () => api.getAvailableFilaments(model, targetLocation ?? undefined),
  597. }))
  598. : [],
  599. });
  600. const crossModelFilaments = useMemo(() => {
  601. const seen = new Set<string>();
  602. const merged: NonNullable<typeof availableFilaments> = [];
  603. for (const query of candidateFilamentQueries) {
  604. for (const filament of query.data ?? []) {
  605. // Same type+colour loaded on two models is one choice, not two.
  606. const key = `${filament.type}|${filament.color}|${filament.tray_info_idx}`;
  607. if (!seen.has(key)) {
  608. seen.add(key);
  609. merged.push(filament);
  610. }
  611. }
  612. }
  613. return merged;
  614. }, [candidateFilamentQueries]);
  615. const effectiveAvailableFilaments = isCrossModel ? crossModelFilaments : availableFilaments;
  616. // Only fetch printer status when single printer selected (for filament mapping)
  617. const { data: printerStatus, isLoading: printerStatusLoading } = useQuery({
  618. queryKey: ['printer-status', effectivePrinterId],
  619. queryFn: () => api.getPrinterStatus(effectivePrinterId!),
  620. enabled: !!effectivePrinterId,
  621. });
  622. // Single-printer flow: gate prefer_lowest on this printer's backup state.
  623. // Multi-printer flow gates per-printer inside the hook (different printers
  624. // may have different backup states), so we pass the raw setting down.
  625. const singlePrinterPreferLowest = effectivePreferLowest(
  626. settings?.prefer_lowest_filament,
  627. printerStatus?.ams_filament_backup,
  628. );
  629. const asapToastShouldPromiseLaterStart = async (): Promise<boolean> => {
  630. if (scheduleOptions.scheduleType !== 'asap' || assignmentMode !== 'printer') return false;
  631. if (selectedPrinters.length === 0) return false;
  632. try {
  633. const statuses = await Promise.all(
  634. selectedPrinters.map((printerId) =>
  635. queryClient.fetchQuery({
  636. queryKey: ['printer-status', printerId],
  637. queryFn: () => api.getPrinterStatus(printerId),
  638. staleTime: 0,
  639. }),
  640. ),
  641. );
  642. return statuses.some((status) => !isPrinterCurrentlyDispatchable(status));
  643. } catch {
  644. return true;
  645. }
  646. };
  647. /** The success toast of a create submit that queued `count` items. */
  648. const showQueuedToast = async (count: number) => {
  649. const waitForIdleToast = await asapToastShouldPromiseLaterStart();
  650. if (waitForIdleToast) {
  651. showToast(t('queue.printQueuedWillStartWhenIdle'));
  652. } else if (count === 1) {
  653. showToast(assignmentMode === 'model' ? `Queued for any ${targetModel}` : t('queue.printQueued'));
  654. } else {
  655. showToast(t('queue.itemsQueued', { count }));
  656. }
  657. };
  658. // Get AMS mapping from hook (only when single printer selected)
  659. const { amsMapping } = useFilamentMapping(
  660. mappingFilamentReqs,
  661. printerStatus,
  662. manualMappings,
  663. singlePrinterPreferLowest,
  664. effectivePrinterId ? inventoryByTrayIdPerPrinter.get(effectivePrinterId) : undefined,
  665. );
  666. // --- Per-plate filament mapping (multi-plate submissions) ---------------
  667. // Each plate prints its own subset of the file's slots and needs its own AMS
  668. // mapping. `effectiveFilamentReqs` above is keyed on `selectedPlate`, which is
  669. // null the moment two plates are picked, so it holds the union of every plate's
  670. // filaments — matching against that union lets two plates that share a colour
  671. // on different slots compete for the same tray, and sends the loser to a worse
  672. // tray or to none. So when several plates are selected we fetch each plate's
  673. // requirements and map them separately (#2551 follow-up).
  674. const selectedPlateIds = useMemo(() => [...selectedPlates].sort((a, b) => a - b), [selectedPlates]);
  675. const isMultiPlateSelection = selectedPlates.size > 1;
  676. const perPlateReqQueries = useQueries({
  677. queries: (isMultiPlateSelection ? selectedPlateIds : []).map((plateId) => ({
  678. queryKey: isLibraryFile
  679. ? ['library-file-filaments', libraryFileId, plateId]
  680. : ['archive-filaments', archiveId, plateId],
  681. queryFn: () =>
  682. isLibraryFile
  683. ? api.getLibraryFileFilamentRequirements(libraryFileId!, plateId)
  684. : api.getArchiveFilamentRequirements(archiveId!, plateId),
  685. enabled: isLibraryFile ? !!libraryFileId : !!archiveId,
  686. // Same policy as the single-plate query above: these keys are shared, and a
  687. // retrying observer would leave the plate looking merely slow for seconds.
  688. retry: false,
  689. })),
  690. });
  691. // A plate that has not answered yet and a plate whose 3MF cannot be read look
  692. // identical from here — both are simply absent from `perPlateReqs`. Neither may
  693. // be treated as "this plate needs no filament": that would queue it with no
  694. // mapping and no force-colour overrides, and it would print in whatever happens
  695. // to be loaded. Both states gate submission instead (see `canSubmit`).
  696. // `isPending` is "no data yet", not "a request is in flight" — a background
  697. // refetch of a plate we already have must not disable the button under the user.
  698. const perPlateReqsPending = perPlateReqQueries.some((q) => q.isPending);
  699. const perPlateReqsFailed = perPlateReqQueries.some((q) => q.isError);
  700. const perPlateReqs = useMemo(() => {
  701. const byPlate = new Map<number, FilamentReqsData>();
  702. selectedPlateIds.forEach((plateId, i) => {
  703. const data = perPlateReqQueries[i]?.data;
  704. if (data) byPlate.set(plateId, data);
  705. });
  706. return byPlate;
  707. // Keyed on each query's last update stamp, not on the query objects (fresh every
  708. // render) and not on a spread of their data (a dep array whose *length* changes
  709. // with the plate count, which React treats as always-changed and warns about).
  710. // eslint-disable-next-line react-hooks/exhaustive-deps
  711. }, [selectedPlateIds, perPlateReqQueries.map((q) => q.dataUpdatedAt).join('|')]);
  712. // Per-plate twin of `mappingFilamentReqs`: slot ids are global to the file, so
  713. // one override applies to every plate that prints that slot (#3133).
  714. const mappingPerPlateReqs = useMemo(() => {
  715. const byPlate = new Map<number, FilamentReqsData>();
  716. for (const [plateId, reqs] of perPlateReqs) {
  717. byPlate.set(plateId, withFilamentOverrides(reqs, filamentOverrides) ?? reqs);
  718. }
  719. return byPlate;
  720. }, [perPlateReqs, filamentOverrides]);
  721. // Manual slot overrides are per plate: slot 3 of plate 1 and slot 3 of plate 2
  722. // are different prints and may want different trays.
  723. const [manualMappingsByPlate, setManualMappingsByPlate] = useState<Record<number, Record<number, number>>>({});
  724. // Rack position per filament group (#1784), and one set per plate for the
  725. // per-plate panels — each plate has its own groups.
  726. const [nozzleRackChoice, setNozzleRackChoice] = useState<Record<number, number>>(() => {
  727. // Re-opening an item shows the positions it was queued with, so editing
  728. // one filament does not silently drop the rest.
  729. if (mode === 'edit-queue-item' && queueItem?.nozzle_rack_choice) {
  730. const seeded: Record<number, number> = {};
  731. for (const [groupId, position] of Object.entries(queueItem.nozzle_rack_choice)) {
  732. const group = Number(groupId);
  733. if (Number.isInteger(group) && Number.isInteger(position)) seeded[group] = position;
  734. }
  735. return seeded;
  736. }
  737. return {};
  738. });
  739. const [nozzleRackChoiceByPlate, setNozzleRackChoiceByPlate] =
  740. useState<Record<number, Record<number, number>>>({});
  741. // Only ever computed for a single target printer: a tray id means nothing on a
  742. // different printer, so a fan-out across printers must not reuse these.
  743. const perPlateAmsMappings = useMemo(() => {
  744. const byPlate = new Map<number, number[] | undefined>();
  745. if (!isMultiPlateSelection || !effectivePrinterId || selectedPrinters.length !== 1) return byPlate;
  746. const loaded = buildLoadedFilaments(printerStatus);
  747. const ftsActive = printerStatus?.fila_switch?.installed === true;
  748. const inventoryByTrayId = inventoryByTrayIdPerPrinter.get(effectivePrinterId);
  749. for (const plateId of selectedPlateIds) {
  750. const reqs = mappingPerPlateReqs.get(plateId);
  751. if (!reqs) continue;
  752. const comparison = buildFilamentComparison(
  753. reqs,
  754. loaded,
  755. manualMappingsByPlate[plateId] ?? {},
  756. singlePrinterPreferLowest,
  757. inventoryByTrayId,
  758. ftsActive,
  759. );
  760. byPlate.set(plateId, buildAmsMapping(comparison));
  761. }
  762. return byPlate;
  763. }, [
  764. isMultiPlateSelection,
  765. effectivePrinterId,
  766. printerStatus,
  767. inventoryByTrayIdPerPrinter,
  768. selectedPlateIds,
  769. mappingPerPlateReqs,
  770. manualMappingsByPlate,
  771. singlePrinterPreferLowest,
  772. selectedPrinters.length,
  773. ]);
  774. // Multi-printer filament mapping (for per-printer configuration)
  775. const multiPrinterMapping = useMultiPrinterFilamentMapping(
  776. selectedPrinters,
  777. printers,
  778. mappingFilamentReqs,
  779. manualMappings,
  780. perPrinterConfigs,
  781. setPerPrinterConfigs,
  782. settings?.prefer_lowest_filament,
  783. inventoryByTrayIdPerPrinter,
  784. sharedMappingPrinterId,
  785. );
  786. // Auto-select first plate when plates load (single or multi-plate). A plate
  787. // chosen before the plates were known (a reprint's or a queue item's) that
  788. // the file doesn't have, because the file changed since, is dropped: left
  789. // selected, it would be printed or keep the selection from ever falling
  790. // back to a plate the file has (#3395).
  791. useEffect(() => {
  792. const list = platesData?.plates;
  793. if (!list?.length) return;
  794. setSelectedPlates((prev) => {
  795. const kept = [...prev].filter((index) => list.some((p) => p.index === index));
  796. if (kept.length > 0 && kept.length === prev.size) return prev;
  797. return new Set(kept.length > 0 ? kept : [list[0].index]);
  798. });
  799. }, [platesData, selectedPlates.size]);
  800. // Cross-model: the candidate list owns plate choice, and `platesData` is the
  801. // primary file's. `selectedPlate` still keys the filament-requirements query,
  802. // so it has to follow that file's dropdown — otherwise the override panel
  803. // describes plate 1 while the job runs plate 3 (#3101). An untouched dropdown
  804. // renders its first plate, which is what the auto-select above already set.
  805. useEffect(() => {
  806. if (!isCrossModel || !libraryFileId) return;
  807. const chosen = candidatePlates[libraryFileId];
  808. if (chosen == null) return;
  809. setSelectedPlates((prev) => (prev.size === 1 && prev.has(chosen) ? prev : new Set([chosen])));
  810. }, [isCrossModel, libraryFileId, candidatePlates]);
  811. // Auto-select the default printer (Settings), else the only one available.
  812. // The default is offered once per opening: deselecting it to pick another
  813. // printer must not bring it back, and neither may settings that arrive after
  814. // a printer was already chosen. It is not offered where the printer list is
  815. // hidden (several variants, or printing to a model), nor when the file was
  816. // sliced for another model.
  817. const defaultPrinterOffered = useRef(false);
  818. useEffect(() => {
  819. // Skip auto-select for edit mode (already initialized from queueItem)
  820. if (mode === 'edit-queue-item') return;
  821. if (selectedPrinters.length > 0) {
  822. defaultPrinterOffered.current = true;
  823. return;
  824. }
  825. const activePrinters = printers?.filter(p => p.is_active) || [];
  826. const defaultId = settings?.default_printer_id;
  827. const preferred =
  828. defaultId != null && !isCrossModel && assignmentMode === 'printer' && !sourceDetailsPending
  829. ? activePrinters.find(p => p.id === defaultId && (!selectorModel || p.model === selectorModel))
  830. : undefined;
  831. if (preferred && !defaultPrinterOffered.current) {
  832. defaultPrinterOffered.current = true;
  833. setSelectedPrinters([preferred.id]);
  834. } else if (activePrinters.length === 1) {
  835. setSelectedPrinters([activePrinters[0].id]);
  836. }
  837. }, [mode, printers, selectedPrinters.length, settings?.default_printer_id, isCrossModel, assignmentMode, selectorModel, sourceDetailsPending]);
  838. // Clear manual mappings and per-printer configs when printer or plate changes.
  839. // The per-plate mappings go with them: a manual override holds a global tray id,
  840. // which names a different spool on a different printer.
  841. useEffect(() => {
  842. if (mode === 'edit-queue-item') {
  843. // For edit mode, clear mappings if printer selection or plate changed from initial
  844. const printersChanged = JSON.stringify(selectedPrinters.sort()) !== JSON.stringify(initialPrinterIds.sort());
  845. if (printersChanged || selectedPlate !== initialPlateId) {
  846. setManualMappings({});
  847. setManualMappingsByPlate({});
  848. setPerPrinterConfigs({});
  849. setInitialExpandApplied(new Set());
  850. }
  851. // Rack positions name slots of the queued printer's nozzle rack.
  852. if (printersChanged) {
  853. setNozzleRackChoice({});
  854. setNozzleRackChoiceByPlate({});
  855. }
  856. } else {
  857. setManualMappings({});
  858. setManualMappingsByPlate({});
  859. setPerPrinterConfigs({});
  860. setInitialExpandApplied(new Set());
  861. }
  862. }, [mode, selectedPrinters, selectedPlate, initialPrinterIds, initialPlateId]);
  863. // Clear filament overrides when target model or plate changes (but not on initial mount for edit mode).
  864. // `prevTargetModel` is the last model actually targeted, so it skips nulls:
  865. // "Any P2S" -> "Specific Printer" empties targetModel without naming another
  866. // model, and the override is the job's filament, not a tray on some printer —
  867. // it survives the switch and is matched against the chosen printer (#3133).
  868. // Going P2S -> (none) -> X1C still compares P2S with X1C and clears.
  869. const [prevTargetModel, setPrevTargetModel] = useState(targetModel);
  870. const [prevPlateForOverrides, setPrevPlateForOverrides] = useState(selectedPlate);
  871. useEffect(() => {
  872. const modelChanged = targetModel !== null && targetModel !== prevTargetModel;
  873. const plateChanged = selectedPlate !== prevPlateForOverrides;
  874. if (!modelChanged && !plateChanged) return;
  875. if (modelChanged) setPrevTargetModel(targetModel);
  876. if (plateChanged) setPrevPlateForOverrides(selectedPlate);
  877. // A first model after none is a choice, not a change: nothing was picked
  878. // against another model's filaments. That also covers the initial render in
  879. // edit mode, where the values are initialized from queueItem.
  880. if (modelChanged && !plateChanged && prevTargetModel === null) return;
  881. if (mode !== 'edit-queue-item' || prevTargetModel !== null) {
  882. setFilamentOverrides({});
  883. setForceColorMatch({});
  884. }
  885. }, [targetModel, selectedPlate, prevTargetModel, prevPlateForOverrides, mode]);
  886. // The sliced-for metadata loads async. If the user switched to model mode
  887. // before it arrived, the target is still empty (we never silently default
  888. // to another model, #2578) — fill it with the sliced-for model once known,
  889. // provided an active printer of that model exists.
  890. useEffect(() => {
  891. if (assignmentMode !== 'model' || targetModel || !selectorModel) return;
  892. if (printers?.some((p) => p.is_active && p.model === selectorModel)) {
  893. setTargetModel(selectorModel);
  894. }
  895. }, [assignmentMode, targetModel, selectorModel, printers]);
  896. // Auto-expand per-printer mapping when setting is enabled and multiple printers selected
  897. // Only applies once per printer on initial selection, not when user unchecks
  898. useEffect(() => {
  899. if (!settings?.per_printer_mapping_expanded) return;
  900. if (selectedPrinters.length <= 1) return;
  901. // Only auto-configure printers that:
  902. // 1. Haven't had initial expand applied yet
  903. // 2. Have their status loaded (so auto-configure will actually work)
  904. const printersReadyForExpand = selectedPrinters.filter(printerId => {
  905. if (initialExpandApplied.has(printerId)) return false;
  906. // Check if this printer has status loaded
  907. const result = multiPrinterMapping.printerResults.find(r => r.printerId === printerId);
  908. return result && result.status && !result.isLoading;
  909. });
  910. if (printersReadyForExpand.length > 0) {
  911. // Mark these printers as having been initially expanded
  912. setInitialExpandApplied(prev => {
  913. const next = new Set(prev);
  914. printersReadyForExpand.forEach(id => next.add(id));
  915. return next;
  916. });
  917. // Auto-configure printers
  918. printersReadyForExpand.forEach(printerId => {
  919. multiPrinterMapping.autoConfigurePrinter(printerId);
  920. });
  921. }
  922. }, [settings?.per_printer_mapping_expanded, selectedPrinters, initialExpandApplied, multiPrinterMapping]);
  923. // Close on Escape key
  924. useEffect(() => {
  925. const handleKeyDown = (e: KeyboardEvent) => {
  926. if (e.key === 'Escape' && !isSubmitting) onClose();
  927. };
  928. window.addEventListener('keydown', handleKeyDown);
  929. return () => window.removeEventListener('keydown', handleKeyDown);
  930. }, [onClose, isSubmitting]);
  931. const isMultiPlate = platesData?.is_multi_plate ?? false;
  932. const plates = platesData?.plates ?? [];
  933. // The plates that will print, beside the buttons: in a long plate list the
  934. // selected card can be far out of view (#3395). Several files choose theirs
  935. // in the candidate list, where they are in view.
  936. const selectedPlatesSummary =
  937. !isMultiFile && isMultiPlate && plates.length > 1
  938. ? plates
  939. .filter((p) => selectedPlates.has(p.index))
  940. .map((p) => {
  941. const label = t('printModal.plateN', 'Plate {{n}}', { n: p.index });
  942. const name = p.name?.trim();
  943. return name && name !== label ? `${label} – ${name}` : label;
  944. })
  945. .join(', ')
  946. : '';
  947. const filamentWarningMessage = useMemo(() => {
  948. if (!filamentWarningItems || filamentWarningItems.length === 0) return '';
  949. const lines = filamentWarningItems.map((item) =>
  950. // Under AMS Filament Backup the shortfall is against the pooled spools,
  951. // not the one slot — quoting that slot's remaining next to a pooled
  952. // requirement reads as a contradiction ("needs 1441g, remaining 1000g"
  953. // while a second full spool sits next to it).
  954. item.pooled
  955. ? t('printModal.insufficientFilamentLinePooled', {
  956. printer: item.printerName,
  957. slot: item.slotLabel,
  958. required: Math.round(item.requiredGrams),
  959. remaining: Math.round(item.remainingGrams),
  960. })
  961. : t('printModal.insufficientFilamentLine', {
  962. printer: item.printerName,
  963. slot: item.slotLabel,
  964. required: Math.round(item.requiredGrams),
  965. remaining: Math.round(item.remainingGrams),
  966. })
  967. );
  968. return [t('printModal.insufficientFilamentMessage'), ...lines].join('\n');
  969. }, [filamentWarningItems, t]);
  970. // Add to queue mutation (single printer)
  971. const addToQueueMutation = useMutation({
  972. mutationFn: (data: PrintQueueItemCreate) => api.addToQueue(data),
  973. });
  974. // Update queue item mutation. The submit handler reports the outcome and
  975. // closes, once for the whole save: an edit can add entries for further
  976. // printers after this runs.
  977. const updateQueueMutation = useMutation({
  978. mutationFn: (data: PrintQueueItemUpdate) => api.updateQueueItem(queueItem!.id, data),
  979. });
  980. // Get mapping for a specific printer (per-printer override or default).
  981. // A multi-plate submission maps each plate on its own — `amsMapping` and the
  982. // per-printer mappings are both derived from the union of every selected
  983. // plate's filaments, which is not this plate's print (#2551 follow-up).
  984. // Without a per-plate mapping we send none at all and let the scheduler
  985. // compute one at dispatch, which it already does per plate; a union mapping
  986. // would be used verbatim and could feed a slot from the wrong tray.
  987. const getMappingForPrinter = (printerId: number, plateId: number | null): number[] | undefined => {
  988. if (isMultiPlateSelection) {
  989. // Fanning several plates across several printers would be a mapping per
  990. // plate *per printer*; those items go out without one and the scheduler
  991. // maps each plate against the printer it actually picks.
  992. if (plateId === null || selectedPrinters.length !== 1) return undefined;
  993. return perPlateAmsMappings.get(plateId);
  994. }
  995. // For multi-printer selection every printer maps against its own AMS.
  996. // A mapping is a list of global tray IDs, which only mean something on the
  997. // printer they were resolved against, so `amsMapping` — computed against
  998. // the first selected printer — cannot be reused on the rest: the slot index
  999. // still resolves, so nothing looks wrong, and the job prints from whatever
  1000. // sits in that tray on the other machine (#2799).
  1001. //
  1002. // `getFinalMapping` is the single source of truth here: the hook decides
  1003. // per printer which overrides legitimately apply (its own, the shared ones
  1004. // if they were authored against it, otherwise none), and the match badge is
  1005. // derived from that same decision, so the panel cannot promise one mapping
  1006. // while another is submitted. Undefined while a printer's status loads —
  1007. // send none and let the scheduler map it at dispatch, as the multi-plate
  1008. // path above already does.
  1009. if (selectedPrinters.length > 1) {
  1010. return multiPrinterMapping.getFinalMapping(printerId);
  1011. }
  1012. // The single-printer path says the same thing, explicitly. `amsMapping`
  1013. // folds in `manualMappings`, so it is this printer's mapping only while this
  1014. // printer is the one those overrides were authored against. In practice the
  1015. // effect above clears them whenever the selection changes, but that leaves
  1016. // the rule enforced in one place and merely implied in the other — a thin
  1017. // thing to rest on the next time that effect is edited.
  1018. if (sharedMappingPrinterId !== null && sharedMappingPrinterId !== printerId) {
  1019. return multiPrinterMapping.getFinalMapping(printerId);
  1020. }
  1021. return amsMapping;
  1022. };
  1023. // Whether `mapping` sends a slot to a tray of another material (#2799). Only
  1024. // the user can have done that: neither this dialog's matcher nor the
  1025. // scheduler's maps across types. The scheduler re-checks every stored mapping
  1026. // against the printer before dispatch, and a slot on a tray of the wrong type
  1027. // is exactly what a mapping meant for another printer looks like, so it would
  1028. // replace the user's pick. skip_filament_check is the acknowledgement it
  1029. // leaves alone. Same type rule as the scheduler, and a tray or requirement
  1030. // with no type is not judged, as there.
  1031. //
  1032. // Editing seeds the picks from the stored mapping, which may itself be a
  1033. // mapping made for another printer, queued before this check existed. A slot
  1034. // still on the tray the dialog opened with is not a pick made here, so it is
  1035. // left to the scheduler to judge.
  1036. const openedWithTray = (printerId: number, plateId: number | null, slotId: number): number | undefined => {
  1037. if (mode !== 'edit-queue-item' || !Array.isArray(queueItem?.ams_mapping)) return undefined;
  1038. if (printerId !== queueItem.printer_id || plateId !== initialPlateId) return undefined;
  1039. return queueItem.ams_mapping[slotId - 1];
  1040. };
  1041. // The live status the mapping of this printer was matched against.
  1042. const statusForPrinter = (printerId: number) =>
  1043. selectedPrinters.length > 1
  1044. ? multiPrinterMapping.printerResults.find((result) => result.printerId === printerId)?.status
  1045. : printerStatus;
  1046. const mappingSubstitutesMaterial = (
  1047. printerId: number,
  1048. plateId: number | null,
  1049. mapping: number[] | undefined,
  1050. ): boolean => {
  1051. if (!mapping) return false;
  1052. const reqs = isMultiPlateSelection
  1053. ? plateId != null ? mappingPerPlateReqs.get(plateId)?.filaments : undefined
  1054. : mappingFilamentReqs?.filaments;
  1055. if (!reqs) return false;
  1056. const loaded = buildLoadedFilaments(statusForPrinter(printerId));
  1057. return reqs.some((req) => {
  1058. const slotId = req.slot_id ?? 0;
  1059. const tray = slotId > 0 ? mapping[slotId - 1] : undefined;
  1060. if (tray == null || tray < 0) return false;
  1061. if (openedWithTray(printerId, plateId, slotId) === tray) return false;
  1062. const filament = loaded.find((f) => f.globalTrayId === tray);
  1063. return !!filament?.type && !!req.type && !filamentTypesCompatible(filament.type, req.type);
  1064. });
  1065. };
  1066. // Saving an existing job. Only Queue has a manual-start checkbox, so a
  1067. // scheduled job keeps whatever wait it had: a student's scheduled job waits
  1068. // for review (#1620), and editing it must not start it.
  1069. const editManualStart =
  1070. needsReview ||
  1071. (scheduleOptions.scheduleType === 'queue'
  1072. ? scheduleOptions.requireManualStart
  1073. : scheduleOptions.scheduleType === 'scheduled' && !!queueItem?.manual_start);
  1074. // `acknowledgedPrinters`: the printers whose filament warning the user
  1075. // answered with "Print Anyway". Only their jobs skip the scheduler's check;
  1076. // another printer in the same submit was never checked against.
  1077. const handleSubmit = async (
  1078. e?: React.FormEvent,
  1079. options?: { skipFilamentCheck?: boolean; acknowledgedPrinters?: number[] },
  1080. ) => {
  1081. e?.preventDefault();
  1082. if (billingEnabled && selectedCostCenter == null) {
  1083. showToast(t('printModal.noPrintableCostCenters'), 'error');
  1084. return;
  1085. }
  1086. // Separate jobs skip it: it weighs the filaments of the dialog's one file,
  1087. // and each job prints its own. The scheduler's check at dispatch (#1496)
  1088. // still holds any of them back that is short of filament.
  1089. if (
  1090. !options?.skipFilamentCheck &&
  1091. !settings?.disable_filament_warnings &&
  1092. !isEditing &&
  1093. !isSeparateJobs &&
  1094. assignmentMode === 'printer'
  1095. ) {
  1096. const warningItems: FilamentWarningItem[] = [];
  1097. // The spool check follows what is actually dispatched: one job per selected
  1098. // plate, each with the mapping that plate's queue item carries. Two plates
  1099. // can also draw on the same spool, so the demand is summed per tray before
  1100. // it is weighed against what is left on it — 60 g left does not cover two
  1101. // plates of 40 g, even though it covers either one of them (#2551).
  1102. const plateJobs = isMultiPlateSelection
  1103. ? selectedPlateIds.map((plateId) => ({ plateId, reqs: perPlateReqs.get(plateId)?.filaments ?? [] }))
  1104. : [{ plateId: selectedPlate, reqs: effectiveFilamentReqs?.filaments ?? [] }];
  1105. if (plateJobs.some((job) => job.reqs.length > 0) && slotMaterialsPerPrinter.size > 0) {
  1106. for (const printerId of selectedPrinters) {
  1107. const printerStatusForWarning = selectedPrinters.length > 1
  1108. ? multiPrinterMapping.printerResults.find((result) => result.printerId === printerId)?.status
  1109. : printerStatus;
  1110. const loadedFilaments = buildLoadedFilaments(printerStatusForWarning);
  1111. const slotLabelByTray = new Map(loadedFilaments.map((f) => [f.globalTrayId, f.label]));
  1112. // Slots the backend could price. A slot missing here is one with no
  1113. // inventory binding, or one whose Spoolman spool it could not read —
  1114. // both mean "nothing to weigh", never "empty".
  1115. const slotMaterials = slotMaterialsPerPrinter.get(printerId);
  1116. const printerName = printers?.find((p) => p.id === printerId)?.name ?? `Printer ${printerId}`;
  1117. if (!slotMaterials || slotMaterials.size === 0) continue;
  1118. const gramsByTray = new Map<number, number>();
  1119. for (const job of plateJobs) {
  1120. // No mapping means the scheduler picks the trays at dispatch, against
  1121. // an AMS state we cannot see from here — nothing to weigh.
  1122. const printerMapping = getMappingForPrinter(printerId, job.plateId);
  1123. if (!printerMapping) continue;
  1124. job.reqs.forEach((req) => {
  1125. if (!req.slot_id || req.slot_id <= 0) return;
  1126. const globalTrayId = printerMapping[req.slot_id - 1];
  1127. if (!Number.isFinite(globalTrayId) || globalTrayId < 0) return;
  1128. gramsByTray.set(globalTrayId, (gramsByTray.get(globalTrayId) ?? 0) + req.used_grams);
  1129. });
  1130. }
  1131. // With AMS Filament Backup ON the firmware switches to any other slot
  1132. // holding the same material, so the print is only short when the whole
  1133. // pool is (#1762). The dispatcher has accounted for this since #1762 —
  1134. // this check did not, and blocked prints the dispatcher would have run.
  1135. // Dual-extruder printers pool per side: the firmware cannot cross
  1136. // nozzles even with the backup bit set, which is why `extruder` is part
  1137. // of the key the backend hands us.
  1138. const backupOn = printerStatusForWarning?.ams_filament_backup === true;
  1139. const poolKey = (slot: SlotMaterial) => `${slot.material_key}#${slot.extruder}`;
  1140. const pooledGrams = new Map<string, number>();
  1141. const pooledSlotCount = new Map<string, number>();
  1142. const pooledRequired = new Map<string, number>();
  1143. if (backupOn) {
  1144. slotMaterials.forEach((slot) => {
  1145. const key = poolKey(slot);
  1146. pooledGrams.set(key, (pooledGrams.get(key) ?? 0) + slot.remaining_g);
  1147. pooledSlotCount.set(key, (pooledSlotCount.get(key) ?? 0) + 1);
  1148. });
  1149. for (const [globalTrayId, requiredGrams] of gramsByTray) {
  1150. const slot = slotMaterials.get(globalTrayId);
  1151. if (!slot) continue;
  1152. const key = poolKey(slot);
  1153. pooledRequired.set(key, (pooledRequired.get(key) ?? 0) + requiredGrams);
  1154. }
  1155. }
  1156. for (const [globalTrayId, requiredGrams] of gramsByTray) {
  1157. const slot = slotMaterials.get(globalTrayId);
  1158. if (!slot) continue;
  1159. const slotLabel = slotLabelByTray.get(globalTrayId) ?? `Tray ${globalTrayId}`;
  1160. if (backupOn) {
  1161. const key = poolKey(slot);
  1162. const available = pooledGrams.get(key) ?? 0;
  1163. const needed = pooledRequired.get(key) ?? 0;
  1164. if (available >= needed) continue;
  1165. warningItems.push({
  1166. printerId,
  1167. printerName,
  1168. slotLabel,
  1169. requiredGrams: needed,
  1170. remainingGrams: available,
  1171. // A pool of one is just the slot itself — same numbers, so use
  1172. // the plain wording rather than talk about spools that aren't there.
  1173. pooled: (pooledSlotCount.get(key) ?? 1) > 1,
  1174. });
  1175. continue;
  1176. }
  1177. if (slot.remaining_g >= requiredGrams) continue;
  1178. warningItems.push({
  1179. printerId,
  1180. printerName,
  1181. slotLabel,
  1182. requiredGrams,
  1183. remainingGrams: slot.remaining_g,
  1184. });
  1185. }
  1186. }
  1187. }
  1188. if (warningItems.length > 0) {
  1189. setFilamentWarningItems(warningItems);
  1190. return;
  1191. }
  1192. }
  1193. // Validate printer/model selection
  1194. if (assignmentMode === 'printer' && selectedPrinters.length === 0) {
  1195. showToast('Please select at least one printer', 'error');
  1196. return;
  1197. }
  1198. // A cross-model job has no single target model — each candidate carries its
  1199. // own, and the backend gates each of them separately. Both checks below are
  1200. // about the one-model case only.
  1201. if (!isCrossModel && assignmentMode === 'model' && !targetModel) {
  1202. showToast('Please select a target printer model', 'error');
  1203. return;
  1204. }
  1205. // Cross-model safety gate (#2578) — mirrors the backend's 400 so the user
  1206. // gets inline feedback instead of a failed request. Separate jobs are
  1207. // gated per file below; the dialog's own file may no longer be listed.
  1208. if (!isMultiFile && assignmentMode === 'model' && !isGcodeCompatible(slicedForModel, targetModel)) {
  1209. showToast(`File was sliced for ${slicedForModel} and cannot be dispatched to ${targetModel} printers`, 'error');
  1210. return;
  1211. }
  1212. if (separateJobsIncompatible.length > 0) {
  1213. showToast(
  1214. t('printModal.multiFile.incompatible', {
  1215. model: targetModel,
  1216. files: separateJobsIncompatible.map((f) => f.filename).join(', '),
  1217. }),
  1218. 'error',
  1219. );
  1220. return;
  1221. }
  1222. setIsSubmitting(true);
  1223. // Calculate total API calls: plates × printers (or 1 for model-based)
  1224. const platesToQueue = selectedPlates.size > 1
  1225. ? plates.filter(p => selectedPlates.has(p.index))
  1226. : [null];
  1227. const totalCount = assignmentMode === 'model'
  1228. ? platesToQueue.length
  1229. : selectedPrinters.length * platesToQueue.length;
  1230. setSubmitProgress({ current: 0, total: totalCount });
  1231. const results: { success: number; failed: number; errors: string[] } = {
  1232. success: 0,
  1233. failed: 0,
  1234. errors: [],
  1235. };
  1236. // Convert filament overrides from Record to array format for API.
  1237. // Include all slots that either have a user override or have force_color_match enabled
  1238. // (which is the default for model-based assignment).
  1239. // The dialog keeps an override as type + colour only, so an entry that comes
  1240. // back unchanged gets the variant id the item already carried re-attached. A
  1241. // virtual printer writes force-colour entries with the 3MF's tray_info_idx to
  1242. // tell Basic, Matte and Silk PLA apart (#2650); saving the item — which a
  1243. // specific-printer edit now does for the overrides too (#3133) — must not
  1244. // quietly drop that pin. A changed entry is a swap and has no idx to keep.
  1245. const storedOverrideBySlot = new Map(
  1246. (mode === 'edit-queue-item' ? queueItem?.filament_overrides ?? [] : []).map((o) => [o.slot_id, o]),
  1247. );
  1248. const storedVariantFor = (slotId: number, type: string, color: string) => {
  1249. const stored = storedOverrideBySlot.get(slotId);
  1250. return stored?.tray_info_idx && isSameFilament(stored, { type, color }) ? { tray_info_idx: stored.tray_info_idx } : {};
  1251. };
  1252. const buildFilamentOverridesArray = (reqs: FilamentReqsData | undefined) => {
  1253. const entries: Array<{ slot_id: number; type: string; color: string; color_name: string; tray_info_idx?: string; force_color_match: boolean }> = [];
  1254. // Process all slots from filament requirements (to capture force_color_match defaults)
  1255. if (reqs?.filaments) {
  1256. for (const req of reqs.filaments) {
  1257. const userOverride = filamentOverrides[req.slot_id];
  1258. const isForceColor = forceColorMatch[req.slot_id] ?? false;
  1259. const effectiveType = userOverride?.type ?? req.type;
  1260. const effectiveColor = userOverride?.color ?? req.color;
  1261. // Include slot if user changed the filament OR force_color_match is enabled
  1262. if (userOverride || isForceColor) {
  1263. const variant = storedVariantFor(req.slot_id, effectiveType, effectiveColor);
  1264. // A slot left as sliced keeps its own preset; a swapped one only a stored matching one.
  1265. const preset = variant.tray_info_idx ?? (userOverride ? undefined : req.tray_info_idx);
  1266. const colorName = getColorName(effectiveColor, productLineOf(preset, effectiveType, filamentNameByIdx));
  1267. entries.push({ slot_id: req.slot_id, type: effectiveType, color: effectiveColor, color_name: colorName, ...variant, force_color_match: isForceColor });
  1268. }
  1269. }
  1270. } else {
  1271. // Fallback: no filament requirements data — only include explicit user overrides
  1272. for (const [slotId, { type, color }] of Object.entries(filamentOverrides)) {
  1273. const id = parseInt(slotId, 10);
  1274. const isForceColor = forceColorMatch[id] ?? false;
  1275. const variant = storedVariantFor(id, type, color);
  1276. const colorName = getColorName(color, productLineOf(variant.tray_info_idx, type, filamentNameByIdx));
  1277. entries.push({ slot_id: id, type, color, color_name: colorName, ...variant, force_color_match: isForceColor });
  1278. }
  1279. }
  1280. return entries.length > 0 ? entries : undefined;
  1281. };
  1282. const filamentOverridesArray = buildFilamentOverridesArray(effectiveFilamentReqs);
  1283. // A plate only carries the slots it prints (#2552). Slot ids are global to the
  1284. // file, so an override on slot 3 means the same filament in every plate that
  1285. // uses slot 3 — the per-plate list is a subset of the shared state, not a
  1286. // rewrite of it. No fallback to the whole-file list: it holds slots this plate
  1287. // never prints, and submission is gated on every selected plate having answered,
  1288. // so a plate is never missing here.
  1289. const overridesForPlate = (plateId: number | null) =>
  1290. isMultiPlateSelection && plateId !== null
  1291. ? buildFilamentOverridesArray(perPlateReqs.get(plateId))
  1292. : filamentOverridesArray;
  1293. // A specific-printer job carries the slots the user actually changed
  1294. // (#3133): the tray mapping was matched against them, and they are what the
  1295. // scheduler needs if it has to recompute that mapping at dispatch. And the
  1296. // slots ticked "Force color match" (#3445), which were dropped on save, so a
  1297. // recompute fell back to the sliced colour and took any spool of the type.
  1298. //
  1299. // A ticked slot set to a tray of the user's choosing asks for that tray's
  1300. // filament: it is the alternative picked for the slot. Only a tray chosen
  1301. // in this panel, or the one the job was saved with: one the dialog matched
  1302. // on its own may be a stand-in of another colour, and ticking the box there
  1303. // means wait for the colour asked for. A job opened with a forced entry
  1304. // keeps it while its slot stays on the tray it was saved with, whatever
  1305. // that tray holds now (it may have been reloaded since). Everything else
  1306. // keeps the filament the dialog asks for.
  1307. const chosenTray = (printerId: number, plateId: number | null, slotId: number): number | undefined => {
  1308. if (selectedPrinters.length !== 1) return undefined;
  1309. const picks = isMultiPlateSelection
  1310. ? plateId != null ? manualMappingsByPlate[plateId] : undefined
  1311. : sharedMappingPrinterId === null || sharedMappingPrinterId === printerId ? manualMappings : undefined;
  1312. const tray = picks?.[slotId];
  1313. if (tray == null) return undefined;
  1314. const keptForced =
  1315. storedOverrideBySlot.get(slotId)?.force_color_match === true && openedWithTray(printerId, plateId, slotId) === tray;
  1316. return keptForced ? undefined : tray;
  1317. };
  1318. const printerOverridesForPlate = (printerId: number | null, plateId: number | null) => {
  1319. const loaded = printerId != null ? buildLoadedFilaments(statusForPrinter(printerId)) : [];
  1320. // The box is only on screen with one printer selected; a tick left over
  1321. // from before more were added is not saved.
  1322. const ticksShown = selectedPrinters.length === 1;
  1323. const entries = overridesForPlate(plateId)
  1324. ?.flatMap((o) => {
  1325. const changed = !!filamentOverrides[o.slot_id];
  1326. if (!changed && !(o.force_color_match && ticksShown)) return [];
  1327. const tray = o.force_color_match && printerId != null ? chosenTray(printerId, plateId, o.slot_id) : undefined;
  1328. if (tray == null) return [o];
  1329. const filament = loaded.find((f) => f.globalTrayId === tray);
  1330. // A chosen tray that can't be read now (printer off, tray emptied)
  1331. // says nothing about the filament wanted: asking for the sliced one
  1332. // would hold the job against the user's own pick. Saved unforced,
  1333. // as before #3445.
  1334. if (!filament) return changed ? [{ ...o, force_color_match: false }] : [];
  1335. return [{
  1336. slot_id: o.slot_id,
  1337. type: filament.type,
  1338. color: filament.color,
  1339. color_name: filament.colorName,
  1340. ...(filament.trayInfoIdx ? { tray_info_idx: filament.trayInfoIdx } : {}),
  1341. force_color_match: true,
  1342. }];
  1343. });
  1344. return entries && entries.length > 0 ? entries : undefined;
  1345. };
  1346. // Cross-model alternatives (#671): ONE item carrying a candidate per file,
  1347. // in the order the user arranged. This returns before the plate/printer
  1348. // fan-out below because it deliberately fans out to nothing — the whole
  1349. // point is that exactly one of these candidates ever runs.
  1350. //
  1351. // Filament overrides are shared rather than per-candidate, matching how
  1352. // single-model assignment already behaves: the printer is unknown at queue
  1353. // time, so what is expressed here is "this job needs PETG", which is true of
  1354. // every slice of the same job. The AMS mapping is likewise absent — the
  1355. // scheduler computes it against the printer it actually picks.
  1356. if (isCrossModel) {
  1357. try {
  1358. await api.addToQueue({
  1359. variants: candidates.map((c) => ({
  1360. library_file_id: c.id,
  1361. plate_id: candidatePlates[c.id] ?? null,
  1362. filament_overrides: filamentOverridesArray,
  1363. })),
  1364. target_location: targetLocation,
  1365. require_previous_success: scheduleOptions.requirePreviousSuccess,
  1366. auto_off_after: scheduleOptions.autoOffAfter,
  1367. gcode_injection: scheduleOptions.gcodeInjection,
  1368. manual_start: needsReview || (scheduleOptions.scheduleType === 'queue' && scheduleOptions.requireManualStart),
  1369. scheduled_time: scheduleOptions.scheduleType === 'scheduled' && scheduleOptions.scheduledTime
  1370. ? new Date(scheduleOptions.scheduledTime).toISOString()
  1371. : undefined,
  1372. quantity,
  1373. ...printOptions,
  1374. project_id: projectId ?? undefined,
  1375. });
  1376. showToast(t('printModal.variants.queued', { count: candidates.length }), 'success');
  1377. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1378. onSuccess?.();
  1379. onClose();
  1380. } catch (error) {
  1381. showToast(error instanceof Error ? error.message : String(error), 'error');
  1382. } finally {
  1383. setIsSubmitting(false);
  1384. }
  1385. return;
  1386. }
  1387. // Separate jobs (#3462): one ordinary queue item per listed file, files in
  1388. // list order and the selected printers inside each, through the same
  1389. // POST /queue/ the multi-plate fan-out below uses. Returns before that
  1390. // fan-out, which is built around the dialog's one file (its batch, its
  1391. // per-plate quantities and mappings).
  1392. //
  1393. // Each item carries only what is true of every file: printer or model,
  1394. // schedule, options, cost centre. No ams_mapping and no filament_overrides:
  1395. // the mapping and override panels describe the first file's filaments,
  1396. // which are not the others'. Without a mapping the scheduler resolves one at
  1397. // dispatch from the item's own 3MF and the printer's loaded trays
  1398. // (`_ensure_ams_mapping`), as it already does for model-based items. Also
  1399. // left out: estimated_cost (a display hint, the server prices each item
  1400. // itself), skip_filament_check (the spool warning was never shown),
  1401. // nozzle_rack_choice (picked against the first file's filament groups) and
  1402. // batch_id (a batch belongs to one source file; quantity > 1 still makes
  1403. // the server batch each file on its own).
  1404. //
  1405. // The first refused file stops the run: queueing the rest would put them
  1406. // ahead of it, and stopping lets a resubmit carry on from that file
  1407. // without queueing anything twice. What did go in leaves the list, so the
  1408. // list is always exactly what is still to be queued.
  1409. if (isSeparateJobs) {
  1410. const printerIds = assignmentMode === 'printer' ? selectedPrinters : [null];
  1411. // The stagger of the printer fan-out below, per file.
  1412. const useStagger = assignmentMode === 'printer' && scheduleOptions.staggerEnabled && selectedPrinters.length > 1;
  1413. const staggerBaseTime = useStagger
  1414. ? (scheduleOptions.scheduleType === 'scheduled' && scheduleOptions.scheduledTime
  1415. ? new Date(scheduleOptions.scheduledTime).getTime()
  1416. : Date.now())
  1417. : 0;
  1418. const asap = scheduleOptions.scheduleType === 'asap';
  1419. setSubmitProgress({ current: 0, total: candidates.length * printerIds.length });
  1420. try {
  1421. // The rest of a partly queued run goes in right behind the run's own
  1422. // ASAP items as the queue stands now: since the refusal, items may have
  1423. // been added, moved or started, and the count of positions taken would
  1424. // then point somewhere else (#3471 review). The count is the fallback
  1425. // when the queue can't be read.
  1426. let asapInsertedBefore = asapPositionsTaken;
  1427. if (asap && (runItemIds.length > 0 || runBatchIds.length > 0)) {
  1428. try {
  1429. const pending = await api.getQueue(undefined, 'pending');
  1430. asapInsertedBefore = runAsapTail(pending, runItemIds, runBatchIds);
  1431. } catch {
  1432. // Keep the count.
  1433. }
  1434. }
  1435. const outcome = await queueSeparateJobs({
  1436. files: candidates,
  1437. plateByFile: candidatePlates,
  1438. printerIds,
  1439. alreadyQueued: queuedPairs,
  1440. asapInsertedBefore,
  1441. quantity: effectiveQuantity,
  1442. asap,
  1443. buildItem: (file, plateId, printerId, printerIndex) => {
  1444. const item: PrintQueueItemCreate = {
  1445. library_file_id: file.id,
  1446. plate_id: plateId,
  1447. printer_id: assignmentMode === 'printer' ? printerId : null,
  1448. target_model: assignmentMode === 'model' ? targetModel : null,
  1449. target_location: assignmentMode === 'model' ? targetLocation : null,
  1450. require_previous_success: scheduleOptions.requirePreviousSuccess,
  1451. auto_off_after: scheduleOptions.autoOffAfter,
  1452. gcode_injection: scheduleOptions.gcodeInjection,
  1453. manual_start: needsReview || (scheduleOptions.scheduleType === 'queue' && scheduleOptions.requireManualStart),
  1454. scheduled_time: scheduleOptions.scheduleType === 'scheduled' && scheduleOptions.scheduledTime
  1455. ? new Date(scheduleOptions.scheduledTime).toISOString()
  1456. : undefined,
  1457. ...printOptions,
  1458. project_id: projectId ?? undefined,
  1459. cost_center_id: billingEnabled ? selectedCostCenterId : undefined,
  1460. cleanup_library_after_dispatch: cleanupLibraryAfterDispatch,
  1461. };
  1462. if (useStagger) {
  1463. const groupIndex = Math.floor(printerIndex / scheduleOptions.staggerGroupSize);
  1464. if (groupIndex > 0) {
  1465. const offsetMs = groupIndex * scheduleOptions.staggerIntervalMinutes * 60_000;
  1466. item.scheduled_time = new Date(staggerBaseTime + offsetMs).toISOString();
  1467. }
  1468. }
  1469. return item;
  1470. },
  1471. addToQueue: (data) => addToQueueMutation.mutateAsync(data),
  1472. onProgress: (current, total) => setSubmitProgress({ current, total }),
  1473. });
  1474. setAsapPositionsTaken(outcome.asapInserted);
  1475. const allItemIds = [...runItemIds, ...outcome.queuedItemIds];
  1476. const allBatchIds = [...runBatchIds, ...outcome.queuedBatchIds];
  1477. setRunItemIds(allItemIds);
  1478. setRunBatchIds(allBatchIds);
  1479. if (outcome.failure) {
  1480. const allQueued = new Set([...queuedPairs, ...outcome.queuedPairs]);
  1481. setQueuedPairs(allQueued);
  1482. // What is in the queue: the files queued on every printer, and the
  1483. // refused file itself when a printer took it, in this submit or an
  1484. // earlier one, also on a printer that has been deselected since.
  1485. const refusedId = outcome.failure.file.id;
  1486. const refusedFileQueued = fileHasQueuedPair(allQueued, refusedId);
  1487. const queuedIds = refusedFileQueued
  1488. ? [...outcome.queuedFileIds, refusedId]
  1489. : outcome.queuedFileIds;
  1490. const queued = candidates.filter((c) => queuedIds.includes(c.id)).map((c) => c.filename);
  1491. showToast(
  1492. t('printModal.multiFile.failed', {
  1493. filename: outcome.failure.file.filename,
  1494. message: outcome.failure.message,
  1495. queued: queued.length > 0 ? queued.join(', ') : t('common.none'),
  1496. }),
  1497. 'error',
  1498. );
  1499. // Only files queued on every printer leave the list; the refused one
  1500. // stays, even if a printer before the refusal took it.
  1501. const remaining = candidates.filter((c) => !outcome.queuedFileIds.includes(c.id));
  1502. setCandidates(remaining);
  1503. // Any item in the queue makes this run partly queued, also one of
  1504. // the refused file on an earlier printer.
  1505. if (outcome.itemsCreated > 0) setPartlyQueued(true);
  1506. // The opener keeps this if the dialog is closed now: without it the
  1507. // same selection would open empty-handed and queue them again.
  1508. if (allQueued.size > 0) {
  1509. const remainingIds = remaining.map((c) => c.id);
  1510. onSeparateJobsProgress?.({
  1511. queuedPairs: [...allQueued],
  1512. asapInserted: outcome.asapInserted,
  1513. queuedItemIds: allItemIds,
  1514. queuedBatchIds: allBatchIds,
  1515. settings: {
  1516. plateByFile: candidatePlates,
  1517. assignmentMode,
  1518. printerIds: selectedPrinters,
  1519. targetModel,
  1520. targetLocation,
  1521. quantity,
  1522. printOptions,
  1523. scheduleOptions,
  1524. costCenterId: selectedCostCenterId,
  1525. },
  1526. queuedFileIds: (variantFiles ?? []).map((f) => f.id).filter((id) => !remainingIds.includes(id)),
  1527. remainingFileIds: remainingIds,
  1528. });
  1529. }
  1530. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1531. return;
  1532. }
  1533. // Nothing posted means every remaining pair was already queued (a
  1534. // refusing printer deselected since): a success, but "0 items queued"
  1535. // would say otherwise.
  1536. if (outcome.itemsCreated > 0) await showQueuedToast(outcome.itemsCreated);
  1537. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1538. onSuccess?.();
  1539. onClose();
  1540. } catch (error) {
  1541. // queueSeparateJobs reports refusals itself; this is anything else.
  1542. showToast(error instanceof Error ? error.message : String(error), 'error');
  1543. } finally {
  1544. setIsSubmitting(false);
  1545. }
  1546. return;
  1547. }
  1548. // Batch order (#342): a create submission that produces more than one run
  1549. // from one source is pre-created as a batch carrying per-plate targets,
  1550. // and its id is passed to each subsequent addToQueue call. The targets are
  1551. // what make the order able to say a failed run is still owed — without
  1552. // them the batch only knows what it happened to queue. Only for
  1553. // single-target submissions; multi-printer fan-out keeps the old per-item
  1554. // shape, where "how many" is answered by the printer count.
  1555. const plateTargets = platesToQueue.map((plate, index) => {
  1556. const plateIndex = plate ? plate.index : selectedPlate;
  1557. return {
  1558. plate_id: plateIndex,
  1559. plate_name: plate ? (plate.name || null) : null,
  1560. quantity_target: quantityForPlate(plateIndex),
  1561. sort_order: index,
  1562. };
  1563. });
  1564. const totalRuns = plateTargets.reduce((sum, target) => sum + target.quantity_target, 0);
  1565. const shouldAutoBatch =
  1566. mode === 'create'
  1567. && (platesToQueue.length > 1 || totalRuns > 1)
  1568. && (assignmentMode === 'model' || selectedPrinters.length === 1);
  1569. let autoBatchId: number | null = null;
  1570. if (shouldAutoBatch) {
  1571. try {
  1572. const baseName = (archiveName || '').replace(/\.gcode\.3mf$/i, '').replace(/\.3mf$/i, '');
  1573. const batchName = platesToQueue.length > 1
  1574. ? `${baseName || 'Batch'} · ${platesToQueue.length} plates`
  1575. : `${baseName || 'Batch'} ×${totalRuns}`;
  1576. const batch = await api.createBatch({
  1577. name: batchName,
  1578. archive_id: isLibraryFile ? undefined : archiveId,
  1579. library_file_id: isLibraryFile ? libraryFileId : undefined,
  1580. plates: plateTargets,
  1581. });
  1582. autoBatchId = batch.id;
  1583. } catch {
  1584. // Non-fatal: fall back to ungrouped items so the queue still works.
  1585. // The server still creates a plain batch when quantity > 1, so the
  1586. // queue grouping survives even when the order layer doesn't.
  1587. autoBatchId = null;
  1588. }
  1589. }
  1590. // ASAP items go to the top of the queue in the order this submit creates
  1591. // them. One counter for the whole submit: positions are a single sequence
  1592. // across every printer and model (#3200), so a per-printer counter would put
  1593. // each printer's first item at position 1 and shuffle them.
  1594. let asapInserted = 0;
  1595. const applyAsapInsertion = (queueData: PrintQueueItemCreate, itemCount = 1) => {
  1596. if (scheduleOptions.scheduleType !== 'asap') return;
  1597. queueData.insert_at_top = true;
  1598. queueData.insert_position = asapInserted + 1;
  1599. asapInserted += itemCount;
  1600. };
  1601. // Common queue data for create and edit modes
  1602. // One panel per plate when several are selected, one shared panel
  1603. // otherwise -- the same split the AMS mappings use above.
  1604. const rackChoiceForPlate = (plateId: number | null): Record<number, number> | undefined => {
  1605. const choice = plateId != null && isMultiPlateSelection
  1606. ? nozzleRackChoiceByPlate[plateId]
  1607. : nozzleRackChoice;
  1608. return choice && Object.keys(choice).length > 0 ? choice : undefined;
  1609. };
  1610. const getQueueData = (printerId: number | null, plateOverride?: number | null): PrintQueueItemCreate => {
  1611. const plateId = plateOverride !== undefined ? plateOverride : selectedPlate;
  1612. const plateEstimatedCost =
  1613. plateId != null && isMultiPlateSelection ? estimatedCostsByPlate[plateId] ?? null : estimatedCost;
  1614. return {
  1615. printer_id: assignmentMode === 'printer' ? printerId : null,
  1616. target_model: assignmentMode === 'model' ? targetModel : null,
  1617. target_location: assignmentMode === 'model' ? targetLocation : null,
  1618. filament_overrides: assignmentMode === 'model' ? overridesForPlate(plateId) : printerOverridesForPlate(printerId, plateId),
  1619. // Use library_file_id for library files, archive_id for archives
  1620. archive_id: isLibraryFile ? undefined : archiveId,
  1621. library_file_id: isLibraryFile ? libraryFileId : undefined,
  1622. require_previous_success: scheduleOptions.requirePreviousSuccess,
  1623. auto_off_after: scheduleOptions.autoOffAfter,
  1624. gcode_injection: scheduleOptions.gcodeInjection,
  1625. manual_start: needsReview || (scheduleOptions.scheduleType === 'queue' && scheduleOptions.requireManualStart),
  1626. // When the user clicks "Print Anyway" on the frontend deficit warning,
  1627. // persist that acknowledgement so the scheduler doesn't immediately
  1628. // re-flag the item on its first dispatch tick (#1698-followup).
  1629. skip_filament_check:
  1630. (printerId != null && options?.acknowledgedPrinters?.includes(printerId)) ||
  1631. (printerId != null && mappingSubstitutesMaterial(printerId, plateId, getMappingForPrinter(printerId, plateId)))
  1632. ? true
  1633. : undefined,
  1634. ams_mapping: printerId ? getMappingForPrinter(printerId, plateId) : undefined,
  1635. // Rack positions per filament group (#1784). Only sent in printer mode:
  1636. // in model mode the target printer is not known yet, and the rack it
  1637. // will be dispatched to cannot be validated against here. The dispatcher
  1638. // assigns them itself in that case.
  1639. nozzle_rack_choice: printerId ? rackChoiceForPlate(plateId) : undefined,
  1640. plate_id: plateId,
  1641. scheduled_time: scheduleOptions.scheduleType === 'scheduled' && scheduleOptions.scheduledTime
  1642. ? new Date(scheduleOptions.scheduledTime).toISOString()
  1643. : undefined,
  1644. ...printOptions,
  1645. project_id: projectId ?? undefined,
  1646. cost_center_id: billingEnabled ? selectedCostCenterId : undefined,
  1647. estimated_cost: billingEnabled && selectedCostCenterId != null ? plateEstimatedCost : undefined,
  1648. batch_id: autoBatchId ?? undefined,
  1649. cleanup_library_after_dispatch: cleanupLibraryAfterDispatch,
  1650. };
  1651. };
  1652. // Model-based assignment
  1653. if (assignmentMode === 'model') {
  1654. let progressCounter = 0;
  1655. for (const plate of platesToQueue) {
  1656. progressCounter++;
  1657. setSubmitProgress({ current: progressCounter, total: totalCount });
  1658. const plateId = plate ? plate.index : selectedPlate;
  1659. try {
  1660. if (mode === 'edit-queue-item' && !plate) {
  1661. // Edit mode - update with target_model (only for single plate)
  1662. const updateData: PrintQueueItemUpdate = {
  1663. printer_id: null,
  1664. target_model: targetModel,
  1665. target_location: targetLocation,
  1666. filament_overrides: filamentOverridesArray || null,
  1667. require_previous_success: scheduleOptions.requirePreviousSuccess,
  1668. auto_off_after: scheduleOptions.autoOffAfter,
  1669. gcode_injection: scheduleOptions.gcodeInjection,
  1670. manual_start: editManualStart,
  1671. ams_mapping: undefined,
  1672. plate_id: plateId,
  1673. scheduled_time: scheduleOptions.scheduleType === 'scheduled' && scheduleOptions.scheduledTime
  1674. ? new Date(scheduleOptions.scheduledTime).toISOString()
  1675. : null,
  1676. ...printOptions,
  1677. cost_center_id: billingEnabled ? selectedCostCenterId : undefined,
  1678. estimated_cost: billingEnabled && selectedCostCenterId != null ? estimatedCost : undefined,
  1679. };
  1680. await updateQueueMutation.mutateAsync(updateData);
  1681. } else {
  1682. // Add-to-queue mode with model-based assignment
  1683. const queueData = getQueueData(null, plateId);
  1684. const plateQuantity = quantityForPlate(plateId);
  1685. if (plateQuantity > 1) queueData.quantity = plateQuantity;
  1686. applyAsapInsertion(queueData, plateQuantity);
  1687. await addToQueueMutation.mutateAsync(queueData);
  1688. }
  1689. results.success++;
  1690. } catch (error) {
  1691. results.failed++;
  1692. const plateName = plate ? (plate.name || `Plate ${plate.index}`) : '';
  1693. results.errors.push(plateName ? `${plateName}: ${(error as Error).message}` : (error as Error).message);
  1694. }
  1695. }
  1696. } else {
  1697. // Printer-based assignment: loop through plates × printers
  1698. // Compute stagger base time once before the loop
  1699. const useStagger = scheduleOptions.staggerEnabled
  1700. && !isEditing
  1701. && selectedPrinters.length > 1;
  1702. const staggerBaseTime = useStagger
  1703. ? (scheduleOptions.scheduleType === 'scheduled' && scheduleOptions.scheduledTime
  1704. ? new Date(scheduleOptions.scheduledTime).getTime()
  1705. : Date.now())
  1706. : 0;
  1707. let progressCounter = 0;
  1708. for (const plate of platesToQueue) {
  1709. const plateId = plate ? plate.index : selectedPlate;
  1710. for (let i = 0; i < selectedPrinters.length; i++) {
  1711. const printerId = selectedPrinters[i];
  1712. progressCounter++;
  1713. setSubmitProgress({ current: progressCounter, total: totalCount });
  1714. try {
  1715. if (isEditing && progressCounter === 1) {
  1716. // Edit mode - update the original queue item for the first entry
  1717. const printerMapping = getMappingForPrinter(printerId, plateId);
  1718. const updateData: PrintQueueItemUpdate = {
  1719. printer_id: printerId,
  1720. target_model: null,
  1721. target_location: null,
  1722. // null, not undefined: omitting the field left a model job's
  1723. // overrides on the row after it moved to a printer, whatever the
  1724. // user did with them here (#3133).
  1725. filament_overrides: printerOverridesForPlate(printerId, plateId) ?? null,
  1726. require_previous_success: scheduleOptions.requirePreviousSuccess,
  1727. auto_off_after: scheduleOptions.autoOffAfter,
  1728. gcode_injection: scheduleOptions.gcodeInjection,
  1729. manual_start: editManualStart,
  1730. ams_mapping: printerMapping,
  1731. // Only ever set here, never cleared: an earlier "Print Anyway"
  1732. // stays acknowledged across an edit on the same printer. On
  1733. // another printer the backend drops it unless sent here.
  1734. skip_filament_check: mappingSubstitutesMaterial(printerId, plateId, printerMapping) ? true : undefined,
  1735. // null, not undefined: an operator who cleared their picks
  1736. // means "assign these again", and undefined would leave the
  1737. // stale ones on the row (#1784).
  1738. nozzle_rack_choice: rackChoiceForPlate(plateId) ?? null,
  1739. plate_id: plateId,
  1740. scheduled_time: scheduleOptions.scheduleType === 'scheduled' && scheduleOptions.scheduledTime
  1741. ? new Date(scheduleOptions.scheduledTime).toISOString()
  1742. : null,
  1743. ...printOptions,
  1744. cost_center_id: billingEnabled ? selectedCostCenterId : undefined,
  1745. estimated_cost: billingEnabled && selectedCostCenterId != null
  1746. ? (plateId != null && isMultiPlateSelection
  1747. ? estimatedCostsByPlate[plateId] ?? null
  1748. : estimatedCost)
  1749. : undefined,
  1750. };
  1751. await updateQueueMutation.mutateAsync(updateData);
  1752. } else {
  1753. // New print mode, staggered print, or edit mode with additional entries
  1754. const queueData = getQueueData(printerId, plateId);
  1755. const plateQuantity = quantityForPlate(plateId);
  1756. if (plateQuantity > 1) queueData.quantity = plateQuantity;
  1757. applyAsapInsertion(queueData, plateQuantity);
  1758. // Apply stagger offset for groups after the first
  1759. if (useStagger) {
  1760. const groupIndex = Math.floor(i / scheduleOptions.staggerGroupSize);
  1761. if (groupIndex > 0) {
  1762. const offsetMs = groupIndex * scheduleOptions.staggerIntervalMinutes * 60_000;
  1763. queueData.scheduled_time = new Date(staggerBaseTime + offsetMs).toISOString();
  1764. }
  1765. // Group 0 with ASAP: no scheduled_time (start immediately)
  1766. // Group 0 with scheduled: keeps the scheduled_time from getQueueData
  1767. }
  1768. await addToQueueMutation.mutateAsync(queueData);
  1769. }
  1770. results.success++;
  1771. } catch (error) {
  1772. results.failed++;
  1773. const printerName = printers?.find(p => p.id === printerId)?.name || `Printer ${printerId}`;
  1774. const plateName = plate ? (plate.name || `Plate ${plate.index}`) : '';
  1775. const label = plateName ? `${printerName} (${plateName})` : printerName;
  1776. results.errors.push(`${label}: ${(error as Error).message}`);
  1777. }
  1778. }
  1779. }
  1780. }
  1781. setIsSubmitting(false);
  1782. // Show result toast
  1783. if (results.failed === 0) {
  1784. if (isEditing) {
  1785. if (mode === 'edit-queue-item') {
  1786. showToast('Queue item updated');
  1787. }
  1788. } else {
  1789. await showQueuedToast(results.success);
  1790. }
  1791. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1792. onSuccess?.();
  1793. onClose();
  1794. } else if (results.success === 0) {
  1795. showToast(`Failed: ${results.errors[0]}`, 'error');
  1796. } else {
  1797. showToast(`${results.success} succeeded, ${results.failed} failed`, 'error');
  1798. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1799. }
  1800. };
  1801. const isPending = isSubmitting || updateQueueMutation.isPending;
  1802. // A single-printer AMS job must wait for the printer's live status before it
  1803. // can resolve the filament mapping. Submitting mid-load matched against zero
  1804. // known trays and serialized an all-[-1] mapping, which dispatched the print
  1805. // to the empty external feed (#2589). Separate jobs send no mapping at all
  1806. // (the scheduler maps each against its own file at dispatch), so they have
  1807. // nothing to wait for.
  1808. const waitingForAmsStatus =
  1809. !isSeparateJobs && assignmentMode === 'printer' && selectedPrinters.length === 1 && printerStatusLoading;
  1810. const canSubmit = useMemo(() => {
  1811. if (isPending) return false;
  1812. // Billing requires a server-authorized cost center. Wait for the query and
  1813. // keep submission disabled when the user has no printable center, rather
  1814. // than letting the API fail with an unexplained 400.
  1815. if (billingEnabled && (loadingCostCenters || selectedCostCenter == null)) return false;
  1816. // Need valid printer/model selection
  1817. if (assignmentMode === 'printer' && selectedPrinters.length === 0) return false;
  1818. // Both are about the single-model case. A cross-model job has no one target
  1819. // model, and each candidate is gated against its own by the backend (#671).
  1820. if (!isCrossModel && assignmentMode === 'model' && !targetModel) return false;
  1821. // Cross-model mismatch cannot be queued (#2578); separate jobs per file.
  1822. if (!isMultiFile && assignmentMode === 'model' && !isGcodeCompatible(slicedForModel, targetModel)) return false;
  1823. if (separateJobsIncompatible.length > 0) return false;
  1824. // Each listed file's plate comes from the list, in either mode.
  1825. if (isMultiFile && !candidatePlatesReady) return false;
  1826. // For multi-plate files, need at least one plate selected. Separate jobs
  1827. // take each file's plate from the candidate list, not from this selection.
  1828. if (!isSeparateJobs && isMultiPlate && selectedPlates.size === 0) return false;
  1829. // Every selected plate has to have answered before we can queue it: a plate
  1830. // still in flight would be sent with no mapping and no overrides, and one that
  1831. // failed to load cannot be mapped at all. Deselect the failing plate to queue
  1832. // the rest — the banner above says which state we are in.
  1833. if (perPlateReqsPending || perPlateReqsFailed) return false;
  1834. // The printer's live status first (#2589, see waitingForAmsStatus).
  1835. if (waitingForAmsStatus) return false;
  1836. return true;
  1837. }, [
  1838. selectedPrinters.length,
  1839. assignmentMode,
  1840. targetModel,
  1841. slicedForModel,
  1842. isMultiPlate,
  1843. selectedPlates.size,
  1844. isPending,
  1845. perPlateReqsPending,
  1846. perPlateReqsFailed,
  1847. waitingForAmsStatus,
  1848. isCrossModel,
  1849. isMultiFile,
  1850. isSeparateJobs,
  1851. separateJobsIncompatible,
  1852. candidatePlatesReady,
  1853. billingEnabled,
  1854. loadingCostCenters,
  1855. selectedCostCenter,
  1856. ]);
  1857. // Quantity only applies for single-printer or model-based assignment (not multi-printer)
  1858. const effectiveQuantity = (assignmentMode === 'printer' && selectedPrinters.length > 1) ? 1 : quantity;
  1859. // On a multi-plate file the per-plate steppers own the quantity and the
  1860. // global field is hidden (#342) — the reporter's case is "plate 1 once,
  1861. // plate 2 twice", which one shared number cannot express. Single-plate
  1862. // files, and edit mode, keep the single field exactly as before.
  1863. // Several files are excluded, alternatives and separate jobs alike: their
  1864. // plate choice is per candidate and lives in VariantCandidates, so there are
  1865. // no per-plate steppers to own the number and the global Quantity field
  1866. // below is the only one there is (#3101).
  1867. const usePerPlateQuantities =
  1868. mode === 'create' && !isMultiFile && isMultiPlate && plates.length > 1;
  1869. /** Runs to queue for one plate. `null` = the single-plate / whole-file case. */
  1870. const quantityForPlate = (plateIndex: number | null): number => {
  1871. if (!usePerPlateQuantities || plateIndex == null) return effectiveQuantity;
  1872. // Multi-printer fan-out already means one copy per printer; multiplying by
  1873. // a per-plate count on top would silently produce plates × printers × n.
  1874. if (assignmentMode === 'printer' && selectedPrinters.length > 1) return 1;
  1875. return Math.max(1, plateQuantities[plateIndex] ?? 1);
  1876. };
  1877. // Clear gcode_injection if the admin removes all snippets while the modal
  1878. // is open — the checkbox itself hides via hasGcodeSnippets in
  1879. // ScheduleOptions, but the boolean would otherwise stay true and ship to
  1880. // the API. The previous gate also reset the flag whenever effectiveQuantity
  1881. // dropped to <= 1, which silently un-ticked the checkbox on every single-
  1882. // print create flow (#1852). The scheduler reads item.gcode_injection per
  1883. // queue item regardless of batch size, so there's no underlying reason for
  1884. // the quantity-1 case to be blocked.
  1885. useEffect(() => {
  1886. if (mode === 'create' && scheduleOptions.gcodeInjection && !hasGcodeSnippets(settings)) {
  1887. setScheduleOptions((opts) => ({ ...opts, gcodeInjection: false }));
  1888. }
  1889. }, [mode, settings, scheduleOptions.gcodeInjection]);
  1890. // Modal title and action button text based on mode
  1891. const getModalConfig = () => {
  1892. if (!isEditing) {
  1893. return {
  1894. title: t('common.print'),
  1895. icon: Printer,
  1896. submitText: t('common.print'),
  1897. submitIcon: Printer,
  1898. loadingText: submitProgress.total > 1
  1899. ? t('queue.addingProgress', { current: submitProgress.current, total: submitProgress.total })
  1900. : t('queue.adding'),
  1901. };
  1902. }
  1903. // edit-queue-item mode
  1904. return {
  1905. title: t('queue.editQueueItem'),
  1906. icon: Pencil,
  1907. submitText: t('common.save'),
  1908. submitIcon: Pencil,
  1909. loadingText: submitProgress.total > 1
  1910. ? t('queue.savingProgress', { current: submitProgress.current, total: submitProgress.total })
  1911. : t('common.saving'),
  1912. };
  1913. };
  1914. const modalConfig = getModalConfig();
  1915. const TitleIcon = modalConfig.icon;
  1916. const SubmitIcon = modalConfig.submitIcon;
  1917. // Show filament mapping when:
  1918. // - Single printer selected
  1919. // - For archives: plate is selected (for multi-plate) or not required (single-plate)
  1920. // - For library files: always show (no plate selection)
  1921. // Never for separate jobs: the panel maps the first file's filaments, and
  1922. // each job is mapped against its own file at dispatch.
  1923. const showFilamentMapping = !isSeparateJobs && effectivePrinterId && selectedPlates.size <= 1 && (
  1924. isLibraryFile || (isMultiPlate ? selectedPlate !== null : true)
  1925. );
  1926. useEffect(() => {
  1927. if (!showFilamentMapping || archiveDataMissing || selectedPrinters.length !== 1) {
  1928. setEstimatedCost(null);
  1929. }
  1930. }, [archiveDataMissing, selectedPrinters.length, showFilamentMapping]);
  1931. // Several plates on one printer: one mapping panel per plate, each mapping only
  1932. // the slots its own plate prints. Multi-printer fan-out would be a panel per
  1933. // plate *per printer*, so those items ship without a mapping and the scheduler
  1934. // computes one per plate when it picks the printer.
  1935. const showPerPlateFilamentMapping =
  1936. !isSeparateJobs && !!effectivePrinterId && isMultiPlateSelection && selectedPrinters.length === 1;
  1937. // Model mode has no printer and so no trays to map onto; what it offers instead
  1938. // is the filament each slot must be printed in, which the scheduler matches
  1939. // against whatever printer of the model it picks. Needs the model's loaded
  1940. // filaments to offer as alternatives.
  1941. // Cross-model items have no targetModel by design — their candidates each
  1942. // carry their own — so gate on having somewhere to source choices from.
  1943. // Separate jobs send no overrides: the slots listed are the first file's.
  1944. const showFilamentOverride =
  1945. assignmentMode === 'model'
  1946. && !isSeparateJobs
  1947. && (isCrossModel || !!targetModel)
  1948. && !!effectiveAvailableFilaments
  1949. && effectiveAvailableFilaments.length > 0;
  1950. // Dual-nozzle gate for the Nozzle Offset Calibration toggle (#1682).
  1951. // Mirrors backend `DUAL_NOZZLE_MODELS` so model-based assignment can show
  1952. // the toggle without a specific printer selected. For printer-mode we rely
  1953. // on the canonical `nozzle_count` field auto-detected from MQTT.
  1954. const DUAL_NOZZLE_MODELS = useMemo(
  1955. () => new Set(['H2D', 'H2DPRO', 'H2C', 'X2D']),
  1956. [],
  1957. );
  1958. const showDualNozzleOptions = useMemo(() => {
  1959. if (assignmentMode === 'model') {
  1960. if (!targetModel) return false;
  1961. return DUAL_NOZZLE_MODELS.has(targetModel.toUpperCase().replace(/[\s-]/g, ''));
  1962. }
  1963. if (!printers || selectedPrinters.length === 0) return false;
  1964. return selectedPrinters.some(id => printers.find(p => p.id === id)?.nozzle_count === 2);
  1965. }, [assignmentMode, targetModel, printers, selectedPrinters, DUAL_NOZZLE_MODELS]);
  1966. return (
  1967. <div
  1968. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  1969. onClick={isSubmitting ? undefined : onClose}
  1970. >
  1971. {/* 4xl rather than the 2xl this was: the filament rows carry the most
  1972. horizontal content in the dialog — a required name, a nozzle picker on
  1973. rack machines, and an AMS slot dropdown naming type, colour and
  1974. remaining weight — and anything narrower truncated the name to
  1975. "Bamb..." (#1784). 4xl is 896px, so it still fits a 1024-wide laptop
  1976. with the surrounding padding, and `w-full` keeps it fluid below that. */}
  1977. <Card
  1978. className="w-full max-w-4xl max-h-[90vh] overflow-y-auto"
  1979. onClick={(e) => e.stopPropagation()}
  1980. >
  1981. <CardContent className="p-0">
  1982. {/* Header */}
  1983. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  1984. <div className="flex items-center gap-2">
  1985. <TitleIcon className="w-5 h-5 text-bambu-green" />
  1986. <h2 className="text-lg font-semibold text-white">{modalConfig.title}</h2>
  1987. </div>
  1988. <Button variant="ghost" size="sm" onClick={onClose} disabled={isSubmitting}>
  1989. <X className="w-5 h-5" />
  1990. </Button>
  1991. </div>
  1992. <form onSubmit={handleSubmit} className="p-4 space-y-4">
  1993. {/* Archive name */}
  1994. <p className="text-sm text-bambu-gray">
  1995. <span className="block text-bambu-gray mb-1">Print Job</span>
  1996. <span className="text-white font-medium truncate block">{archiveName}</span>
  1997. </p>
  1998. {/* Build-plate badge for the selected (or sole) plate — surfaced
  1999. early so the user knows which plate to mount before scheduling
  2000. (#1281). PlateSelector renders its own per-plate badges for
  2001. multi-plate files; this badge covers the single-plate case and
  2002. the multi-plate case where exactly one plate is selected.
  2003. Not for separate jobs: it would name the first file's plate. */}
  2004. {(() => {
  2005. if (isSeparateJobs || !plates.length) return null;
  2006. const target = selectedPlate != null
  2007. ? plates.find(p => p.index === selectedPlate)
  2008. : plates[0];
  2009. const bed = getBedTypeInfo(target?.bed_type);
  2010. if (!bed) return null;
  2011. return (
  2012. <p className="flex items-center gap-1.5 text-xs text-bambu-gray -mt-2" title={bed.label}>
  2013. <img src={bed.icon} alt="" className="w-4 h-4 object-contain flex-shrink-0" />
  2014. <span className="truncate">{bed.label}</span>
  2015. </p>
  2016. );
  2017. })()}
  2018. {/* Plate selection - first so users know filament requirements before
  2019. selecting printers. Cross-model has no use for it: the plate is
  2020. chosen per candidate in the list below, and this selector's own
  2021. choice never reached the request — it only decided which plate
  2022. the filament panel described (#3101). Separate jobs likewise. */}
  2023. {!isMultiFile && (
  2024. <PlateSelector
  2025. plates={plates}
  2026. isMultiPlate={isMultiPlate}
  2027. selectedPlates={selectedPlates}
  2028. onToggle={(plateIndex) => {
  2029. setSelectedPlates(prev => {
  2030. const next = new Set(prev);
  2031. if (!isEditing) {
  2032. // Multi-select: toggle the plate
  2033. if (next.has(plateIndex)) {
  2034. next.delete(plateIndex);
  2035. } else {
  2036. next.add(plateIndex);
  2037. }
  2038. } else {
  2039. // Single-select: replace selection
  2040. next.clear();
  2041. next.add(plateIndex);
  2042. }
  2043. return next;
  2044. });
  2045. }}
  2046. onSelectAll={!isEditing ? () => setSelectedPlates(new Set(plates.map(p => p.index))) : undefined}
  2047. onDeselectAll={!isEditing ? () => setSelectedPlates(new Set()) : undefined}
  2048. multiSelect={!isEditing}
  2049. quantities={usePerPlateQuantities ? plateQuantities : undefined}
  2050. onQuantityChange={usePerPlateQuantities
  2051. ? (plateIndex, value) => setPlateQuantities(prev => ({ ...prev, [plateIndex]: value }))
  2052. : undefined}
  2053. />
  2054. )}
  2055. {/* What the marked files become (#3462). Only for a selection made
  2056. in the File Manager: a version group is one job sliced for
  2057. different printers, for which only alternatives make sense.
  2058. Its hint, or why Alternatives is blocked, is the one
  2059. explanation of the mode, so the list below shows none. */}
  2060. {showModeToggle && (
  2061. <MultiFileModeToggle
  2062. value={multiFileMode}
  2063. onChange={handleMultiFileModeChange}
  2064. blockedModel={duplicateModel(candidates)}
  2065. disabled={isPending}
  2066. />
  2067. )}
  2068. {/* Cross-model alternatives (#671) replace the printer picker entirely:
  2069. the user already answered "which printer" by choosing these files,
  2070. and the remaining question is only which they'd rather have.
  2071. Separate jobs use the same list for their queue order and keep
  2072. the printer picker below. */}
  2073. {isMultiFile && (
  2074. <VariantCandidates
  2075. candidates={candidates}
  2076. onReorder={setCandidates}
  2077. plateByFile={candidatePlates}
  2078. onPlateChange={(fileId, plateId) =>
  2079. setCandidatePlates((prev) => ({ ...prev, [fileId]: plateId }))
  2080. }
  2081. onPlatesReadyChange={setCandidatePlatesReady}
  2082. title={isSeparateJobs ? t('printModal.multiFile.orderTitle') : undefined}
  2083. help={showModeToggle ? '' : isSeparateJobs ? t('printModal.multiFile.separateHint') : undefined}
  2084. />
  2085. )}
  2086. {hasEditingVariants && (
  2087. <VariantCandidates
  2088. candidates={editingVariants}
  2089. readOnly
  2090. readOnlyNote={t('printModal.variants.editNote')}
  2091. onReorder={() => {}}
  2092. plateByFile={{}}
  2093. onPlateChange={() => {}}
  2094. />
  2095. )}
  2096. {/* Printer selection with per-printer mapping — hidden when printer is pre-selected via props */}
  2097. {!isCrossModel && !hasEditingVariants && !initialSelectedPrinterIds?.length && (
  2098. <PrinterSelector
  2099. printers={printers || []}
  2100. selectedPrinterIds={selectedPrinters}
  2101. onMultiSelect={setSelectedPrinters}
  2102. isLoading={loadingPrinters}
  2103. allowMultiple={true}
  2104. showInactive={mode === 'edit-queue-item'}
  2105. disableBusy={false}
  2106. printerMappingResults={multiPrinterMapping.printerResults}
  2107. // The per-printer tray editor inside the selector maps one filament
  2108. // list onto each printer. Several plates have several lists, and a
  2109. // fan-out across printers ships no mapping at all (the scheduler maps
  2110. // each plate against the printer it picks), so the editor would be
  2111. // collecting tray choices it then throws away. Withhold its input.
  2112. // Separate jobs alike: those are the first file's filaments, and
  2113. // every job ships without a mapping.
  2114. filamentReqs={isMultiPlateSelection || isSeparateJobs ? undefined : mappingFilamentReqs}
  2115. onAutoConfigurePrinter={multiPrinterMapping.autoConfigurePrinter}
  2116. onUpdatePrinterConfig={multiPrinterMapping.updatePrinterConfig}
  2117. assignmentMode={assignmentMode}
  2118. onAssignmentModeChange={setAssignmentMode}
  2119. targetModel={targetModel}
  2120. onTargetModelChange={setTargetModel}
  2121. targetLocation={targetLocation}
  2122. onTargetLocationChange={setTargetLocation}
  2123. slicedForModel={selectorModel}
  2124. />
  2125. )}
  2126. {/* "Any X" for separate jobs: each file is gated on its own (#2578),
  2127. and the backend would refuse these one by one. */}
  2128. {separateJobsIncompatible.length > 0 && (
  2129. <div className="p-3 mb-2 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded-lg flex items-center gap-2">
  2130. <AlertCircle className="w-4 h-4 text-red-600 dark:text-red-400 flex-shrink-0" />
  2131. <span className="text-sm text-red-700 dark:text-red-400">
  2132. {t('printModal.multiFile.incompatible', {
  2133. model: targetModel,
  2134. files: separateJobsIncompatible.map((f) => f.filename).join(', '),
  2135. })}
  2136. </span>
  2137. </div>
  2138. )}
  2139. {/* Filament override - shown in model mode when filament requirements are available */}
  2140. {showFilamentOverride && !isMultiPlateSelection && effectiveFilamentReqs && (
  2141. <FilamentOverride
  2142. filamentReqs={effectiveFilamentReqs}
  2143. availableFilaments={effectiveAvailableFilaments!}
  2144. overrides={filamentOverrides}
  2145. onChange={setFilamentOverrides}
  2146. forceColorMatch={forceColorMatch}
  2147. onForceColorMatchChange={(slotId, value) =>
  2148. setForceColorMatch((prev) => ({ ...prev, [slotId]: value }))
  2149. }
  2150. />
  2151. )}
  2152. {/* Filament override, one panel per selected plate. `effectiveFilamentReqs`
  2153. is keyed on `selectedPlate`, which is null as soon as two plates are
  2154. picked, so a multi-plate selection used to render this panel from
  2155. whatever the whole-file query had left in the cache — the union of every
  2156. plate's filaments, or nothing at all once the plates query was warm and
  2157. the whole-file query therefore never ran, which is why the section
  2158. vanished on the second open of the dialog (#2552). */}
  2159. {showFilamentOverride && isMultiPlateSelection && selectedPlateIds.map((plateId, idx) => {
  2160. const plate = plates.find((p) => p.index === plateId);
  2161. const plateReqs = perPlateReqs.get(plateId);
  2162. if (!plateReqs) return null;
  2163. return (
  2164. <FilamentOverride
  2165. key={plateId}
  2166. plateLabel={plate?.name || t('printModal.plateN', 'Plate {{n}}', { n: plateId })}
  2167. showHint={idx === 0}
  2168. filamentReqs={plateReqs}
  2169. availableFilaments={availableFilaments!}
  2170. overrides={filamentOverrides}
  2171. onChange={setFilamentOverrides}
  2172. forceColorMatch={forceColorMatch}
  2173. onForceColorMatchChange={(slotId, value) =>
  2174. setForceColorMatch((prev) => ({ ...prev, [slotId]: value }))
  2175. }
  2176. />
  2177. );
  2178. })}
  2179. {/* Compatibility warning when sliced model doesn't match selected printer */}
  2180. {!isSeparateJobs && slicedForModel && assignmentMode === 'printer' && selectedPrinters.length === 1 && (() => {
  2181. const selectedPrinter = printers?.find(p => p.id === selectedPrinters[0]);
  2182. if (selectedPrinter && selectedPrinter.model && slicedForModel !== selectedPrinter.model) {
  2183. return (
  2184. <div className="p-3 mb-2 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg flex items-center gap-2">
  2185. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 flex-shrink-0" />
  2186. <span className="text-sm text-yellow-700 dark:text-yellow-400">
  2187. File was sliced for {slicedForModel}, but printing on {selectedPrinter.model}
  2188. </span>
  2189. </div>
  2190. );
  2191. }
  2192. return null;
  2193. })()}
  2194. {/* The same warning for separate jobs, naming each file that was
  2195. sliced for another model. Every selected printer gets every
  2196. file, so there is one line per model among them; with mixed
  2197. files the picker shows all printers unfiltered. A warning, not
  2198. a block, as for one file. */}
  2199. {isSeparateJobs && assignmentMode === 'printer' && (() => {
  2200. const printerModels = new Set(
  2201. selectedPrinters
  2202. .map((id) => printers?.find((p) => p.id === id)?.model)
  2203. .filter((model): model is string => !!model),
  2204. );
  2205. return [...printerModels].map((printerModel) => {
  2206. const mismatched = filesNotSlicedFor(candidates, printerModel);
  2207. if (mismatched.length === 0) return null;
  2208. return (
  2209. <div
  2210. key={printerModel}
  2211. className="p-3 mb-2 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded-lg flex items-center gap-2"
  2212. >
  2213. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 flex-shrink-0" />
  2214. <span className="text-sm text-yellow-700 dark:text-yellow-400">
  2215. {t('printModal.multiFile.notSlicedFor', {
  2216. model: printerModel,
  2217. files: mismatched.map((f) => f.filename).join(', '),
  2218. })}
  2219. </span>
  2220. </div>
  2221. );
  2222. });
  2223. })()}
  2224. {/* Warning when archive data couldn't be loaded */}
  2225. {archiveDataMissing && (
  2226. <div className="flex items-start gap-2 p-3 mb-2 bg-orange-50 dark:bg-orange-500/10 border border-orange-300 dark:border-orange-500/30 rounded-lg text-sm">
  2227. <AlertCircle className="w-4 h-4 text-orange-600 dark:text-orange-400 mt-0.5 flex-shrink-0" />
  2228. <p className="text-orange-700 dark:text-orange-400">
  2229. Archive data unavailable. The source file may have been deleted. Filament mapping is disabled.
  2230. </p>
  2231. </div>
  2232. )}
  2233. {/* A selected plate whose filaments could not be read cannot be mapped and
  2234. cannot carry its forced colours, so it is not queued silently — say so
  2235. and hold the button until the plate is deselected. */}
  2236. {perPlateReqsFailed && (
  2237. <div className="flex items-start gap-2 p-3 mb-2 bg-orange-50 dark:bg-orange-500/10 border border-orange-300 dark:border-orange-500/30 rounded-lg text-sm">
  2238. <AlertCircle className="w-4 h-4 text-orange-600 dark:text-orange-400 mt-0.5 flex-shrink-0" />
  2239. <p className="text-orange-700 dark:text-orange-400">
  2240. {t(
  2241. 'printModal.plateFilamentsUnreadable',
  2242. "The filaments of a selected plate could not be read, so it can't be mapped. Deselect it to queue the others.",
  2243. )}
  2244. </p>
  2245. </div>
  2246. )}
  2247. {/* Filament mapping - only show when single printer selected */}
  2248. {showFilamentMapping && !archiveDataMissing && selectedPrinters.length === 1 && (
  2249. <FilamentMapping
  2250. printerId={effectivePrinterId!}
  2251. filamentReqs={mappingFilamentReqs}
  2252. manualMappings={manualMappings}
  2253. onManualMappingChange={(next) => {
  2254. // This panel only renders for a single selected printer, so
  2255. // its tray IDs belong to that printer alone (#2799).
  2256. setSharedMappingPrinterId(effectivePrinterId!);
  2257. setManualMappings(next);
  2258. }}
  2259. onEstimatedCostChange={setEstimatedCost}
  2260. budgetAvailable={billingEnabled ? selectedCostCenter?.budget_available ?? null : null}
  2261. quantity={effectiveQuantity}
  2262. defaultExpanded={!!initialSelectedPrinterIds?.length || (settings?.per_printer_mapping_expanded ?? false)}
  2263. currencySymbol={currencySymbol}
  2264. defaultCostPerKg={defaultCostPerKg}
  2265. forceColorMatch={forceColorMatch}
  2266. onForceColorMatchChange={(slotId, value) =>
  2267. setForceColorMatch((prev) => ({ ...prev, [slotId]: value }))
  2268. }
  2269. archiveAmsMapping={archiveSlicerAmsMapping}
  2270. nozzleRackChoice={nozzleRackChoice}
  2271. onNozzleRackChoiceChange={setNozzleRackChoice}
  2272. />
  2273. )}
  2274. {/* Filament mapping, one panel per selected plate — each plate is its
  2275. own print with its own slots, so it gets its own AMS mapping. */}
  2276. {showPerPlateFilamentMapping && !archiveDataMissing && selectedPlateIds.map((plateId) => {
  2277. const plate = plates.find((p) => p.index === plateId);
  2278. const plateReqs = mappingPerPlateReqs.get(plateId);
  2279. if (!plateReqs) return null;
  2280. return (
  2281. <FilamentMapping
  2282. key={plateId}
  2283. printerId={effectivePrinterId!}
  2284. plateLabel={plate?.name || t('printModal.plateN', 'Plate {{n}}', { n: plateId })}
  2285. filamentReqs={plateReqs}
  2286. manualMappings={manualMappingsByPlate[plateId] ?? {}}
  2287. onManualMappingChange={(mappings) =>
  2288. setManualMappingsByPlate((prev) => ({ ...prev, [plateId]: mappings }))
  2289. }
  2290. onEstimatedCostChange={(cost) =>
  2291. setEstimatedCostsByPlate((prev) => ({ ...prev, [plateId]: cost }))
  2292. }
  2293. budgetAvailable={billingEnabled ? selectedCostCenter?.budget_available ?? null : null}
  2294. quantity={quantityForPlate(plateId)}
  2295. defaultExpanded={false}
  2296. currencySymbol={currencySymbol}
  2297. defaultCostPerKg={defaultCostPerKg}
  2298. forceColorMatch={forceColorMatch}
  2299. onForceColorMatchChange={(slotId, value) =>
  2300. setForceColorMatch((prev) => ({ ...prev, [slotId]: value }))
  2301. }
  2302. archiveAmsMapping={archiveSlicerAmsMapping}
  2303. nozzleRackChoice={nozzleRackChoiceByPlate[plateId] ?? {}}
  2304. onNozzleRackChoiceChange={(choice) =>
  2305. setNozzleRackChoiceByPlate((prev) => ({ ...prev, [plateId]: choice }))
  2306. }
  2307. />
  2308. );
  2309. })}
  2310. {/* Print options */}
  2311. {(mode === 'create' || effectivePrinterCount > 0 || (assignmentMode === 'model' && targetModel)) && (
  2312. <PrintOptionsPanel
  2313. options={printOptions}
  2314. onChange={setPrintOptions}
  2315. defaultExpanded={!!initialSelectedPrinterIds?.length}
  2316. showDualNozzleOptions={showDualNozzleOptions}
  2317. />
  2318. )}
  2319. {billingEnabled && printableCostCenters.length > 0 && (
  2320. <CostCenterSelect
  2321. costCenters={printableCostCenters}
  2322. selectedCostCenterId={selectedCostCenterId}
  2323. onChange={setSelectedCostCenterId}
  2324. />
  2325. )}
  2326. {billingEnabled && !loadingCostCenters && printableCostCenters.length === 0 && (
  2327. <div
  2328. role="alert"
  2329. className="p-3 bg-yellow-100 dark:bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-800 dark:text-yellow-300 flex items-start gap-2"
  2330. >
  2331. <AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
  2332. {t('printModal.noPrintableCostCenters')}
  2333. </div>
  2334. )}
  2335. {/* Quantity — create multiple copies (batch). Hidden for multi-printer
  2336. selection, and for multi-plate files where the per-plate steppers
  2337. in PlateSelector own the number instead (#342). */}
  2338. {mode !== 'edit-queue-item' && !usePerPlateQuantities
  2339. && (assignmentMode === 'model' || selectedPrinters.length <= 1) && (
  2340. <div className="flex items-center gap-3">
  2341. <label htmlFor="printQuantity" className="text-sm text-bambu-gray whitespace-nowrap">
  2342. {t('queue.quantity', 'Quantity')}
  2343. </label>
  2344. <NumberInput
  2345. id="printQuantity"
  2346. min={1}
  2347. max={999}
  2348. value={quantity}
  2349. onChange={setQuantity}
  2350. fallback={1}
  2351. className="w-20 px-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green"
  2352. />
  2353. {quantity > 1 && (
  2354. <span className="text-xs text-bambu-gray">
  2355. {/* Separate jobs post the quantity once per listed file. */}
  2356. {t('queue.quantityHint', 'Creates {{count}} queue items', {
  2357. count: isSeparateJobs ? quantity * candidates.length : quantity,
  2358. })}
  2359. </span>
  2360. )}
  2361. </div>
  2362. )}
  2363. {/* Schedule options */}
  2364. <ScheduleOptionsPanel
  2365. options={scheduleOptions}
  2366. onChange={setScheduleOptions}
  2367. dateFormat={settings?.date_format || 'system'}
  2368. timeFormat={settings?.time_format || 'system'}
  2369. canControlPrinter={hasPermission('printers:control')}
  2370. showStagger={!isEditing && assignmentMode === 'printer' && selectedPrinters.length > 1}
  2371. printerCount={selectedPrinters.length}
  2372. hasGcodeSnippets={hasGcodeSnippets(settings)}
  2373. needsReview={needsReview}
  2374. />
  2375. {/* Outcome prompt (#1898) sits outside the collapsed Print Options
  2376. panel so it is discoverable; it edits the same printOptions
  2377. field as the row inside the panel. */}
  2378. <button
  2379. type="button"
  2380. aria-pressed={printOptions.confirm_outcome}
  2381. title={t('printModal.askForOutcomeTitle')}
  2382. onClick={() => setPrintOptions((prev) => ({ ...prev, confirm_outcome: !prev.confirm_outcome }))}
  2383. className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-sm transition-colors ${
  2384. printOptions.confirm_outcome
  2385. ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
  2386. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  2387. }`}
  2388. >
  2389. <ThumbsUp className="w-4 h-4" />
  2390. {t('printModal.askForOutcome')}
  2391. </button>
  2392. {/* Error message */}
  2393. {updateQueueMutation.isError && (
  2394. <div className="mb-4 p-3 bg-red-100 dark:bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-700 dark:text-red-400">
  2395. {(updateQueueMutation.error as Error)?.message || 'Failed to complete operation'}
  2396. </div>
  2397. )}
  2398. {/* Waiting for the printer's AMS status: submitting now would map
  2399. against zero known trays and dispatch to the empty external feed (#2589). */}
  2400. {waitingForAmsStatus && (
  2401. <div className="mb-4 p-3 bg-blue-100 dark:bg-blue-500/20 border border-blue-500/50 rounded-lg text-sm text-blue-700 dark:text-blue-400 flex items-center gap-2">
  2402. <Loader2 className="w-4 h-4 animate-spin" />
  2403. {t('printModal.waitingForAmsStatus', {
  2404. printer: printers?.find((p) => p.id === effectivePrinterId)?.name ?? '',
  2405. })}
  2406. </div>
  2407. )}
  2408. {selectedPlatesSummary && (
  2409. <p
  2410. className="flex items-center gap-1.5 text-sm text-bambu-gray min-w-0"
  2411. title={selectedPlatesSummary}
  2412. data-testid="selected-plates-summary"
  2413. >
  2414. <Layers className="w-4 h-4 flex-shrink-0" />
  2415. <span className="truncate">{selectedPlatesSummary}</span>
  2416. </p>
  2417. )}
  2418. {/* Actions */}
  2419. <div className="flex gap-3 pt-2">
  2420. <Button type="button" variant="secondary" onClick={onClose} className="flex-1" disabled={isSubmitting}>
  2421. Cancel
  2422. </Button>
  2423. <Button
  2424. type="submit"
  2425. disabled={!canSubmit}
  2426. className="flex-1"
  2427. >
  2428. {isPending ? (
  2429. <>
  2430. <Loader2 className="w-4 h-4 animate-spin" />
  2431. {modalConfig.loadingText}
  2432. </>
  2433. ) : (
  2434. <>
  2435. <SubmitIcon className="w-4 h-4" />
  2436. {modalConfig.submitText}
  2437. </>
  2438. )}
  2439. </Button>
  2440. </div>
  2441. </form>
  2442. </CardContent>
  2443. </Card>
  2444. {filamentWarningItems && filamentWarningItems.length > 0 && (
  2445. <ConfirmModal
  2446. title={t('printModal.insufficientFilamentTitle')}
  2447. message={filamentWarningMessage}
  2448. confirmText={t('printModal.printAnyway')}
  2449. cancelText={t('common.cancel')}
  2450. variant="warning"
  2451. onConfirm={() => {
  2452. const acknowledgedPrinters = [...new Set(filamentWarningItems.map((item) => item.printerId))];
  2453. setFilamentWarningItems(null);
  2454. void handleSubmit(undefined, { skipFilamentCheck: true, acknowledgedPrinters });
  2455. }}
  2456. onCancel={() => setFilamentWarningItems(null)}
  2457. />
  2458. )}
  2459. </div>
  2460. );
  2461. }
  2462. // Re-export types for convenience
  2463. export type { PrintModalMode, PrintModalProps } from './types';