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