QueuePage.tsx 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382
  1. import { useState, useMemo, useEffect, useCallback } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import { Link } from 'react-router-dom';
  5. import {
  6. DndContext,
  7. DragOverlay,
  8. closestCenter,
  9. KeyboardSensor,
  10. PointerSensor,
  11. useSensor,
  12. useSensors,
  13. } from '@dnd-kit/core';
  14. import type { DragEndEvent, DragStartEvent } from '@dnd-kit/core';
  15. import {
  16. SortableContext,
  17. sortableKeyboardCoordinates,
  18. useSortable,
  19. verticalListSortingStrategy,
  20. } from '@dnd-kit/sortable';
  21. import { CSS } from '@dnd-kit/utilities';
  22. import { queueItemDisplayName } from '../utils/queueItemName';
  23. import {
  24. Clock,
  25. Trash2,
  26. Play,
  27. X,
  28. CheckCircle,
  29. XCircle,
  30. AlertCircle,
  31. Calendar,
  32. Printer,
  33. GripVertical,
  34. SkipForward,
  35. ExternalLink,
  36. Power,
  37. StopCircle,
  38. Pencil,
  39. RefreshCw,
  40. Timer,
  41. ListOrdered,
  42. Layers,
  43. ArrowUp,
  44. ArrowDown,
  45. Hand,
  46. Check,
  47. CheckSquare,
  48. Square,
  49. User,
  50. Pause,
  51. Weight,
  52. ChevronDown,
  53. ChevronRight,
  54. ChevronUp,
  55. List,
  56. GanttChart,
  57. Code,
  58. Snail,
  59. Package,
  60. PackageOpen,
  61. Ungroup,
  62. Ban,
  63. PlayCircle,
  64. Workflow,
  65. ThumbsUp,
  66. } from 'lucide-react';
  67. import { api, ApiError } from '../api/client';
  68. import { PipelineRunsView } from './PipelineRunsPage';
  69. import { type TimeFormat, formatETA, formatDuration, formatRelativeTime, parseUTCDate } from '../utils/date';
  70. import { getBedTypeInfo } from '../utils/bedType';
  71. import { getColorName } from '../utils/colors';
  72. import type { PrintQueueItem, PrintQueueBulkUpdate, Permission, CalibrationMode, PrinterStatus, SlotSpoolIdentity } from '../api/client';
  73. import { formatSlotLabel, getEmptySlotKind } from '../utils/amsHelpers';
  74. import type { PlateMetadata } from '../types/plates';
  75. import { Card } from '../components/Card';
  76. import { FilamentSwatch } from '../components/FilamentSwatch';
  77. import { Button } from '../components/Button';
  78. import { ConfirmModal } from '../components/ConfirmModal';
  79. import { PrintModal } from '../components/PrintModal';
  80. import { useToast } from '../contexts/ToastContext';
  81. import { useAuth } from '../contexts/AuthContext';
  82. import { QueueStatsBar } from '../components/QueueStatsBar';
  83. import { CompactHistoryRow } from '../components/CompactHistoryRow';
  84. import { QueueTimelineView } from '../components/QueueTimelineView';
  85. import { compareQueueOrder } from '../utils/queueOrder';
  86. import { BatchOrdersView } from '../components/BatchOrdersView';
  87. import { buildLoadedFilaments, type LoadedFilament } from '../hooks/useFilamentMapping';
  88. type QueueFilamentDisplay = {
  89. slotId: number;
  90. type: string;
  91. color: string;
  92. colorName: string;
  93. slotLabel?: string;
  94. spoolName?: string;
  95. extraColors?: string;
  96. effectType?: string;
  97. subtype?: string;
  98. /** The stored mapping names a slot the printer reports as empty. */
  99. emptySlot?: boolean;
  100. };
  101. /**
  102. * Slot label for a mapped tray the printer positively reports as empty.
  103. *
  104. * The scheduler dispatches a stored mapping as-is, so a spool unloaded after
  105. * queueing leaves the job pointed at an empty slot. Returns undefined when the
  106. * status doesn't describe that slot (offline, still loading, unit removed) or
  107. * when the slot may still hold an unconfigured spool (a non-RFID spool has no
  108. * tray_type either, #2527), so the card only warns on a positive finding.
  109. */
  110. function emptyMappedSlotLabel(status: PrinterStatus | undefined, trayId: number): string | undefined {
  111. // The external holder reports no presence signal (the status route sends
  112. // vt_tray without state / exists), so its emptiness can't be confirmed.
  113. if (!status?.connected || trayId >= 254) return undefined;
  114. const isHt = trayId >= 128;
  115. const amsId = isHt ? trayId : Math.floor(trayId / 4);
  116. const slot = isHt ? 0 : trayId % 4;
  117. const unit = status.ams?.find((ams) => ams.id === amsId);
  118. const tray = isHt ? unit?.tray[0] : unit?.tray.find((candidate) => candidate.id === slot);
  119. if (getEmptySlotKind(tray) !== 'physical') return undefined;
  120. return formatSlotLabel(amsId, slot, isHt, false);
  121. }
  122. /**
  123. * The backup tray each mapped tray handed over to during the running print.
  124. *
  125. * With AMS Filament Backup on, a spool that runs out is replaced by an identical
  126. * one in another slot, and the job's stored mapping still names the empty slot.
  127. * The printer's tray log shows the switch: a tray the mapping doesn't name, right
  128. * after the tray it took over from. A backup that runs out in turn hands over
  129. * again, so the chain resolves to the slot the mapping named.
  130. */
  131. function backupTrays(mapping: number[] | null | undefined, log: [number, number][] | undefined): Map<number, number> {
  132. const backups = new Map<number, number>();
  133. if (!mapping?.length || !log?.length) return backups;
  134. const mapped = new Set(mapping.filter((tray) => tray >= 0));
  135. // Backup tray -> the mapped tray it stands in for.
  136. const standsInFor = new Map<number, number>();
  137. let previous: number | undefined;
  138. for (const [tray] of log) {
  139. if (previous !== undefined && !mapped.has(tray) && !standsInFor.has(tray)) {
  140. const original = mapped.has(previous) ? previous : standsInFor.get(previous);
  141. if (original !== undefined) {
  142. standsInFor.set(tray, original);
  143. backups.set(original, tray);
  144. }
  145. }
  146. previous = tray;
  147. }
  148. return backups;
  149. }
  150. function queueFilamentLabel(filament: QueueFilamentDisplay): string {
  151. return filament.slotLabel
  152. ? [
  153. filament.slotLabel,
  154. filament.spoolName || filament.type,
  155. filament.colorName,
  156. ].filter(Boolean).join(' · ')
  157. : filament.colorName;
  158. }
  159. /**
  160. * Resolve the filament colours a queued job is actually configured to use.
  161. *
  162. * Plate metadata is the source of truth for which 3MF slots the selected plate
  163. * consumes. A queue-level override replaces only its matching slot, so a
  164. * multi-colour job can mix original 3MF colours and user-selected overrides
  165. * without losing either (#3132).
  166. */
  167. function resolveQueueFilaments(
  168. item: PrintQueueItem,
  169. plates: PlateMetadata[],
  170. loadedFilaments: LoadedFilament[] = [],
  171. status?: PrinterStatus,
  172. emptyLabel = 'Empty',
  173. ): QueueFilamentDisplay[] {
  174. // A stored AMS mapping names the physical tray that will actually feed a 3MF
  175. // slot. Once its live tray data is available, that is more specific than
  176. // either the queue override or the original slice. When the printer reports
  177. // that tray as empty, keep the intended colour but say the slot is empty.
  178. // While the job prints, a slot whose spool ran out shows the backup spool the
  179. // printer switched to instead.
  180. const backups =
  181. item.status === 'printing' ? backupTrays(item.ams_mapping, status?.tray_change_log) : new Map<number, number>();
  182. const resolveSlot = (planned: QueueFilamentDisplay): QueueFilamentDisplay => {
  183. const slotId = planned.slotId;
  184. const storedTrayId = slotId > 0 ? item.ams_mapping?.[slotId - 1] : undefined;
  185. if (storedTrayId == null || storedTrayId < 0) return planned;
  186. const mappedTrayId = backups.get(storedTrayId) ?? storedTrayId;
  187. const loaded = loadedFilaments.find((filament) => filament.globalTrayId === mappedTrayId);
  188. if (loaded) {
  189. return {
  190. slotId,
  191. type: loaded.type,
  192. color: loaded.color,
  193. colorName: loaded.colorName,
  194. slotLabel: loaded.label,
  195. spoolName: loaded.spoolName,
  196. extraColors: loaded.extraColors,
  197. effectType: loaded.effectType,
  198. subtype: loaded.spoolSubtype,
  199. };
  200. }
  201. const emptySlotLabel = emptyMappedSlotLabel(status, mappedTrayId);
  202. if (emptySlotLabel) {
  203. return { ...planned, slotLabel: emptySlotLabel, spoolName: emptyLabel, emptySlot: true };
  204. }
  205. return planned;
  206. };
  207. const selectedPlate =
  208. item.plate_id != null
  209. ? plates.find((plate) => plate.index === item.plate_id)
  210. : plates[0];
  211. if (selectedPlate) {
  212. const overrides = new Map(
  213. (item.filament_overrides ?? []).map((override) => [override.slot_id, override]),
  214. );
  215. return selectedPlate.filaments
  216. .filter((filament) => filament.used_in_plate !== false && filament.used_grams > 0)
  217. .map((filament) => {
  218. const override = overrides.get(filament.slot_id);
  219. const color = override?.color ?? filament.color;
  220. const type = override?.type ?? filament.type;
  221. return resolveSlot({
  222. slotId: filament.slot_id,
  223. type,
  224. color,
  225. colorName: override?.color_name?.trim() || getColorName(color, type),
  226. });
  227. });
  228. }
  229. // The queue row can render before plate metadata arrives (or an old source
  230. // may no longer expose it). Prefer a resolved physical tray when possible,
  231. // then explicit queue overrides because they describe the user's intention.
  232. if (item.filament_overrides?.length) {
  233. return item.filament_overrides.map((override) =>
  234. resolveSlot({
  235. slotId: override.slot_id,
  236. type: override.type,
  237. color: override.color,
  238. colorName:
  239. override.color_name?.trim() ||
  240. getColorName(override.color, override.type),
  241. }),
  242. );
  243. }
  244. // Last-resort compatibility fallback for older/simpler queue responses.
  245. if (item.filament_color) {
  246. return [
  247. resolveSlot({
  248. slotId: 1,
  249. type: item.filament_type ?? '',
  250. color: item.filament_color,
  251. colorName: getColorName(item.filament_color, item.filament_type),
  252. }),
  253. ];
  254. }
  255. return [];
  256. }
  257. function formatWeight(g: number, useKg = false): string {
  258. if (useKg && g >= 1000) return `${(g / 1000).toFixed(1)}kg`;
  259. return `${Math.round(g)}g`;
  260. }
  261. function StatusBadge({ status, waitingReason, printerState, t }: { status: PrintQueueItem['status']; waitingReason?: string | null; printerState?: string | null; t: (key: string) => string }) {
  262. // Special case: pending with waiting_reason shows as "Waiting"
  263. if (status === 'pending' && waitingReason) {
  264. return (
  265. <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-purple-700 dark:text-purple-400 bg-purple-50 dark:bg-purple-400/10 border-purple-200 dark:border-purple-400/20">
  266. <Clock className="w-3.5 h-3.5" />
  267. {t('queue.status.waiting')}
  268. </span>
  269. );
  270. }
  271. // Special case: printing but printer is paused
  272. if (status === 'printing' && printerState === 'PAUSE') {
  273. return (
  274. <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-yellow-700 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-400/10 border-yellow-200 dark:border-yellow-400/20">
  275. <Pause className="w-3.5 h-3.5" />
  276. {t('queue.status.paused')}
  277. </span>
  278. );
  279. }
  280. const config = {
  281. pending: { icon: Clock, color: 'text-status-warning bg-status-warning/10 border-status-warning/20', label: t('queue.status.pending') },
  282. printing: { icon: Play, color: 'text-blue-700 dark:text-blue-400 bg-blue-50 dark:bg-blue-400/10 border-blue-200 dark:border-blue-400/20', label: t('queue.status.printing') },
  283. completed: { icon: CheckCircle, color: 'text-status-ok bg-status-ok/10 border-status-ok/20', label: t('queue.status.completed') },
  284. failed: { icon: XCircle, color: 'text-status-error bg-status-error/10 border-status-error/20', label: t('queue.status.failed') },
  285. skipped: { icon: SkipForward, color: 'text-orange-700 dark:text-orange-400 bg-orange-50 dark:bg-orange-400/10 border-orange-200 dark:border-orange-400/20', label: t('queue.status.skipped') },
  286. cancelled: { icon: X, color: 'text-gray-400 bg-gray-400/10 border-gray-400/20', label: t('queue.status.cancelled') },
  287. };
  288. const { icon: Icon, color, label } = config[status];
  289. return (
  290. <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${color}`}>
  291. <Icon className="w-3.5 h-3.5" />
  292. {label}
  293. </span>
  294. );
  295. }
  296. // Bulk edit modal for multiple queue items
  297. function BulkEditModal({
  298. selectedCount,
  299. printers,
  300. onSave,
  301. onClose,
  302. isSaving,
  303. canControlPrinter,
  304. hasGcodeSnippets,
  305. t,
  306. }: {
  307. selectedCount: number;
  308. printers: { id: number; name: string; nozzle_count?: number }[];
  309. onSave: (data: Partial<PrintQueueBulkUpdate>) => void;
  310. onClose: () => void;
  311. isSaving: boolean;
  312. canControlPrinter: boolean;
  313. hasGcodeSnippets: boolean;
  314. t: (key: string, options?: Record<string, unknown>) => string;
  315. }) {
  316. const [printerId, setPrinterId] = useState<number | null | 'unchanged'>('unchanged');
  317. const [manualStart, setManualStart] = useState<boolean | 'unchanged'>('unchanged');
  318. const [autoOffAfter, setAutoOffAfter] = useState<boolean | 'unchanged'>('unchanged');
  319. const [requirePreviousSuccess, setRequirePreviousSuccess] = useState<boolean | 'unchanged'>('unchanged');
  320. const [gcodeInjection, setGcodeInjection] = useState<boolean | 'unchanged'>('unchanged');
  321. const [bedLevelling, setBedLevelling] = useState<CalibrationMode | 'unchanged'>('unchanged');
  322. const [flowCali, setFlowCali] = useState<CalibrationMode | 'unchanged'>('unchanged');
  323. const [vibrationCali, setVibrationCali] = useState<boolean | 'unchanged'>('unchanged');
  324. const [layerInspect, setLayerInspect] = useState<boolean | 'unchanged'>('unchanged');
  325. const [timelapse, setTimelapse] = useState<boolean | 'unchanged'>('unchanged');
  326. const [useAms, setUseAms] = useState<boolean | 'unchanged'>('unchanged');
  327. const [confirmOutcome, setConfirmOutcome] = useState<boolean | 'unchanged'>('unchanged');
  328. const [nozzleOffsetCali, setNozzleOffsetCali] = useState<CalibrationMode | 'unchanged'>('unchanged');
  329. // Show the dual-nozzle-only toggle when the user has at least one
  330. // dual-nozzle printer registered (H2D/H2D Pro/H2C/X2D). Single-nozzle
  331. // queues never see it — the MQTT layer ignores the field anyway.
  332. const hasDualNozzlePrinter = printers.some(p => p.nozzle_count === 2);
  333. const handleSave = () => {
  334. const data: Partial<PrintQueueBulkUpdate> = {};
  335. if (printerId !== 'unchanged') data.printer_id = printerId;
  336. if (manualStart !== 'unchanged') data.manual_start = manualStart;
  337. if (autoOffAfter !== 'unchanged') data.auto_off_after = autoOffAfter;
  338. if (requirePreviousSuccess !== 'unchanged') data.require_previous_success = requirePreviousSuccess;
  339. if (gcodeInjection !== 'unchanged') data.gcode_injection = gcodeInjection;
  340. if (bedLevelling !== 'unchanged') data.bed_levelling = bedLevelling;
  341. if (flowCali !== 'unchanged') data.flow_cali = flowCali;
  342. if (vibrationCali !== 'unchanged') data.vibration_cali = vibrationCali;
  343. if (layerInspect !== 'unchanged') data.layer_inspect = layerInspect;
  344. if (timelapse !== 'unchanged') data.timelapse = timelapse;
  345. if (useAms !== 'unchanged') data.use_ams = useAms;
  346. if (confirmOutcome !== 'unchanged') data.confirm_outcome = confirmOutcome;
  347. if (nozzleOffsetCali !== 'unchanged') data.nozzle_offset_cali = nozzleOffsetCali;
  348. onSave(data);
  349. };
  350. const hasChanges = printerId !== 'unchanged' || manualStart !== 'unchanged' || autoOffAfter !== 'unchanged' ||
  351. requirePreviousSuccess !== 'unchanged' || bedLevelling !== 'unchanged' || flowCali !== 'unchanged' ||
  352. vibrationCali !== 'unchanged' || layerInspect !== 'unchanged' || timelapse !== 'unchanged' || useAms !== 'unchanged' ||
  353. confirmOutcome !== 'unchanged' || nozzleOffsetCali !== 'unchanged' || gcodeInjection !== 'unchanged';
  354. return (
  355. <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
  356. <div className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto">
  357. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  358. <h2 className="text-lg font-semibold text-white">
  359. {t('queue.bulkEdit.title', { count: selectedCount })}
  360. </h2>
  361. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  362. <X className="w-5 h-5 text-bambu-gray" />
  363. </button>
  364. </div>
  365. <div className="p-4 space-y-4">
  366. <p className="text-sm text-bambu-gray">
  367. {t('queue.bulkEdit.description')}
  368. </p>
  369. {/* Printer Assignment */}
  370. <div>
  371. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printer')}</label>
  372. <select
  373. value={printerId === null ? 'null' : printerId === 'unchanged' ? 'unchanged' : String(printerId)}
  374. onChange={(e) => {
  375. const val = e.target.value;
  376. if (val === 'unchanged') setPrinterId('unchanged');
  377. else if (val === 'null') setPrinterId(null);
  378. else setPrinterId(Number(val));
  379. }}
  380. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  381. >
  382. <option value="unchanged">{t('queue.bulkEdit.noChange')}</option>
  383. <option value="null">{t('queue.filter.unassigned')}</option>
  384. {printers.map(p => (
  385. <option key={p.id} value={p.id}>{p.name}</option>
  386. ))}
  387. </select>
  388. </div>
  389. {/* Queue Options */}
  390. <div>
  391. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.queueOptions')}</label>
  392. <div className="space-y-2">
  393. <TriStateToggle label={t('queue.bulkEdit.staged')} value={manualStart} onChange={setManualStart} t={t} />
  394. <TriStateToggle label={t('queue.bulkEdit.autoPowerOff')} value={autoOffAfter} onChange={setAutoOffAfter} disabled={!canControlPrinter} t={t} />
  395. <TriStateToggle label={t('queue.bulkEdit.requirePrevious')} value={requirePreviousSuccess} onChange={setRequirePreviousSuccess} t={t} />
  396. {/* Same gate as the print modal's checkbox (#3058): hidden until an
  397. admin has saved a snippet for some printer model, so the toggle
  398. never promises an injection that has nothing to inject. */}
  399. {hasGcodeSnippets && (
  400. <TriStateToggle label={t('queue.bulkEdit.gcodeInjection')} value={gcodeInjection} onChange={setGcodeInjection} t={t} />
  401. )}
  402. </div>
  403. </div>
  404. {/* Print Options */}
  405. <div>
  406. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printOptions')}</label>
  407. <div className="space-y-2">
  408. <CalibrationModeToggle label={t('queue.bulkEdit.bedLevelling')} value={bedLevelling} onChange={setBedLevelling} t={t} />
  409. <CalibrationModeToggle label={t('queue.bulkEdit.flowCalibration')} value={flowCali} onChange={setFlowCali} t={t} />
  410. <TriStateToggle label={t('queue.bulkEdit.vibrationCalibration')} value={vibrationCali} onChange={setVibrationCali} t={t} />
  411. <TriStateToggle label={t('queue.bulkEdit.layerInspection')} value={layerInspect} onChange={setLayerInspect} t={t} />
  412. <TriStateToggle label={t('queue.bulkEdit.timelapse')} value={timelapse} onChange={setTimelapse} t={t} />
  413. <TriStateToggle label={t('queue.bulkEdit.useAms')} value={useAms} onChange={setUseAms} t={t} />
  414. <TriStateToggle label={t('queue.bulkEdit.confirmOutcome')} value={confirmOutcome} onChange={setConfirmOutcome} t={t} />
  415. {hasDualNozzlePrinter && (
  416. <CalibrationModeToggle label={t('queue.bulkEdit.nozzleOffsetCali')} value={nozzleOffsetCali} onChange={setNozzleOffsetCali} t={t} />
  417. )}
  418. </div>
  419. </div>
  420. </div>
  421. <div className="flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
  422. <Button variant="secondary" onClick={onClose}>{t('common.cancel')}</Button>
  423. <Button
  424. onClick={handleSave}
  425. disabled={!hasChanges || isSaving}
  426. >
  427. {isSaving ? t('common.saving') : t('queue.bulkEdit.applyChanges')}
  428. </Button>
  429. </div>
  430. </div>
  431. </div>
  432. );
  433. }
  434. // Tri-state toggle for bulk edit (unchanged / on / off)
  435. function TriStateToggle({
  436. label,
  437. value,
  438. onChange,
  439. disabled,
  440. t,
  441. }: {
  442. label: string;
  443. value: boolean | 'unchanged';
  444. onChange: (val: boolean | 'unchanged') => void;
  445. disabled?: boolean;
  446. t: (key: string) => string;
  447. }) {
  448. return (
  449. <div className={`flex items-center justify-between py-1 ${disabled ? 'opacity-50' : ''}`}>
  450. <span className="text-sm text-bambu-gray">{label}</span>
  451. <div className="flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5">
  452. <button
  453. onClick={() => onChange('unchanged')}
  454. disabled={disabled}
  455. className={`px-2 py-1 text-xs rounded ${value === 'unchanged' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'} disabled:cursor-not-allowed`}
  456. >
  457. —
  458. </button>
  459. <button
  460. onClick={() => onChange(false)}
  461. disabled={disabled}
  462. className={`px-2 py-1 text-xs rounded ${value === false ? 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' : 'text-bambu-gray hover:text-white'} disabled:cursor-not-allowed`}
  463. >
  464. {t('common.off')}
  465. </button>
  466. <button
  467. onClick={() => onChange(true)}
  468. disabled={disabled}
  469. className={`px-2 py-1 text-xs rounded ${value === true ? 'bg-bambu-green/20 text-bambu-green' : 'text-bambu-gray hover:text-white'} disabled:cursor-not-allowed`}
  470. >
  471. {t('common.on')}
  472. </button>
  473. </div>
  474. </div>
  475. );
  476. }
  477. // Four-state selector for the tri-state calibration options in bulk edit
  478. // (unchanged / off / auto / on). Mirrors TriStateToggle's chrome.
  479. function CalibrationModeToggle({
  480. label,
  481. value,
  482. onChange,
  483. t,
  484. }: {
  485. label: string;
  486. value: CalibrationMode | 'unchanged';
  487. onChange: (val: CalibrationMode | 'unchanged') => void;
  488. t: (key: string) => string;
  489. }) {
  490. const modes: Array<{ key: CalibrationMode | 'unchanged'; label: string; active: string }> = [
  491. { key: 'unchanged', label: '—', active: 'bg-bambu-dark-tertiary text-white' },
  492. { key: 'off', label: t('settings.calibrationMode_off'), active: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' },
  493. { key: 'auto', label: t('settings.calibrationMode_auto'), active: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400' },
  494. { key: 'on', label: t('settings.calibrationMode_on'), active: 'bg-bambu-green/20 text-bambu-green' },
  495. ];
  496. return (
  497. <div className="flex items-center justify-between py-1">
  498. <span className="text-sm text-bambu-gray">{label}</span>
  499. <div className="flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5">
  500. {modes.map(({ key, label: modeLabel, active }) => (
  501. <button
  502. key={key}
  503. onClick={() => onChange(key)}
  504. className={`px-2 py-1 text-xs rounded ${value === key ? active : 'text-bambu-gray hover:text-white'}`}
  505. >
  506. {modeLabel}
  507. </button>
  508. ))}
  509. </div>
  510. </div>
  511. );
  512. }
  513. // Sortable queue item for drag and drop
  514. function SortableQueueItem({
  515. item,
  516. position,
  517. onEdit,
  518. onCancel,
  519. onRemove,
  520. onStop,
  521. onRequeue,
  522. onStart,
  523. onMoveUp,
  524. onMoveDown,
  525. timeFormat = 'system',
  526. isSelected = false,
  527. onToggleSelect,
  528. hasPermission,
  529. canModify,
  530. printerState,
  531. showEta = false,
  532. etaNow,
  533. t,
  534. }: {
  535. item: PrintQueueItem;
  536. position?: number;
  537. onEdit: () => void;
  538. onCancel: () => void;
  539. onRemove: () => void;
  540. onStop: () => void;
  541. onRequeue: () => void;
  542. onStart: () => void;
  543. // Mobile tap-to-reorder (#2667). Undefined = at a list boundary (button
  544. // shown disabled) or reordering isn't available; the desktop drag handle
  545. // is unaffected. Move one step among siblings, then persist via reorder.
  546. onMoveUp?: () => void;
  547. onMoveDown?: () => void;
  548. timeFormat?: TimeFormat;
  549. isSelected?: boolean;
  550. onToggleSelect?: () => void;
  551. hasPermission: (permission: Permission) => boolean;
  552. canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
  553. printerState?: string | null;
  554. // Whether this item qualifies for an "if started now" ETA (#2740), and the
  555. // instant to measure it from. Both are decided by the page so every row on
  556. // screen quotes the same clock.
  557. showEta?: boolean;
  558. etaNow?: number;
  559. t: (key: string, options?: Record<string, unknown>) => string;
  560. }) {
  561. const { hasAnyPermission } = useAuth();
  562. // Their waiting jobs are started by someone who manages the queue (#1620)
  563. const awaitingReview = !hasAnyPermission('queue:update_all', 'queue:start_unreviewed');
  564. const hasPhysicalAmsMapping =
  565. item.printer_id != null && (item.ams_mapping?.some((trayId) => trayId >= 0) ?? false);
  566. // Printing rows already need live status for progress. A queued item with a
  567. // stored AMS mapping also needs it so the card can turn global tray ids into
  568. // the actual slot / colour that will feed the print (#3132). React Query
  569. // deduplicates rows sharing a printer.
  570. const { data: status } = useQuery({
  571. queryKey: ['printerStatus', item.printer_id],
  572. queryFn: () => api.getPrinterStatus(item.printer_id!),
  573. refetchInterval: printerState === 'printing' ? 30000 : false,
  574. enabled: item.printer_id != null && (printerState === 'printing' || hasPhysicalAmsMapping),
  575. });
  576. // Inventory identity is display-only: printer telemetry knows the tray colour
  577. // and material but not that a third-party spool is e.g. "eSUN PLA Basic".
  578. // Reuse the same payload / key as PrintModal so a mapped queue row names the
  579. // physical spool consistently with the mapping picker.
  580. const { data: inventoryRemain } = useQuery({
  581. queryKey: ['printer-inventory-remain', item.printer_id],
  582. queryFn: () => api.getInventoryRemain(item.printer_id!),
  583. enabled: hasPhysicalAmsMapping,
  584. staleTime: 30 * 1000,
  585. });
  586. const slotSpools = useMemo(() => {
  587. const slots = inventoryRemain?.slot_materials;
  588. if (!slots?.length) return undefined;
  589. const map = new Map<number, SlotSpoolIdentity>();
  590. slots.forEach((slot) => {
  591. if (slot.spool) map.set(slot.global_tray_id, slot.spool);
  592. });
  593. return map.size > 0 ? map : undefined;
  594. }, [inventoryRemain]);
  595. const loadedFilaments = useMemo(
  596. () => buildLoadedFilaments(status, slotSpools),
  597. [status, slotSpools],
  598. );
  599. // Determine if we're printing a library file
  600. const isLibraryFile = !!item.library_file_id && !item.archive_id;
  601. // Fetch archive plate details. Skip when the linked archive has been
  602. // soft-deleted (#1348 follow-up): its 3MF is gone from disk so the
  603. // /plates endpoint just 404-storms the queue page.
  604. const { data: archivePlatesData } = useQuery({
  605. queryKey: ['archive-plates', item.archive_id],
  606. queryFn: () => api.getArchivePlates(item.archive_id!),
  607. enabled: !!item.archive_id && !isLibraryFile && !item.archive_deleted,
  608. });
  609. // Fetch library file plate details
  610. const { data: libraryPlatesData } = useQuery({
  611. queryKey: ['library-file-plates', item.library_file_id],
  612. queryFn: () => api.getLibraryFilePlates(item.library_file_id!),
  613. enabled: isLibraryFile && !!item.library_file_id,
  614. });
  615. // Combine plates data from either source
  616. const platesData = isLibraryFile ? libraryPlatesData : archivePlatesData;
  617. const plates = platesData?.plates ?? [];
  618. const queueFilaments = resolveQueueFilaments(item, plates, loadedFilaments, status, t('ams.empty'));
  619. const canReorder = hasPermission('queue:reorder');
  620. const {
  621. attributes,
  622. listeners,
  623. setNodeRef,
  624. transform,
  625. transition,
  626. isDragging,
  627. } = useSortable({ id: item.id, disabled: item.status !== 'pending' || !canReorder });
  628. const style = {
  629. transform: CSS.Transform.toString(transform),
  630. transition,
  631. };
  632. const isPrinting = item.status === 'printing';
  633. const isPending = item.status === 'pending';
  634. const isHistory = ['completed', 'failed', 'skipped', 'cancelled'].includes(item.status);
  635. // This is an "if started now" estimate, not a cumulative queue forecast, so
  636. // it is only shown for items the page determined could actually start now
  637. // (see etaEligibleIds). etaNow is the caller's ticking clock — deriving the
  638. // ETA from it rather than from Date.now() keeps this render deterministic and
  639. // stops the value freezing at first paint.
  640. const queueItemEta =
  641. isPending && showEta && item.print_time_seconds != null && item.print_time_seconds > 0
  642. ? formatETA(item.print_time_seconds / 60, timeFormat, t, etaNow)
  643. : null;
  644. const isMobileSelectable = isPending && onToggleSelect;
  645. return (
  646. <div
  647. ref={setNodeRef}
  648. style={style}
  649. className={`
  650. group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
  651. border-l-[3px] ${
  652. isPrinting ? 'border-l-blue-500' :
  653. isPending ? 'border-l-yellow-500' :
  654. item.status === 'completed' ? 'border-l-emerald-500' :
  655. item.status === 'failed' ? 'border-l-red-500' :
  656. 'border-l-gray-500'
  657. }
  658. ${isDragging ? 'opacity-50 scale-[1.02] shadow-xl z-50' : ''}
  659. ${isPrinting ? 'border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent' : ''}
  660. ${isSelected && isMobileSelectable ? 'sm:border-bambu-dark-tertiary border-bambu-green/40' : ''}
  661. ${!isSelected && !isPrinting ? 'border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80' : ''}
  662. ${isMobileSelectable ? 'cursor-pointer sm:cursor-default' : ''}
  663. `}
  664. onClick={isMobileSelectable ? () => {
  665. if (window.innerWidth < 640) onToggleSelect();
  666. } : undefined}
  667. >
  668. {/* Mobile selected left accent bar */}
  669. {isMobileSelectable && isSelected && (
  670. <div className="sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green" />
  671. )}
  672. <div className="flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4">
  673. {/* Mobile reorder arrows (#2667). The desktop drag handle is hidden on
  674. phones and touch-drag is unreliable there, so pending rows get
  675. tap-to-move up/down controls instead. Shown only below `sm`. */}
  676. {isPending && (onMoveUp || onMoveDown) && (
  677. <div
  678. className="flex sm:hidden flex-col shrink-0 -my-1"
  679. onClick={(e) => e.stopPropagation()}
  680. >
  681. <button
  682. type="button"
  683. onClick={onMoveUp}
  684. disabled={!onMoveUp}
  685. title={t('queue.moveUp')}
  686. aria-label={t('queue.moveUp')}
  687. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  688. >
  689. <ChevronUp className="w-5 h-5" />
  690. </button>
  691. <button
  692. type="button"
  693. onClick={onMoveDown}
  694. disabled={!onMoveDown}
  695. title={t('queue.moveDown')}
  696. aria-label={t('queue.moveDown')}
  697. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  698. >
  699. <ChevronDown className="w-5 h-5" />
  700. </button>
  701. </div>
  702. )}
  703. {/* Mobile selection indicator — left accent bar only, no tick */}
  704. {/* Selection checkbox for pending items - hidden on mobile, tap card instead */}
  705. {isPending && onToggleSelect && (
  706. <button
  707. onClick={(e) => {
  708. e.stopPropagation();
  709. onToggleSelect();
  710. }}
  711. className={`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${
  712. isSelected
  713. ? 'bg-bambu-green border-bambu-green text-white'
  714. : 'border-white/30 bg-black/30 hover:border-bambu-green/50'
  715. }`}
  716. >
  717. {isSelected && <Check className="w-4 h-4" />}
  718. </button>
  719. )}
  720. {/* Drag handle or position number - hidden on mobile */}
  721. {isPending ? (
  722. <div
  723. {...attributes}
  724. {...listeners}
  725. className="hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-none shrink-0"
  726. >
  727. <GripVertical className="w-4 h-4 text-bambu-gray" />
  728. </div>
  729. ) : position !== undefined ? (
  730. <div className="hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium shrink-0">
  731. #{position}
  732. </div>
  733. ) : (
  734. <div className="hidden sm:block w-8 shrink-0" />
  735. )}
  736. {/* Thumbnail - use plate-specific thumbnail if plate_id is set */}
  737. <div className="w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden">
  738. {item.archive_thumbnail ? (
  739. <img
  740. src={
  741. item.plate_id != null
  742. ? api.getArchivePlateThumbnail(item.archive_id!, item.plate_id)
  743. : api.getArchiveThumbnail(item.archive_id!)
  744. }
  745. alt=""
  746. className="w-full h-full object-cover"
  747. />
  748. ) : item.library_file_thumbnail ? (
  749. <img
  750. src={
  751. item.plate_id != null
  752. ? api.getLibraryFilePlateThumbnail(item.library_file_id!, item.plate_id)
  753. : api.getLibraryFileThumbnailUrl(item.library_file_id!)
  754. }
  755. alt=""
  756. className="w-full h-full object-cover"
  757. />
  758. ) : (
  759. <div className="w-full h-full flex items-center justify-center text-bambu-gray">
  760. <Layers className="w-5 h-5 sm:w-6 sm:h-6" />
  761. </div>
  762. )}
  763. </div>
  764. {/* Info */}
  765. <div className="flex-1 min-w-0">
  766. <div className="flex items-center gap-2 mb-1">
  767. <p className="text-sm sm:text-base text-white font-medium truncate">
  768. {queueItemDisplayName(item, (n) => t('common.plusNMore', { count: n }))}
  769. {(platesData?.is_multi_plate ?? false) && item.plate_id !== undefined && item.plate_id !== null && ` • ${plates.find(plate => plate.index === item.plate_id)?.name || t('queue.plateNumber', { index: item.plate_id })}`}
  770. </p>
  771. {item.archive_id ? (
  772. <Link
  773. to={`/archives?highlight=${item.archive_id}`}
  774. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  775. title={t('queue.viewArchive')}
  776. >
  777. <ExternalLink className="w-3.5 h-3.5" />
  778. </Link>
  779. ) : item.library_file_id ? (
  780. <Link
  781. to={`/library?highlight=${item.library_file_id}`}
  782. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  783. title={t('queue.viewInFileManager')}
  784. >
  785. <ExternalLink className="w-3.5 h-3.5" />
  786. </Link>
  787. ) : null}
  788. {item.batch_name && (
  789. <span className="flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-cyan-100 dark:bg-cyan-500/20 text-cyan-700 dark:text-cyan-300 rounded border border-cyan-300 dark:border-cyan-500/30">
  790. {item.batch_name}
  791. </span>
  792. )}
  793. </div>
  794. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray">
  795. <span className={`flex items-center gap-1 sm:gap-1.5 ${item.printer_id === null && !item.target_model ? 'text-orange-700 dark:text-orange-400' : ''} ${item.target_model && !item.printer_id ? 'text-blue-700 dark:text-blue-400' : ''}`}>
  796. <Printer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  797. <span className="truncate max-w-[120px] sm:max-w-none">
  798. {/* A cross-model item (#671) is waiting on several models at once.
  799. Showing only target_model would name whichever candidate is
  800. first and read as a lie the moment the other one runs. */}
  801. {(item.variants?.length ?? 0) > 1 && !item.printer_id
  802. ? `${t('queue.filter.any')} ${item.variants!.map(v => v.target_model).join(' / ')}${item.target_location ? ` @ ${item.target_location}` : ''}`
  803. : item.target_model && !item.printer_id
  804. ? `${t('queue.filter.any')} ${item.target_model}${item.target_location ? ` @ ${item.target_location}` : ''}${item.required_filament_types?.length ? ` (${item.required_filament_types.join(', ')})` : ''}`
  805. : item.printer_id === null
  806. ? t('queue.filter.unassigned')
  807. : (item.printer_name || `${t('common.printer')} #${item.printer_id}`)}
  808. </span>
  809. </span>
  810. {item.print_time_seconds && (
  811. <span className="flex items-center gap-1 sm:gap-1.5">
  812. <Timer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  813. {formatDuration(item.print_time_seconds)}
  814. </span>
  815. )}
  816. {queueItemEta && (
  817. <span
  818. data-testid="queue-item-eta"
  819. className="text-bambu-green font-medium"
  820. title={t('queue.time.etaIfStartedNow')}
  821. >
  822. ETA {queueItemEta}
  823. </span>
  824. )}
  825. {item.filament_used_grams && (
  826. <span className="flex items-center gap-1 sm:gap-1.5">
  827. <Weight className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  828. {formatWeight(item.filament_used_grams)}
  829. </span>
  830. )}
  831. {queueFilaments.length > 2 ? (
  832. <span
  833. data-testid="queue-filament-compact"
  834. className="flex items-center gap-0.5 flex-shrink-0"
  835. title={queueFilaments.map(queueFilamentLabel).join('\n')}
  836. // The tooltip needs a hover; touch screens and screen readers
  837. // get the same lines through the accessible name instead.
  838. role="img"
  839. aria-label={queueFilaments.map(queueFilamentLabel).join(', ')}
  840. >
  841. {queueFilaments.map((filament) => (
  842. <FilamentSwatch
  843. key={`filament-${filament.slotId}`}
  844. rgba={filament.color}
  845. extraColors={filament.extraColors}
  846. effectType={filament.effectType}
  847. subtype={filament.subtype}
  848. className="w-2.5 h-2.5 sm:w-3 sm:h-3 pointer-events-none"
  849. effectSize="table"
  850. />
  851. ))}
  852. {queueFilaments.some((filament) => filament.emptySlot) && (
  853. <AlertCircle
  854. className="w-3 h-3 ml-0.5 text-yellow-700 dark:text-yellow-400"
  855. aria-hidden="true"
  856. />
  857. )}
  858. </span>
  859. ) : (
  860. queueFilaments.map((filament) => {
  861. const mappedLabel = queueFilamentLabel(filament);
  862. return (
  863. <span
  864. key={`filament-${filament.slotId}`}
  865. className="flex items-center gap-1 sm:gap-1.5 min-w-0"
  866. title={mappedLabel}
  867. >
  868. <FilamentSwatch
  869. rgba={filament.color}
  870. extraColors={filament.extraColors}
  871. effectType={filament.effectType}
  872. subtype={filament.subtype}
  873. className="w-3 h-3 sm:w-3.5 sm:h-3.5"
  874. effectSize="table"
  875. />
  876. <span
  877. className={`truncate max-w-[110px] sm:max-w-[260px]${
  878. filament.emptySlot ? ' text-yellow-700 dark:text-yellow-400' : ''
  879. }`}
  880. >
  881. {mappedLabel}
  882. </span>
  883. </span>
  884. );
  885. })
  886. )}
  887. {(() => {
  888. // Build plate badge so the user knows which plate to mount before
  889. // walking to the printer (#1281). Hidden when the 3MF doesn't
  890. // carry curr_bed_type or the slicer used an unknown label.
  891. const bed = getBedTypeInfo(item.bed_type);
  892. if (!bed) return null;
  893. return (
  894. <span className="flex items-center gap-1 sm:gap-1.5" title={bed.label}>
  895. <img src={bed.icon} alt="" className="w-3.5 h-3.5 sm:w-4 sm:h-4 object-contain" />
  896. <span className="truncate max-w-[120px]">{bed.label}</span>
  897. </span>
  898. );
  899. })()}
  900. {item.created_by_username && (
  901. <span className="hidden sm:flex items-center gap-1.5" title={t('queue.addedBy', { name: item.created_by_username })}>
  902. <User className="w-3.5 h-3.5" />
  903. {item.created_by_username}
  904. </span>
  905. )}
  906. {isPending && !item.manual_start && (
  907. <span className="flex items-center gap-1.5">
  908. <Clock className="w-3.5 h-3.5" />
  909. {/* An item with no scheduled time used to render as "ASAP", which is the
  910. name of a dispatch mode the user may well not have picked -- ASAP and
  911. Queue differ only in insert position, and neither is stored on the
  912. item, so the two are indistinguishable here. Someone who chose Queue
  913. saw their row labelled ASAP and read it as Bambuddy overriding them
  914. (#2557, #3018). This column answers "when does it run", so it now says
  915. that instead of borrowing a mode name. */}
  916. {item.scheduled_time
  917. ? ((parseUTCDate(item.scheduled_time)?.getTime() ?? 0) - Date.now() < -60000
  918. ? t?.('queue.time.overdue') ?? 'Overdue'
  919. : formatRelativeTime(item.scheduled_time, timeFormat, t))
  920. : t?.('queue.time.whenFree') ?? 'When a printer is free'}
  921. </span>
  922. )}
  923. </div>
  924. {/* Options badges */}
  925. <div className="flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2">
  926. {item.manual_start && (
  927. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-400 rounded-full border border-purple-200 dark:border-purple-500/20 flex items-center gap-1">
  928. <Hand className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  929. {awaitingReview ? t('queue.badges.awaitingReview') : t('queue.badges.staged')}
  930. </span>
  931. )}
  932. {item.require_previous_success && (
  933. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-50 dark:bg-orange-500/10 text-orange-700 dark:text-orange-400 rounded-full border border-orange-200 dark:border-orange-500/20">
  934. {t('queue.badges.requiresPrevious')}
  935. </span>
  936. )}
  937. {item.auto_off_after && (
  938. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 rounded-full border border-blue-200 dark:border-blue-500/20 flex items-center gap-1">
  939. <Power className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  940. {t('queue.badges.autoPowerOff')}
  941. </span>
  942. )}
  943. {item.gcode_injection && (
  944. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-50 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 rounded-full border border-emerald-200 dark:border-emerald-500/20 flex items-center gap-1">
  945. <Code className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  946. {t('queue.badges.gcodeInjection')}
  947. </span>
  948. )}
  949. {item.confirm_outcome && (
  950. <span
  951. title={t('queue.badges.confirmOutcomeTitle')}
  952. className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 rounded-full border border-green-200 dark:border-green-500/20 flex items-center gap-1"
  953. >
  954. <ThumbsUp className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  955. {t('queue.badges.confirmOutcome')}
  956. </span>
  957. )}
  958. </div>
  959. {/* Progress bar for printing items - TODO: integrate with WebSocket */}
  960. {isPrinting && status && (() => {
  961. // Gate progress/remaining/layer on printer actually running this print.
  962. // Between dispatch and RUNNING transition (H2D/P1 MQTT lag), status.progress
  963. // is stale from the previous print — showing 100% then snapping back to 0%
  964. // once the new print starts. Only trust these fields when state is active.
  965. const isActive = status.state === 'RUNNING' || status.state === 'PAUSE';
  966. const progress = isActive ? (status.progress || 0) : 0;
  967. const remaining = isActive ? status.remaining_time : null;
  968. const layerNum = isActive ? status.layer_num : null;
  969. const totalLayers = isActive ? status.total_layers : null;
  970. return (
  971. <div className="mt-2 sm:mt-3">
  972. <div className="flex items-center justify-between text-xs sm:text-sm">
  973. <div className="flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3">
  974. <div
  975. className="bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all"
  976. style={{ width: `${progress}%` }}
  977. />
  978. </div>
  979. <span className="text-white">{Math.round(progress)}%</span>
  980. </div>
  981. <div className="flex flex-wrap items-center gap-2 sm:gap-3 mt-1.5 sm:mt-2 text-[10px] sm:text-xs text-bambu-gray">
  982. {remaining != null && remaining > 0 && (
  983. <>
  984. <span className="flex items-center gap-1">
  985. <Clock className="w-3 h-3" />
  986. {formatDuration(remaining * 60)}
  987. </span>
  988. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  989. ETA {formatETA(remaining, timeFormat, t)}
  990. </span>
  991. </>
  992. )}
  993. {layerNum != null && totalLayers != null && totalLayers > 0 && (
  994. <span className="flex items-center gap-1">
  995. <Layers className="w-3 h-3" />
  996. {layerNum}/{totalLayers}
  997. </span>
  998. )}
  999. </div>
  1000. </div>
  1001. );
  1002. })()}
  1003. {/* Waiting reason for model-based assignments */}
  1004. {item.waiting_reason && item.status === 'pending' && (
  1005. <p className="text-[10px] sm:text-xs text-purple-700 dark:text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1">
  1006. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  1007. <span>{item.waiting_reason}</span>
  1008. </p>
  1009. )}
  1010. {/* Filament-short flag from the dispatch pre-flight (#1496). */}
  1011. {item.filament_short && item.status === 'pending' && (
  1012. <p
  1013. className="text-[10px] sm:text-xs text-yellow-700 dark:text-yellow-400 mt-1.5 sm:mt-2 flex items-start gap-1"
  1014. title={t('queue.filamentShort.rowTooltip')}
  1015. >
  1016. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  1017. <span>{t('queue.filamentShort.rowBadge')}</span>
  1018. </p>
  1019. )}
  1020. {/* Archive carries the slicer's own live-resolved AMS-slot pick
  1021. (extra_data.slicer_ams_mapping) — reprints of this archive reuse
  1022. the exact physical spool instead of re-deriving one. */}
  1023. {item.archive_has_slicer_ams_mapping && (
  1024. <p
  1025. className="text-[10px] sm:text-xs text-green-700 dark:text-green-400 mt-1.5 sm:mt-2 flex items-start gap-1"
  1026. title={t('queue.slicerAmsMapping.rowTooltip')}
  1027. >
  1028. <Check className="w-3 h-3 mt-0.5 flex-shrink-0" />
  1029. <span>{t('queue.slicerAmsMapping.rowBadge')}</span>
  1030. </p>
  1031. )}
  1032. {/* Error message */}
  1033. {item.error_message && (
  1034. <p className="text-[10px] sm:text-xs text-red-700 dark:text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1">
  1035. <AlertCircle className="w-3 h-3" />
  1036. {item.error_message}
  1037. </p>
  1038. )}
  1039. </div>
  1040. {/* Status badge + Actions */}
  1041. <div className="flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
  1042. <StatusBadge status={item.status} waitingReason={item.waiting_reason} printerState={printerState} t={t} />
  1043. <div className="flex items-center gap-0.5 sm:gap-1">
  1044. {isPrinting && (
  1045. <Button
  1046. variant="ghost"
  1047. size="sm"
  1048. onClick={onStop}
  1049. disabled={!canModify('queue', 'update', item.created_by_id)}
  1050. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noStopPrint') : t('queue.actions.stopPrint')}
  1051. className="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-500/10 p-1.5 sm:p-2"
  1052. >
  1053. <StopCircle className="w-4 h-4" />
  1054. </Button>
  1055. )}
  1056. {isPending && (
  1057. <>
  1058. {item.manual_start && (
  1059. <Button
  1060. variant="ghost"
  1061. size="sm"
  1062. onClick={onStart}
  1063. disabled={awaitingReview || !canModify('queue', 'update', item.created_by_id)}
  1064. title={
  1065. awaitingReview
  1066. ? t('queue.permissions.awaitingReview')
  1067. : !canModify('queue', 'update', item.created_by_id)
  1068. ? t('queue.permissions.noStartPrint')
  1069. : t('queue.actions.startPrint')
  1070. }
  1071. className="text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2"
  1072. >
  1073. <Play className="w-4 h-4" />
  1074. </Button>
  1075. )}
  1076. <Button
  1077. variant="ghost"
  1078. size="sm"
  1079. onClick={onEdit}
  1080. disabled={!canModify('queue', 'update', item.created_by_id)}
  1081. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noEdit') : t('common.edit')}
  1082. className="p-1.5 sm:p-2"
  1083. >
  1084. <Pencil className="w-4 h-4" />
  1085. </Button>
  1086. <Button
  1087. variant="ghost"
  1088. size="sm"
  1089. onClick={onCancel}
  1090. disabled={!canModify('queue', 'delete', item.created_by_id)}
  1091. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noCancel') : t('common.cancel')}
  1092. className="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-500/10 p-1.5 sm:p-2"
  1093. >
  1094. <X className="w-4 h-4" />
  1095. </Button>
  1096. </>
  1097. )}
  1098. {isHistory && (
  1099. <>
  1100. <Button
  1101. variant="ghost"
  1102. size="sm"
  1103. onClick={onRequeue}
  1104. disabled={!hasPermission('queue:create')}
  1105. title={!hasPermission('queue:create') ? t('queue.permissions.noRequeue') : t('queue.actions.requeue')}
  1106. className="text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2"
  1107. >
  1108. <RefreshCw className="w-4 h-4" />
  1109. </Button>
  1110. <Button
  1111. variant="ghost"
  1112. size="sm"
  1113. onClick={onRemove}
  1114. disabled={!canModify('queue', 'delete', item.created_by_id)}
  1115. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noRemove') : t('common.remove')}
  1116. className="p-1.5 sm:p-2"
  1117. >
  1118. <Trash2 className="w-4 h-4" />
  1119. </Button>
  1120. </>
  1121. )}
  1122. </div>
  1123. </div>
  1124. </div>
  1125. </div>
  1126. );
  1127. }
  1128. type QueueRow =
  1129. | { kind: 'item'; item: PrintQueueItem }
  1130. | { kind: 'batch'; batchId: number; batchName: string; items: PrintQueueItem[] };
  1131. interface QueueRowRenderProps {
  1132. row: QueueRow;
  1133. collapsed: boolean;
  1134. onToggleBatch?: () => void;
  1135. onUngroup?: () => void;
  1136. setEditItem: (item: PrintQueueItem) => void;
  1137. setConfirmAction: (a: { type: 'cancel' | 'remove' | 'stop'; item: PrintQueueItem }) => void;
  1138. startMutation: { mutate: (vars: { id: number; skipFilamentCheck?: boolean }) => void };
  1139. selectedItems: number[];
  1140. handleToggleSelect: (id: number) => void;
  1141. timeFormat: TimeFormat;
  1142. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1143. hasPermission: (p: any) => boolean;
  1144. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1145. canModify: (resource: any, action: any, createdById?: number | null) => boolean;
  1146. t: (key: string, options?: Record<string, unknown>) => string;
  1147. // Items that qualify for an "if started now" ETA, and the shared clock it is
  1148. // measured from (#2740).
  1149. etaEligibleIds: Set<number>;
  1150. etaNow: number;
  1151. aggregateForRows: (rows: QueueRow[]) => { count: number; time: number; weight: number };
  1152. // Mobile tap-to-reorder (#2667). onMoveUp/onMoveDown move this whole row
  1153. // (single item or batch) one step among its siblings; onMoveBlock is the
  1154. // low-level primitive SortableBatchRow uses to move a child within the
  1155. // batch. All undefined when reordering isn't available (non-manual sort).
  1156. onMoveUp?: () => void;
  1157. onMoveDown?: () => void;
  1158. onMoveBlock?: (movingIds: number[], anchorId: number, placeAfter: boolean) => void;
  1159. }
  1160. /** Renders either a single item or a collapsible batch group containing N
  1161. * sibling items. The batch parent shows aggregate stats; children render
  1162. * with the existing SortableQueueItem (only draggable inside the batch). */
  1163. function QueueRowRender(props: QueueRowRenderProps) {
  1164. const {
  1165. row,
  1166. setEditItem,
  1167. setConfirmAction,
  1168. startMutation,
  1169. selectedItems,
  1170. handleToggleSelect,
  1171. timeFormat,
  1172. hasPermission,
  1173. canModify,
  1174. t,
  1175. etaEligibleIds,
  1176. etaNow,
  1177. onMoveUp,
  1178. onMoveDown,
  1179. } = props;
  1180. if (row.kind === 'item') {
  1181. return (
  1182. <SortableQueueItem
  1183. item={row.item}
  1184. onEdit={() => setEditItem(row.item)}
  1185. onCancel={() => setConfirmAction({ type: 'cancel', item: row.item })}
  1186. onRemove={() => {}}
  1187. onStop={() => {}}
  1188. onRequeue={() => {}}
  1189. onStart={() => startMutation.mutate({ id: row.item.id })}
  1190. onMoveUp={onMoveUp}
  1191. onMoveDown={onMoveDown}
  1192. timeFormat={timeFormat}
  1193. isSelected={selectedItems.includes(row.item.id)}
  1194. onToggleSelect={() => handleToggleSelect(row.item.id)}
  1195. hasPermission={hasPermission}
  1196. canModify={canModify}
  1197. showEta={etaEligibleIds.has(row.item.id)}
  1198. etaNow={etaNow}
  1199. t={t}
  1200. />
  1201. );
  1202. }
  1203. return <SortableBatchRow {...props} />;
  1204. }
  1205. /** Batch parent header registered with dnd-kit so the whole group can be
  1206. * reordered as one unit. Drag handle lives in the header itself; children
  1207. * remain individually draggable while expanded for within-batch reorder. */
  1208. function SortableBatchRow({
  1209. row,
  1210. collapsed,
  1211. onToggleBatch,
  1212. onUngroup,
  1213. setEditItem,
  1214. setConfirmAction,
  1215. startMutation,
  1216. selectedItems,
  1217. handleToggleSelect,
  1218. timeFormat,
  1219. hasPermission,
  1220. canModify,
  1221. t,
  1222. etaEligibleIds,
  1223. etaNow,
  1224. aggregateForRows,
  1225. onMoveUp,
  1226. onMoveDown,
  1227. onMoveBlock,
  1228. }: QueueRowRenderProps) {
  1229. // Dispatcher (QueueRowRender) only mounts this with row.kind === 'batch';
  1230. // narrow up-front so the hook below can reference batchId unconditionally.
  1231. const batchRow = row as Extract<QueueRow, { kind: 'batch' }>;
  1232. const canReorder = hasPermission('queue:reorder');
  1233. const {
  1234. attributes,
  1235. listeners,
  1236. setNodeRef,
  1237. transform,
  1238. transition,
  1239. isDragging,
  1240. } = useSortable({ id: `batch-${batchRow.batchId}`, disabled: !canReorder });
  1241. const style = {
  1242. transform: CSS.Transform.toString(transform),
  1243. transition,
  1244. };
  1245. const agg = aggregateForRows([batchRow]);
  1246. const allChildIds = batchRow.items.map((i) => i.id);
  1247. const allSelected = allChildIds.length > 0 && allChildIds.every((id) => selectedItems.includes(id));
  1248. // Status rollup: worst-of-children (failed > printing > pending).
  1249. const childStatuses = new Set(batchRow.items.map((i) => i.status));
  1250. // We never put non-pending into a batch grouping but render defensively.
  1251. const rollupStatus: PrintQueueItem['status'] = childStatuses.has('failed')
  1252. ? 'failed'
  1253. : childStatuses.has('printing')
  1254. ? 'printing'
  1255. : 'pending';
  1256. const pendingChildren = batchRow.items.filter((i) => i.status === 'pending').length;
  1257. return (
  1258. <div
  1259. ref={setNodeRef}
  1260. style={style}
  1261. className={`bg-bambu-dark-secondary rounded-xl border border-l-[3px] border-l-cyan-400 border-bambu-dark-tertiary overflow-hidden ${
  1262. isDragging ? 'opacity-50 scale-[1.01] shadow-xl z-50' : ''
  1263. }`}
  1264. >
  1265. {/* Parent header */}
  1266. <div className="flex items-center gap-2 sm:gap-3 p-3 sm:p-4">
  1267. {/* Mobile reorder arrows for the whole group (#2667), mirroring the
  1268. desktop drag handle which is hidden on phones. */}
  1269. {canReorder && (onMoveUp || onMoveDown) && (
  1270. <div className="flex sm:hidden flex-col shrink-0 -my-1">
  1271. <button
  1272. type="button"
  1273. onClick={onMoveUp}
  1274. disabled={!onMoveUp}
  1275. title={t('queue.moveUp')}
  1276. aria-label={t('queue.moveUp')}
  1277. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  1278. >
  1279. <ChevronUp className="w-5 h-5" />
  1280. </button>
  1281. <button
  1282. type="button"
  1283. onClick={onMoveDown}
  1284. disabled={!onMoveDown}
  1285. title={t('queue.moveDown')}
  1286. aria-label={t('queue.moveDown')}
  1287. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  1288. >
  1289. <ChevronDown className="w-5 h-5" />
  1290. </button>
  1291. </div>
  1292. )}
  1293. <button
  1294. onClick={(e) => {
  1295. e.stopPropagation();
  1296. allChildIds.forEach((id) => {
  1297. if (allSelected && selectedItems.includes(id)) {
  1298. handleToggleSelect(id);
  1299. } else if (!allSelected && !selectedItems.includes(id)) {
  1300. handleToggleSelect(id);
  1301. }
  1302. });
  1303. }}
  1304. className={`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${
  1305. allSelected
  1306. ? 'bg-bambu-green border-bambu-green text-white'
  1307. : 'border-white/30 bg-black/30 hover:border-bambu-green/50'
  1308. }`}
  1309. title={allSelected ? t('queue.bulkEdit.deselectAll') : t('queue.bulkEdit.selectAll')}
  1310. >
  1311. {allSelected && <Check className="w-4 h-4" />}
  1312. </button>
  1313. {canReorder && (
  1314. <div
  1315. {...attributes}
  1316. {...listeners}
  1317. className="hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-none shrink-0"
  1318. title={t('queue.batch.dragGroup', { defaultValue: 'Drag group' })}
  1319. >
  1320. <GripVertical className="w-4 h-4 text-bambu-gray" />
  1321. </div>
  1322. )}
  1323. <button
  1324. onClick={onToggleBatch}
  1325. className="flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary transition-colors shrink-0"
  1326. title={collapsed ? t('queue.batch.expand') : t('queue.batch.collapse')}
  1327. >
  1328. {collapsed ? (
  1329. <ChevronRight className="w-4 h-4 text-bambu-gray" />
  1330. ) : (
  1331. <ChevronDown className="w-4 h-4 text-bambu-gray" />
  1332. )}
  1333. </button>
  1334. <div className="w-10 h-10 sm:w-12 sm:h-12 flex-shrink-0 bg-bambu-dark rounded-lg flex items-center justify-center">
  1335. {collapsed ? (
  1336. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  1337. ) : (
  1338. <PackageOpen className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  1339. )}
  1340. </div>
  1341. <div className="flex-1 min-w-0">
  1342. <div className="flex items-center gap-2 mb-1">
  1343. <p className="text-sm sm:text-base text-white font-medium truncate">{batchRow.batchName}</p>
  1344. <span className="flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-cyan-100 dark:bg-cyan-500/15 text-cyan-700 dark:text-cyan-300 rounded border border-cyan-300 dark:border-cyan-500/30">
  1345. {t('queue.batch.label', { count: agg.count })}
  1346. </span>
  1347. </div>
  1348. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray">
  1349. {agg.time > 0 && (
  1350. <span className="flex items-center gap-1 sm:gap-1.5">
  1351. <Timer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  1352. {formatDuration(agg.time)}
  1353. </span>
  1354. )}
  1355. {agg.weight > 0 && (
  1356. <span className="flex items-center gap-1 sm:gap-1.5">
  1357. <Weight className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  1358. {formatWeight(agg.weight)}
  1359. </span>
  1360. )}
  1361. {pendingChildren > 0 && rollupStatus === 'pending' && (
  1362. <span className="flex items-center gap-1 sm:gap-1.5 text-yellow-700 dark:text-yellow-400">
  1363. <Clock className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  1364. {t('queue.batch.pendingCount', { count: pendingChildren })}
  1365. </span>
  1366. )}
  1367. </div>
  1368. </div>
  1369. <div className="flex items-center gap-1 shrink-0">
  1370. {onUngroup && (
  1371. <Button
  1372. variant="ghost"
  1373. size="sm"
  1374. onClick={onUngroup}
  1375. title={t('queue.batch.ungroup')}
  1376. className="text-cyan-700 dark:text-cyan-300 hover:text-cyan-900 dark:hover:text-cyan-200 hover:bg-cyan-50 dark:hover:bg-cyan-500/10 p-1.5 sm:p-2"
  1377. >
  1378. <Ungroup className="w-4 h-4" />
  1379. </Button>
  1380. )}
  1381. </div>
  1382. </div>
  1383. {/* Children (only when expanded) */}
  1384. {!collapsed && (
  1385. <div className="border-t border-bambu-dark-tertiary bg-black/20 p-2 sm:p-3 space-y-2">
  1386. {batchRow.items.map((child, ci) => (
  1387. <SortableQueueItem
  1388. key={child.id}
  1389. item={child}
  1390. onEdit={() => setEditItem(child)}
  1391. onCancel={() => setConfirmAction({ type: 'cancel', item: child })}
  1392. onRemove={() => {}}
  1393. onStop={() => {}}
  1394. onRequeue={() => {}}
  1395. onStart={() => startMutation.mutate({ id: child.id })}
  1396. onMoveUp={
  1397. onMoveBlock && ci > 0
  1398. ? () => onMoveBlock([child.id], batchRow.items[ci - 1].id, false)
  1399. : undefined
  1400. }
  1401. onMoveDown={
  1402. onMoveBlock && ci < batchRow.items.length - 1
  1403. ? () => onMoveBlock([child.id], batchRow.items[ci + 1].id, true)
  1404. : undefined
  1405. }
  1406. timeFormat={timeFormat}
  1407. isSelected={selectedItems.includes(child.id)}
  1408. onToggleSelect={() => handleToggleSelect(child.id)}
  1409. hasPermission={hasPermission}
  1410. canModify={canModify}
  1411. showEta={etaEligibleIds.has(child.id)}
  1412. etaNow={etaNow}
  1413. t={t}
  1414. />
  1415. ))}
  1416. </div>
  1417. )}
  1418. </div>
  1419. );
  1420. }
  1421. type HistoryRow =
  1422. | { kind: 'item'; item: PrintQueueItem }
  1423. | { kind: 'batch'; batchId: number; batchName: string; items: PrintQueueItem[] };
  1424. interface HistorySectionProps {
  1425. items: PrintQueueItem[];
  1426. collapsed: boolean;
  1427. visibleCount: number;
  1428. onShowMore: () => void;
  1429. sortBy: 'date' | 'name' | 'printer';
  1430. sortAsc: boolean;
  1431. onSortByChange: (v: 'date' | 'name' | 'printer') => void;
  1432. onSortAscToggle: () => void;
  1433. onRemove: (item: PrintQueueItem) => void;
  1434. onRequeue: (item: PrintQueueItem) => void;
  1435. timeFormat: TimeFormat;
  1436. batchCollapsed: Record<number, boolean>;
  1437. toggleBatchCollapsed: (id: number) => void;
  1438. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1439. hasPermission: (p: any) => boolean;
  1440. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1441. canModify: (resource: any, action: any, createdById?: number | null) => boolean;
  1442. t: (key: string, options?: Record<string, unknown>) => string;
  1443. }
  1444. function HistorySection({
  1445. items,
  1446. visibleCount,
  1447. onShowMore,
  1448. sortBy,
  1449. sortAsc,
  1450. onSortByChange,
  1451. onSortAscToggle,
  1452. onRemove,
  1453. onRequeue,
  1454. timeFormat,
  1455. batchCollapsed,
  1456. toggleBatchCollapsed,
  1457. hasPermission,
  1458. canModify,
  1459. t,
  1460. }: HistorySectionProps) {
  1461. if (items.length === 0) {
  1462. return (
  1463. <Card className="p-12 text-center border-dashed">
  1464. <ListOrdered className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  1465. <h3 className="text-xl font-medium text-white mb-2">{t('queue.history.emptyTitle')}</h3>
  1466. <p className="text-bambu-gray max-w-md mx-auto">{t('queue.history.emptyDescription')}</p>
  1467. </Card>
  1468. );
  1469. }
  1470. // Group siblings sharing a batch_id into a single collapsible row.
  1471. // First-seen order is preserved for batches; items keep their sorted
  1472. // position from the parent's sort selector.
  1473. const rows: HistoryRow[] = [];
  1474. const seenBatches = new Set<number>();
  1475. for (const item of items.slice(0, visibleCount)) {
  1476. if (item.batch_id != null) {
  1477. if (seenBatches.has(item.batch_id)) continue;
  1478. seenBatches.add(item.batch_id);
  1479. const siblings = items.filter((s) => s.batch_id === item.batch_id);
  1480. rows.push({
  1481. kind: 'batch',
  1482. batchId: item.batch_id,
  1483. batchName: item.batch_name || t('queue.batch.defaultName'),
  1484. items: siblings,
  1485. });
  1486. } else {
  1487. rows.push({ kind: 'item', item });
  1488. }
  1489. }
  1490. return (
  1491. <div>
  1492. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  1493. <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
  1494. {t('queue.sections.history')}
  1495. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  1496. ({t('queue.itemCount', { count: items.length })})
  1497. </span>
  1498. </h2>
  1499. <div className="flex items-center gap-2">
  1500. <select
  1501. className="px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1502. value={sortBy}
  1503. onChange={(e) => onSortByChange(e.target.value as 'date' | 'name' | 'printer')}
  1504. >
  1505. <option value="date">{t('queue.sort.byDate')}</option>
  1506. <option value="name">{t('queue.sort.byName')}</option>
  1507. <option value="printer">{t('queue.sort.byPrinter')}</option>
  1508. </select>
  1509. <Button
  1510. variant="ghost"
  1511. size="sm"
  1512. onClick={onSortAscToggle}
  1513. title={sortAsc ? t('queue.sort.ascendingOldest') : t('queue.sort.descendingNewest')}
  1514. className="px-2"
  1515. >
  1516. {sortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  1517. </Button>
  1518. </div>
  1519. </div>
  1520. <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2">
  1521. {rows.map((row) => {
  1522. if (row.kind === 'item') {
  1523. return (
  1524. <CompactHistoryRow
  1525. key={row.item.id}
  1526. item={row.item}
  1527. onRemove={() => onRemove(row.item)}
  1528. onRequeue={() => onRequeue(row.item)}
  1529. timeFormat={timeFormat}
  1530. hasPermission={hasPermission}
  1531. canModify={canModify}
  1532. t={t}
  1533. />
  1534. );
  1535. }
  1536. // Batch group — spans the full grid width so it visually anchors
  1537. // its children below it. The children themselves render in the
  1538. // same responsive grid pattern inside the expanded body.
  1539. const collapsed = batchCollapsed[row.batchId] ?? true;
  1540. const completed = row.items.filter((i) => i.status === 'completed').length;
  1541. const failed = row.items.filter((i) => i.status === 'failed').length;
  1542. const skipped = row.items.filter((i) => i.status === 'skipped').length;
  1543. const cancelled = row.items.filter((i) => i.status === 'cancelled').length;
  1544. const latest = row.items
  1545. .map((i) => i.completed_at || i.created_at)
  1546. .filter((v): v is string => !!v)
  1547. .sort()
  1548. .at(-1);
  1549. return (
  1550. <div
  1551. key={`batch-${row.batchId}`}
  1552. className="md:col-span-2 xl:col-span-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary border-l-[3px] border-l-cyan-400"
  1553. >
  1554. <button
  1555. onClick={() => toggleBatchCollapsed(row.batchId)}
  1556. className="w-full flex items-center gap-2 sm:gap-3 px-3 py-2 hover:bg-bambu-dark/30 transition-colors text-left"
  1557. title={collapsed ? t('queue.batch.expand') : t('queue.batch.collapse')}
  1558. >
  1559. {collapsed ? (
  1560. <ChevronRight className="w-4 h-4 text-bambu-gray shrink-0" />
  1561. ) : (
  1562. <ChevronDown className="w-4 h-4 text-bambu-gray shrink-0" />
  1563. )}
  1564. {collapsed ? (
  1565. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300 shrink-0" />
  1566. ) : (
  1567. <PackageOpen className="w-5 h-5 text-cyan-700 dark:text-cyan-300 shrink-0" />
  1568. )}
  1569. <span className="text-sm text-white font-medium truncate min-w-0 flex-1">
  1570. {row.batchName}
  1571. </span>
  1572. <div className="flex items-center gap-2 text-xs text-bambu-gray shrink-0">
  1573. {completed > 0 && (
  1574. <span className="flex items-center gap-1 text-emerald-700 dark:text-emerald-400">
  1575. <CheckCircle className="w-3 h-3" />
  1576. {completed}
  1577. </span>
  1578. )}
  1579. {failed > 0 && (
  1580. <span className="flex items-center gap-1 text-red-700 dark:text-red-400">
  1581. <XCircle className="w-3 h-3" />
  1582. {failed}
  1583. </span>
  1584. )}
  1585. {skipped > 0 && (
  1586. <span className="flex items-center gap-1 text-orange-700 dark:text-orange-400">
  1587. <SkipForward className="w-3 h-3" />
  1588. {skipped}
  1589. </span>
  1590. )}
  1591. {cancelled > 0 && (
  1592. <span className="flex items-center gap-1 text-gray-400">
  1593. <Ban className="w-3 h-3" />
  1594. {cancelled}
  1595. </span>
  1596. )}
  1597. <span title={latest ?? undefined}>
  1598. {latest ? formatRelativeTime(latest, timeFormat, t) : null}
  1599. </span>
  1600. </div>
  1601. </button>
  1602. {!collapsed && (
  1603. <div className="border-t border-bambu-dark-tertiary bg-black/20 p-2 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2">
  1604. {row.items.map((child) => (
  1605. <CompactHistoryRow
  1606. key={child.id}
  1607. item={child}
  1608. onRemove={() => onRemove(child)}
  1609. onRequeue={() => onRequeue(child)}
  1610. timeFormat={timeFormat}
  1611. hasPermission={hasPermission}
  1612. canModify={canModify}
  1613. t={t}
  1614. />
  1615. ))}
  1616. </div>
  1617. )}
  1618. </div>
  1619. );
  1620. })}
  1621. </div>
  1622. {items.length > visibleCount && (
  1623. <div className="mt-4 flex flex-col items-center gap-2">
  1624. <Button variant="secondary" size="sm" onClick={onShowMore}>
  1625. {t('queue.history.showMore')}
  1626. </Button>
  1627. <span className="text-xs text-bambu-gray">
  1628. {t('queue.history.showingCount', {
  1629. shown: Math.min(visibleCount, items.length),
  1630. total: items.length,
  1631. })}
  1632. </span>
  1633. </div>
  1634. )}
  1635. </div>
  1636. );
  1637. }
  1638. const HISTORY_PAGE_SIZE = 50;
  1639. export function QueuePage() {
  1640. const { t } = useTranslation();
  1641. const queryClient = useQueryClient();
  1642. const { showToast } = useToast();
  1643. const { hasPermission, hasAnyPermission, canModify } = useAuth();
  1644. const [filterPrinter, setFilterPrinter] = useState<number | null>(null);
  1645. const [filterStatus, setFilterStatus] = useState<string>('');
  1646. const [filterLocation, setFilterLocation] = useState<string>('');
  1647. const [showClearHistoryConfirm, setShowClearHistoryConfirm] = useState(false);
  1648. const [editItem, setEditItem] = useState<PrintQueueItem | null>(null);
  1649. const [requeueItem, setRequeueItem] = useState<PrintQueueItem | null>(null);
  1650. const [confirmAction, setConfirmAction] = useState<{
  1651. type: 'cancel' | 'remove' | 'stop';
  1652. item: PrintQueueItem;
  1653. } | null>(null);
  1654. const [selectedItems, setSelectedItems] = useState<number[]>([]);
  1655. const [showBulkEditModal, setShowBulkEditModal] = useState(false);
  1656. // #1818: per-printer Resume-after-failure confirm modal. Tracks which
  1657. // printer's gate the user is about to clear; null when no modal is open.
  1658. const [resumeConfirm, setResumeConfirm] = useState<{
  1659. printerId: number;
  1660. printerName: string;
  1661. skippedCount: number;
  1662. } | null>(null);
  1663. const [historySortBy, setHistorySortBy] = useState<'date' | 'name' | 'printer'>(() => {
  1664. const saved = localStorage.getItem('queue.historySortBy');
  1665. return (saved as 'date' | 'name' | 'printer') || 'date';
  1666. });
  1667. const [historySortAsc, setHistorySortAsc] = useState(() => {
  1668. const saved = localStorage.getItem('queue.historySortAsc');
  1669. return saved !== null ? saved === 'true' : false;
  1670. });
  1671. // #2682: History renders progressively — start at one page, grow on demand.
  1672. // Reset happens only on a deliberate re-sort / filter change (below), NOT on
  1673. // the periodic queue poll, so an expanded view doesn't snap back mid-scroll.
  1674. const [historyVisibleCount, setHistoryVisibleCount] = useState(HISTORY_PAGE_SIZE);
  1675. const [pendingSortBy, setPendingSortBy] = useState<'position' | 'name' | 'printer' | 'time'>(() => {
  1676. const saved = localStorage.getItem('queue.pendingSortBy');
  1677. return (saved as 'position' | 'name' | 'printer' | 'time') || 'position';
  1678. });
  1679. const [pendingSortAsc, setPendingSortAsc] = useState(() => {
  1680. const saved = localStorage.getItem('queue.pendingSortAsc');
  1681. return saved !== null ? saved === 'true' : true;
  1682. });
  1683. // historyCollapsed legacy state retained only for localStorage migration; the
  1684. // History tab renders unconditionally so this no longer drives the UI.
  1685. // Tabbed page structure: Active queue stays as the main view; History
  1686. // and Timeline split off. Persists per-user via localStorage.
  1687. // /queue?batch=<id>: a link to one batch (e.g. from Bambuddy Orders), read once.
  1688. const [focusBatchId] = useState<number | null>(() => {
  1689. const id = Number(new URLSearchParams(window.location.search).get('batch'));
  1690. return Number.isInteger(id) && id > 0 ? id : null;
  1691. });
  1692. const [activeTab, setActiveTab] = useState<'queue' | 'batches' | 'history' | 'timeline' | 'pipelines'>(() => {
  1693. // URL deep-link wins so the legacy /pipelines/runs redirect lands on the
  1694. // right tab. localStorage holds the per-user last-selected fallback.
  1695. const search = new URLSearchParams(window.location.search);
  1696. const url = search.get('tab');
  1697. // A link to one batch (/queue?batch=<id>) opens the tab that shows it.
  1698. if (search.get('batch')) return 'batches';
  1699. if (url === 'pipelines' || url === 'history' || url === 'timeline' || url === 'queue' || url === 'batches') {
  1700. return url;
  1701. }
  1702. const saved = localStorage.getItem('queue.activeTab');
  1703. if (saved === 'history' || saved === 'timeline' || saved === 'pipelines' || saved === 'batches') return saved;
  1704. return 'queue';
  1705. });
  1706. // Active-tab layout toggle. "position" = today's flat list; "printer"
  1707. // groups items under per-printer section headers with aggregate stats.
  1708. const [activeLayout, setActiveLayout] = useState<'position' | 'printer'>(() => {
  1709. const saved = localStorage.getItem('queue.activeLayout');
  1710. return saved === 'printer' ? 'printer' : 'position';
  1711. });
  1712. // Per-batch collapse state, keyed by batch_id. Default = collapsed
  1713. // (matches the SimplyPrint/Files convention — show the rollup first).
  1714. const [batchCollapsed, setBatchCollapsed] = useState<Record<number, boolean>>(() => {
  1715. try {
  1716. const saved = localStorage.getItem('queue.batchCollapsed');
  1717. return saved ? JSON.parse(saved) : {};
  1718. } catch {
  1719. return {};
  1720. }
  1721. });
  1722. // Multi-drag bookkeeping for DragOverlay. Numeric for single items, string
  1723. // `batch-<id>` when a whole group is being dragged.
  1724. const [activeDragId, setActiveDragId] = useState<number | string | null>(null);
  1725. // "Group as batch" modal.
  1726. const [groupBatchModal, setGroupBatchModal] = useState(false);
  1727. // Ungroup confirm.
  1728. const [ungroupBatchId, setUngroupBatchId] = useState<number | null>(null);
  1729. // Persist sort settings to localStorage
  1730. useEffect(() => {
  1731. localStorage.setItem('queue.historySortBy', historySortBy);
  1732. }, [historySortBy]);
  1733. useEffect(() => {
  1734. localStorage.setItem('queue.historySortAsc', String(historySortAsc));
  1735. }, [historySortAsc]);
  1736. // Collapse History back to a single page when the user re-sorts or changes
  1737. // the location filter (deliberate view changes). Intentionally excludes the
  1738. // queue poll so periodic refetches keep the expanded count.
  1739. useEffect(() => {
  1740. setHistoryVisibleCount(HISTORY_PAGE_SIZE);
  1741. }, [historySortBy, historySortAsc, filterLocation]);
  1742. useEffect(() => {
  1743. localStorage.setItem('queue.pendingSortBy', pendingSortBy);
  1744. }, [pendingSortBy]);
  1745. useEffect(() => {
  1746. localStorage.setItem('queue.pendingSortAsc', String(pendingSortAsc));
  1747. }, [pendingSortAsc]);
  1748. useEffect(() => {
  1749. localStorage.setItem('queue.activeTab', activeTab);
  1750. }, [activeTab]);
  1751. useEffect(() => {
  1752. localStorage.setItem('queue.activeLayout', activeLayout);
  1753. }, [activeLayout]);
  1754. useEffect(() => {
  1755. localStorage.setItem('queue.batchCollapsed', JSON.stringify(batchCollapsed));
  1756. }, [batchCollapsed]);
  1757. const sensors = useSensors(
  1758. useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
  1759. useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  1760. );
  1761. const { data: settings } = useQuery({
  1762. queryKey: ['settings'],
  1763. queryFn: api.getSettings,
  1764. });
  1765. const timeFormat: TimeFormat = settings?.time_format || 'system';
  1766. // Badge count for the Batches tab (#342). Deliberately its own query rather
  1767. // than derived from the queue: an order whose runs have all finished has no
  1768. // queue rows left, and those are precisely the orders the tab exists to
  1769. // surface. Shares the ['batches'] key with the tab itself, so dispatching or
  1770. // cancelling refreshes both.
  1771. const { data: activeBatches } = useQuery({
  1772. queryKey: ['batches', 'active'],
  1773. queryFn: () => api.getBatches('active'),
  1774. });
  1775. const activeBatchCount = activeBatches?.length ?? 0;
  1776. const { data: queue, isLoading } = useQuery({
  1777. queryKey: ['queue', filterPrinter, filterStatus],
  1778. queryFn: () => api.getQueue(filterPrinter || undefined, filterStatus || undefined),
  1779. refetchInterval: 5000,
  1780. });
  1781. const { data: printers } = useQuery({
  1782. queryKey: ['printers'],
  1783. queryFn: () => api.getPrinters(),
  1784. });
  1785. const sjfMutation = useMutation({
  1786. mutationFn: (enabled: boolean) => api.updateSettings({ queue_shortest_first: enabled }),
  1787. onSuccess: () => {
  1788. queryClient.invalidateQueries({ queryKey: ['settings'] });
  1789. },
  1790. });
  1791. const cancelMutation = useMutation({
  1792. mutationFn: (id: number) => api.cancelQueueItem(id),
  1793. onSuccess: () => {
  1794. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1795. showToast(t('queue.toast.cancelled'));
  1796. },
  1797. onError: () => showToast(t('queue.toast.cancelFailed'), 'error'),
  1798. });
  1799. const removeMutation = useMutation({
  1800. mutationFn: (id: number) => api.removeFromQueue(id),
  1801. onSuccess: (result) => {
  1802. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1803. queryClient.invalidateQueries({ queryKey: ['batches'] });
  1804. // The backend keeps an order's last run for a plate, cancelled rather
  1805. // than deleted, so the order can still re-queue it (#2960). Say so:
  1806. // the row stays on screen and silence would read as a failed delete.
  1807. showToast(result.deleted === false ? t('queue.toast.keptForOrder') : t('queue.toast.removed'));
  1808. },
  1809. onError: () => showToast(t('queue.toast.removeFailed'), 'error'),
  1810. });
  1811. const stopMutation = useMutation({
  1812. mutationFn: (id: number) => api.stopQueueItem(id),
  1813. onSuccess: () => {
  1814. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1815. showToast(t('queue.toast.stopped'));
  1816. },
  1817. onError: () => showToast(t('queue.toast.stopFailed'), 'error'),
  1818. });
  1819. // Filament-deficit confirmation state (#1496). When the backend returns
  1820. // 409 with `code=insufficient_filament` we stash the deficit + item id
  1821. // here; the modal at the bottom of the page reads it and the "Print
  1822. // Anyway" path re-issues the start with `skipFilamentCheck=true`.
  1823. const [filamentShortConfirm, setFilamentShortConfirm] = useState<{
  1824. itemId: number;
  1825. deficit: Array<{
  1826. slot_id: number;
  1827. required_grams: number;
  1828. remaining_grams: number | null;
  1829. filament_type?: string | null;
  1830. }>;
  1831. } | null>(null);
  1832. // A filament the printer has no tray for at all (#2799): 409 with
  1833. // `code=unmatched_filament` and the missing filaments. Same "Print Anyway"
  1834. // path as the deficit above.
  1835. const [filamentMissingConfirm, setFilamentMissingConfirm] = useState<{
  1836. itemId: number;
  1837. missing: string[];
  1838. } | null>(null);
  1839. const startMutation = useMutation({
  1840. mutationFn: ({ id, skipFilamentCheck }: { id: number; skipFilamentCheck?: boolean }) =>
  1841. api.startQueueItem(id, { skipFilamentCheck }),
  1842. onSuccess: () => {
  1843. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1844. showToast(t('queue.toast.released'));
  1845. setFilamentShortConfirm(null);
  1846. setFilamentMissingConfirm(null);
  1847. },
  1848. onError: (error: unknown, variables) => {
  1849. if (error instanceof ApiError && error.status === 409 && error.code === 'insufficient_filament') {
  1850. const deficitRaw = (error.detail?.deficit ?? []) as Array<{
  1851. slot_id: number;
  1852. required_grams: number;
  1853. remaining_grams: number | null;
  1854. filament_type?: string | null;
  1855. }>;
  1856. setFilamentShortConfirm({ itemId: variables.id, deficit: deficitRaw });
  1857. return;
  1858. }
  1859. if (error instanceof ApiError && error.status === 409 && error.code === 'unmatched_filament') {
  1860. const missing = (error.detail?.missing ?? []) as string[];
  1861. setFilamentMissingConfirm({ itemId: variables.id, missing });
  1862. return;
  1863. }
  1864. showToast(t('queue.toast.startFailed'), 'error');
  1865. },
  1866. });
  1867. const reorderMutation = useMutation({
  1868. mutationFn: (items: { id: number; position: number }[]) => api.reorderQueue(items),
  1869. onSuccess: () => {
  1870. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1871. },
  1872. onError: () => showToast(t('queue.toast.reorderFailed'), 'error'),
  1873. });
  1874. const clearHistoryMutation = useMutation({
  1875. mutationFn: async () => {
  1876. const historyItems = queue?.filter(i =>
  1877. ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)
  1878. ) || [];
  1879. let cleared = 0;
  1880. let kept = 0;
  1881. for (const item of historyItems) {
  1882. const result = await api.removeFromQueue(item.id);
  1883. // A row a batch order still needs is kept rather than deleted, so the
  1884. // count has to come from what the backend actually did (#2960).
  1885. if (result.deleted === false) kept += 1;
  1886. else cleared += 1;
  1887. }
  1888. return { cleared, kept };
  1889. },
  1890. onSuccess: ({ cleared, kept }) => {
  1891. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1892. queryClient.invalidateQueries({ queryKey: ['batches'] });
  1893. showToast(
  1894. kept > 0
  1895. ? `${t('queue.toast.historyCleared', { count: cleared })} ${t('queue.toast.historyKeptForOrders', { kept })}`
  1896. : t('queue.toast.historyCleared', { count: cleared })
  1897. );
  1898. },
  1899. onError: () => showToast(t('queue.toast.clearHistoryFailed'), 'error'),
  1900. });
  1901. const bulkUpdateMutation = useMutation({
  1902. mutationFn: (data: PrintQueueBulkUpdate) => api.bulkUpdateQueue(data),
  1903. onSuccess: (result) => {
  1904. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1905. setSelectedItems([]);
  1906. setShowBulkEditModal(false);
  1907. showToast(result.message);
  1908. },
  1909. onError: () => showToast(t('queue.toast.updateFailed'), 'error'),
  1910. });
  1911. const bulkCancelMutation = useMutation({
  1912. mutationFn: async (ids: number[]) => {
  1913. for (const id of ids) {
  1914. await api.cancelQueueItem(id);
  1915. }
  1916. return ids.length;
  1917. },
  1918. onSuccess: (count) => {
  1919. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1920. setSelectedItems([]);
  1921. showToast(t('queue.toast.bulkCancelled', { count }));
  1922. },
  1923. onError: () => showToast(t('queue.toast.bulkCancelFailed'), 'error'),
  1924. });
  1925. const resumeAfterFailureMutation = useMutation({
  1926. mutationFn: (printerId: number) => api.resumeQueueAfterFailure(printerId),
  1927. onSuccess: (result) => {
  1928. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1929. setResumeConfirm(null);
  1930. showToast(
  1931. t('queue.toast.resumedAfterFailure', {
  1932. restored: result.restored,
  1933. acknowledged: result.acknowledged,
  1934. }),
  1935. );
  1936. },
  1937. onError: () => showToast(t('queue.toast.resumeAfterFailureFailed'), 'error'),
  1938. });
  1939. const createBatchMutation = useMutation({
  1940. mutationFn: (data: { name: string; item_ids: number[] }) => api.createBatch(data),
  1941. onSuccess: (batch) => {
  1942. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1943. setSelectedItems([]);
  1944. setGroupBatchModal(false);
  1945. // New batches start expanded so the user sees what they just grouped.
  1946. setBatchCollapsed((prev) => ({ ...prev, [batch.id]: false }));
  1947. showToast(t('queue.toast.batchCreated', { name: batch.name }));
  1948. },
  1949. onError: () => showToast(t('queue.toast.batchCreateFailed'), 'error'),
  1950. });
  1951. const ungroupBatchMutation = useMutation({
  1952. mutationFn: (id: number) => api.ungroupBatch(id),
  1953. onSuccess: (result) => {
  1954. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1955. setUngroupBatchId(null);
  1956. showToast(t('queue.toast.batchUngrouped', { count: result.ungrouped_count }));
  1957. },
  1958. onError: () => showToast(t('queue.toast.batchUngroupFailed'), 'error'),
  1959. });
  1960. const handleToggleSelect = (id: number) => {
  1961. setSelectedItems(prev =>
  1962. prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
  1963. );
  1964. };
  1965. // Get unique locations from printers for the filter dropdown
  1966. const uniqueLocations = useMemo(() => {
  1967. const locations = new Set<string>();
  1968. printers?.forEach(p => {
  1969. if (p.location) locations.add(p.location);
  1970. });
  1971. // Also include locations from queue items (for model-based assignments)
  1972. queue?.forEach(item => {
  1973. if (item.target_location) locations.add(item.target_location);
  1974. });
  1975. return Array.from(locations).sort();
  1976. }, [printers, queue]);
  1977. // Helper to check if a queue item matches the location filter
  1978. const matchesLocationFilter = useCallback((item: PrintQueueItem): boolean => {
  1979. if (!filterLocation) return true;
  1980. // For model-based assignments, check target_location
  1981. if (item.target_location) return item.target_location === filterLocation;
  1982. // For printer-based assignments, check the printer's location
  1983. if (item.printer_id) {
  1984. const printer = printers?.find(p => p.id === item.printer_id);
  1985. return printer?.location === filterLocation;
  1986. }
  1987. return false;
  1988. }, [filterLocation, printers]);
  1989. const pendingItems = useMemo(() => {
  1990. let items = queue?.filter(i => i.status === 'pending') || [];
  1991. // Apply location filter
  1992. if (filterLocation) {
  1993. items = items.filter(matchesLocationFilter);
  1994. }
  1995. // Helper to get scheduled time as timestamp (ASAP/placeholder = 0 for earliest)
  1996. const getScheduledTime = (item: PrintQueueItem): number => {
  1997. if (!item.scheduled_time) return 0;
  1998. const time = parseUTCDate(item.scheduled_time)?.getTime() ?? 0;
  1999. // Placeholder dates (> 6 months out) are treated as ASAP
  2000. const sixMonthsFromNow = Date.now() + (180 * 24 * 60 * 60 * 1000);
  2001. return time > sixMonthsFromNow ? 0 : time;
  2002. };
  2003. // When SJF is enabled, override sort to match scheduler order
  2004. if (settings?.queue_shortest_first) {
  2005. return [...items].sort((a, b) => compareQueueOrder(a, b, true));
  2006. }
  2007. return [...items].sort((a, b) => {
  2008. let cmp: number;
  2009. if (pendingSortBy === 'name') {
  2010. const aName = a.archive_name || a.library_file_name || '';
  2011. const bName = b.archive_name || b.library_file_name || '';
  2012. cmp = aName.localeCompare(bName);
  2013. } else if (pendingSortBy === 'printer') {
  2014. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  2015. } else if (pendingSortBy === 'time') {
  2016. // Sort by scheduled start time (when print will begin)
  2017. cmp = getScheduledTime(a) - getScheduledTime(b);
  2018. } else {
  2019. cmp = a.position - b.position;
  2020. }
  2021. return pendingSortAsc ? cmp : -cmp;
  2022. });
  2023. }, [queue, pendingSortBy, pendingSortAsc, matchesLocationFilter, filterLocation, settings?.queue_shortest_first]);
  2024. const handleSelectAll = () => {
  2025. const allPendingIds = pendingItems.map(i => i.id);
  2026. if (selectedItems.length === allPendingIds.length) {
  2027. setSelectedItems([]);
  2028. } else {
  2029. setSelectedItems(allPendingIds);
  2030. }
  2031. };
  2032. const activeItems = useMemo(() => {
  2033. let items = queue?.filter(i => i.status === 'printing') || [];
  2034. if (filterLocation) {
  2035. items = items.filter(matchesLocationFilter);
  2036. }
  2037. return items;
  2038. }, [queue, filterLocation, matchesLocationFilter]);
  2039. // Queue items eligible for an "if started now" ETA (#2740).
  2040. //
  2041. // The ETA answers "when would this finish if it began right now", so it may
  2042. // only appear on items that really could begin right now. waiting_reason now
  2043. // covers the pinned-printer case too (#3074), but it is still not enough on
  2044. // its own: it says whether the scheduler had a reason to hold the item on its
  2045. // last pass, not whether this item is the one that printer takes next. Two
  2046. // items pinned to the same free printer both come back with no reason, and
  2047. // only one of them can start now — which is what the ordering below works out.
  2048. //
  2049. // Computed from the unfiltered queue on purpose — hiding a printer behind the
  2050. // location filter must not make its printer look free.
  2051. const etaEligibleIds = useMemo(() => {
  2052. const eligible = new Set<number>();
  2053. if (!queue) return eligible;
  2054. const busyPrinters = new Set<number>();
  2055. queue.forEach(item => {
  2056. if (item.status === 'printing' && item.printer_id) busyPrinters.add(item.printer_id);
  2057. });
  2058. const isFutureScheduled = (item: PrintQueueItem): boolean => {
  2059. if (!item.scheduled_time) return false;
  2060. return (parseUTCDate(item.scheduled_time)?.getTime() ?? 0) > Date.now();
  2061. };
  2062. // Mirrors the scheduler's own ordering so "next up" here means the item the
  2063. // scheduler would actually dispatch next, not whatever the user sorted by.
  2064. // Bucketed by printer immediately below, so the within-lane comparator is
  2065. // the right one -- no cross-lane grouping needed.
  2066. const schedulerOrder = (a: PrintQueueItem, b: PrintQueueItem): number =>
  2067. compareQueueOrder(a, b, settings?.queue_shortest_first ?? false);
  2068. // Claimants for each printer, in the order the scheduler would take them.
  2069. // Staged and future-scheduled items are excluded: the scheduler skips both
  2070. // without marking the printer busy, so neither holds up the item behind it.
  2071. const contenders = new Map<number, PrintQueueItem[]>();
  2072. queue
  2073. .filter(
  2074. item =>
  2075. item.status === 'pending' &&
  2076. item.printer_id != null &&
  2077. !item.manual_start &&
  2078. !isFutureScheduled(item)
  2079. )
  2080. .sort(schedulerOrder)
  2081. .forEach(item => {
  2082. const list = contenders.get(item.printer_id!) ?? [];
  2083. list.push(item);
  2084. contenders.set(item.printer_id!, list);
  2085. });
  2086. queue.forEach(item => {
  2087. if (item.status !== 'pending') return;
  2088. // Blocked, scheduled for later, or no usable duration to add.
  2089. if (item.waiting_reason) return;
  2090. if (isFutureScheduled(item)) return;
  2091. if (item.print_time_seconds == null || item.print_time_seconds <= 0) return;
  2092. // Conditional on an earlier print's outcome, which the UI cannot see: the
  2093. // scheduler may skip it outright rather than ever running it.
  2094. if (item.require_previous_success) return;
  2095. // Model-based items have no printer yet; an empty waiting_reason is the
  2096. // scheduler saying it found one, so trust that.
  2097. if (item.printer_id == null) {
  2098. eligible.add(item.id);
  2099. return;
  2100. }
  2101. if (busyPrinters.has(item.printer_id)) return;
  2102. // Staged items wait on the user, not on the queue, so they are startable
  2103. // whenever their printer is free regardless of what is queued ahead.
  2104. if (item.manual_start) {
  2105. eligible.add(item.id);
  2106. return;
  2107. }
  2108. if (contenders.get(item.printer_id)?.[0]?.id === item.id) eligible.add(item.id);
  2109. });
  2110. return eligible;
  2111. }, [queue, settings?.queue_shortest_first]);
  2112. // The ETA is "now + duration", so it goes stale on its own. Nothing else
  2113. // re-renders these rows while the queue payload is unchanged (react-query's
  2114. // structural sharing keeps the reference stable), so drive it from a clock of
  2115. // our own. Only runs while an ETA is actually on screen.
  2116. const [etaNow, setEtaNow] = useState(() => Date.now());
  2117. const hasEtas = etaEligibleIds.size > 0;
  2118. useEffect(() => {
  2119. if (!hasEtas) return;
  2120. setEtaNow(Date.now());
  2121. const id = setInterval(() => setEtaNow(Date.now()), 30000);
  2122. return () => clearInterval(id);
  2123. }, [hasEtas]);
  2124. // Get unique printer IDs from active items to fetch their statuses
  2125. const activePrinterIds = useMemo(() => {
  2126. const ids = new Set<number>();
  2127. activeItems.forEach(item => {
  2128. if (item.printer_id) ids.add(item.printer_id);
  2129. });
  2130. return Array.from(ids);
  2131. }, [activeItems]);
  2132. // Fetch printer statuses for printers with active jobs
  2133. const printerStatusQueries = useQueries({
  2134. queries: activePrinterIds.map(printerId => ({
  2135. queryKey: ['printerStatus', printerId],
  2136. queryFn: () => api.getPrinterStatus(printerId),
  2137. refetchInterval: 5000,
  2138. })),
  2139. });
  2140. // Build a map of printer_id -> state for quick lookup
  2141. const printerStateMap = useMemo(() => {
  2142. const map: Record<number, string | null> = {};
  2143. activePrinterIds.forEach((printerId, index) => {
  2144. const result = printerStatusQueries[index];
  2145. if (result?.data?.state) {
  2146. map[printerId] = result.data.state;
  2147. }
  2148. });
  2149. return map;
  2150. }, [activePrinterIds, printerStatusQueries]);
  2151. // Build a map of printer_id -> full status for timeline view
  2152. const printerStatusMap = useMemo(() => {
  2153. const map: Record<number, { progress?: number; remaining_time?: number; state?: string }> = {};
  2154. activePrinterIds.forEach((printerId, index) => {
  2155. const result = printerStatusQueries[index];
  2156. if (result?.data) {
  2157. map[printerId] = {
  2158. progress: result.data.progress ?? undefined,
  2159. remaining_time: result.data.remaining_time ?? undefined,
  2160. state: result.data.state ?? undefined,
  2161. };
  2162. }
  2163. });
  2164. return map;
  2165. }, [activePrinterIds, printerStatusQueries]);
  2166. const historyItems = useMemo(() => {
  2167. let items = queue?.filter(i => ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)) || [];
  2168. if (filterLocation) {
  2169. items = items.filter(matchesLocationFilter);
  2170. }
  2171. return [...items].sort((a, b) => {
  2172. let cmp: number;
  2173. if (historySortBy === 'name') {
  2174. const aName = a.archive_name || a.library_file_name || '';
  2175. const bName = b.archive_name || b.library_file_name || '';
  2176. cmp = aName.localeCompare(bName);
  2177. } else if (historySortBy === 'printer') {
  2178. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  2179. } else {
  2180. // Default: by date - most recent first (desc) is the natural order
  2181. cmp = (parseUTCDate(b.completed_at || b.created_at)?.getTime() ?? 0) - (parseUTCDate(a.completed_at || a.created_at)?.getTime() ?? 0);
  2182. }
  2183. return historySortAsc ? -cmp : cmp;
  2184. });
  2185. }, [queue, historySortBy, historySortAsc, matchesLocationFilter, filterLocation]);
  2186. // Calculate total queue time
  2187. const totalQueueTime = useMemo(() => {
  2188. return pendingItems.reduce((acc, item) => acc + (item.print_time_seconds || 0), 0);
  2189. }, [pendingItems]);
  2190. // Calculate total material weight
  2191. const totalWeight = useMemo(() => {
  2192. return pendingItems.reduce((acc, item) => acc + (item.filament_used_grams || 0), 0);
  2193. }, [pendingItems]);
  2194. const handleDragStart = (event: DragStartEvent) => {
  2195. const id = event.active.id;
  2196. setActiveDragId(typeof id === 'number' || typeof id === 'string' ? id : null);
  2197. };
  2198. const handleDragEnd = (event: DragEndEvent) => {
  2199. const { active, over } = event;
  2200. setActiveDragId(null);
  2201. if (!over || active.id === over.id) return;
  2202. // Resolve dragged source → movingIds (preserving order from pendingItems).
  2203. // - `batch-<id>`: every child of that batch, in their current order
  2204. // - selected + dragged is one of them: contiguous multi-drag block
  2205. // - otherwise: single row
  2206. let movingIds: number[];
  2207. const activeId = active.id;
  2208. if (typeof activeId === 'string' && activeId.startsWith('batch-')) {
  2209. const batchId = Number(activeId.slice('batch-'.length));
  2210. movingIds = pendingItems.filter((i) => i.batch_id === batchId).map((i) => i.id);
  2211. } else {
  2212. const draggedId = activeId as number;
  2213. movingIds = selectedItems.includes(draggedId) && selectedItems.length > 1
  2214. ? selectedItems.slice().sort((a, b) => {
  2215. const ai = pendingItems.findIndex((i) => i.id === a);
  2216. const bi = pendingItems.findIndex((i) => i.id === b);
  2217. return ai - bi;
  2218. })
  2219. : [draggedId];
  2220. }
  2221. if (movingIds.length === 0) return;
  2222. // Resolve drop target → index inside pendingItems. A `batch-<id>` drop
  2223. // target anchors at the batch's first child, so dropping above another
  2224. // batch lands the moving block immediately before it.
  2225. let overIndex: number;
  2226. const overId = over.id;
  2227. if (typeof overId === 'string' && overId.startsWith('batch-')) {
  2228. const overBatchId = Number(overId.slice('batch-'.length));
  2229. overIndex = pendingItems.findIndex((i) => i.batch_id === overBatchId);
  2230. } else {
  2231. overIndex = pendingItems.findIndex((i) => i.id === overId);
  2232. }
  2233. if (overIndex === -1) return;
  2234. // Remove the moving items, then re-insert at overIndex (adjusted).
  2235. const overAnchor = pendingItems[overIndex];
  2236. const remaining = pendingItems.filter((i) => !movingIds.includes(i.id));
  2237. let insertAt = remaining.findIndex((i) => i.id === overAnchor.id);
  2238. if (insertAt === -1) insertAt = overIndex;
  2239. // If dragging downward across the drop target, insert AFTER it; upward
  2240. // = before. dnd-kit's `over` is the row under the pointer, not the gap.
  2241. const firstMovingIndex = pendingItems.findIndex((i) => i.id === movingIds[0]);
  2242. if (firstMovingIndex < overIndex) insertAt += 1;
  2243. const reordered = [
  2244. ...remaining.slice(0, insertAt),
  2245. ...movingIds
  2246. .map((id) => pendingItems.find((i) => i.id === id))
  2247. .filter((x): x is PrintQueueItem => !!x),
  2248. ...remaining.slice(insertAt),
  2249. ];
  2250. const updates = reordered.map((item, index) => ({
  2251. id: item.id,
  2252. position: index + 1,
  2253. }));
  2254. reorderMutation.mutate(updates);
  2255. };
  2256. // Group pending items by batch_id. Items with batch_id null render as
  2257. // standalone rows; items sharing a batch_id render as a collapsible
  2258. // group keyed by that id. Items inside a group keep their original
  2259. // relative order from pendingItems.
  2260. const groupedRows = useMemo<QueueRow[]>(() => {
  2261. const rows: QueueRow[] = [];
  2262. const seenBatches = new Set<number>();
  2263. for (const item of pendingItems) {
  2264. if (item.batch_id != null) {
  2265. if (seenBatches.has(item.batch_id)) continue;
  2266. seenBatches.add(item.batch_id);
  2267. const siblings = pendingItems.filter((s) => s.batch_id === item.batch_id);
  2268. rows.push({
  2269. kind: 'batch',
  2270. batchId: item.batch_id,
  2271. batchName: item.batch_name || t('queue.batch.defaultName'),
  2272. items: siblings,
  2273. });
  2274. } else {
  2275. rows.push({ kind: 'item', item });
  2276. }
  2277. }
  2278. return rows;
  2279. }, [pendingItems, t]);
  2280. // Mobile tap-to-reorder (#2667). The desktop drag handle is hidden on
  2281. // phones and touch-drag is unreliable, so pending rows get up/down arrows.
  2282. // Reordering only has a defined meaning in the manual "position" sort with
  2283. // SJF off — any other sort re-orders the list itself, so we don't offer it.
  2284. const canReorderManually =
  2285. hasPermission('queue:reorder') &&
  2286. pendingSortBy === 'position' &&
  2287. !settings?.queue_shortest_first;
  2288. const rowItemIds = (row: QueueRow): number[] =>
  2289. row.kind === 'item' ? [row.item.id] : row.items.map((i) => i.id);
  2290. // Move a block of items to sit immediately before (or after) an anchor item
  2291. // in the global pending order, then persist — the same remove-and-reinsert
  2292. // shape as handleDragEnd, so arrows and drag agree. Anchoring to a real item
  2293. // id keeps it correct in the printer-grouped layout, where a bucket's rows
  2294. // aren't contiguous in the global order.
  2295. const moveBlockRelativeTo = (
  2296. movingIds: number[],
  2297. anchorId: number,
  2298. placeAfter: boolean,
  2299. ) => {
  2300. const remaining = pendingItems.filter((i) => !movingIds.includes(i.id));
  2301. let insertAt = remaining.findIndex((i) => i.id === anchorId);
  2302. if (insertAt === -1) return;
  2303. if (placeAfter) insertAt += 1;
  2304. const movingItems = movingIds
  2305. .map((id) => pendingItems.find((i) => i.id === id))
  2306. .filter((x): x is PrintQueueItem => !!x);
  2307. const reordered = [
  2308. ...remaining.slice(0, insertAt),
  2309. ...movingItems,
  2310. ...remaining.slice(insertAt),
  2311. ];
  2312. reorderMutation.mutate(
  2313. reordered.map((item, index) => ({ id: item.id, position: index + 1 })),
  2314. );
  2315. };
  2316. // Build up/down thunks for the row at `idx` within its displayed sibling
  2317. // list (the flat list, or a single printer bucket). Undefined at a boundary
  2318. // (button rendered disabled) or when manual reorder isn't available.
  2319. const rowMovers = (
  2320. rows: QueueRow[],
  2321. idx: number,
  2322. ): { onMoveUp?: () => void; onMoveDown?: () => void } => {
  2323. if (!canReorderManually) return {};
  2324. const moving = rowItemIds(rows[idx]);
  2325. const onMoveUp =
  2326. idx > 0
  2327. ? () => moveBlockRelativeTo(moving, rowItemIds(rows[idx - 1])[0], false)
  2328. : undefined;
  2329. const onMoveDown =
  2330. idx < rows.length - 1
  2331. ? () => {
  2332. const next = rowItemIds(rows[idx + 1]);
  2333. moveBlockRelativeTo(moving, next[next.length - 1], true);
  2334. }
  2335. : undefined;
  2336. return { onMoveUp, onMoveDown };
  2337. };
  2338. // SortableContext ID list.
  2339. // - Standalone pending items: their numeric id.
  2340. // - Batch parents: the synthetic `batch-<id>` string, always present so the
  2341. // group itself is draggable and acts as a drop target whether collapsed
  2342. // or expanded.
  2343. // - Expanded batch children: their numeric id, so within-batch reorder
  2344. // keeps working. Collapsed children are detached from the DOM and
  2345. // intentionally omitted to keep dnd-kit's collision resolver clean.
  2346. const sortableIds = useMemo<(number | string)[]>(() => {
  2347. const ids: (number | string)[] = [];
  2348. for (const row of groupedRows) {
  2349. if (row.kind === 'item') {
  2350. ids.push(row.item.id);
  2351. } else {
  2352. ids.push(`batch-${row.batchId}`);
  2353. const collapsed = batchCollapsed[row.batchId] ?? true;
  2354. if (!collapsed) {
  2355. for (const child of row.items) ids.push(child.id);
  2356. }
  2357. }
  2358. }
  2359. return ids;
  2360. }, [groupedRows, batchCollapsed]);
  2361. // Items already in a batch can't be grouped; "Group as batch" only shows
  2362. // when 2+ ungrouped items are selected.
  2363. const canGroupSelected = useMemo(() => {
  2364. if (selectedItems.length < 2) return false;
  2365. return selectedItems.every((id) => {
  2366. const item = pendingItems.find((p) => p.id === id);
  2367. return item && item.batch_id == null;
  2368. });
  2369. }, [selectedItems, pendingItems]);
  2370. const toggleBatchCollapsed = (id: number) => {
  2371. setBatchCollapsed((prev) => ({ ...prev, [id]: !(prev[id] ?? true) }));
  2372. };
  2373. // Group by printer view. Items are bucketed by printer_id (null = model
  2374. // assignment or unassigned, keyed by target_model or "unassigned").
  2375. type PrinterBucket = {
  2376. key: string;
  2377. printerId: number | null;
  2378. targetModel: string | null;
  2379. label: string;
  2380. isUnassigned: boolean;
  2381. rows: QueueRow[];
  2382. };
  2383. const printerBuckets = useMemo<PrinterBucket[]>(() => {
  2384. const buckets = new Map<string, PrinterBucket>();
  2385. const bucketForItem = (item: PrintQueueItem): { key: string; label: string; printerId: number | null; targetModel: string | null; isUnassigned: boolean } => {
  2386. if (item.printer_id) {
  2387. return {
  2388. key: `printer:${item.printer_id}`,
  2389. label: item.printer_name || `Printer #${item.printer_id}`,
  2390. printerId: item.printer_id,
  2391. targetModel: null,
  2392. isUnassigned: false,
  2393. };
  2394. }
  2395. // A cross-model item (#671) is waiting on several models. Its own
  2396. // target_model is just the first candidate mirrored onto the row, so
  2397. // bucketing on it would file the job under one printer it might never
  2398. // run on — and the row underneath already says "Any H2D / X1C".
  2399. if ((item.variants?.length ?? 0) > 1) {
  2400. const models = item.variants!.map((v) => v.target_model).join(' / ');
  2401. return {
  2402. key: `models:${models}`,
  2403. label: `${t('queue.filter.any')} ${models}`,
  2404. printerId: null,
  2405. targetModel: null,
  2406. isUnassigned: false,
  2407. };
  2408. }
  2409. if (item.target_model) {
  2410. return {
  2411. key: `model:${item.target_model}`,
  2412. label: `${t('queue.filter.any')} ${item.target_model}`,
  2413. printerId: null,
  2414. targetModel: item.target_model,
  2415. isUnassigned: false,
  2416. };
  2417. }
  2418. return {
  2419. key: 'unassigned',
  2420. label: t('queue.filter.unassigned'),
  2421. printerId: null,
  2422. targetModel: null,
  2423. isUnassigned: true,
  2424. };
  2425. };
  2426. for (const row of groupedRows) {
  2427. const representative = row.kind === 'item' ? row.item : row.items[0];
  2428. if (!representative) continue;
  2429. const meta = bucketForItem(representative);
  2430. if (!buckets.has(meta.key)) {
  2431. buckets.set(meta.key, { ...meta, rows: [] });
  2432. }
  2433. buckets.get(meta.key)!.rows.push(row);
  2434. }
  2435. return Array.from(buckets.values()).sort((a, b) => {
  2436. if (a.isUnassigned && !b.isUnassigned) return 1;
  2437. if (!a.isUnassigned && b.isUnassigned) return -1;
  2438. return a.label.localeCompare(b.label);
  2439. });
  2440. }, [groupedRows, t]);
  2441. // #1818: printers whose queue is gated by a prior failure that's poisoning
  2442. // downstream `require_previous_success` items. We surface a per-printer
  2443. // Resume banner above the active queue so the user can clear the gate +
  2444. // restore the skipped jobs in one click, without re-queuing each one.
  2445. // Detection key: skipped + the scheduler's exact gate string. Other skip
  2446. // reasons (filament deficit, etc.) get their own UX and stay untouched.
  2447. const gateBlockedPrinters = useMemo<
  2448. Array<{ printerId: number; printerName: string; skippedCount: number }>
  2449. >(() => {
  2450. const counts = new Map<number, { name: string; count: number }>();
  2451. queue?.forEach((item) => {
  2452. if (
  2453. item.status === 'skipped' &&
  2454. item.error_message === 'Previous print failed or was aborted' &&
  2455. item.printer_id
  2456. ) {
  2457. const existing = counts.get(item.printer_id);
  2458. if (existing) {
  2459. existing.count += 1;
  2460. } else {
  2461. counts.set(item.printer_id, {
  2462. name: item.printer_name || `Printer #${item.printer_id}`,
  2463. count: 1,
  2464. });
  2465. }
  2466. }
  2467. });
  2468. return Array.from(counts.entries())
  2469. .map(([printerId, { name, count }]) => ({
  2470. printerId,
  2471. printerName: name,
  2472. skippedCount: count,
  2473. }))
  2474. .sort((a, b) => a.printerName.localeCompare(b.printerName));
  2475. }, [queue]);
  2476. const aggregateForRows = (rows: QueueRow[]) => {
  2477. let count = 0;
  2478. let time = 0;
  2479. let weight = 0;
  2480. for (const row of rows) {
  2481. const items = row.kind === 'item' ? [row.item] : row.items;
  2482. for (const item of items) {
  2483. count += 1;
  2484. time += item.print_time_seconds || 0;
  2485. weight += item.filament_used_grams || 0;
  2486. }
  2487. }
  2488. return { count, time, weight };
  2489. };
  2490. return (
  2491. <div className="p-4 md:p-8">
  2492. {/* Header */}
  2493. <div className="flex items-center justify-between mb-6">
  2494. <div>
  2495. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  2496. <ListOrdered className="w-7 h-7 text-bambu-green" />
  2497. {t('queue.title')}
  2498. </h1>
  2499. <p className="text-bambu-gray mt-1">{t('queue.subtitle')}</p>
  2500. </div>
  2501. </div>
  2502. {/* Tab strip — Active queue is the main view; History and Timeline
  2503. live in their own tabs so the queue page stays focused. */}
  2504. <div className="flex gap-1 border-b border-bambu-dark-tertiary mb-6 overflow-x-auto">
  2505. {([
  2506. { id: 'queue' as const, label: t('queue.tabs.queue'), icon: Clock, count: pendingItems.length + activeItems.length },
  2507. { id: 'batches' as const, label: t('queue.tabs.batches'), icon: Package, count: activeBatchCount },
  2508. { id: 'history' as const, label: t('queue.tabs.history'), icon: ListOrdered, count: historyItems.length },
  2509. { id: 'timeline' as const, label: t('queue.tabs.timeline'), icon: GanttChart, count: null as number | null },
  2510. // Slicer Pipelines dashboard (#1425 PR C). Lives here instead of
  2511. // its own sidebar entry so the Print Queue page is the single
  2512. // place an operator looks for "what's running / what ran".
  2513. { id: 'pipelines' as const, label: t('queue.tabs.pipelines'), icon: Workflow, count: null as number | null },
  2514. ]).map(({ id, label, icon: Icon, count }) => (
  2515. <button
  2516. key={id}
  2517. onClick={() => setActiveTab(id)}
  2518. className={`px-4 py-2.5 text-sm flex items-center gap-2 border-b-2 -mb-px transition-colors whitespace-nowrap ${
  2519. activeTab === id
  2520. ? 'text-white border-bambu-green font-medium'
  2521. : 'text-bambu-gray border-transparent hover:text-white'
  2522. }`}
  2523. >
  2524. <Icon className="w-4 h-4" />
  2525. {label}
  2526. {count !== null && count > 0 && (
  2527. <span className={`text-xs px-1.5 py-0.5 rounded-full ${
  2528. activeTab === id ? 'bg-bambu-green/20 text-bambu-green' : 'bg-bambu-dark-tertiary text-bambu-gray'
  2529. }`}>
  2530. {count}
  2531. </span>
  2532. )}
  2533. </button>
  2534. ))}
  2535. </div>
  2536. {/* Summary Stats — about the print queue, not pipelines. */}
  2537. {activeTab !== 'pipelines' && activeTab !== 'batches' && <QueueStatsBar
  2538. activeCount={activeItems.length}
  2539. pendingCount={pendingItems.length}
  2540. totalTime={totalQueueTime}
  2541. totalWeight={totalWeight}
  2542. historyCount={historyItems.length}
  2543. t={t}
  2544. />}
  2545. {/* #1818: Resume-after-failure banner. One row per printer whose queue
  2546. is gated by a prior failed/aborted print. Visible regardless of
  2547. tab/layout so the user can clear the gate without hunting for
  2548. skipped items. Hidden entirely when no gates are active. */}
  2549. {activeTab === 'queue' && gateBlockedPrinters.length > 0 && hasPermission('queue:update_all' as Permission) && (
  2550. <div className="mb-4 space-y-2">
  2551. {gateBlockedPrinters.map(({ printerId, printerName, skippedCount }) => (
  2552. <div
  2553. key={printerId}
  2554. className="flex items-center gap-3 px-4 py-3 bg-orange-50 dark:bg-orange-500/10 border border-orange-300 dark:border-orange-500/30 rounded-lg"
  2555. >
  2556. <AlertCircle className="w-5 h-5 text-orange-600 dark:text-orange-400 flex-shrink-0" />
  2557. <div className="flex-1 min-w-0">
  2558. <div className="text-sm text-orange-800 dark:text-orange-200">
  2559. {t('queue.resumeAfterFailure.banner', {
  2560. printer: printerName,
  2561. count: skippedCount,
  2562. })}
  2563. </div>
  2564. <div className="text-xs text-orange-800/80 dark:text-orange-200/70 mt-0.5">
  2565. {t('queue.resumeAfterFailure.bannerHint')}
  2566. </div>
  2567. </div>
  2568. <button
  2569. onClick={() =>
  2570. setResumeConfirm({ printerId, printerName, skippedCount })
  2571. }
  2572. className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-100 dark:bg-orange-500/20 hover:bg-orange-200 dark:hover:bg-orange-500/30 text-orange-900 dark:text-orange-100 text-sm rounded-md border border-orange-300 dark:border-orange-500/40 transition-colors flex-shrink-0"
  2573. >
  2574. <PlayCircle className="w-4 h-4" />
  2575. {t('queue.resumeAfterFailure.button')}
  2576. </button>
  2577. </div>
  2578. ))}
  2579. </div>
  2580. )}
  2581. {/* Filters — about the print queue items (printer / status / location).
  2582. The Pipelines tab has its own pipeline + status filters inside the
  2583. dashboard, so this row is hidden when that tab is active. */}
  2584. {activeTab !== 'pipelines' && activeTab !== 'batches' && (
  2585. <div className="flex flex-wrap items-center gap-2 sm:gap-4 mb-6">
  2586. <select
  2587. className="px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none"
  2588. value={filterPrinter === -1 ? 'unassigned' : (filterPrinter || '')}
  2589. onChange={(e) => {
  2590. const val = e.target.value;
  2591. if (val === 'unassigned') setFilterPrinter(-1);
  2592. else if (val === '') setFilterPrinter(null);
  2593. else setFilterPrinter(Number(val));
  2594. }}
  2595. >
  2596. <option value="">{t('queue.filter.allPrinters')}</option>
  2597. <option value="unassigned">{t('queue.filter.unassigned')}</option>
  2598. {printers?.map((p) => (
  2599. <option key={p.id} value={p.id}>{p.name}</option>
  2600. ))}
  2601. </select>
  2602. <select
  2603. className="px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none"
  2604. value={filterStatus}
  2605. onChange={(e) => setFilterStatus(e.target.value)}
  2606. >
  2607. <option value="">{t('queue.filter.allStatus')}</option>
  2608. <option value="pending">{t('queue.status.pending')}</option>
  2609. <option value="printing">{t('queue.status.printing')}</option>
  2610. <option value="completed">{t('queue.status.completed')}</option>
  2611. <option value="failed">{t('queue.status.failed')}</option>
  2612. <option value="skipped">{t('queue.status.skipped')}</option>
  2613. <option value="cancelled">{t('queue.status.cancelled')}</option>
  2614. </select>
  2615. {uniqueLocations.length > 0 && (
  2616. <select
  2617. className="px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none"
  2618. value={filterLocation}
  2619. onChange={(e) => setFilterLocation(e.target.value)}
  2620. >
  2621. <option value="">{t('queue.filter.allLocations')}</option>
  2622. {uniqueLocations.map((loc) => (
  2623. <option key={loc} value={loc}>{loc}</option>
  2624. ))}
  2625. </select>
  2626. )}
  2627. <div className="hidden sm:block flex-1" />
  2628. {activeTab === 'history' && historyItems.length > 0 && (
  2629. <Button
  2630. className="w-full sm:w-auto"
  2631. variant="secondary"
  2632. size="sm"
  2633. onClick={() => setShowClearHistoryConfirm(true)}
  2634. disabled={!hasPermission('queue:delete_all')}
  2635. title={!hasPermission('queue:delete_all') ? t('queue.permissions.noClearHistory') : undefined}
  2636. >
  2637. <Trash2 className="w-4 h-4" />
  2638. {t('queue.clearHistory')}
  2639. </Button>
  2640. )}
  2641. </div>
  2642. )}
  2643. {/* Queue-tab controls: layout toggle (Position / Printer) + SJF.
  2644. Hidden on History/Timeline tabs since they don't apply. */}
  2645. {activeTab === 'queue' && (
  2646. <div className="flex flex-wrap items-center gap-3 mb-6">
  2647. <div className="inline-flex items-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-0.5">
  2648. <button
  2649. className={`px-3 py-1.5 text-xs sm:text-sm rounded-md transition-colors flex items-center gap-1.5 ${
  2650. activeLayout === 'position' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'
  2651. }`}
  2652. onClick={() => setActiveLayout('position')}
  2653. title={t('queue.layout.flatList')}
  2654. >
  2655. <List className="w-3.5 h-3.5" />
  2656. <span className="hidden sm:inline">{t('queue.layout.flatList')}</span>
  2657. </button>
  2658. <button
  2659. className={`px-3 py-1.5 text-xs sm:text-sm rounded-md transition-colors flex items-center gap-1.5 ${
  2660. activeLayout === 'printer' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'
  2661. }`}
  2662. onClick={() => setActiveLayout('printer')}
  2663. title={t('queue.layout.groupByPrinter')}
  2664. >
  2665. <Printer className="w-3.5 h-3.5" />
  2666. <span className="hidden sm:inline">{t('queue.layout.byPrinter')}</span>
  2667. </button>
  2668. </div>
  2669. <button
  2670. onClick={() => {
  2671. const newValue = !(settings?.queue_shortest_first ?? false);
  2672. sjfMutation.mutate(newValue);
  2673. }}
  2674. className={`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${
  2675. settings?.queue_shortest_first
  2676. ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
  2677. : 'bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  2678. }`}
  2679. title={t('queue.sjf.tooltip', 'Shortest Job First — scheduler prioritizes shorter prints')}
  2680. >
  2681. <Snail className="w-4 h-4" />
  2682. <span className="hidden sm:inline">{t('queue.sjf.label', 'SJF')}</span>
  2683. <span className={`w-1.5 h-1.5 rounded-full ${settings?.queue_shortest_first ? 'bg-bambu-green' : 'bg-bambu-gray'}`} />
  2684. </button>
  2685. </div>
  2686. )}
  2687. {/* Pipelines tab short-circuits before the queue-empty branch so the
  2688. dashboard renders even when the regular queue is empty. */}
  2689. {activeTab === 'pipelines' ? (
  2690. <PipelineRunsView />
  2691. ) : activeTab === 'batches' ? (
  2692. <BatchOrdersView hasPermission={hasPermission} t={t} focusBatchId={focusBatchId} />
  2693. ) : isLoading ? (
  2694. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  2695. ) : queue?.length === 0 ? (
  2696. <Card className="p-12 text-center border-dashed">
  2697. <Calendar className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  2698. <h3 className="text-xl font-medium text-white mb-2">{t('queue.empty.title')}</h3>
  2699. <p className="text-bambu-gray max-w-md mx-auto">
  2700. {t('queue.empty.description')}
  2701. </p>
  2702. </Card>
  2703. ) : activeTab === 'timeline' ? (
  2704. <QueueTimelineView
  2705. queueItems={queue || []}
  2706. printers={printers || []}
  2707. printerStatuses={printerStatusMap}
  2708. sjfEnabled={settings?.queue_shortest_first ?? false}
  2709. onItemClick={(item) => {
  2710. if (['completed', 'failed', 'skipped', 'cancelled'].includes(item.status)) {
  2711. setRequeueItem(item);
  2712. } else if (item.status === 'pending') {
  2713. setEditItem(item);
  2714. } else if (item.status === 'printing') {
  2715. setConfirmAction({ type: 'stop', item });
  2716. }
  2717. }}
  2718. t={t}
  2719. />
  2720. ) : activeTab === 'history' ? (
  2721. <HistorySection
  2722. items={historyItems}
  2723. collapsed={false}
  2724. visibleCount={historyVisibleCount}
  2725. onShowMore={() => setHistoryVisibleCount((c) => c + HISTORY_PAGE_SIZE)}
  2726. sortBy={historySortBy}
  2727. sortAsc={historySortAsc}
  2728. onSortByChange={setHistorySortBy}
  2729. onSortAscToggle={() => setHistorySortAsc(!historySortAsc)}
  2730. onRemove={(item) => setConfirmAction({ type: 'remove', item })}
  2731. onRequeue={setRequeueItem}
  2732. timeFormat={timeFormat}
  2733. batchCollapsed={batchCollapsed}
  2734. toggleBatchCollapsed={toggleBatchCollapsed}
  2735. hasPermission={hasPermission}
  2736. canModify={canModify}
  2737. t={t}
  2738. />
  2739. ) : (
  2740. <div className="space-y-6 sm:space-y-8">
  2741. {/* Active Prints */}
  2742. {activeItems.length > 0 && (
  2743. <div>
  2744. <h2 className="text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2">
  2745. <div className="w-2 h-2 rounded-full bg-blue-400 animate-pulse" />
  2746. {t('queue.sections.currentlyPrinting')}
  2747. </h2>
  2748. <div className="space-y-2 sm:space-y-3">
  2749. {activeItems.map((item) => (
  2750. <SortableQueueItem
  2751. key={item.id}
  2752. item={item}
  2753. onEdit={() => {}}
  2754. onCancel={() => {}}
  2755. onRemove={() => {}}
  2756. onStop={() => setConfirmAction({ type: 'stop', item })}
  2757. onRequeue={() => {}}
  2758. onStart={() => {}}
  2759. timeFormat={timeFormat}
  2760. hasPermission={hasPermission}
  2761. canModify={canModify}
  2762. printerState={item.printer_id ? printerStateMap[item.printer_id] : null}
  2763. t={t}
  2764. />
  2765. ))}
  2766. </div>
  2767. </div>
  2768. )}
  2769. {/* Pending Queue */}
  2770. {pendingItems.length > 0 && (
  2771. <div>
  2772. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  2773. <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
  2774. <Clock className="w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 dark:text-yellow-400" />
  2775. {t('queue.sections.queued')}
  2776. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  2777. ({t('queue.itemCount', { count: pendingItems.length })})
  2778. </span>
  2779. <span className="hidden sm:inline text-xs text-bambu-gray ml-2" title={t('queue.reorderHint')}>
  2780. {t('queue.dragToReorder')}
  2781. </span>
  2782. </h2>
  2783. <div className="flex items-center gap-2">
  2784. <select
  2785. className="px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2786. value={pendingSortBy}
  2787. onChange={(e) => setPendingSortBy(e.target.value as 'position' | 'name' | 'printer' | 'time')}
  2788. >
  2789. <option value="position">{t('queue.sort.byPosition')}</option>
  2790. <option value="name">{t('queue.sort.byName')}</option>
  2791. <option value="printer">{t('queue.sort.byPrinter')}</option>
  2792. <option value="time">{t('queue.sort.bySchedule')}</option>
  2793. </select>
  2794. <Button
  2795. variant="ghost"
  2796. size="sm"
  2797. onClick={() => setPendingSortAsc(!pendingSortAsc)}
  2798. title={pendingSortAsc ? t('common.ascending') : t('common.descending')}
  2799. className="px-2"
  2800. >
  2801. {pendingSortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  2802. </Button>
  2803. </div>
  2804. </div>
  2805. {/* Bulk action toolbar (now with "Group as batch") */}
  2806. <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-3 sm:mb-4 p-2 sm:p-3 bg-bambu-dark rounded-lg">
  2807. <Button
  2808. variant="ghost"
  2809. size="sm"
  2810. onClick={handleSelectAll}
  2811. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm"
  2812. >
  2813. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? (
  2814. <CheckSquare className="w-4 h-4 text-bambu-green" />
  2815. ) : (
  2816. <Square className="w-4 h-4" />
  2817. )}
  2818. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? t('queue.bulkEdit.deselectAll') : t('queue.bulkEdit.selectAll')}
  2819. </Button>
  2820. {selectedItems.length > 0 && (
  2821. <>
  2822. <span className="text-xs sm:text-sm text-bambu-gray">
  2823. {t('queue.bulkEdit.selected', { count: selectedItems.length })}
  2824. </span>
  2825. <div className="hidden sm:block h-4 w-px bg-bambu-dark-tertiary" />
  2826. {canGroupSelected && (
  2827. <Button
  2828. variant="ghost"
  2829. size="sm"
  2830. onClick={() => setGroupBatchModal(true)}
  2831. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-cyan-700 dark:text-cyan-300 hover:text-cyan-900 dark:hover:text-cyan-200"
  2832. title={t('queue.batch.groupAsBatch')}
  2833. >
  2834. <Package className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2835. <span className="hidden sm:inline">{t('queue.batch.groupAsBatch')}</span>
  2836. </Button>
  2837. )}
  2838. <Button
  2839. variant="ghost"
  2840. size="sm"
  2841. onClick={() => setShowBulkEditModal(true)}
  2842. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light"
  2843. disabled={!hasAnyPermission('queue:update_own', 'queue:update_all')}
  2844. title={!hasAnyPermission('queue:update_own', 'queue:update_all') ? t('queue.permissions.noEditItems') : t('queue.bulkEdit.editSelected')}
  2845. >
  2846. <Pencil className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2847. <span className="hidden sm:inline">{t('queue.bulkEdit.editSelected')}</span>
  2848. </Button>
  2849. <Button
  2850. variant="ghost"
  2851. size="sm"
  2852. onClick={() => bulkCancelMutation.mutate(selectedItems)}
  2853. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"
  2854. disabled={bulkCancelMutation.isPending || !hasAnyPermission('queue:delete_own', 'queue:delete_all')}
  2855. title={!hasAnyPermission('queue:delete_own', 'queue:delete_all') ? t('queue.permissions.noCancelItems') : t('queue.bulkEdit.cancelSelected')}
  2856. >
  2857. <X className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2858. <span className="hidden sm:inline">{t('queue.bulkEdit.cancelSelected')}</span>
  2859. </Button>
  2860. </>
  2861. )}
  2862. </div>
  2863. <DndContext
  2864. sensors={sensors}
  2865. collisionDetection={closestCenter}
  2866. onDragStart={handleDragStart}
  2867. onDragEnd={handleDragEnd}
  2868. >
  2869. <SortableContext
  2870. items={sortableIds}
  2871. strategy={verticalListSortingStrategy}
  2872. >
  2873. {activeLayout === 'position' ? (
  2874. <div className="space-y-2 sm:space-y-3">
  2875. {groupedRows.map((row, idx) => (
  2876. <QueueRowRender
  2877. key={row.kind === 'item' ? `item-${row.item.id}` : `batch-${row.batchId}`}
  2878. row={row}
  2879. collapsed={row.kind === 'batch' ? (batchCollapsed[row.batchId] ?? true) : false}
  2880. onToggleBatch={row.kind === 'batch' ? () => toggleBatchCollapsed(row.batchId) : undefined}
  2881. onUngroup={row.kind === 'batch' ? () => setUngroupBatchId(row.batchId) : undefined}
  2882. setEditItem={setEditItem}
  2883. setConfirmAction={setConfirmAction}
  2884. startMutation={startMutation}
  2885. selectedItems={selectedItems}
  2886. handleToggleSelect={handleToggleSelect}
  2887. timeFormat={timeFormat}
  2888. hasPermission={hasPermission}
  2889. canModify={canModify}
  2890. t={t}
  2891. etaEligibleIds={etaEligibleIds}
  2892. etaNow={etaNow}
  2893. aggregateForRows={aggregateForRows}
  2894. {...rowMovers(groupedRows, idx)}
  2895. onMoveBlock={canReorderManually ? moveBlockRelativeTo : undefined}
  2896. />
  2897. ))}
  2898. </div>
  2899. ) : (
  2900. <div className="space-y-4">
  2901. {printerBuckets.map((bucket) => {
  2902. const agg = aggregateForRows(bucket.rows);
  2903. return (
  2904. <div key={bucket.key}>
  2905. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-t-lg">
  2906. <Printer className={`w-4 h-4 ${bucket.isUnassigned ? 'text-orange-600 dark:text-orange-400' : bucket.targetModel ? 'text-blue-600 dark:text-blue-400' : 'text-bambu-green'}`} />
  2907. <span className="font-semibold text-white text-sm">{bucket.label}</span>
  2908. <span className="text-xs text-bambu-gray flex flex-wrap gap-x-3">
  2909. <span>{t('queue.itemCount', { count: agg.count })}</span>
  2910. {agg.time > 0 && <span>{formatDuration(agg.time)}</span>}
  2911. {agg.weight > 0 && <span>{formatWeight(agg.weight)}</span>}
  2912. </span>
  2913. </div>
  2914. <div className="bg-bambu-dark/40 border border-t-0 border-bambu-dark-tertiary rounded-b-lg p-2 space-y-2">
  2915. {bucket.rows.map((row, idx) => (
  2916. <QueueRowRender
  2917. key={row.kind === 'item' ? `item-${row.item.id}` : `batch-${row.batchId}`}
  2918. row={row}
  2919. collapsed={row.kind === 'batch' ? (batchCollapsed[row.batchId] ?? true) : false}
  2920. onToggleBatch={row.kind === 'batch' ? () => toggleBatchCollapsed(row.batchId) : undefined}
  2921. onUngroup={row.kind === 'batch' ? () => setUngroupBatchId(row.batchId) : undefined}
  2922. setEditItem={setEditItem}
  2923. setConfirmAction={setConfirmAction}
  2924. startMutation={startMutation}
  2925. selectedItems={selectedItems}
  2926. handleToggleSelect={handleToggleSelect}
  2927. timeFormat={timeFormat}
  2928. hasPermission={hasPermission}
  2929. canModify={canModify}
  2930. t={t}
  2931. etaEligibleIds={etaEligibleIds}
  2932. etaNow={etaNow}
  2933. aggregateForRows={aggregateForRows}
  2934. {...rowMovers(bucket.rows, idx)}
  2935. onMoveBlock={canReorderManually ? moveBlockRelativeTo : undefined}
  2936. />
  2937. ))}
  2938. </div>
  2939. </div>
  2940. );
  2941. })}
  2942. </div>
  2943. )}
  2944. </SortableContext>
  2945. <DragOverlay>
  2946. {(() => {
  2947. if (activeDragId === null) return null;
  2948. // Batch drag — show the group ghost with copy count.
  2949. if (typeof activeDragId === 'string' && activeDragId.startsWith('batch-')) {
  2950. const batchId = Number(activeDragId.slice('batch-'.length));
  2951. const siblings = pendingItems.filter((i) => i.batch_id === batchId);
  2952. if (siblings.length === 0) return null;
  2953. const name = siblings[0].batch_name || t('queue.batch.defaultName');
  2954. return (
  2955. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border-2 border-cyan-400 rounded-lg shadow-2xl">
  2956. <Package className="w-4 h-4 text-cyan-700 dark:text-cyan-300" />
  2957. <span className="text-sm text-white font-medium">
  2958. {t('queue.dragGhost.batch', {
  2959. defaultValue: '{{name}} ({{count}} copies)',
  2960. name,
  2961. count: siblings.length,
  2962. })}
  2963. </span>
  2964. </div>
  2965. );
  2966. }
  2967. // Multi-row drag — show the N-item ghost.
  2968. if (typeof activeDragId === 'number' && selectedItems.includes(activeDragId) && selectedItems.length > 1) {
  2969. return (
  2970. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border-2 border-cyan-400 rounded-lg shadow-2xl">
  2971. <Package className="w-4 h-4 text-cyan-700 dark:text-cyan-300" />
  2972. <span className="text-sm text-white font-medium">
  2973. {t('queue.dragGhost.multiCount', { count: selectedItems.length })}
  2974. </span>
  2975. </div>
  2976. );
  2977. }
  2978. return null;
  2979. })()}
  2980. </DragOverlay>
  2981. </DndContext>
  2982. </div>
  2983. )}
  2984. </div>
  2985. )}
  2986. {/* Edit Modal */}
  2987. {editItem && (
  2988. <PrintModal
  2989. mode="edit-queue-item"
  2990. archiveId={editItem.archive_id ?? undefined}
  2991. libraryFileId={editItem.library_file_id ?? undefined}
  2992. archiveName={queueItemDisplayName(editItem, (n) => t('common.plusNMore', { count: n }))}
  2993. queueItem={editItem}
  2994. onClose={() => setEditItem(null)}
  2995. />
  2996. )}
  2997. {/* Re-queue Modal */}
  2998. {requeueItem && (
  2999. <PrintModal
  3000. mode="create"
  3001. archiveId={requeueItem.archive_id ?? undefined}
  3002. libraryFileId={requeueItem.library_file_id ?? undefined}
  3003. archiveName={queueItemDisplayName(requeueItem, (n) => t('common.plusNMore', { count: n }))}
  3004. onClose={() => setRequeueItem(null)}
  3005. />
  3006. )}
  3007. {/* Confirm Action Modal */}
  3008. {filamentShortConfirm && (
  3009. <ConfirmModal
  3010. title={t('queue.filamentShort.confirmTitle')}
  3011. message={
  3012. t('queue.filamentShort.confirmIntro') + '\n\n' +
  3013. filamentShortConfirm.deficit
  3014. .map((d) =>
  3015. t('queue.filamentShort.lineItem', {
  3016. slot: d.slot_id,
  3017. required: Math.round(d.required_grams),
  3018. remaining:
  3019. d.remaining_grams == null
  3020. ? t('queue.filamentShort.unknown')
  3021. : Math.round(d.remaining_grams),
  3022. }),
  3023. )
  3024. .join('\n')
  3025. }
  3026. confirmText={t('queue.filamentShort.printAnyway')}
  3027. variant="warning"
  3028. onConfirm={() => {
  3029. startMutation.mutate({ id: filamentShortConfirm.itemId, skipFilamentCheck: true });
  3030. }}
  3031. onCancel={() => setFilamentShortConfirm(null)}
  3032. />
  3033. )}
  3034. {filamentMissingConfirm && (
  3035. <ConfirmModal
  3036. title={t('queue.filamentMissing.confirmTitle')}
  3037. message={t('queue.filamentMissing.confirmIntro') + '\n\n' + filamentMissingConfirm.missing.join('\n')}
  3038. confirmText={t('queue.filamentShort.printAnyway')}
  3039. variant="warning"
  3040. onConfirm={() => {
  3041. startMutation.mutate({ id: filamentMissingConfirm.itemId, skipFilamentCheck: true });
  3042. }}
  3043. onCancel={() => setFilamentMissingConfirm(null)}
  3044. />
  3045. )}
  3046. {confirmAction && (
  3047. <ConfirmModal
  3048. title={
  3049. confirmAction.type === 'cancel' ? t('queue.confirm.cancelTitle') :
  3050. confirmAction.type === 'stop' ? t('queue.confirm.stopTitle') :
  3051. t('queue.confirm.removeTitle')
  3052. }
  3053. message={
  3054. confirmAction.type === 'cancel'
  3055. ? t('queue.confirm.cancelMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  3056. : confirmAction.type === 'stop'
  3057. ? t('queue.confirm.stopMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  3058. : t('queue.confirm.removeMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisItem') })
  3059. }
  3060. confirmText={
  3061. confirmAction.type === 'cancel' ? t('queue.confirm.cancelButton') :
  3062. confirmAction.type === 'stop' ? t('queue.confirm.stopButton') :
  3063. t('common.remove')
  3064. }
  3065. variant="danger"
  3066. onConfirm={() => {
  3067. if (confirmAction.type === 'cancel') {
  3068. cancelMutation.mutate(confirmAction.item.id);
  3069. } else if (confirmAction.type === 'stop') {
  3070. stopMutation.mutate(confirmAction.item.id);
  3071. } else {
  3072. removeMutation.mutate(confirmAction.item.id);
  3073. }
  3074. setConfirmAction(null);
  3075. }}
  3076. onCancel={() => setConfirmAction(null)}
  3077. />
  3078. )}
  3079. {/* #1818: Resume-after-failure confirm */}
  3080. {resumeConfirm && (
  3081. <ConfirmModal
  3082. title={t('queue.resumeAfterFailure.confirmTitle')}
  3083. message={t('queue.resumeAfterFailure.confirmMessage', {
  3084. printer: resumeConfirm.printerName,
  3085. count: resumeConfirm.skippedCount,
  3086. })}
  3087. confirmText={t('queue.resumeAfterFailure.button')}
  3088. variant="warning"
  3089. onConfirm={() => resumeAfterFailureMutation.mutate(resumeConfirm.printerId)}
  3090. onCancel={() => setResumeConfirm(null)}
  3091. />
  3092. )}
  3093. {/* Clear History Confirm Modal */}
  3094. {showClearHistoryConfirm && (
  3095. <ConfirmModal
  3096. title={t('queue.confirm.clearHistoryTitle')}
  3097. message={t('queue.confirm.clearHistoryMessage', { count: historyItems.length })}
  3098. confirmText={t('queue.clearHistory')}
  3099. variant="danger"
  3100. onConfirm={() => {
  3101. clearHistoryMutation.mutate();
  3102. setShowClearHistoryConfirm(false);
  3103. }}
  3104. onCancel={() => setShowClearHistoryConfirm(false)}
  3105. />
  3106. )}
  3107. {/* Bulk Edit Modal */}
  3108. {showBulkEditModal && (
  3109. <BulkEditModal
  3110. selectedCount={selectedItems.length}
  3111. printers={printers?.map(p => ({ id: p.id, name: p.name, nozzle_count: p.nozzle_count })) || []}
  3112. onSave={(data) => {
  3113. if (Object.keys(data).length > 0) {
  3114. bulkUpdateMutation.mutate({ item_ids: selectedItems, ...data });
  3115. }
  3116. }}
  3117. onClose={() => setShowBulkEditModal(false)}
  3118. isSaving={bulkUpdateMutation.isPending}
  3119. canControlPrinter={hasPermission('printers:control')}
  3120. hasGcodeSnippets={!!settings?.gcode_snippets}
  3121. t={t}
  3122. />
  3123. )}
  3124. {/* Group as batch modal — name prompt */}
  3125. {groupBatchModal && (
  3126. <GroupBatchModal
  3127. itemCount={selectedItems.length}
  3128. isSaving={createBatchMutation.isPending}
  3129. defaultName={(() => {
  3130. // Suggest a name derived from the first selected item's source.
  3131. const first = pendingItems.find((i) => selectedItems.includes(i.id));
  3132. const raw = first?.archive_name || first?.library_file_name || '';
  3133. const cleaned = raw.replace(/\.gcode\.3mf$/i, '').replace(/\.3mf$/i, '');
  3134. return cleaned ? `${cleaned}` : t('queue.batch.defaultName');
  3135. })()}
  3136. onSave={(name) => createBatchMutation.mutate({ name, item_ids: selectedItems })}
  3137. onClose={() => setGroupBatchModal(false)}
  3138. t={t}
  3139. />
  3140. )}
  3141. {/* Ungroup batch confirm */}
  3142. {ungroupBatchId !== null && (
  3143. <ConfirmModal
  3144. title={t('queue.batch.ungroupConfirmTitle')}
  3145. message={t('queue.batch.ungroupConfirmMessage')}
  3146. confirmText={t('queue.batch.ungroup')}
  3147. variant="warning"
  3148. onConfirm={() => ungroupBatchMutation.mutate(ungroupBatchId)}
  3149. onCancel={() => setUngroupBatchId(null)}
  3150. />
  3151. )}
  3152. </div>
  3153. );
  3154. }
  3155. interface GroupBatchModalProps {
  3156. itemCount: number;
  3157. defaultName: string;
  3158. isSaving: boolean;
  3159. onSave: (name: string) => void;
  3160. onClose: () => void;
  3161. t: (key: string, options?: Record<string, unknown>) => string;
  3162. }
  3163. function GroupBatchModal({ itemCount, defaultName, isSaving, onSave, onClose, t }: GroupBatchModalProps) {
  3164. const [name, setName] = useState(defaultName);
  3165. return (
  3166. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
  3167. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-6 w-full max-w-md">
  3168. <h3 className="text-lg font-semibold text-white mb-2 flex items-center gap-2">
  3169. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  3170. {t('queue.batch.groupAsBatch')}
  3171. </h3>
  3172. <p className="text-sm text-bambu-gray mb-4">
  3173. {t('queue.batch.groupAsBatchDescription', { count: itemCount })}
  3174. </p>
  3175. <label className="block text-sm font-medium text-white mb-2">
  3176. {t('queue.batch.nameLabel')}
  3177. </label>
  3178. <input
  3179. type="text"
  3180. autoFocus
  3181. value={name}
  3182. onChange={(e) => setName(e.target.value)}
  3183. placeholder={t('queue.batch.namePlaceholder')}
  3184. maxLength={120}
  3185. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none mb-5"
  3186. />
  3187. <div className="flex justify-end gap-2">
  3188. <Button variant="ghost" size="sm" onClick={onClose} disabled={isSaving}>
  3189. {t('common.cancel')}
  3190. </Button>
  3191. <Button
  3192. variant="primary"
  3193. size="sm"
  3194. onClick={() => {
  3195. const trimmed = name.trim();
  3196. if (trimmed) onSave(trimmed);
  3197. }}
  3198. disabled={isSaving || !name.trim()}
  3199. >
  3200. {isSaving ? t('common.saving') : t('queue.batch.create')}
  3201. </Button>
  3202. </div>
  3203. </div>
  3204. </div>
  3205. );
  3206. }