QueuePage.tsx 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  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 {
  23. Clock,
  24. Trash2,
  25. Play,
  26. X,
  27. CheckCircle,
  28. XCircle,
  29. AlertCircle,
  30. Calendar,
  31. Printer,
  32. GripVertical,
  33. SkipForward,
  34. ExternalLink,
  35. Power,
  36. StopCircle,
  37. Pencil,
  38. RefreshCw,
  39. Timer,
  40. ListOrdered,
  41. Layers,
  42. ArrowUp,
  43. ArrowDown,
  44. Hand,
  45. Check,
  46. CheckSquare,
  47. Square,
  48. User,
  49. Pause,
  50. Weight,
  51. ChevronDown,
  52. ChevronRight,
  53. List,
  54. GanttChart,
  55. Code,
  56. Snail,
  57. Package,
  58. PackageOpen,
  59. Ungroup,
  60. Ban,
  61. PlayCircle,
  62. Workflow,
  63. } from 'lucide-react';
  64. import { api, ApiError } from '../api/client';
  65. import { PipelineRunsView } from './PipelineRunsPage';
  66. import { type TimeFormat, formatETA, formatDuration, formatRelativeTime, parseUTCDate } from '../utils/date';
  67. import { getBedTypeInfo } from '../utils/bedType';
  68. import type { PrintQueueItem, PrintQueueBulkUpdate, Permission, CalibrationMode } from '../api/client';
  69. import { Card } from '../components/Card';
  70. import { Button } from '../components/Button';
  71. import { ConfirmModal } from '../components/ConfirmModal';
  72. import { PrintModal } from '../components/PrintModal';
  73. import { useToast } from '../contexts/ToastContext';
  74. import { useAuth } from '../contexts/AuthContext';
  75. import { QueueStatsBar } from '../components/QueueStatsBar';
  76. import { CompactHistoryRow } from '../components/CompactHistoryRow';
  77. import { QueueTimelineView } from '../components/QueueTimelineView';
  78. function formatWeight(g: number, useKg = false): string {
  79. if (useKg && g >= 1000) return `${(g / 1000).toFixed(1)}kg`;
  80. return `${Math.round(g)}g`;
  81. }
  82. function StatusBadge({ status, waitingReason, printerState, t }: { status: PrintQueueItem['status']; waitingReason?: string | null; printerState?: string | null; t: (key: string) => string }) {
  83. // Special case: pending with waiting_reason shows as "Waiting"
  84. if (status === 'pending' && waitingReason) {
  85. return (
  86. <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">
  87. <Clock className="w-3.5 h-3.5" />
  88. {t('queue.status.waiting')}
  89. </span>
  90. );
  91. }
  92. // Special case: printing but printer is paused
  93. if (status === 'printing' && printerState === 'PAUSE') {
  94. return (
  95. <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">
  96. <Pause className="w-3.5 h-3.5" />
  97. {t('queue.status.paused')}
  98. </span>
  99. );
  100. }
  101. const config = {
  102. pending: { icon: Clock, color: 'text-status-warning bg-status-warning/10 border-status-warning/20', label: t('queue.status.pending') },
  103. 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') },
  104. completed: { icon: CheckCircle, color: 'text-status-ok bg-status-ok/10 border-status-ok/20', label: t('queue.status.completed') },
  105. failed: { icon: XCircle, color: 'text-status-error bg-status-error/10 border-status-error/20', label: t('queue.status.failed') },
  106. 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') },
  107. cancelled: { icon: X, color: 'text-gray-400 bg-gray-400/10 border-gray-400/20', label: t('queue.status.cancelled') },
  108. };
  109. const { icon: Icon, color, label } = config[status];
  110. return (
  111. <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${color}`}>
  112. <Icon className="w-3.5 h-3.5" />
  113. {label}
  114. </span>
  115. );
  116. }
  117. // Bulk edit modal for multiple queue items
  118. function BulkEditModal({
  119. selectedCount,
  120. printers,
  121. onSave,
  122. onClose,
  123. isSaving,
  124. canControlPrinter,
  125. t,
  126. }: {
  127. selectedCount: number;
  128. printers: { id: number; name: string; nozzle_count?: number }[];
  129. onSave: (data: Partial<PrintQueueBulkUpdate>) => void;
  130. onClose: () => void;
  131. isSaving: boolean;
  132. canControlPrinter: boolean;
  133. t: (key: string, options?: Record<string, unknown>) => string;
  134. }) {
  135. const [printerId, setPrinterId] = useState<number | null | 'unchanged'>('unchanged');
  136. const [manualStart, setManualStart] = useState<boolean | 'unchanged'>('unchanged');
  137. const [autoOffAfter, setAutoOffAfter] = useState<boolean | 'unchanged'>('unchanged');
  138. const [requirePreviousSuccess, setRequirePreviousSuccess] = useState<boolean | 'unchanged'>('unchanged');
  139. const [bedLevelling, setBedLevelling] = useState<CalibrationMode | 'unchanged'>('unchanged');
  140. const [flowCali, setFlowCali] = useState<CalibrationMode | 'unchanged'>('unchanged');
  141. const [vibrationCali, setVibrationCali] = useState<boolean | 'unchanged'>('unchanged');
  142. const [layerInspect, setLayerInspect] = useState<boolean | 'unchanged'>('unchanged');
  143. const [timelapse, setTimelapse] = useState<boolean | 'unchanged'>('unchanged');
  144. const [useAms, setUseAms] = useState<boolean | 'unchanged'>('unchanged');
  145. const [nozzleOffsetCali, setNozzleOffsetCali] = useState<CalibrationMode | 'unchanged'>('unchanged');
  146. // Show the dual-nozzle-only toggle when the user has at least one
  147. // dual-nozzle printer registered (H2D/H2D Pro/H2C/X2D). Single-nozzle
  148. // queues never see it — the MQTT layer ignores the field anyway.
  149. const hasDualNozzlePrinter = printers.some(p => p.nozzle_count === 2);
  150. const handleSave = () => {
  151. const data: Partial<PrintQueueBulkUpdate> = {};
  152. if (printerId !== 'unchanged') data.printer_id = printerId;
  153. if (manualStart !== 'unchanged') data.manual_start = manualStart;
  154. if (autoOffAfter !== 'unchanged') data.auto_off_after = autoOffAfter;
  155. if (requirePreviousSuccess !== 'unchanged') data.require_previous_success = requirePreviousSuccess;
  156. if (bedLevelling !== 'unchanged') data.bed_levelling = bedLevelling;
  157. if (flowCali !== 'unchanged') data.flow_cali = flowCali;
  158. if (vibrationCali !== 'unchanged') data.vibration_cali = vibrationCali;
  159. if (layerInspect !== 'unchanged') data.layer_inspect = layerInspect;
  160. if (timelapse !== 'unchanged') data.timelapse = timelapse;
  161. if (useAms !== 'unchanged') data.use_ams = useAms;
  162. if (nozzleOffsetCali !== 'unchanged') data.nozzle_offset_cali = nozzleOffsetCali;
  163. onSave(data);
  164. };
  165. const hasChanges = printerId !== 'unchanged' || manualStart !== 'unchanged' || autoOffAfter !== 'unchanged' ||
  166. requirePreviousSuccess !== 'unchanged' || bedLevelling !== 'unchanged' || flowCali !== 'unchanged' ||
  167. vibrationCali !== 'unchanged' || layerInspect !== 'unchanged' || timelapse !== 'unchanged' || useAms !== 'unchanged' ||
  168. nozzleOffsetCali !== 'unchanged';
  169. return (
  170. <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
  171. <div className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto">
  172. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  173. <h2 className="text-lg font-semibold text-white">
  174. {t('queue.bulkEdit.title', { count: selectedCount })}
  175. </h2>
  176. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  177. <X className="w-5 h-5 text-bambu-gray" />
  178. </button>
  179. </div>
  180. <div className="p-4 space-y-4">
  181. <p className="text-sm text-bambu-gray">
  182. {t('queue.bulkEdit.description')}
  183. </p>
  184. {/* Printer Assignment */}
  185. <div>
  186. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printer')}</label>
  187. <select
  188. value={printerId === null ? 'null' : printerId === 'unchanged' ? 'unchanged' : String(printerId)}
  189. onChange={(e) => {
  190. const val = e.target.value;
  191. if (val === 'unchanged') setPrinterId('unchanged');
  192. else if (val === 'null') setPrinterId(null);
  193. else setPrinterId(Number(val));
  194. }}
  195. 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"
  196. >
  197. <option value="unchanged">{t('queue.bulkEdit.noChange')}</option>
  198. <option value="null">{t('queue.filter.unassigned')}</option>
  199. {printers.map(p => (
  200. <option key={p.id} value={p.id}>{p.name}</option>
  201. ))}
  202. </select>
  203. </div>
  204. {/* Queue Options */}
  205. <div>
  206. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.queueOptions')}</label>
  207. <div className="space-y-2">
  208. <TriStateToggle label={t('queue.bulkEdit.staged')} value={manualStart} onChange={setManualStart} t={t} />
  209. <TriStateToggle label={t('queue.bulkEdit.autoPowerOff')} value={autoOffAfter} onChange={setAutoOffAfter} disabled={!canControlPrinter} t={t} />
  210. <TriStateToggle label={t('queue.bulkEdit.requirePrevious')} value={requirePreviousSuccess} onChange={setRequirePreviousSuccess} t={t} />
  211. </div>
  212. </div>
  213. {/* Print Options */}
  214. <div>
  215. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printOptions')}</label>
  216. <div className="space-y-2">
  217. <CalibrationModeToggle label={t('queue.bulkEdit.bedLevelling')} value={bedLevelling} onChange={setBedLevelling} t={t} />
  218. <CalibrationModeToggle label={t('queue.bulkEdit.flowCalibration')} value={flowCali} onChange={setFlowCali} t={t} />
  219. <TriStateToggle label={t('queue.bulkEdit.vibrationCalibration')} value={vibrationCali} onChange={setVibrationCali} t={t} />
  220. <TriStateToggle label={t('queue.bulkEdit.layerInspection')} value={layerInspect} onChange={setLayerInspect} t={t} />
  221. <TriStateToggle label={t('queue.bulkEdit.timelapse')} value={timelapse} onChange={setTimelapse} t={t} />
  222. <TriStateToggle label={t('queue.bulkEdit.useAms')} value={useAms} onChange={setUseAms} t={t} />
  223. {hasDualNozzlePrinter && (
  224. <CalibrationModeToggle label={t('queue.bulkEdit.nozzleOffsetCali')} value={nozzleOffsetCali} onChange={setNozzleOffsetCali} t={t} />
  225. )}
  226. </div>
  227. </div>
  228. </div>
  229. <div className="flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
  230. <Button variant="secondary" onClick={onClose}>{t('common.cancel')}</Button>
  231. <Button
  232. onClick={handleSave}
  233. disabled={!hasChanges || isSaving}
  234. >
  235. {isSaving ? t('common.saving') : t('queue.bulkEdit.applyChanges')}
  236. </Button>
  237. </div>
  238. </div>
  239. </div>
  240. );
  241. }
  242. // Tri-state toggle for bulk edit (unchanged / on / off)
  243. function TriStateToggle({
  244. label,
  245. value,
  246. onChange,
  247. disabled,
  248. t,
  249. }: {
  250. label: string;
  251. value: boolean | 'unchanged';
  252. onChange: (val: boolean | 'unchanged') => void;
  253. disabled?: boolean;
  254. t: (key: string) => string;
  255. }) {
  256. return (
  257. <div className={`flex items-center justify-between py-1 ${disabled ? 'opacity-50' : ''}`}>
  258. <span className="text-sm text-bambu-gray">{label}</span>
  259. <div className="flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5">
  260. <button
  261. onClick={() => onChange('unchanged')}
  262. disabled={disabled}
  263. 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`}
  264. >
  265. —
  266. </button>
  267. <button
  268. onClick={() => onChange(false)}
  269. disabled={disabled}
  270. 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`}
  271. >
  272. {t('common.off')}
  273. </button>
  274. <button
  275. onClick={() => onChange(true)}
  276. disabled={disabled}
  277. 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`}
  278. >
  279. {t('common.on')}
  280. </button>
  281. </div>
  282. </div>
  283. );
  284. }
  285. // Four-state selector for the tri-state calibration options in bulk edit
  286. // (unchanged / off / auto / on). Mirrors TriStateToggle's chrome.
  287. function CalibrationModeToggle({
  288. label,
  289. value,
  290. onChange,
  291. t,
  292. }: {
  293. label: string;
  294. value: CalibrationMode | 'unchanged';
  295. onChange: (val: CalibrationMode | 'unchanged') => void;
  296. t: (key: string) => string;
  297. }) {
  298. const modes: Array<{ key: CalibrationMode | 'unchanged'; label: string; active: string }> = [
  299. { key: 'unchanged', label: '—', active: 'bg-bambu-dark-tertiary text-white' },
  300. { key: 'off', label: t('settings.calibrationMode_off'), active: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' },
  301. { key: 'auto', label: t('settings.calibrationMode_auto'), active: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400' },
  302. { key: 'on', label: t('settings.calibrationMode_on'), active: 'bg-bambu-green/20 text-bambu-green' },
  303. ];
  304. return (
  305. <div className="flex items-center justify-between py-1">
  306. <span className="text-sm text-bambu-gray">{label}</span>
  307. <div className="flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5">
  308. {modes.map(({ key, label: modeLabel, active }) => (
  309. <button
  310. key={key}
  311. onClick={() => onChange(key)}
  312. className={`px-2 py-1 text-xs rounded ${value === key ? active : 'text-bambu-gray hover:text-white'}`}
  313. >
  314. {modeLabel}
  315. </button>
  316. ))}
  317. </div>
  318. </div>
  319. );
  320. }
  321. // Sortable queue item for drag and drop
  322. function SortableQueueItem({
  323. item,
  324. position,
  325. onEdit,
  326. onCancel,
  327. onRemove,
  328. onStop,
  329. onRequeue,
  330. onStart,
  331. timeFormat = 'system',
  332. isSelected = false,
  333. onToggleSelect,
  334. hasPermission,
  335. canModify,
  336. printerState,
  337. t,
  338. }: {
  339. item: PrintQueueItem;
  340. position?: number;
  341. onEdit: () => void;
  342. onCancel: () => void;
  343. onRemove: () => void;
  344. onStop: () => void;
  345. onRequeue: () => void;
  346. onStart: () => void;
  347. timeFormat?: TimeFormat;
  348. isSelected?: boolean;
  349. onToggleSelect?: () => void;
  350. hasPermission: (permission: Permission) => boolean;
  351. canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
  352. printerState?: string | null;
  353. t: (key: string, options?: Record<string, unknown>) => string;
  354. }) {
  355. // Fetch printer status every 30 seconds while printing to monitor progress
  356. const { data: status } = useQuery({
  357. queryKey: ['printerStatus', item.printer_id],
  358. queryFn: () => api.getPrinterStatus(item.printer_id!),
  359. refetchInterval: 30000,
  360. enabled: item.printer_id != null && printerState === 'printing',
  361. });
  362. // Determine if we're printing a library file
  363. const isLibraryFile = !!item.library_file_id && !item.archive_id;
  364. // Fetch archive plate details. Skip when the linked archive has been
  365. // soft-deleted (#1348 follow-up): its 3MF is gone from disk so the
  366. // /plates endpoint just 404-storms the queue page.
  367. const { data: archivePlatesData } = useQuery({
  368. queryKey: ['archive-plates', item.archive_id],
  369. queryFn: () => api.getArchivePlates(item.archive_id!),
  370. enabled: !!item.archive_id && !isLibraryFile && !item.archive_deleted,
  371. });
  372. // Fetch library file plate details
  373. const { data: libraryPlatesData } = useQuery({
  374. queryKey: ['library-file-plates', item.library_file_id],
  375. queryFn: () => api.getLibraryFilePlates(item.library_file_id!),
  376. enabled: isLibraryFile && !!item.library_file_id,
  377. });
  378. // Combine plates data from either source
  379. const platesData = isLibraryFile ? libraryPlatesData : archivePlatesData;
  380. const plates = platesData?.plates ?? [];
  381. const canReorder = hasPermission('queue:reorder');
  382. const {
  383. attributes,
  384. listeners,
  385. setNodeRef,
  386. transform,
  387. transition,
  388. isDragging,
  389. } = useSortable({ id: item.id, disabled: item.status !== 'pending' || !canReorder });
  390. const style = {
  391. transform: CSS.Transform.toString(transform),
  392. transition,
  393. };
  394. const isPrinting = item.status === 'printing';
  395. const isPending = item.status === 'pending';
  396. const isHistory = ['completed', 'failed', 'skipped', 'cancelled'].includes(item.status);
  397. const isMobileSelectable = isPending && onToggleSelect;
  398. return (
  399. <div
  400. ref={setNodeRef}
  401. style={style}
  402. className={`
  403. group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
  404. border-l-[3px] ${
  405. isPrinting ? 'border-l-blue-500' :
  406. isPending ? 'border-l-yellow-500' :
  407. item.status === 'completed' ? 'border-l-emerald-500' :
  408. item.status === 'failed' ? 'border-l-red-500' :
  409. 'border-l-gray-500'
  410. }
  411. ${isDragging ? 'opacity-50 scale-[1.02] shadow-xl z-50' : ''}
  412. ${isPrinting ? 'border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent' : ''}
  413. ${isSelected && isMobileSelectable ? 'sm:border-bambu-dark-tertiary border-bambu-green/40' : ''}
  414. ${!isSelected && !isPrinting ? 'border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80' : ''}
  415. ${isMobileSelectable ? 'sm:cursor-default' : ''}
  416. `}
  417. onClick={isMobileSelectable ? () => {
  418. if (window.innerWidth < 640) onToggleSelect();
  419. } : undefined}
  420. >
  421. {/* Mobile selected left accent bar */}
  422. {isMobileSelectable && isSelected && (
  423. <div className="sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green" />
  424. )}
  425. <div className="flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4">
  426. {/* Mobile selection indicator — left accent bar only, no tick */}
  427. {/* Selection checkbox for pending items - hidden on mobile, tap card instead */}
  428. {isPending && onToggleSelect && (
  429. <button
  430. onClick={(e) => {
  431. e.stopPropagation();
  432. onToggleSelect();
  433. }}
  434. className={`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${
  435. isSelected
  436. ? 'bg-bambu-green border-bambu-green text-white'
  437. : 'border-white/30 bg-black/30 hover:border-bambu-green/50'
  438. }`}
  439. >
  440. {isSelected && <Check className="w-4 h-4" />}
  441. </button>
  442. )}
  443. {/* Drag handle or position number - hidden on mobile */}
  444. {isPending ? (
  445. <div
  446. {...attributes}
  447. {...listeners}
  448. 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-manipulation shrink-0"
  449. >
  450. <GripVertical className="w-4 h-4 text-bambu-gray" />
  451. </div>
  452. ) : position !== undefined ? (
  453. <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">
  454. #{position}
  455. </div>
  456. ) : (
  457. <div className="hidden sm:block w-8 shrink-0" />
  458. )}
  459. {/* Thumbnail - use plate-specific thumbnail if plate_id is set */}
  460. <div className="w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden">
  461. {item.archive_thumbnail ? (
  462. <img
  463. src={
  464. item.plate_id != null
  465. ? api.getArchivePlateThumbnail(item.archive_id!, item.plate_id)
  466. : api.getArchiveThumbnail(item.archive_id!)
  467. }
  468. alt=""
  469. className="w-full h-full object-cover"
  470. />
  471. ) : item.library_file_thumbnail ? (
  472. <img
  473. src={
  474. item.plate_id != null
  475. ? api.getLibraryFilePlateThumbnail(item.library_file_id!, item.plate_id)
  476. : api.getLibraryFileThumbnailUrl(item.library_file_id!)
  477. }
  478. alt=""
  479. className="w-full h-full object-cover"
  480. />
  481. ) : (
  482. <div className="w-full h-full flex items-center justify-center text-bambu-gray">
  483. <Layers className="w-5 h-5 sm:w-6 sm:h-6" />
  484. </div>
  485. )}
  486. </div>
  487. {/* Info */}
  488. <div className="flex-1 min-w-0">
  489. <div className="flex items-center gap-2 mb-1">
  490. <p className="text-sm sm:text-base text-white font-medium truncate">
  491. {item.archive_name || item.library_file_name || `File #${item.archive_id || item.library_file_id}`}
  492. {(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 })}`}
  493. </p>
  494. {item.archive_id ? (
  495. <Link
  496. to={`/archives?highlight=${item.archive_id}`}
  497. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  498. title={t('queue.viewArchive')}
  499. >
  500. <ExternalLink className="w-3.5 h-3.5" />
  501. </Link>
  502. ) : item.library_file_id ? (
  503. <Link
  504. to={`/library?highlight=${item.library_file_id}`}
  505. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  506. title={t('queue.viewInFileManager')}
  507. >
  508. <ExternalLink className="w-3.5 h-3.5" />
  509. </Link>
  510. ) : null}
  511. {item.batch_name && (
  512. <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">
  513. {item.batch_name}
  514. </span>
  515. )}
  516. </div>
  517. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray">
  518. <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' : ''}`}>
  519. <Printer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  520. <span className="truncate max-w-[120px] sm:max-w-none">
  521. {item.target_model && !item.printer_id
  522. ? `${t('queue.filter.any')} ${item.target_model}${item.target_location ? ` @ ${item.target_location}` : ''}${item.required_filament_types?.length ? ` (${item.required_filament_types.join(', ')})` : ''}`
  523. : item.printer_id === null
  524. ? t('queue.filter.unassigned')
  525. : (item.printer_name || `${t('common.printer')} #${item.printer_id}`)}
  526. </span>
  527. </span>
  528. {item.print_time_seconds && (
  529. <span className="flex items-center gap-1 sm:gap-1.5">
  530. <Timer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  531. {formatDuration(item.print_time_seconds)}
  532. </span>
  533. )}
  534. {item.filament_used_grams && (
  535. <span className="flex items-center gap-1 sm:gap-1.5">
  536. <Weight className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  537. {formatWeight(item.filament_used_grams)}
  538. </span>
  539. )}
  540. {(() => {
  541. // Build plate badge so the user knows which plate to mount before
  542. // walking to the printer (#1281). Hidden when the 3MF doesn't
  543. // carry curr_bed_type or the slicer used an unknown label.
  544. const bed = getBedTypeInfo(item.bed_type);
  545. if (!bed) return null;
  546. return (
  547. <span className="flex items-center gap-1 sm:gap-1.5" title={bed.label}>
  548. <img src={bed.icon} alt="" className="w-3.5 h-3.5 sm:w-4 sm:h-4 object-contain" />
  549. <span className="truncate max-w-[120px]">{bed.label}</span>
  550. </span>
  551. );
  552. })()}
  553. {item.created_by_username && (
  554. <span className="hidden sm:flex items-center gap-1.5" title={t('queue.addedBy', { name: item.created_by_username })}>
  555. <User className="w-3.5 h-3.5" />
  556. {item.created_by_username}
  557. </span>
  558. )}
  559. {isPending && !item.manual_start && (
  560. <span className="flex items-center gap-1.5">
  561. <Clock className="w-3.5 h-3.5" />
  562. {item.scheduled_time
  563. ? ((parseUTCDate(item.scheduled_time)?.getTime() ?? 0) - Date.now() < -60000
  564. ? t?.('queue.time.overdue') ?? 'Overdue'
  565. : formatRelativeTime(item.scheduled_time, timeFormat, t))
  566. : t?.('queue.time.asap') ?? 'ASAP'}
  567. </span>
  568. )}
  569. </div>
  570. {/* Options badges */}
  571. <div className="flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2">
  572. {item.manual_start && (
  573. <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">
  574. <Hand className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  575. {t('queue.badges.staged')}
  576. </span>
  577. )}
  578. {item.require_previous_success && (
  579. <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">
  580. {t('queue.badges.requiresPrevious')}
  581. </span>
  582. )}
  583. {item.auto_off_after && (
  584. <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">
  585. <Power className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  586. {t('queue.badges.autoPowerOff')}
  587. </span>
  588. )}
  589. {item.gcode_injection && (
  590. <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">
  591. <Code className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  592. {t('queue.badges.gcodeInjection')}
  593. </span>
  594. )}
  595. </div>
  596. {/* Progress bar for printing items - TODO: integrate with WebSocket */}
  597. {isPrinting && status && (() => {
  598. // Gate progress/remaining/layer on printer actually running this print.
  599. // Between dispatch and RUNNING transition (H2D/P1 MQTT lag), status.progress
  600. // is stale from the previous print — showing 100% then snapping back to 0%
  601. // once the new print starts. Only trust these fields when state is active.
  602. const isActive = status.state === 'RUNNING' || status.state === 'PAUSE';
  603. const progress = isActive ? (status.progress || 0) : 0;
  604. const remaining = isActive ? status.remaining_time : null;
  605. const layerNum = isActive ? status.layer_num : null;
  606. const totalLayers = isActive ? status.total_layers : null;
  607. return (
  608. <div className="mt-2 sm:mt-3">
  609. <div className="flex items-center justify-between text-xs sm:text-sm">
  610. <div className="flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3">
  611. <div
  612. className="bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all"
  613. style={{ width: `${progress}%` }}
  614. />
  615. </div>
  616. <span className="text-white">{Math.round(progress)}%</span>
  617. </div>
  618. <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">
  619. {remaining != null && remaining > 0 && (
  620. <>
  621. <span className="flex items-center gap-1">
  622. <Clock className="w-3 h-3" />
  623. {formatDuration(remaining * 60)}
  624. </span>
  625. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  626. ETA {formatETA(remaining, timeFormat, t)}
  627. </span>
  628. </>
  629. )}
  630. {layerNum != null && totalLayers != null && totalLayers > 0 && (
  631. <span className="flex items-center gap-1">
  632. <Layers className="w-3 h-3" />
  633. {layerNum}/{totalLayers}
  634. </span>
  635. )}
  636. </div>
  637. </div>
  638. );
  639. })()}
  640. {/* Waiting reason for model-based assignments */}
  641. {item.waiting_reason && item.status === 'pending' && (
  642. <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">
  643. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  644. <span>{item.waiting_reason}</span>
  645. </p>
  646. )}
  647. {/* Filament-short flag from the dispatch pre-flight (#1496). */}
  648. {item.filament_short && item.status === 'pending' && (
  649. <p
  650. className="text-[10px] sm:text-xs text-yellow-700 dark:text-yellow-400 mt-1.5 sm:mt-2 flex items-start gap-1"
  651. title={t('queue.filamentShort.rowTooltip')}
  652. >
  653. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  654. <span>{t('queue.filamentShort.rowBadge')}</span>
  655. </p>
  656. )}
  657. {/* Error message */}
  658. {item.error_message && (
  659. <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">
  660. <AlertCircle className="w-3 h-3" />
  661. {item.error_message}
  662. </p>
  663. )}
  664. </div>
  665. {/* Status badge + Actions */}
  666. <div className="flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
  667. <StatusBadge status={item.status} waitingReason={item.waiting_reason} printerState={printerState} t={t} />
  668. <div className="flex items-center gap-0.5 sm:gap-1">
  669. {isPrinting && (
  670. <Button
  671. variant="ghost"
  672. size="sm"
  673. onClick={onStop}
  674. disabled={!canModify('queue', 'update', item.created_by_id)}
  675. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noStopPrint') : t('queue.actions.stopPrint')}
  676. 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"
  677. >
  678. <StopCircle className="w-4 h-4" />
  679. </Button>
  680. )}
  681. {isPending && (
  682. <>
  683. {item.manual_start && (
  684. <Button
  685. variant="ghost"
  686. size="sm"
  687. onClick={onStart}
  688. disabled={!canModify('queue', 'update', item.created_by_id)}
  689. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noStartPrint') : t('queue.actions.startPrint')}
  690. className="text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2"
  691. >
  692. <Play className="w-4 h-4" />
  693. </Button>
  694. )}
  695. <Button
  696. variant="ghost"
  697. size="sm"
  698. onClick={onEdit}
  699. disabled={!canModify('queue', 'update', item.created_by_id)}
  700. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noEdit') : t('common.edit')}
  701. className="p-1.5 sm:p-2"
  702. >
  703. <Pencil className="w-4 h-4" />
  704. </Button>
  705. <Button
  706. variant="ghost"
  707. size="sm"
  708. onClick={onCancel}
  709. disabled={!canModify('queue', 'delete', item.created_by_id)}
  710. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noCancel') : t('common.cancel')}
  711. 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"
  712. >
  713. <X className="w-4 h-4" />
  714. </Button>
  715. </>
  716. )}
  717. {isHistory && (
  718. <>
  719. <Button
  720. variant="ghost"
  721. size="sm"
  722. onClick={onRequeue}
  723. disabled={!hasPermission('queue:create')}
  724. title={!hasPermission('queue:create') ? t('queue.permissions.noRequeue') : t('queue.actions.requeue')}
  725. className="text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2"
  726. >
  727. <RefreshCw className="w-4 h-4" />
  728. </Button>
  729. <Button
  730. variant="ghost"
  731. size="sm"
  732. onClick={onRemove}
  733. disabled={!canModify('queue', 'delete', item.created_by_id)}
  734. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noRemove') : t('common.remove')}
  735. className="p-1.5 sm:p-2"
  736. >
  737. <Trash2 className="w-4 h-4" />
  738. </Button>
  739. </>
  740. )}
  741. </div>
  742. </div>
  743. </div>
  744. </div>
  745. );
  746. }
  747. type QueueRow =
  748. | { kind: 'item'; item: PrintQueueItem }
  749. | { kind: 'batch'; batchId: number; batchName: string; items: PrintQueueItem[] };
  750. interface QueueRowRenderProps {
  751. row: QueueRow;
  752. collapsed: boolean;
  753. onToggleBatch?: () => void;
  754. onUngroup?: () => void;
  755. setEditItem: (item: PrintQueueItem) => void;
  756. setConfirmAction: (a: { type: 'cancel' | 'remove' | 'stop'; item: PrintQueueItem }) => void;
  757. startMutation: { mutate: (vars: { id: number; skipFilamentCheck?: boolean }) => void };
  758. selectedItems: number[];
  759. handleToggleSelect: (id: number) => void;
  760. timeFormat: TimeFormat;
  761. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  762. hasPermission: (p: any) => boolean;
  763. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  764. canModify: (resource: any, action: any, createdById?: number | null) => boolean;
  765. t: (key: string, options?: Record<string, unknown>) => string;
  766. aggregateForRows: (rows: QueueRow[]) => { count: number; time: number; weight: number };
  767. }
  768. /** Renders either a single item or a collapsible batch group containing N
  769. * sibling items. The batch parent shows aggregate stats; children render
  770. * with the existing SortableQueueItem (only draggable inside the batch). */
  771. function QueueRowRender(props: QueueRowRenderProps) {
  772. const {
  773. row,
  774. setEditItem,
  775. setConfirmAction,
  776. startMutation,
  777. selectedItems,
  778. handleToggleSelect,
  779. timeFormat,
  780. hasPermission,
  781. canModify,
  782. t,
  783. } = props;
  784. if (row.kind === 'item') {
  785. return (
  786. <SortableQueueItem
  787. item={row.item}
  788. onEdit={() => setEditItem(row.item)}
  789. onCancel={() => setConfirmAction({ type: 'cancel', item: row.item })}
  790. onRemove={() => {}}
  791. onStop={() => {}}
  792. onRequeue={() => {}}
  793. onStart={() => startMutation.mutate({ id: row.item.id })}
  794. timeFormat={timeFormat}
  795. isSelected={selectedItems.includes(row.item.id)}
  796. onToggleSelect={() => handleToggleSelect(row.item.id)}
  797. hasPermission={hasPermission}
  798. canModify={canModify}
  799. t={t}
  800. />
  801. );
  802. }
  803. return <SortableBatchRow {...props} />;
  804. }
  805. /** Batch parent header registered with dnd-kit so the whole group can be
  806. * reordered as one unit. Drag handle lives in the header itself; children
  807. * remain individually draggable while expanded for within-batch reorder. */
  808. function SortableBatchRow({
  809. row,
  810. collapsed,
  811. onToggleBatch,
  812. onUngroup,
  813. setEditItem,
  814. setConfirmAction,
  815. startMutation,
  816. selectedItems,
  817. handleToggleSelect,
  818. timeFormat,
  819. hasPermission,
  820. canModify,
  821. t,
  822. aggregateForRows,
  823. }: QueueRowRenderProps) {
  824. // Dispatcher (QueueRowRender) only mounts this with row.kind === 'batch';
  825. // narrow up-front so the hook below can reference batchId unconditionally.
  826. const batchRow = row as Extract<QueueRow, { kind: 'batch' }>;
  827. const canReorder = hasPermission('queue:reorder');
  828. const {
  829. attributes,
  830. listeners,
  831. setNodeRef,
  832. transform,
  833. transition,
  834. isDragging,
  835. } = useSortable({ id: `batch-${batchRow.batchId}`, disabled: !canReorder });
  836. const style = {
  837. transform: CSS.Transform.toString(transform),
  838. transition,
  839. };
  840. const agg = aggregateForRows([batchRow]);
  841. const allChildIds = batchRow.items.map((i) => i.id);
  842. const allSelected = allChildIds.length > 0 && allChildIds.every((id) => selectedItems.includes(id));
  843. // Status rollup: worst-of-children (failed > printing > pending).
  844. const childStatuses = new Set(batchRow.items.map((i) => i.status));
  845. // We never put non-pending into a batch grouping but render defensively.
  846. const rollupStatus: PrintQueueItem['status'] = childStatuses.has('failed')
  847. ? 'failed'
  848. : childStatuses.has('printing')
  849. ? 'printing'
  850. : 'pending';
  851. const pendingChildren = batchRow.items.filter((i) => i.status === 'pending').length;
  852. return (
  853. <div
  854. ref={setNodeRef}
  855. style={style}
  856. className={`bg-bambu-dark-secondary rounded-xl border border-l-[3px] border-l-cyan-400 border-bambu-dark-tertiary overflow-hidden ${
  857. isDragging ? 'opacity-50 scale-[1.01] shadow-xl z-50' : ''
  858. }`}
  859. >
  860. {/* Parent header */}
  861. <div className="flex items-center gap-2 sm:gap-3 p-3 sm:p-4">
  862. <button
  863. onClick={(e) => {
  864. e.stopPropagation();
  865. allChildIds.forEach((id) => {
  866. if (allSelected && selectedItems.includes(id)) {
  867. handleToggleSelect(id);
  868. } else if (!allSelected && !selectedItems.includes(id)) {
  869. handleToggleSelect(id);
  870. }
  871. });
  872. }}
  873. className={`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${
  874. allSelected
  875. ? 'bg-bambu-green border-bambu-green text-white'
  876. : 'border-white/30 bg-black/30 hover:border-bambu-green/50'
  877. }`}
  878. title={allSelected ? t('queue.bulkEdit.deselectAll') : t('queue.bulkEdit.selectAll')}
  879. >
  880. {allSelected && <Check className="w-4 h-4" />}
  881. </button>
  882. {canReorder && (
  883. <div
  884. {...attributes}
  885. {...listeners}
  886. 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-manipulation shrink-0"
  887. title={t('queue.batch.dragGroup', { defaultValue: 'Drag group' })}
  888. >
  889. <GripVertical className="w-4 h-4 text-bambu-gray" />
  890. </div>
  891. )}
  892. <button
  893. onClick={onToggleBatch}
  894. className="flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary transition-colors shrink-0"
  895. title={collapsed ? t('queue.batch.expand') : t('queue.batch.collapse')}
  896. >
  897. {collapsed ? (
  898. <ChevronRight className="w-4 h-4 text-bambu-gray" />
  899. ) : (
  900. <ChevronDown className="w-4 h-4 text-bambu-gray" />
  901. )}
  902. </button>
  903. <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">
  904. {collapsed ? (
  905. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  906. ) : (
  907. <PackageOpen className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  908. )}
  909. </div>
  910. <div className="flex-1 min-w-0">
  911. <div className="flex items-center gap-2 mb-1">
  912. <p className="text-sm sm:text-base text-white font-medium truncate">{batchRow.batchName}</p>
  913. <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">
  914. {t('queue.batch.label', { count: agg.count })}
  915. </span>
  916. </div>
  917. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray">
  918. {agg.time > 0 && (
  919. <span className="flex items-center gap-1 sm:gap-1.5">
  920. <Timer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  921. {formatDuration(agg.time)}
  922. </span>
  923. )}
  924. {agg.weight > 0 && (
  925. <span className="flex items-center gap-1 sm:gap-1.5">
  926. <Weight className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  927. {formatWeight(agg.weight)}
  928. </span>
  929. )}
  930. {pendingChildren > 0 && rollupStatus === 'pending' && (
  931. <span className="flex items-center gap-1 sm:gap-1.5 text-yellow-700 dark:text-yellow-400">
  932. <Clock className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  933. {t('queue.batch.pendingCount', { count: pendingChildren })}
  934. </span>
  935. )}
  936. </div>
  937. </div>
  938. <div className="flex items-center gap-1 shrink-0">
  939. {onUngroup && (
  940. <Button
  941. variant="ghost"
  942. size="sm"
  943. onClick={onUngroup}
  944. title={t('queue.batch.ungroup')}
  945. 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"
  946. >
  947. <Ungroup className="w-4 h-4" />
  948. </Button>
  949. )}
  950. </div>
  951. </div>
  952. {/* Children (only when expanded) */}
  953. {!collapsed && (
  954. <div className="border-t border-bambu-dark-tertiary bg-black/20 p-2 sm:p-3 space-y-2">
  955. {batchRow.items.map((child) => (
  956. <SortableQueueItem
  957. key={child.id}
  958. item={child}
  959. onEdit={() => setEditItem(child)}
  960. onCancel={() => setConfirmAction({ type: 'cancel', item: child })}
  961. onRemove={() => {}}
  962. onStop={() => {}}
  963. onRequeue={() => {}}
  964. onStart={() => startMutation.mutate({ id: child.id })}
  965. timeFormat={timeFormat}
  966. isSelected={selectedItems.includes(child.id)}
  967. onToggleSelect={() => handleToggleSelect(child.id)}
  968. hasPermission={hasPermission}
  969. canModify={canModify}
  970. t={t}
  971. />
  972. ))}
  973. </div>
  974. )}
  975. </div>
  976. );
  977. }
  978. type HistoryRow =
  979. | { kind: 'item'; item: PrintQueueItem }
  980. | { kind: 'batch'; batchId: number; batchName: string; items: PrintQueueItem[] };
  981. interface HistorySectionProps {
  982. items: PrintQueueItem[];
  983. collapsed: boolean;
  984. sortBy: 'date' | 'name' | 'printer';
  985. sortAsc: boolean;
  986. onSortByChange: (v: 'date' | 'name' | 'printer') => void;
  987. onSortAscToggle: () => void;
  988. onRemove: (item: PrintQueueItem) => void;
  989. onRequeue: (item: PrintQueueItem) => void;
  990. timeFormat: TimeFormat;
  991. batchCollapsed: Record<number, boolean>;
  992. toggleBatchCollapsed: (id: number) => void;
  993. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  994. hasPermission: (p: any) => boolean;
  995. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  996. canModify: (resource: any, action: any, createdById?: number | null) => boolean;
  997. t: (key: string, options?: Record<string, unknown>) => string;
  998. }
  999. function HistorySection({
  1000. items,
  1001. sortBy,
  1002. sortAsc,
  1003. onSortByChange,
  1004. onSortAscToggle,
  1005. onRemove,
  1006. onRequeue,
  1007. timeFormat,
  1008. batchCollapsed,
  1009. toggleBatchCollapsed,
  1010. hasPermission,
  1011. canModify,
  1012. t,
  1013. }: HistorySectionProps) {
  1014. if (items.length === 0) {
  1015. return (
  1016. <Card className="p-12 text-center border-dashed">
  1017. <ListOrdered className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  1018. <h3 className="text-xl font-medium text-white mb-2">{t('queue.history.emptyTitle')}</h3>
  1019. <p className="text-bambu-gray max-w-md mx-auto">{t('queue.history.emptyDescription')}</p>
  1020. </Card>
  1021. );
  1022. }
  1023. // Group siblings sharing a batch_id into a single collapsible row.
  1024. // First-seen order is preserved for batches; items keep their sorted
  1025. // position from the parent's sort selector.
  1026. const rows: HistoryRow[] = [];
  1027. const seenBatches = new Set<number>();
  1028. for (const item of items.slice(0, 50)) {
  1029. if (item.batch_id != null) {
  1030. if (seenBatches.has(item.batch_id)) continue;
  1031. seenBatches.add(item.batch_id);
  1032. const siblings = items.filter((s) => s.batch_id === item.batch_id);
  1033. rows.push({
  1034. kind: 'batch',
  1035. batchId: item.batch_id,
  1036. batchName: item.batch_name || t('queue.batch.defaultName'),
  1037. items: siblings,
  1038. });
  1039. } else {
  1040. rows.push({ kind: 'item', item });
  1041. }
  1042. }
  1043. return (
  1044. <div>
  1045. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  1046. <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
  1047. {t('queue.sections.history')}
  1048. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  1049. ({t('queue.itemCount', { count: items.length })})
  1050. </span>
  1051. </h2>
  1052. <div className="flex items-center gap-2">
  1053. <select
  1054. 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"
  1055. value={sortBy}
  1056. onChange={(e) => onSortByChange(e.target.value as 'date' | 'name' | 'printer')}
  1057. >
  1058. <option value="date">{t('queue.sort.byDate')}</option>
  1059. <option value="name">{t('queue.sort.byName')}</option>
  1060. <option value="printer">{t('queue.sort.byPrinter')}</option>
  1061. </select>
  1062. <Button
  1063. variant="ghost"
  1064. size="sm"
  1065. onClick={onSortAscToggle}
  1066. title={sortAsc ? t('queue.sort.ascendingOldest') : t('queue.sort.descendingNewest')}
  1067. className="px-2"
  1068. >
  1069. {sortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  1070. </Button>
  1071. </div>
  1072. </div>
  1073. <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2">
  1074. {rows.map((row) => {
  1075. if (row.kind === 'item') {
  1076. return (
  1077. <CompactHistoryRow
  1078. key={row.item.id}
  1079. item={row.item}
  1080. onRemove={() => onRemove(row.item)}
  1081. onRequeue={() => onRequeue(row.item)}
  1082. timeFormat={timeFormat}
  1083. hasPermission={hasPermission}
  1084. canModify={canModify}
  1085. t={t}
  1086. />
  1087. );
  1088. }
  1089. // Batch group — spans the full grid width so it visually anchors
  1090. // its children below it. The children themselves render in the
  1091. // same responsive grid pattern inside the expanded body.
  1092. const collapsed = batchCollapsed[row.batchId] ?? true;
  1093. const completed = row.items.filter((i) => i.status === 'completed').length;
  1094. const failed = row.items.filter((i) => i.status === 'failed').length;
  1095. const skipped = row.items.filter((i) => i.status === 'skipped').length;
  1096. const cancelled = row.items.filter((i) => i.status === 'cancelled').length;
  1097. const latest = row.items
  1098. .map((i) => i.completed_at || i.created_at)
  1099. .filter((v): v is string => !!v)
  1100. .sort()
  1101. .at(-1);
  1102. return (
  1103. <div
  1104. key={`batch-${row.batchId}`}
  1105. 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"
  1106. >
  1107. <button
  1108. onClick={() => toggleBatchCollapsed(row.batchId)}
  1109. className="w-full flex items-center gap-2 sm:gap-3 px-3 py-2 hover:bg-bambu-dark/30 transition-colors text-left"
  1110. title={collapsed ? t('queue.batch.expand') : t('queue.batch.collapse')}
  1111. >
  1112. {collapsed ? (
  1113. <ChevronRight className="w-4 h-4 text-bambu-gray shrink-0" />
  1114. ) : (
  1115. <ChevronDown className="w-4 h-4 text-bambu-gray shrink-0" />
  1116. )}
  1117. {collapsed ? (
  1118. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300 shrink-0" />
  1119. ) : (
  1120. <PackageOpen className="w-5 h-5 text-cyan-700 dark:text-cyan-300 shrink-0" />
  1121. )}
  1122. <span className="text-sm text-white font-medium truncate min-w-0 flex-1">
  1123. {row.batchName}
  1124. </span>
  1125. <div className="flex items-center gap-2 text-xs text-bambu-gray shrink-0">
  1126. {completed > 0 && (
  1127. <span className="flex items-center gap-1 text-emerald-700 dark:text-emerald-400">
  1128. <CheckCircle className="w-3 h-3" />
  1129. {completed}
  1130. </span>
  1131. )}
  1132. {failed > 0 && (
  1133. <span className="flex items-center gap-1 text-red-700 dark:text-red-400">
  1134. <XCircle className="w-3 h-3" />
  1135. {failed}
  1136. </span>
  1137. )}
  1138. {skipped > 0 && (
  1139. <span className="flex items-center gap-1 text-orange-700 dark:text-orange-400">
  1140. <SkipForward className="w-3 h-3" />
  1141. {skipped}
  1142. </span>
  1143. )}
  1144. {cancelled > 0 && (
  1145. <span className="flex items-center gap-1 text-gray-400">
  1146. <Ban className="w-3 h-3" />
  1147. {cancelled}
  1148. </span>
  1149. )}
  1150. <span title={latest ?? undefined}>
  1151. {latest ? formatRelativeTime(latest, timeFormat, t) : null}
  1152. </span>
  1153. </div>
  1154. </button>
  1155. {!collapsed && (
  1156. <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">
  1157. {row.items.map((child) => (
  1158. <CompactHistoryRow
  1159. key={child.id}
  1160. item={child}
  1161. onRemove={() => onRemove(child)}
  1162. onRequeue={() => onRequeue(child)}
  1163. timeFormat={timeFormat}
  1164. hasPermission={hasPermission}
  1165. canModify={canModify}
  1166. t={t}
  1167. />
  1168. ))}
  1169. </div>
  1170. )}
  1171. </div>
  1172. );
  1173. })}
  1174. </div>
  1175. </div>
  1176. );
  1177. }
  1178. export function QueuePage() {
  1179. const { t } = useTranslation();
  1180. const queryClient = useQueryClient();
  1181. const { showToast } = useToast();
  1182. const { hasPermission, hasAnyPermission, canModify } = useAuth();
  1183. const [filterPrinter, setFilterPrinter] = useState<number | null>(null);
  1184. const [filterStatus, setFilterStatus] = useState<string>('');
  1185. const [filterLocation, setFilterLocation] = useState<string>('');
  1186. const [showClearHistoryConfirm, setShowClearHistoryConfirm] = useState(false);
  1187. const [editItem, setEditItem] = useState<PrintQueueItem | null>(null);
  1188. const [requeueItem, setRequeueItem] = useState<PrintQueueItem | null>(null);
  1189. const [confirmAction, setConfirmAction] = useState<{
  1190. type: 'cancel' | 'remove' | 'stop';
  1191. item: PrintQueueItem;
  1192. } | null>(null);
  1193. const [selectedItems, setSelectedItems] = useState<number[]>([]);
  1194. const [showBulkEditModal, setShowBulkEditModal] = useState(false);
  1195. // #1818: per-printer Resume-after-failure confirm modal. Tracks which
  1196. // printer's gate the user is about to clear; null when no modal is open.
  1197. const [resumeConfirm, setResumeConfirm] = useState<{
  1198. printerId: number;
  1199. printerName: string;
  1200. skippedCount: number;
  1201. } | null>(null);
  1202. const [historySortBy, setHistorySortBy] = useState<'date' | 'name' | 'printer'>(() => {
  1203. const saved = localStorage.getItem('queue.historySortBy');
  1204. return (saved as 'date' | 'name' | 'printer') || 'date';
  1205. });
  1206. const [historySortAsc, setHistorySortAsc] = useState(() => {
  1207. const saved = localStorage.getItem('queue.historySortAsc');
  1208. return saved !== null ? saved === 'true' : false;
  1209. });
  1210. const [pendingSortBy, setPendingSortBy] = useState<'position' | 'name' | 'printer' | 'time'>(() => {
  1211. const saved = localStorage.getItem('queue.pendingSortBy');
  1212. return (saved as 'position' | 'name' | 'printer' | 'time') || 'position';
  1213. });
  1214. const [pendingSortAsc, setPendingSortAsc] = useState(() => {
  1215. const saved = localStorage.getItem('queue.pendingSortAsc');
  1216. return saved !== null ? saved === 'true' : true;
  1217. });
  1218. // historyCollapsed legacy state retained only for localStorage migration; the
  1219. // History tab renders unconditionally so this no longer drives the UI.
  1220. // Tabbed page structure: Active queue stays as the main view; History
  1221. // and Timeline split off. Persists per-user via localStorage.
  1222. const [activeTab, setActiveTab] = useState<'queue' | 'history' | 'timeline' | 'pipelines'>(() => {
  1223. // URL deep-link wins so the legacy /pipelines/runs redirect lands on the
  1224. // right tab. localStorage holds the per-user last-selected fallback.
  1225. const search = new URLSearchParams(window.location.search);
  1226. const url = search.get('tab');
  1227. if (url === 'pipelines' || url === 'history' || url === 'timeline' || url === 'queue') {
  1228. return url;
  1229. }
  1230. const saved = localStorage.getItem('queue.activeTab');
  1231. if (saved === 'history' || saved === 'timeline' || saved === 'pipelines') return saved;
  1232. return 'queue';
  1233. });
  1234. // Active-tab layout toggle. "position" = today's flat list; "printer"
  1235. // groups items under per-printer section headers with aggregate stats.
  1236. const [activeLayout, setActiveLayout] = useState<'position' | 'printer'>(() => {
  1237. const saved = localStorage.getItem('queue.activeLayout');
  1238. return saved === 'printer' ? 'printer' : 'position';
  1239. });
  1240. // Per-batch collapse state, keyed by batch_id. Default = collapsed
  1241. // (matches the SimplyPrint/Files convention — show the rollup first).
  1242. const [batchCollapsed, setBatchCollapsed] = useState<Record<number, boolean>>(() => {
  1243. try {
  1244. const saved = localStorage.getItem('queue.batchCollapsed');
  1245. return saved ? JSON.parse(saved) : {};
  1246. } catch {
  1247. return {};
  1248. }
  1249. });
  1250. // Multi-drag bookkeeping for DragOverlay. Numeric for single items, string
  1251. // `batch-<id>` when a whole group is being dragged.
  1252. const [activeDragId, setActiveDragId] = useState<number | string | null>(null);
  1253. // "Group as batch" modal.
  1254. const [groupBatchModal, setGroupBatchModal] = useState(false);
  1255. // Ungroup confirm.
  1256. const [ungroupBatchId, setUngroupBatchId] = useState<number | null>(null);
  1257. // Persist sort settings to localStorage
  1258. useEffect(() => {
  1259. localStorage.setItem('queue.historySortBy', historySortBy);
  1260. }, [historySortBy]);
  1261. useEffect(() => {
  1262. localStorage.setItem('queue.historySortAsc', String(historySortAsc));
  1263. }, [historySortAsc]);
  1264. useEffect(() => {
  1265. localStorage.setItem('queue.pendingSortBy', pendingSortBy);
  1266. }, [pendingSortBy]);
  1267. useEffect(() => {
  1268. localStorage.setItem('queue.pendingSortAsc', String(pendingSortAsc));
  1269. }, [pendingSortAsc]);
  1270. useEffect(() => {
  1271. localStorage.setItem('queue.activeTab', activeTab);
  1272. }, [activeTab]);
  1273. useEffect(() => {
  1274. localStorage.setItem('queue.activeLayout', activeLayout);
  1275. }, [activeLayout]);
  1276. useEffect(() => {
  1277. localStorage.setItem('queue.batchCollapsed', JSON.stringify(batchCollapsed));
  1278. }, [batchCollapsed]);
  1279. const sensors = useSensors(
  1280. useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
  1281. useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  1282. );
  1283. const { data: settings } = useQuery({
  1284. queryKey: ['settings'],
  1285. queryFn: api.getSettings,
  1286. });
  1287. const timeFormat: TimeFormat = settings?.time_format || 'system';
  1288. const { data: queue, isLoading } = useQuery({
  1289. queryKey: ['queue', filterPrinter, filterStatus],
  1290. queryFn: () => api.getQueue(filterPrinter || undefined, filterStatus || undefined),
  1291. refetchInterval: 5000,
  1292. });
  1293. const { data: printers } = useQuery({
  1294. queryKey: ['printers'],
  1295. queryFn: () => api.getPrinters(),
  1296. });
  1297. const sjfMutation = useMutation({
  1298. mutationFn: (enabled: boolean) => api.updateSettings({ queue_shortest_first: enabled }),
  1299. onSuccess: () => {
  1300. queryClient.invalidateQueries({ queryKey: ['settings'] });
  1301. },
  1302. });
  1303. const cancelMutation = useMutation({
  1304. mutationFn: (id: number) => api.cancelQueueItem(id),
  1305. onSuccess: () => {
  1306. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1307. showToast(t('queue.toast.cancelled'));
  1308. },
  1309. onError: () => showToast(t('queue.toast.cancelFailed'), 'error'),
  1310. });
  1311. const removeMutation = useMutation({
  1312. mutationFn: (id: number) => api.removeFromQueue(id),
  1313. onSuccess: () => {
  1314. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1315. showToast(t('queue.toast.removed'));
  1316. },
  1317. onError: () => showToast(t('queue.toast.removeFailed'), 'error'),
  1318. });
  1319. const stopMutation = useMutation({
  1320. mutationFn: (id: number) => api.stopQueueItem(id),
  1321. onSuccess: () => {
  1322. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1323. showToast(t('queue.toast.stopped'));
  1324. },
  1325. onError: () => showToast(t('queue.toast.stopFailed'), 'error'),
  1326. });
  1327. // Filament-deficit confirmation state (#1496). When the backend returns
  1328. // 409 with `code=insufficient_filament` we stash the deficit + item id
  1329. // here; the modal at the bottom of the page reads it and the "Print
  1330. // Anyway" path re-issues the start with `skipFilamentCheck=true`.
  1331. const [filamentShortConfirm, setFilamentShortConfirm] = useState<{
  1332. itemId: number;
  1333. deficit: Array<{
  1334. slot_id: number;
  1335. required_grams: number;
  1336. remaining_grams: number | null;
  1337. filament_type?: string | null;
  1338. }>;
  1339. } | null>(null);
  1340. const startMutation = useMutation({
  1341. mutationFn: ({ id, skipFilamentCheck }: { id: number; skipFilamentCheck?: boolean }) =>
  1342. api.startQueueItem(id, { skipFilamentCheck }),
  1343. onSuccess: () => {
  1344. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1345. showToast(t('queue.toast.released'));
  1346. setFilamentShortConfirm(null);
  1347. },
  1348. onError: (error: unknown, variables) => {
  1349. if (error instanceof ApiError && error.status === 409 && error.code === 'insufficient_filament') {
  1350. const deficitRaw = (error.detail?.deficit ?? []) as Array<{
  1351. slot_id: number;
  1352. required_grams: number;
  1353. remaining_grams: number | null;
  1354. filament_type?: string | null;
  1355. }>;
  1356. setFilamentShortConfirm({ itemId: variables.id, deficit: deficitRaw });
  1357. return;
  1358. }
  1359. showToast(t('queue.toast.startFailed'), 'error');
  1360. },
  1361. });
  1362. const reorderMutation = useMutation({
  1363. mutationFn: (items: { id: number; position: number }[]) => api.reorderQueue(items),
  1364. onSuccess: () => {
  1365. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1366. },
  1367. onError: () => showToast(t('queue.toast.reorderFailed'), 'error'),
  1368. });
  1369. const clearHistoryMutation = useMutation({
  1370. mutationFn: async () => {
  1371. const historyItems = queue?.filter(i =>
  1372. ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)
  1373. ) || [];
  1374. for (const item of historyItems) {
  1375. await api.removeFromQueue(item.id);
  1376. }
  1377. return historyItems.length;
  1378. },
  1379. onSuccess: (count) => {
  1380. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1381. showToast(t('queue.toast.historyCleared', { count }));
  1382. },
  1383. onError: () => showToast(t('queue.toast.clearHistoryFailed'), 'error'),
  1384. });
  1385. const bulkUpdateMutation = useMutation({
  1386. mutationFn: (data: PrintQueueBulkUpdate) => api.bulkUpdateQueue(data),
  1387. onSuccess: (result) => {
  1388. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1389. setSelectedItems([]);
  1390. setShowBulkEditModal(false);
  1391. showToast(result.message);
  1392. },
  1393. onError: () => showToast(t('queue.toast.updateFailed'), 'error'),
  1394. });
  1395. const bulkCancelMutation = useMutation({
  1396. mutationFn: async (ids: number[]) => {
  1397. for (const id of ids) {
  1398. await api.cancelQueueItem(id);
  1399. }
  1400. return ids.length;
  1401. },
  1402. onSuccess: (count) => {
  1403. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1404. setSelectedItems([]);
  1405. showToast(t('queue.toast.bulkCancelled', { count }));
  1406. },
  1407. onError: () => showToast(t('queue.toast.bulkCancelFailed'), 'error'),
  1408. });
  1409. const resumeAfterFailureMutation = useMutation({
  1410. mutationFn: (printerId: number) => api.resumeQueueAfterFailure(printerId),
  1411. onSuccess: (result) => {
  1412. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1413. setResumeConfirm(null);
  1414. showToast(
  1415. t('queue.toast.resumedAfterFailure', {
  1416. restored: result.restored,
  1417. acknowledged: result.acknowledged,
  1418. }),
  1419. );
  1420. },
  1421. onError: () => showToast(t('queue.toast.resumeAfterFailureFailed'), 'error'),
  1422. });
  1423. const createBatchMutation = useMutation({
  1424. mutationFn: (data: { name: string; item_ids: number[] }) => api.createBatch(data),
  1425. onSuccess: (batch) => {
  1426. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1427. setSelectedItems([]);
  1428. setGroupBatchModal(false);
  1429. // New batches start expanded so the user sees what they just grouped.
  1430. setBatchCollapsed((prev) => ({ ...prev, [batch.id]: false }));
  1431. showToast(t('queue.toast.batchCreated', { name: batch.name }));
  1432. },
  1433. onError: () => showToast(t('queue.toast.batchCreateFailed'), 'error'),
  1434. });
  1435. const ungroupBatchMutation = useMutation({
  1436. mutationFn: (id: number) => api.ungroupBatch(id),
  1437. onSuccess: (result) => {
  1438. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1439. setUngroupBatchId(null);
  1440. showToast(t('queue.toast.batchUngrouped', { count: result.ungrouped_count }));
  1441. },
  1442. onError: () => showToast(t('queue.toast.batchUngroupFailed'), 'error'),
  1443. });
  1444. const handleToggleSelect = (id: number) => {
  1445. setSelectedItems(prev =>
  1446. prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
  1447. );
  1448. };
  1449. // Get unique locations from printers for the filter dropdown
  1450. const uniqueLocations = useMemo(() => {
  1451. const locations = new Set<string>();
  1452. printers?.forEach(p => {
  1453. if (p.location) locations.add(p.location);
  1454. });
  1455. // Also include locations from queue items (for model-based assignments)
  1456. queue?.forEach(item => {
  1457. if (item.target_location) locations.add(item.target_location);
  1458. });
  1459. return Array.from(locations).sort();
  1460. }, [printers, queue]);
  1461. // Helper to check if a queue item matches the location filter
  1462. const matchesLocationFilter = useCallback((item: PrintQueueItem): boolean => {
  1463. if (!filterLocation) return true;
  1464. // For model-based assignments, check target_location
  1465. if (item.target_location) return item.target_location === filterLocation;
  1466. // For printer-based assignments, check the printer's location
  1467. if (item.printer_id) {
  1468. const printer = printers?.find(p => p.id === item.printer_id);
  1469. return printer?.location === filterLocation;
  1470. }
  1471. return false;
  1472. }, [filterLocation, printers]);
  1473. const pendingItems = useMemo(() => {
  1474. let items = queue?.filter(i => i.status === 'pending') || [];
  1475. // Apply location filter
  1476. if (filterLocation) {
  1477. items = items.filter(matchesLocationFilter);
  1478. }
  1479. // Helper to get scheduled time as timestamp (ASAP/placeholder = 0 for earliest)
  1480. const getScheduledTime = (item: PrintQueueItem): number => {
  1481. if (!item.scheduled_time) return 0;
  1482. const time = parseUTCDate(item.scheduled_time)?.getTime() ?? 0;
  1483. // Placeholder dates (> 6 months out) are treated as ASAP
  1484. const sixMonthsFromNow = Date.now() + (180 * 24 * 60 * 60 * 1000);
  1485. return time > sixMonthsFromNow ? 0 : time;
  1486. };
  1487. // When SJF is enabled, override sort to match scheduler order
  1488. if (settings?.queue_shortest_first) {
  1489. return [...items].sort((a, b) => {
  1490. // Group by printer first (nulls = model-based, grouped by target_model)
  1491. const aPrinter = a.printer_id ?? -(a.target_model?.charCodeAt(0) ?? 0);
  1492. const bPrinter = b.printer_id ?? -(b.target_model?.charCodeAt(0) ?? 0);
  1493. if (aPrinter !== bPrinter) return aPrinter - bPrinter;
  1494. // Within same printer/model: jumped items first (starvation guard)
  1495. const aJumped = a.been_jumped ? 1 : 0;
  1496. const bJumped = b.been_jumped ? 1 : 0;
  1497. if (aJumped !== bJumped) return bJumped - aJumped;
  1498. // Shortest print time next (nulls last)
  1499. const aTime = a.print_time_seconds ?? Infinity;
  1500. const bTime = b.print_time_seconds ?? Infinity;
  1501. if (aTime !== bTime) return aTime - bTime;
  1502. // Position as tiebreaker
  1503. return a.position - b.position;
  1504. });
  1505. }
  1506. return [...items].sort((a, b) => {
  1507. let cmp: number;
  1508. if (pendingSortBy === 'name') {
  1509. const aName = a.archive_name || a.library_file_name || '';
  1510. const bName = b.archive_name || b.library_file_name || '';
  1511. cmp = aName.localeCompare(bName);
  1512. } else if (pendingSortBy === 'printer') {
  1513. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  1514. } else if (pendingSortBy === 'time') {
  1515. // Sort by scheduled start time (when print will begin)
  1516. cmp = getScheduledTime(a) - getScheduledTime(b);
  1517. } else {
  1518. cmp = a.position - b.position;
  1519. }
  1520. return pendingSortAsc ? cmp : -cmp;
  1521. });
  1522. }, [queue, pendingSortBy, pendingSortAsc, matchesLocationFilter, filterLocation, settings?.queue_shortest_first]);
  1523. const handleSelectAll = () => {
  1524. const allPendingIds = pendingItems.map(i => i.id);
  1525. if (selectedItems.length === allPendingIds.length) {
  1526. setSelectedItems([]);
  1527. } else {
  1528. setSelectedItems(allPendingIds);
  1529. }
  1530. };
  1531. const activeItems = useMemo(() => {
  1532. let items = queue?.filter(i => i.status === 'printing') || [];
  1533. if (filterLocation) {
  1534. items = items.filter(matchesLocationFilter);
  1535. }
  1536. return items;
  1537. }, [queue, filterLocation, matchesLocationFilter]);
  1538. // Get unique printer IDs from active items to fetch their statuses
  1539. const activePrinterIds = useMemo(() => {
  1540. const ids = new Set<number>();
  1541. activeItems.forEach(item => {
  1542. if (item.printer_id) ids.add(item.printer_id);
  1543. });
  1544. return Array.from(ids);
  1545. }, [activeItems]);
  1546. // Fetch printer statuses for printers with active jobs
  1547. const printerStatusQueries = useQueries({
  1548. queries: activePrinterIds.map(printerId => ({
  1549. queryKey: ['printerStatus', printerId],
  1550. queryFn: () => api.getPrinterStatus(printerId),
  1551. refetchInterval: 5000,
  1552. })),
  1553. });
  1554. // Build a map of printer_id -> state for quick lookup
  1555. const printerStateMap = useMemo(() => {
  1556. const map: Record<number, string | null> = {};
  1557. activePrinterIds.forEach((printerId, index) => {
  1558. const result = printerStatusQueries[index];
  1559. if (result?.data?.state) {
  1560. map[printerId] = result.data.state;
  1561. }
  1562. });
  1563. return map;
  1564. }, [activePrinterIds, printerStatusQueries]);
  1565. // Build a map of printer_id -> full status for timeline view
  1566. const printerStatusMap = useMemo(() => {
  1567. const map: Record<number, { progress?: number; remaining_time?: number; state?: string }> = {};
  1568. activePrinterIds.forEach((printerId, index) => {
  1569. const result = printerStatusQueries[index];
  1570. if (result?.data) {
  1571. map[printerId] = {
  1572. progress: result.data.progress ?? undefined,
  1573. remaining_time: result.data.remaining_time ?? undefined,
  1574. state: result.data.state ?? undefined,
  1575. };
  1576. }
  1577. });
  1578. return map;
  1579. }, [activePrinterIds, printerStatusQueries]);
  1580. const historyItems = useMemo(() => {
  1581. let items = queue?.filter(i => ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)) || [];
  1582. if (filterLocation) {
  1583. items = items.filter(matchesLocationFilter);
  1584. }
  1585. return [...items].sort((a, b) => {
  1586. let cmp: number;
  1587. if (historySortBy === 'name') {
  1588. const aName = a.archive_name || a.library_file_name || '';
  1589. const bName = b.archive_name || b.library_file_name || '';
  1590. cmp = aName.localeCompare(bName);
  1591. } else if (historySortBy === 'printer') {
  1592. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  1593. } else {
  1594. // Default: by date - most recent first (desc) is the natural order
  1595. cmp = (parseUTCDate(b.completed_at || b.created_at)?.getTime() ?? 0) - (parseUTCDate(a.completed_at || a.created_at)?.getTime() ?? 0);
  1596. }
  1597. return historySortAsc ? -cmp : cmp;
  1598. });
  1599. }, [queue, historySortBy, historySortAsc, matchesLocationFilter, filterLocation]);
  1600. // Calculate total queue time
  1601. const totalQueueTime = useMemo(() => {
  1602. return pendingItems.reduce((acc, item) => acc + (item.print_time_seconds || 0), 0);
  1603. }, [pendingItems]);
  1604. // Calculate total material weight
  1605. const totalWeight = useMemo(() => {
  1606. return pendingItems.reduce((acc, item) => acc + (item.filament_used_grams || 0), 0);
  1607. }, [pendingItems]);
  1608. const handleDragStart = (event: DragStartEvent) => {
  1609. const id = event.active.id;
  1610. setActiveDragId(typeof id === 'number' || typeof id === 'string' ? id : null);
  1611. };
  1612. const handleDragEnd = (event: DragEndEvent) => {
  1613. const { active, over } = event;
  1614. setActiveDragId(null);
  1615. if (!over || active.id === over.id) return;
  1616. // Resolve dragged source → movingIds (preserving order from pendingItems).
  1617. // - `batch-<id>`: every child of that batch, in their current order
  1618. // - selected + dragged is one of them: contiguous multi-drag block
  1619. // - otherwise: single row
  1620. let movingIds: number[];
  1621. const activeId = active.id;
  1622. if (typeof activeId === 'string' && activeId.startsWith('batch-')) {
  1623. const batchId = Number(activeId.slice('batch-'.length));
  1624. movingIds = pendingItems.filter((i) => i.batch_id === batchId).map((i) => i.id);
  1625. } else {
  1626. const draggedId = activeId as number;
  1627. movingIds = selectedItems.includes(draggedId) && selectedItems.length > 1
  1628. ? selectedItems.slice().sort((a, b) => {
  1629. const ai = pendingItems.findIndex((i) => i.id === a);
  1630. const bi = pendingItems.findIndex((i) => i.id === b);
  1631. return ai - bi;
  1632. })
  1633. : [draggedId];
  1634. }
  1635. if (movingIds.length === 0) return;
  1636. // Resolve drop target → index inside pendingItems. A `batch-<id>` drop
  1637. // target anchors at the batch's first child, so dropping above another
  1638. // batch lands the moving block immediately before it.
  1639. let overIndex: number;
  1640. const overId = over.id;
  1641. if (typeof overId === 'string' && overId.startsWith('batch-')) {
  1642. const overBatchId = Number(overId.slice('batch-'.length));
  1643. overIndex = pendingItems.findIndex((i) => i.batch_id === overBatchId);
  1644. } else {
  1645. overIndex = pendingItems.findIndex((i) => i.id === overId);
  1646. }
  1647. if (overIndex === -1) return;
  1648. // Remove the moving items, then re-insert at overIndex (adjusted).
  1649. const overAnchor = pendingItems[overIndex];
  1650. const remaining = pendingItems.filter((i) => !movingIds.includes(i.id));
  1651. let insertAt = remaining.findIndex((i) => i.id === overAnchor.id);
  1652. if (insertAt === -1) insertAt = overIndex;
  1653. // If dragging downward across the drop target, insert AFTER it; upward
  1654. // = before. dnd-kit's `over` is the row under the pointer, not the gap.
  1655. const firstMovingIndex = pendingItems.findIndex((i) => i.id === movingIds[0]);
  1656. if (firstMovingIndex < overIndex) insertAt += 1;
  1657. const reordered = [
  1658. ...remaining.slice(0, insertAt),
  1659. ...movingIds
  1660. .map((id) => pendingItems.find((i) => i.id === id))
  1661. .filter((x): x is PrintQueueItem => !!x),
  1662. ...remaining.slice(insertAt),
  1663. ];
  1664. const updates = reordered.map((item, index) => ({
  1665. id: item.id,
  1666. position: index + 1,
  1667. }));
  1668. reorderMutation.mutate(updates);
  1669. };
  1670. // Group pending items by batch_id. Items with batch_id null render as
  1671. // standalone rows; items sharing a batch_id render as a collapsible
  1672. // group keyed by that id. Items inside a group keep their original
  1673. // relative order from pendingItems.
  1674. const groupedRows = useMemo<QueueRow[]>(() => {
  1675. const rows: QueueRow[] = [];
  1676. const seenBatches = new Set<number>();
  1677. for (const item of pendingItems) {
  1678. if (item.batch_id != null) {
  1679. if (seenBatches.has(item.batch_id)) continue;
  1680. seenBatches.add(item.batch_id);
  1681. const siblings = pendingItems.filter((s) => s.batch_id === item.batch_id);
  1682. rows.push({
  1683. kind: 'batch',
  1684. batchId: item.batch_id,
  1685. batchName: item.batch_name || t('queue.batch.defaultName'),
  1686. items: siblings,
  1687. });
  1688. } else {
  1689. rows.push({ kind: 'item', item });
  1690. }
  1691. }
  1692. return rows;
  1693. }, [pendingItems, t]);
  1694. // SortableContext ID list.
  1695. // - Standalone pending items: their numeric id.
  1696. // - Batch parents: the synthetic `batch-<id>` string, always present so the
  1697. // group itself is draggable and acts as a drop target whether collapsed
  1698. // or expanded.
  1699. // - Expanded batch children: their numeric id, so within-batch reorder
  1700. // keeps working. Collapsed children are detached from the DOM and
  1701. // intentionally omitted to keep dnd-kit's collision resolver clean.
  1702. const sortableIds = useMemo<(number | string)[]>(() => {
  1703. const ids: (number | string)[] = [];
  1704. for (const row of groupedRows) {
  1705. if (row.kind === 'item') {
  1706. ids.push(row.item.id);
  1707. } else {
  1708. ids.push(`batch-${row.batchId}`);
  1709. const collapsed = batchCollapsed[row.batchId] ?? true;
  1710. if (!collapsed) {
  1711. for (const child of row.items) ids.push(child.id);
  1712. }
  1713. }
  1714. }
  1715. return ids;
  1716. }, [groupedRows, batchCollapsed]);
  1717. // Items already in a batch can't be grouped; "Group as batch" only shows
  1718. // when 2+ ungrouped items are selected.
  1719. const canGroupSelected = useMemo(() => {
  1720. if (selectedItems.length < 2) return false;
  1721. return selectedItems.every((id) => {
  1722. const item = pendingItems.find((p) => p.id === id);
  1723. return item && item.batch_id == null;
  1724. });
  1725. }, [selectedItems, pendingItems]);
  1726. const toggleBatchCollapsed = (id: number) => {
  1727. setBatchCollapsed((prev) => ({ ...prev, [id]: !(prev[id] ?? true) }));
  1728. };
  1729. // Group by printer view. Items are bucketed by printer_id (null = model
  1730. // assignment or unassigned, keyed by target_model or "unassigned").
  1731. type PrinterBucket = {
  1732. key: string;
  1733. printerId: number | null;
  1734. targetModel: string | null;
  1735. label: string;
  1736. isUnassigned: boolean;
  1737. rows: QueueRow[];
  1738. };
  1739. const printerBuckets = useMemo<PrinterBucket[]>(() => {
  1740. const buckets = new Map<string, PrinterBucket>();
  1741. const bucketForItem = (item: PrintQueueItem): { key: string; label: string; printerId: number | null; targetModel: string | null; isUnassigned: boolean } => {
  1742. if (item.printer_id) {
  1743. return {
  1744. key: `printer:${item.printer_id}`,
  1745. label: item.printer_name || `Printer #${item.printer_id}`,
  1746. printerId: item.printer_id,
  1747. targetModel: null,
  1748. isUnassigned: false,
  1749. };
  1750. }
  1751. if (item.target_model) {
  1752. return {
  1753. key: `model:${item.target_model}`,
  1754. label: `${t('queue.filter.any')} ${item.target_model}`,
  1755. printerId: null,
  1756. targetModel: item.target_model,
  1757. isUnassigned: false,
  1758. };
  1759. }
  1760. return {
  1761. key: 'unassigned',
  1762. label: t('queue.filter.unassigned'),
  1763. printerId: null,
  1764. targetModel: null,
  1765. isUnassigned: true,
  1766. };
  1767. };
  1768. for (const row of groupedRows) {
  1769. const representative = row.kind === 'item' ? row.item : row.items[0];
  1770. if (!representative) continue;
  1771. const meta = bucketForItem(representative);
  1772. if (!buckets.has(meta.key)) {
  1773. buckets.set(meta.key, { ...meta, rows: [] });
  1774. }
  1775. buckets.get(meta.key)!.rows.push(row);
  1776. }
  1777. return Array.from(buckets.values()).sort((a, b) => {
  1778. if (a.isUnassigned && !b.isUnassigned) return 1;
  1779. if (!a.isUnassigned && b.isUnassigned) return -1;
  1780. return a.label.localeCompare(b.label);
  1781. });
  1782. }, [groupedRows, t]);
  1783. // #1818: printers whose queue is gated by a prior failure that's poisoning
  1784. // downstream `require_previous_success` items. We surface a per-printer
  1785. // Resume banner above the active queue so the user can clear the gate +
  1786. // restore the skipped jobs in one click, without re-queuing each one.
  1787. // Detection key: skipped + the scheduler's exact gate string. Other skip
  1788. // reasons (filament deficit, etc.) get their own UX and stay untouched.
  1789. const gateBlockedPrinters = useMemo<
  1790. Array<{ printerId: number; printerName: string; skippedCount: number }>
  1791. >(() => {
  1792. const counts = new Map<number, { name: string; count: number }>();
  1793. queue?.forEach((item) => {
  1794. if (
  1795. item.status === 'skipped' &&
  1796. item.error_message === 'Previous print failed or was aborted' &&
  1797. item.printer_id
  1798. ) {
  1799. const existing = counts.get(item.printer_id);
  1800. if (existing) {
  1801. existing.count += 1;
  1802. } else {
  1803. counts.set(item.printer_id, {
  1804. name: item.printer_name || `Printer #${item.printer_id}`,
  1805. count: 1,
  1806. });
  1807. }
  1808. }
  1809. });
  1810. return Array.from(counts.entries())
  1811. .map(([printerId, { name, count }]) => ({
  1812. printerId,
  1813. printerName: name,
  1814. skippedCount: count,
  1815. }))
  1816. .sort((a, b) => a.printerName.localeCompare(b.printerName));
  1817. }, [queue]);
  1818. const aggregateForRows = (rows: QueueRow[]) => {
  1819. let count = 0;
  1820. let time = 0;
  1821. let weight = 0;
  1822. for (const row of rows) {
  1823. const items = row.kind === 'item' ? [row.item] : row.items;
  1824. for (const item of items) {
  1825. count += 1;
  1826. time += item.print_time_seconds || 0;
  1827. weight += item.filament_used_grams || 0;
  1828. }
  1829. }
  1830. return { count, time, weight };
  1831. };
  1832. return (
  1833. <div className="p-4 md:p-8">
  1834. {/* Header */}
  1835. <div className="flex items-center justify-between mb-6">
  1836. <div>
  1837. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  1838. <ListOrdered className="w-7 h-7 text-bambu-green" />
  1839. {t('queue.title')}
  1840. </h1>
  1841. <p className="text-bambu-gray mt-1">{t('queue.subtitle')}</p>
  1842. </div>
  1843. </div>
  1844. {/* Tab strip — Active queue is the main view; History and Timeline
  1845. live in their own tabs so the queue page stays focused. */}
  1846. <div className="flex gap-1 border-b border-bambu-dark-tertiary mb-6 overflow-x-auto">
  1847. {([
  1848. { id: 'queue' as const, label: t('queue.tabs.queue'), icon: Clock, count: pendingItems.length + activeItems.length },
  1849. { id: 'history' as const, label: t('queue.tabs.history'), icon: ListOrdered, count: historyItems.length },
  1850. { id: 'timeline' as const, label: t('queue.tabs.timeline'), icon: GanttChart, count: null as number | null },
  1851. // Slicer Pipelines dashboard (#1425 PR C). Lives here instead of
  1852. // its own sidebar entry so the Print Queue page is the single
  1853. // place an operator looks for "what's running / what ran".
  1854. { id: 'pipelines' as const, label: t('queue.tabs.pipelines'), icon: Workflow, count: null as number | null },
  1855. ]).map(({ id, label, icon: Icon, count }) => (
  1856. <button
  1857. key={id}
  1858. onClick={() => setActiveTab(id)}
  1859. className={`px-4 py-2.5 text-sm flex items-center gap-2 border-b-2 -mb-px transition-colors whitespace-nowrap ${
  1860. activeTab === id
  1861. ? 'text-white border-bambu-green font-medium'
  1862. : 'text-bambu-gray border-transparent hover:text-white'
  1863. }`}
  1864. >
  1865. <Icon className="w-4 h-4" />
  1866. {label}
  1867. {count !== null && count > 0 && (
  1868. <span className={`text-xs px-1.5 py-0.5 rounded-full ${
  1869. activeTab === id ? 'bg-bambu-green/20 text-bambu-green' : 'bg-bambu-dark-tertiary text-bambu-gray'
  1870. }`}>
  1871. {count}
  1872. </span>
  1873. )}
  1874. </button>
  1875. ))}
  1876. </div>
  1877. {/* Summary Stats — about the print queue, not pipelines. */}
  1878. {activeTab !== 'pipelines' && <QueueStatsBar
  1879. activeCount={activeItems.length}
  1880. pendingCount={pendingItems.length}
  1881. totalTime={totalQueueTime}
  1882. totalWeight={totalWeight}
  1883. historyCount={historyItems.length}
  1884. t={t}
  1885. />}
  1886. {/* #1818: Resume-after-failure banner. One row per printer whose queue
  1887. is gated by a prior failed/aborted print. Visible regardless of
  1888. tab/layout so the user can clear the gate without hunting for
  1889. skipped items. Hidden entirely when no gates are active. */}
  1890. {activeTab === 'queue' && gateBlockedPrinters.length > 0 && hasPermission('queue:update_all' as Permission) && (
  1891. <div className="mb-4 space-y-2">
  1892. {gateBlockedPrinters.map(({ printerId, printerName, skippedCount }) => (
  1893. <div
  1894. key={printerId}
  1895. 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"
  1896. >
  1897. <AlertCircle className="w-5 h-5 text-orange-600 dark:text-orange-400 flex-shrink-0" />
  1898. <div className="flex-1 min-w-0">
  1899. <div className="text-sm text-orange-800 dark:text-orange-200">
  1900. {t('queue.resumeAfterFailure.banner', {
  1901. printer: printerName,
  1902. count: skippedCount,
  1903. })}
  1904. </div>
  1905. <div className="text-xs text-orange-800/80 dark:text-orange-200/70 mt-0.5">
  1906. {t('queue.resumeAfterFailure.bannerHint')}
  1907. </div>
  1908. </div>
  1909. <button
  1910. onClick={() =>
  1911. setResumeConfirm({ printerId, printerName, skippedCount })
  1912. }
  1913. 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"
  1914. >
  1915. <PlayCircle className="w-4 h-4" />
  1916. {t('queue.resumeAfterFailure.button')}
  1917. </button>
  1918. </div>
  1919. ))}
  1920. </div>
  1921. )}
  1922. {/* Filters — about the print queue items (printer / status / location).
  1923. The Pipelines tab has its own pipeline + status filters inside the
  1924. dashboard, so this row is hidden when that tab is active. */}
  1925. {activeTab !== 'pipelines' && (
  1926. <div className="flex flex-wrap items-center gap-2 sm:gap-4 mb-6">
  1927. <select
  1928. 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"
  1929. value={filterPrinter === -1 ? 'unassigned' : (filterPrinter || '')}
  1930. onChange={(e) => {
  1931. const val = e.target.value;
  1932. if (val === 'unassigned') setFilterPrinter(-1);
  1933. else if (val === '') setFilterPrinter(null);
  1934. else setFilterPrinter(Number(val));
  1935. }}
  1936. >
  1937. <option value="">{t('queue.filter.allPrinters')}</option>
  1938. <option value="unassigned">{t('queue.filter.unassigned')}</option>
  1939. {printers?.map((p) => (
  1940. <option key={p.id} value={p.id}>{p.name}</option>
  1941. ))}
  1942. </select>
  1943. <select
  1944. 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"
  1945. value={filterStatus}
  1946. onChange={(e) => setFilterStatus(e.target.value)}
  1947. >
  1948. <option value="">{t('queue.filter.allStatus')}</option>
  1949. <option value="pending">{t('queue.status.pending')}</option>
  1950. <option value="printing">{t('queue.status.printing')}</option>
  1951. <option value="completed">{t('queue.status.completed')}</option>
  1952. <option value="failed">{t('queue.status.failed')}</option>
  1953. <option value="skipped">{t('queue.status.skipped')}</option>
  1954. <option value="cancelled">{t('queue.status.cancelled')}</option>
  1955. </select>
  1956. {uniqueLocations.length > 0 && (
  1957. <select
  1958. 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"
  1959. value={filterLocation}
  1960. onChange={(e) => setFilterLocation(e.target.value)}
  1961. >
  1962. <option value="">{t('queue.filter.allLocations')}</option>
  1963. {uniqueLocations.map((loc) => (
  1964. <option key={loc} value={loc}>{loc}</option>
  1965. ))}
  1966. </select>
  1967. )}
  1968. <div className="hidden sm:block flex-1" />
  1969. {activeTab === 'history' && historyItems.length > 0 && (
  1970. <Button
  1971. className="w-full sm:w-auto"
  1972. variant="secondary"
  1973. size="sm"
  1974. onClick={() => setShowClearHistoryConfirm(true)}
  1975. disabled={!hasPermission('queue:delete_all')}
  1976. title={!hasPermission('queue:delete_all') ? t('queue.permissions.noClearHistory') : undefined}
  1977. >
  1978. <Trash2 className="w-4 h-4" />
  1979. {t('queue.clearHistory')}
  1980. </Button>
  1981. )}
  1982. </div>
  1983. )}
  1984. {/* Queue-tab controls: layout toggle (Position / Printer) + SJF.
  1985. Hidden on History/Timeline tabs since they don't apply. */}
  1986. {activeTab === 'queue' && (
  1987. <div className="flex flex-wrap items-center gap-3 mb-6">
  1988. <div className="inline-flex items-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-0.5">
  1989. <button
  1990. className={`px-3 py-1.5 text-xs sm:text-sm rounded-md transition-colors flex items-center gap-1.5 ${
  1991. activeLayout === 'position' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'
  1992. }`}
  1993. onClick={() => setActiveLayout('position')}
  1994. title={t('queue.layout.flatList')}
  1995. >
  1996. <List className="w-3.5 h-3.5" />
  1997. <span className="hidden sm:inline">{t('queue.layout.flatList')}</span>
  1998. </button>
  1999. <button
  2000. className={`px-3 py-1.5 text-xs sm:text-sm rounded-md transition-colors flex items-center gap-1.5 ${
  2001. activeLayout === 'printer' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'
  2002. }`}
  2003. onClick={() => setActiveLayout('printer')}
  2004. title={t('queue.layout.groupByPrinter')}
  2005. >
  2006. <Printer className="w-3.5 h-3.5" />
  2007. <span className="hidden sm:inline">{t('queue.layout.byPrinter')}</span>
  2008. </button>
  2009. </div>
  2010. <button
  2011. onClick={() => {
  2012. const newValue = !(settings?.queue_shortest_first ?? false);
  2013. sjfMutation.mutate(newValue);
  2014. }}
  2015. className={`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${
  2016. settings?.queue_shortest_first
  2017. ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
  2018. : 'bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  2019. }`}
  2020. title={t('queue.sjf.tooltip', 'Shortest Job First — scheduler prioritizes shorter prints')}
  2021. >
  2022. <Snail className="w-4 h-4" />
  2023. <span className="hidden sm:inline">{t('queue.sjf.label', 'SJF')}</span>
  2024. <span className={`w-1.5 h-1.5 rounded-full ${settings?.queue_shortest_first ? 'bg-bambu-green' : 'bg-bambu-gray'}`} />
  2025. </button>
  2026. </div>
  2027. )}
  2028. {/* Pipelines tab short-circuits before the queue-empty branch so the
  2029. dashboard renders even when the regular queue is empty. */}
  2030. {activeTab === 'pipelines' ? (
  2031. <PipelineRunsView />
  2032. ) : isLoading ? (
  2033. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  2034. ) : queue?.length === 0 ? (
  2035. <Card className="p-12 text-center border-dashed">
  2036. <Calendar className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  2037. <h3 className="text-xl font-medium text-white mb-2">{t('queue.empty.title')}</h3>
  2038. <p className="text-bambu-gray max-w-md mx-auto">
  2039. {t('queue.empty.description')}
  2040. </p>
  2041. </Card>
  2042. ) : activeTab === 'timeline' ? (
  2043. <QueueTimelineView
  2044. queueItems={queue || []}
  2045. printers={printers || []}
  2046. printerStatuses={printerStatusMap}
  2047. onItemClick={(item) => {
  2048. if (['completed', 'failed', 'skipped', 'cancelled'].includes(item.status)) {
  2049. setRequeueItem(item);
  2050. } else if (item.status === 'pending') {
  2051. setEditItem(item);
  2052. } else if (item.status === 'printing') {
  2053. setConfirmAction({ type: 'stop', item });
  2054. }
  2055. }}
  2056. t={t}
  2057. />
  2058. ) : activeTab === 'history' ? (
  2059. <HistorySection
  2060. items={historyItems}
  2061. collapsed={false}
  2062. sortBy={historySortBy}
  2063. sortAsc={historySortAsc}
  2064. onSortByChange={setHistorySortBy}
  2065. onSortAscToggle={() => setHistorySortAsc(!historySortAsc)}
  2066. onRemove={(item) => setConfirmAction({ type: 'remove', item })}
  2067. onRequeue={setRequeueItem}
  2068. timeFormat={timeFormat}
  2069. batchCollapsed={batchCollapsed}
  2070. toggleBatchCollapsed={toggleBatchCollapsed}
  2071. hasPermission={hasPermission}
  2072. canModify={canModify}
  2073. t={t}
  2074. />
  2075. ) : (
  2076. <div className="space-y-6 sm:space-y-8">
  2077. {/* Active Prints */}
  2078. {activeItems.length > 0 && (
  2079. <div>
  2080. <h2 className="text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2">
  2081. <div className="w-2 h-2 rounded-full bg-blue-400 animate-pulse" />
  2082. {t('queue.sections.currentlyPrinting')}
  2083. </h2>
  2084. <div className="space-y-2 sm:space-y-3">
  2085. {activeItems.map((item) => (
  2086. <SortableQueueItem
  2087. key={item.id}
  2088. item={item}
  2089. onEdit={() => {}}
  2090. onCancel={() => {}}
  2091. onRemove={() => {}}
  2092. onStop={() => setConfirmAction({ type: 'stop', item })}
  2093. onRequeue={() => {}}
  2094. onStart={() => {}}
  2095. timeFormat={timeFormat}
  2096. hasPermission={hasPermission}
  2097. canModify={canModify}
  2098. printerState={item.printer_id ? printerStateMap[item.printer_id] : null}
  2099. t={t}
  2100. />
  2101. ))}
  2102. </div>
  2103. </div>
  2104. )}
  2105. {/* Pending Queue */}
  2106. {pendingItems.length > 0 && (
  2107. <div>
  2108. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  2109. <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
  2110. <Clock className="w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 dark:text-yellow-400" />
  2111. {t('queue.sections.queued')}
  2112. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  2113. ({t('queue.itemCount', { count: pendingItems.length })})
  2114. </span>
  2115. <span className="hidden sm:inline text-xs text-bambu-gray ml-2" title={t('queue.reorderHint')}>
  2116. {t('queue.dragToReorder')}
  2117. </span>
  2118. </h2>
  2119. <div className="flex items-center gap-2">
  2120. <select
  2121. 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"
  2122. value={pendingSortBy}
  2123. onChange={(e) => setPendingSortBy(e.target.value as 'position' | 'name' | 'printer' | 'time')}
  2124. >
  2125. <option value="position">{t('queue.sort.byPosition')}</option>
  2126. <option value="name">{t('queue.sort.byName')}</option>
  2127. <option value="printer">{t('queue.sort.byPrinter')}</option>
  2128. <option value="time">{t('queue.sort.bySchedule')}</option>
  2129. </select>
  2130. <Button
  2131. variant="ghost"
  2132. size="sm"
  2133. onClick={() => setPendingSortAsc(!pendingSortAsc)}
  2134. title={pendingSortAsc ? t('common.ascending') : t('common.descending')}
  2135. className="px-2"
  2136. >
  2137. {pendingSortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  2138. </Button>
  2139. </div>
  2140. </div>
  2141. {/* Bulk action toolbar (now with "Group as batch") */}
  2142. <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">
  2143. <Button
  2144. variant="ghost"
  2145. size="sm"
  2146. onClick={handleSelectAll}
  2147. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm"
  2148. >
  2149. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? (
  2150. <CheckSquare className="w-4 h-4 text-bambu-green" />
  2151. ) : (
  2152. <Square className="w-4 h-4" />
  2153. )}
  2154. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? t('queue.bulkEdit.deselectAll') : t('queue.bulkEdit.selectAll')}
  2155. </Button>
  2156. {selectedItems.length > 0 && (
  2157. <>
  2158. <span className="text-xs sm:text-sm text-bambu-gray">
  2159. {t('queue.bulkEdit.selected', { count: selectedItems.length })}
  2160. </span>
  2161. <div className="hidden sm:block h-4 w-px bg-bambu-dark-tertiary" />
  2162. {canGroupSelected && (
  2163. <Button
  2164. variant="ghost"
  2165. size="sm"
  2166. onClick={() => setGroupBatchModal(true)}
  2167. 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"
  2168. title={t('queue.batch.groupAsBatch')}
  2169. >
  2170. <Package className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2171. <span className="hidden sm:inline">{t('queue.batch.groupAsBatch')}</span>
  2172. </Button>
  2173. )}
  2174. <Button
  2175. variant="ghost"
  2176. size="sm"
  2177. onClick={() => setShowBulkEditModal(true)}
  2178. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light"
  2179. disabled={!hasAnyPermission('queue:update_own', 'queue:update_all')}
  2180. title={!hasAnyPermission('queue:update_own', 'queue:update_all') ? t('queue.permissions.noEditItems') : t('queue.bulkEdit.editSelected')}
  2181. >
  2182. <Pencil className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2183. <span className="hidden sm:inline">{t('queue.bulkEdit.editSelected')}</span>
  2184. </Button>
  2185. <Button
  2186. variant="ghost"
  2187. size="sm"
  2188. onClick={() => bulkCancelMutation.mutate(selectedItems)}
  2189. 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"
  2190. disabled={bulkCancelMutation.isPending || !hasAnyPermission('queue:delete_own', 'queue:delete_all')}
  2191. title={!hasAnyPermission('queue:delete_own', 'queue:delete_all') ? t('queue.permissions.noCancelItems') : t('queue.bulkEdit.cancelSelected')}
  2192. >
  2193. <X className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2194. <span className="hidden sm:inline">{t('queue.bulkEdit.cancelSelected')}</span>
  2195. </Button>
  2196. </>
  2197. )}
  2198. </div>
  2199. <DndContext
  2200. sensors={sensors}
  2201. collisionDetection={closestCenter}
  2202. onDragStart={handleDragStart}
  2203. onDragEnd={handleDragEnd}
  2204. >
  2205. <SortableContext
  2206. items={sortableIds}
  2207. strategy={verticalListSortingStrategy}
  2208. >
  2209. {activeLayout === 'position' ? (
  2210. <div className="space-y-2 sm:space-y-3">
  2211. {groupedRows.map((row) => (
  2212. <QueueRowRender
  2213. key={row.kind === 'item' ? `item-${row.item.id}` : `batch-${row.batchId}`}
  2214. row={row}
  2215. collapsed={row.kind === 'batch' ? (batchCollapsed[row.batchId] ?? true) : false}
  2216. onToggleBatch={row.kind === 'batch' ? () => toggleBatchCollapsed(row.batchId) : undefined}
  2217. onUngroup={row.kind === 'batch' ? () => setUngroupBatchId(row.batchId) : undefined}
  2218. setEditItem={setEditItem}
  2219. setConfirmAction={setConfirmAction}
  2220. startMutation={startMutation}
  2221. selectedItems={selectedItems}
  2222. handleToggleSelect={handleToggleSelect}
  2223. timeFormat={timeFormat}
  2224. hasPermission={hasPermission}
  2225. canModify={canModify}
  2226. t={t}
  2227. aggregateForRows={aggregateForRows}
  2228. />
  2229. ))}
  2230. </div>
  2231. ) : (
  2232. <div className="space-y-4">
  2233. {printerBuckets.map((bucket) => {
  2234. const agg = aggregateForRows(bucket.rows);
  2235. return (
  2236. <div key={bucket.key}>
  2237. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-t-lg">
  2238. <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'}`} />
  2239. <span className="font-semibold text-white text-sm">{bucket.label}</span>
  2240. <span className="text-xs text-bambu-gray flex flex-wrap gap-x-3">
  2241. <span>{t('queue.itemCount', { count: agg.count })}</span>
  2242. {agg.time > 0 && <span>{formatDuration(agg.time)}</span>}
  2243. {agg.weight > 0 && <span>{formatWeight(agg.weight)}</span>}
  2244. </span>
  2245. </div>
  2246. <div className="bg-bambu-dark/40 border border-t-0 border-bambu-dark-tertiary rounded-b-lg p-2 space-y-2">
  2247. {bucket.rows.map((row) => (
  2248. <QueueRowRender
  2249. key={row.kind === 'item' ? `item-${row.item.id}` : `batch-${row.batchId}`}
  2250. row={row}
  2251. collapsed={row.kind === 'batch' ? (batchCollapsed[row.batchId] ?? true) : false}
  2252. onToggleBatch={row.kind === 'batch' ? () => toggleBatchCollapsed(row.batchId) : undefined}
  2253. onUngroup={row.kind === 'batch' ? () => setUngroupBatchId(row.batchId) : undefined}
  2254. setEditItem={setEditItem}
  2255. setConfirmAction={setConfirmAction}
  2256. startMutation={startMutation}
  2257. selectedItems={selectedItems}
  2258. handleToggleSelect={handleToggleSelect}
  2259. timeFormat={timeFormat}
  2260. hasPermission={hasPermission}
  2261. canModify={canModify}
  2262. t={t}
  2263. aggregateForRows={aggregateForRows}
  2264. />
  2265. ))}
  2266. </div>
  2267. </div>
  2268. );
  2269. })}
  2270. </div>
  2271. )}
  2272. </SortableContext>
  2273. <DragOverlay>
  2274. {(() => {
  2275. if (activeDragId === null) return null;
  2276. // Batch drag — show the group ghost with copy count.
  2277. if (typeof activeDragId === 'string' && activeDragId.startsWith('batch-')) {
  2278. const batchId = Number(activeDragId.slice('batch-'.length));
  2279. const siblings = pendingItems.filter((i) => i.batch_id === batchId);
  2280. if (siblings.length === 0) return null;
  2281. const name = siblings[0].batch_name || t('queue.batch.defaultName');
  2282. return (
  2283. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border-2 border-cyan-400 rounded-lg shadow-2xl">
  2284. <Package className="w-4 h-4 text-cyan-700 dark:text-cyan-300" />
  2285. <span className="text-sm text-white font-medium">
  2286. {t('queue.dragGhost.batch', {
  2287. defaultValue: '{{name}} ({{count}} copies)',
  2288. name,
  2289. count: siblings.length,
  2290. })}
  2291. </span>
  2292. </div>
  2293. );
  2294. }
  2295. // Multi-row drag — show the N-item ghost.
  2296. if (typeof activeDragId === 'number' && selectedItems.includes(activeDragId) && selectedItems.length > 1) {
  2297. return (
  2298. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border-2 border-cyan-400 rounded-lg shadow-2xl">
  2299. <Package className="w-4 h-4 text-cyan-700 dark:text-cyan-300" />
  2300. <span className="text-sm text-white font-medium">
  2301. {t('queue.dragGhost.multiCount', { count: selectedItems.length })}
  2302. </span>
  2303. </div>
  2304. );
  2305. }
  2306. return null;
  2307. })()}
  2308. </DragOverlay>
  2309. </DndContext>
  2310. </div>
  2311. )}
  2312. </div>
  2313. )}
  2314. {/* Edit Modal */}
  2315. {editItem && (
  2316. <PrintModal
  2317. mode="edit-queue-item"
  2318. archiveId={editItem.archive_id ?? undefined}
  2319. libraryFileId={editItem.library_file_id ?? undefined}
  2320. archiveName={editItem.archive_name || editItem.library_file_name || `File #${editItem.archive_id || editItem.library_file_id}`}
  2321. queueItem={editItem}
  2322. onClose={() => setEditItem(null)}
  2323. />
  2324. )}
  2325. {/* Re-queue Modal */}
  2326. {requeueItem && (
  2327. <PrintModal
  2328. mode="create"
  2329. archiveId={requeueItem.archive_id ?? undefined}
  2330. libraryFileId={requeueItem.library_file_id ?? undefined}
  2331. archiveName={requeueItem.archive_name || requeueItem.library_file_name || `File #${requeueItem.archive_id || requeueItem.library_file_id}`}
  2332. onClose={() => setRequeueItem(null)}
  2333. />
  2334. )}
  2335. {/* Confirm Action Modal */}
  2336. {filamentShortConfirm && (
  2337. <ConfirmModal
  2338. title={t('queue.filamentShort.confirmTitle')}
  2339. message={
  2340. t('queue.filamentShort.confirmIntro') + '\n\n' +
  2341. filamentShortConfirm.deficit
  2342. .map((d) =>
  2343. t('queue.filamentShort.lineItem', {
  2344. slot: d.slot_id,
  2345. required: Math.round(d.required_grams),
  2346. remaining:
  2347. d.remaining_grams == null
  2348. ? t('queue.filamentShort.unknown')
  2349. : Math.round(d.remaining_grams),
  2350. }),
  2351. )
  2352. .join('\n')
  2353. }
  2354. confirmText={t('queue.filamentShort.printAnyway')}
  2355. variant="warning"
  2356. onConfirm={() => {
  2357. startMutation.mutate({ id: filamentShortConfirm.itemId, skipFilamentCheck: true });
  2358. }}
  2359. onCancel={() => setFilamentShortConfirm(null)}
  2360. />
  2361. )}
  2362. {confirmAction && (
  2363. <ConfirmModal
  2364. title={
  2365. confirmAction.type === 'cancel' ? t('queue.confirm.cancelTitle') :
  2366. confirmAction.type === 'stop' ? t('queue.confirm.stopTitle') :
  2367. t('queue.confirm.removeTitle')
  2368. }
  2369. message={
  2370. confirmAction.type === 'cancel'
  2371. ? t('queue.confirm.cancelMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  2372. : confirmAction.type === 'stop'
  2373. ? t('queue.confirm.stopMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  2374. : t('queue.confirm.removeMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisItem') })
  2375. }
  2376. confirmText={
  2377. confirmAction.type === 'cancel' ? t('queue.confirm.cancelButton') :
  2378. confirmAction.type === 'stop' ? t('queue.confirm.stopButton') :
  2379. t('common.remove')
  2380. }
  2381. variant="danger"
  2382. onConfirm={() => {
  2383. if (confirmAction.type === 'cancel') {
  2384. cancelMutation.mutate(confirmAction.item.id);
  2385. } else if (confirmAction.type === 'stop') {
  2386. stopMutation.mutate(confirmAction.item.id);
  2387. } else {
  2388. removeMutation.mutate(confirmAction.item.id);
  2389. }
  2390. setConfirmAction(null);
  2391. }}
  2392. onCancel={() => setConfirmAction(null)}
  2393. />
  2394. )}
  2395. {/* #1818: Resume-after-failure confirm */}
  2396. {resumeConfirm && (
  2397. <ConfirmModal
  2398. title={t('queue.resumeAfterFailure.confirmTitle')}
  2399. message={t('queue.resumeAfterFailure.confirmMessage', {
  2400. printer: resumeConfirm.printerName,
  2401. count: resumeConfirm.skippedCount,
  2402. })}
  2403. confirmText={t('queue.resumeAfterFailure.button')}
  2404. variant="warning"
  2405. onConfirm={() => resumeAfterFailureMutation.mutate(resumeConfirm.printerId)}
  2406. onCancel={() => setResumeConfirm(null)}
  2407. />
  2408. )}
  2409. {/* Clear History Confirm Modal */}
  2410. {showClearHistoryConfirm && (
  2411. <ConfirmModal
  2412. title={t('queue.confirm.clearHistoryTitle')}
  2413. message={t('queue.confirm.clearHistoryMessage', { count: historyItems.length })}
  2414. confirmText={t('queue.clearHistory')}
  2415. variant="danger"
  2416. onConfirm={() => {
  2417. clearHistoryMutation.mutate();
  2418. setShowClearHistoryConfirm(false);
  2419. }}
  2420. onCancel={() => setShowClearHistoryConfirm(false)}
  2421. />
  2422. )}
  2423. {/* Bulk Edit Modal */}
  2424. {showBulkEditModal && (
  2425. <BulkEditModal
  2426. selectedCount={selectedItems.length}
  2427. printers={printers?.map(p => ({ id: p.id, name: p.name, nozzle_count: p.nozzle_count })) || []}
  2428. onSave={(data) => {
  2429. if (Object.keys(data).length > 0) {
  2430. bulkUpdateMutation.mutate({ item_ids: selectedItems, ...data });
  2431. }
  2432. }}
  2433. onClose={() => setShowBulkEditModal(false)}
  2434. isSaving={bulkUpdateMutation.isPending}
  2435. canControlPrinter={hasPermission('printers:control')}
  2436. t={t}
  2437. />
  2438. )}
  2439. {/* Group as batch modal — name prompt */}
  2440. {groupBatchModal && (
  2441. <GroupBatchModal
  2442. itemCount={selectedItems.length}
  2443. isSaving={createBatchMutation.isPending}
  2444. defaultName={(() => {
  2445. // Suggest a name derived from the first selected item's source.
  2446. const first = pendingItems.find((i) => selectedItems.includes(i.id));
  2447. const raw = first?.archive_name || first?.library_file_name || '';
  2448. const cleaned = raw.replace(/\.gcode\.3mf$/i, '').replace(/\.3mf$/i, '');
  2449. return cleaned ? `${cleaned}` : t('queue.batch.defaultName');
  2450. })()}
  2451. onSave={(name) => createBatchMutation.mutate({ name, item_ids: selectedItems })}
  2452. onClose={() => setGroupBatchModal(false)}
  2453. t={t}
  2454. />
  2455. )}
  2456. {/* Ungroup batch confirm */}
  2457. {ungroupBatchId !== null && (
  2458. <ConfirmModal
  2459. title={t('queue.batch.ungroupConfirmTitle')}
  2460. message={t('queue.batch.ungroupConfirmMessage')}
  2461. confirmText={t('queue.batch.ungroup')}
  2462. variant="warning"
  2463. onConfirm={() => ungroupBatchMutation.mutate(ungroupBatchId)}
  2464. onCancel={() => setUngroupBatchId(null)}
  2465. />
  2466. )}
  2467. </div>
  2468. );
  2469. }
  2470. interface GroupBatchModalProps {
  2471. itemCount: number;
  2472. defaultName: string;
  2473. isSaving: boolean;
  2474. onSave: (name: string) => void;
  2475. onClose: () => void;
  2476. t: (key: string, options?: Record<string, unknown>) => string;
  2477. }
  2478. function GroupBatchModal({ itemCount, defaultName, isSaving, onSave, onClose, t }: GroupBatchModalProps) {
  2479. const [name, setName] = useState(defaultName);
  2480. return (
  2481. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
  2482. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-6 w-full max-w-md">
  2483. <h3 className="text-lg font-semibold text-white mb-2 flex items-center gap-2">
  2484. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  2485. {t('queue.batch.groupAsBatch')}
  2486. </h3>
  2487. <p className="text-sm text-bambu-gray mb-4">
  2488. {t('queue.batch.groupAsBatchDescription', { count: itemCount })}
  2489. </p>
  2490. <label className="block text-sm font-medium text-white mb-2">
  2491. {t('queue.batch.nameLabel')}
  2492. </label>
  2493. <input
  2494. type="text"
  2495. autoFocus
  2496. value={name}
  2497. onChange={(e) => setName(e.target.value)}
  2498. placeholder={t('queue.batch.namePlaceholder')}
  2499. maxLength={120}
  2500. 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"
  2501. />
  2502. <div className="flex justify-end gap-2">
  2503. <Button variant="ghost" size="sm" onClick={onClose} disabled={isSaving}>
  2504. {t('common.cancel')}
  2505. </Button>
  2506. <Button
  2507. variant="primary"
  2508. size="sm"
  2509. onClick={() => {
  2510. const trimmed = name.trim();
  2511. if (trimmed) onSave(trimmed);
  2512. }}
  2513. disabled={isSaving || !name.trim()}
  2514. >
  2515. {isSaving ? t('common.saving') : t('queue.batch.create')}
  2516. </Button>
  2517. </div>
  2518. </div>
  2519. </div>
  2520. );
  2521. }