QueuePage.tsx 141 KB

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