QueuePage.tsx 143 KB

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