QueuePage.tsx 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  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. closestCenter,
  8. KeyboardSensor,
  9. PointerSensor,
  10. useSensor,
  11. useSensors,
  12. } from '@dnd-kit/core';
  13. import type { DragEndEvent } from '@dnd-kit/core';
  14. import {
  15. arrayMove,
  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. } from 'lucide-react';
  58. import { api, ApiError } from '../api/client';
  59. import { type TimeFormat, formatETA, formatDuration, formatRelativeTime, parseUTCDate } from '../utils/date';
  60. import { getBedTypeInfo } from '../utils/bedType';
  61. import type { PrintQueueItem, PrintQueueBulkUpdate, Permission } from '../api/client';
  62. import { Card } from '../components/Card';
  63. import { Button } from '../components/Button';
  64. import { ConfirmModal } from '../components/ConfirmModal';
  65. import { PrintModal } from '../components/PrintModal';
  66. import { useToast } from '../contexts/ToastContext';
  67. import { useAuth } from '../contexts/AuthContext';
  68. import { QueueStatsBar } from '../components/QueueStatsBar';
  69. import { CompactHistoryRow } from '../components/CompactHistoryRow';
  70. import { QueueTimelineView } from '../components/QueueTimelineView';
  71. function formatWeight(g: number, useKg = false): string {
  72. if (useKg && g >= 1000) return `${(g / 1000).toFixed(1)}kg`;
  73. return `${Math.round(g)}g`;
  74. }
  75. function StatusBadge({ status, waitingReason, printerState, t }: { status: PrintQueueItem['status']; waitingReason?: string | null; printerState?: string | null; t: (key: string) => string }) {
  76. // Special case: pending with waiting_reason shows as "Waiting"
  77. if (status === 'pending' && waitingReason) {
  78. return (
  79. <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-purple-400 bg-purple-400/10 border-purple-400/20">
  80. <Clock className="w-3.5 h-3.5" />
  81. {t('queue.status.waiting')}
  82. </span>
  83. );
  84. }
  85. // Special case: printing but printer is paused
  86. if (status === 'printing' && printerState === 'PAUSE') {
  87. return (
  88. <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-yellow-400 bg-yellow-400/10 border-yellow-400/20">
  89. <Pause className="w-3.5 h-3.5" />
  90. {t('queue.status.paused')}
  91. </span>
  92. );
  93. }
  94. const config = {
  95. pending: { icon: Clock, color: 'text-status-warning bg-status-warning/10 border-status-warning/20', label: t('queue.status.pending') },
  96. printing: { icon: Play, color: 'text-blue-400 bg-blue-400/10 border-blue-400/20', label: t('queue.status.printing') },
  97. completed: { icon: CheckCircle, color: 'text-status-ok bg-status-ok/10 border-status-ok/20', label: t('queue.status.completed') },
  98. failed: { icon: XCircle, color: 'text-status-error bg-status-error/10 border-status-error/20', label: t('queue.status.failed') },
  99. skipped: { icon: SkipForward, color: 'text-orange-400 bg-orange-400/10 border-orange-400/20', label: t('queue.status.skipped') },
  100. cancelled: { icon: X, color: 'text-gray-400 bg-gray-400/10 border-gray-400/20', label: t('queue.status.cancelled') },
  101. };
  102. const { icon: Icon, color, label } = config[status];
  103. return (
  104. <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${color}`}>
  105. <Icon className="w-3.5 h-3.5" />
  106. {label}
  107. </span>
  108. );
  109. }
  110. // Bulk edit modal for multiple queue items
  111. function BulkEditModal({
  112. selectedCount,
  113. printers,
  114. onSave,
  115. onClose,
  116. isSaving,
  117. canControlPrinter,
  118. t,
  119. }: {
  120. selectedCount: number;
  121. printers: { id: number; name: string; nozzle_count?: number }[];
  122. onSave: (data: Partial<PrintQueueBulkUpdate>) => void;
  123. onClose: () => void;
  124. isSaving: boolean;
  125. canControlPrinter: boolean;
  126. t: (key: string, options?: Record<string, unknown>) => string;
  127. }) {
  128. const [printerId, setPrinterId] = useState<number | null | 'unchanged'>('unchanged');
  129. const [manualStart, setManualStart] = useState<boolean | 'unchanged'>('unchanged');
  130. const [autoOffAfter, setAutoOffAfter] = useState<boolean | 'unchanged'>('unchanged');
  131. const [requirePreviousSuccess, setRequirePreviousSuccess] = useState<boolean | 'unchanged'>('unchanged');
  132. const [bedLevelling, setBedLevelling] = useState<boolean | 'unchanged'>('unchanged');
  133. const [flowCali, setFlowCali] = useState<boolean | 'unchanged'>('unchanged');
  134. const [vibrationCali, setVibrationCali] = useState<boolean | 'unchanged'>('unchanged');
  135. const [layerInspect, setLayerInspect] = useState<boolean | 'unchanged'>('unchanged');
  136. const [timelapse, setTimelapse] = useState<boolean | 'unchanged'>('unchanged');
  137. const [useAms, setUseAms] = useState<boolean | 'unchanged'>('unchanged');
  138. const [nozzleOffsetCali, setNozzleOffsetCali] = useState<boolean | 'unchanged'>('unchanged');
  139. // Show the dual-nozzle-only toggle when the user has at least one
  140. // dual-nozzle printer registered (H2D/H2D Pro/H2C/X2D). Single-nozzle
  141. // queues never see it — the MQTT layer ignores the field anyway.
  142. const hasDualNozzlePrinter = printers.some(p => p.nozzle_count === 2);
  143. const handleSave = () => {
  144. const data: Partial<PrintQueueBulkUpdate> = {};
  145. if (printerId !== 'unchanged') data.printer_id = printerId;
  146. if (manualStart !== 'unchanged') data.manual_start = manualStart;
  147. if (autoOffAfter !== 'unchanged') data.auto_off_after = autoOffAfter;
  148. if (requirePreviousSuccess !== 'unchanged') data.require_previous_success = requirePreviousSuccess;
  149. if (bedLevelling !== 'unchanged') data.bed_levelling = bedLevelling;
  150. if (flowCali !== 'unchanged') data.flow_cali = flowCali;
  151. if (vibrationCali !== 'unchanged') data.vibration_cali = vibrationCali;
  152. if (layerInspect !== 'unchanged') data.layer_inspect = layerInspect;
  153. if (timelapse !== 'unchanged') data.timelapse = timelapse;
  154. if (useAms !== 'unchanged') data.use_ams = useAms;
  155. if (nozzleOffsetCali !== 'unchanged') data.nozzle_offset_cali = nozzleOffsetCali;
  156. onSave(data);
  157. };
  158. const hasChanges = printerId !== 'unchanged' || manualStart !== 'unchanged' || autoOffAfter !== 'unchanged' ||
  159. requirePreviousSuccess !== 'unchanged' || bedLevelling !== 'unchanged' || flowCali !== 'unchanged' ||
  160. vibrationCali !== 'unchanged' || layerInspect !== 'unchanged' || timelapse !== 'unchanged' || useAms !== 'unchanged' ||
  161. nozzleOffsetCali !== 'unchanged';
  162. return (
  163. <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
  164. <div className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto">
  165. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  166. <h2 className="text-lg font-semibold text-white">
  167. {t('queue.bulkEdit.title', { count: selectedCount })}
  168. </h2>
  169. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  170. <X className="w-5 h-5 text-bambu-gray" />
  171. </button>
  172. </div>
  173. <div className="p-4 space-y-4">
  174. <p className="text-sm text-bambu-gray">
  175. {t('queue.bulkEdit.description')}
  176. </p>
  177. {/* Printer Assignment */}
  178. <div>
  179. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printer')}</label>
  180. <select
  181. value={printerId === null ? 'null' : printerId === 'unchanged' ? 'unchanged' : String(printerId)}
  182. onChange={(e) => {
  183. const val = e.target.value;
  184. if (val === 'unchanged') setPrinterId('unchanged');
  185. else if (val === 'null') setPrinterId(null);
  186. else setPrinterId(Number(val));
  187. }}
  188. 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"
  189. >
  190. <option value="unchanged">{t('queue.bulkEdit.noChange')}</option>
  191. <option value="null">{t('queue.filter.unassigned')}</option>
  192. {printers.map(p => (
  193. <option key={p.id} value={p.id}>{p.name}</option>
  194. ))}
  195. </select>
  196. </div>
  197. {/* Queue Options */}
  198. <div>
  199. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.queueOptions')}</label>
  200. <div className="space-y-2">
  201. <TriStateToggle label={t('queue.bulkEdit.staged')} value={manualStart} onChange={setManualStart} t={t} />
  202. <TriStateToggle label={t('queue.bulkEdit.autoPowerOff')} value={autoOffAfter} onChange={setAutoOffAfter} disabled={!canControlPrinter} t={t} />
  203. <TriStateToggle label={t('queue.bulkEdit.requirePrevious')} value={requirePreviousSuccess} onChange={setRequirePreviousSuccess} t={t} />
  204. </div>
  205. </div>
  206. {/* Print Options */}
  207. <div>
  208. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printOptions')}</label>
  209. <div className="space-y-2">
  210. <TriStateToggle label={t('queue.bulkEdit.bedLevelling')} value={bedLevelling} onChange={setBedLevelling} t={t} />
  211. <TriStateToggle label={t('queue.bulkEdit.flowCalibration')} value={flowCali} onChange={setFlowCali} t={t} />
  212. <TriStateToggle label={t('queue.bulkEdit.vibrationCalibration')} value={vibrationCali} onChange={setVibrationCali} t={t} />
  213. <TriStateToggle label={t('queue.bulkEdit.layerInspection')} value={layerInspect} onChange={setLayerInspect} t={t} />
  214. <TriStateToggle label={t('queue.bulkEdit.timelapse')} value={timelapse} onChange={setTimelapse} t={t} />
  215. <TriStateToggle label={t('queue.bulkEdit.useAms')} value={useAms} onChange={setUseAms} t={t} />
  216. {hasDualNozzlePrinter && (
  217. <TriStateToggle label={t('queue.bulkEdit.nozzleOffsetCali')} value={nozzleOffsetCali} onChange={setNozzleOffsetCali} t={t} />
  218. )}
  219. </div>
  220. </div>
  221. </div>
  222. <div className="flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
  223. <Button variant="secondary" onClick={onClose}>{t('common.cancel')}</Button>
  224. <Button
  225. onClick={handleSave}
  226. disabled={!hasChanges || isSaving}
  227. >
  228. {isSaving ? t('common.saving') : t('queue.bulkEdit.applyChanges')}
  229. </Button>
  230. </div>
  231. </div>
  232. </div>
  233. );
  234. }
  235. // Tri-state toggle for bulk edit (unchanged / on / off)
  236. function TriStateToggle({
  237. label,
  238. value,
  239. onChange,
  240. disabled,
  241. t,
  242. }: {
  243. label: string;
  244. value: boolean | 'unchanged';
  245. onChange: (val: boolean | 'unchanged') => void;
  246. disabled?: boolean;
  247. t: (key: string) => string;
  248. }) {
  249. return (
  250. <div className={`flex items-center justify-between py-1 ${disabled ? 'opacity-50' : ''}`}>
  251. <span className="text-sm text-bambu-gray">{label}</span>
  252. <div className="flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5">
  253. <button
  254. onClick={() => onChange('unchanged')}
  255. disabled={disabled}
  256. 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`}
  257. >
  258. </button>
  259. <button
  260. onClick={() => onChange(false)}
  261. disabled={disabled}
  262. className={`px-2 py-1 text-xs rounded ${value === false ? 'bg-red-500/20 text-red-400' : 'text-bambu-gray hover:text-white'} disabled:cursor-not-allowed`}
  263. >
  264. {t('common.off')}
  265. </button>
  266. <button
  267. onClick={() => onChange(true)}
  268. disabled={disabled}
  269. 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`}
  270. >
  271. {t('common.on')}
  272. </button>
  273. </div>
  274. </div>
  275. );
  276. }
  277. // Sortable queue item for drag and drop
  278. function SortableQueueItem({
  279. item,
  280. position,
  281. onEdit,
  282. onCancel,
  283. onRemove,
  284. onStop,
  285. onRequeue,
  286. onStart,
  287. timeFormat = 'system',
  288. isSelected = false,
  289. onToggleSelect,
  290. hasPermission,
  291. canModify,
  292. printerState,
  293. t,
  294. }: {
  295. item: PrintQueueItem;
  296. position?: number;
  297. onEdit: () => void;
  298. onCancel: () => void;
  299. onRemove: () => void;
  300. onStop: () => void;
  301. onRequeue: () => void;
  302. onStart: () => void;
  303. timeFormat?: TimeFormat;
  304. isSelected?: boolean;
  305. onToggleSelect?: () => void;
  306. hasPermission: (permission: Permission) => boolean;
  307. canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
  308. printerState?: string | null;
  309. t: (key: string, options?: Record<string, unknown>) => string;
  310. }) {
  311. // Fetch printer status every 30 seconds while printing to monitor progress
  312. const { data: status } = useQuery({
  313. queryKey: ['printerStatus', item.printer_id],
  314. queryFn: () => api.getPrinterStatus(item.printer_id!),
  315. refetchInterval: 30000,
  316. enabled: item.printer_id != null && printerState === 'printing',
  317. });
  318. // Determine if we're printing a library file
  319. const isLibraryFile = !!item.library_file_id && !item.archive_id;
  320. // Fetch archive plate details. Skip when the linked archive has been
  321. // soft-deleted (#1348 follow-up): its 3MF is gone from disk so the
  322. // /plates endpoint just 404-storms the queue page.
  323. const { data: archivePlatesData } = useQuery({
  324. queryKey: ['archive-plates', item.archive_id],
  325. queryFn: () => api.getArchivePlates(item.archive_id!),
  326. enabled: !!item.archive_id && !isLibraryFile && !item.archive_deleted,
  327. });
  328. // Fetch library file plate details
  329. const { data: libraryPlatesData } = useQuery({
  330. queryKey: ['library-file-plates', item.library_file_id],
  331. queryFn: () => api.getLibraryFilePlates(item.library_file_id!),
  332. enabled: isLibraryFile && !!item.library_file_id,
  333. });
  334. // Combine plates data from either source
  335. const platesData = isLibraryFile ? libraryPlatesData : archivePlatesData;
  336. const plates = platesData?.plates ?? [];
  337. const canReorder = hasPermission('queue:reorder');
  338. const {
  339. attributes,
  340. listeners,
  341. setNodeRef,
  342. transform,
  343. transition,
  344. isDragging,
  345. } = useSortable({ id: item.id, disabled: item.status !== 'pending' || !canReorder });
  346. const style = {
  347. transform: CSS.Transform.toString(transform),
  348. transition,
  349. };
  350. const isPrinting = item.status === 'printing';
  351. const isPending = item.status === 'pending';
  352. const isHistory = ['completed', 'failed', 'skipped', 'cancelled'].includes(item.status);
  353. const isMobileSelectable = isPending && onToggleSelect;
  354. return (
  355. <div
  356. ref={setNodeRef}
  357. style={style}
  358. className={`
  359. group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
  360. border-l-[3px] ${
  361. isPrinting ? 'border-l-blue-500' :
  362. isPending ? 'border-l-yellow-500' :
  363. item.status === 'completed' ? 'border-l-emerald-500' :
  364. item.status === 'failed' ? 'border-l-red-500' :
  365. 'border-l-gray-500'
  366. }
  367. ${isDragging ? 'opacity-50 scale-[1.02] shadow-xl z-50' : ''}
  368. ${isPrinting ? 'border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent' : ''}
  369. ${isSelected && isMobileSelectable ? 'sm:border-bambu-dark-tertiary border-bambu-green/40' : ''}
  370. ${!isSelected && !isPrinting ? 'border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80' : ''}
  371. ${isMobileSelectable ? 'sm:cursor-default' : ''}
  372. `}
  373. onClick={isMobileSelectable ? () => {
  374. if (window.innerWidth < 640) onToggleSelect();
  375. } : undefined}
  376. >
  377. {/* Mobile selected left accent bar */}
  378. {isMobileSelectable && isSelected && (
  379. <div className="sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green" />
  380. )}
  381. <div className="flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4">
  382. {/* Mobile selection indicator — left accent bar only, no tick */}
  383. {/* Selection checkbox for pending items - hidden on mobile, tap card instead */}
  384. {isPending && onToggleSelect && (
  385. <button
  386. onClick={(e) => {
  387. e.stopPropagation();
  388. onToggleSelect();
  389. }}
  390. className={`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${
  391. isSelected
  392. ? 'bg-bambu-green border-bambu-green text-white'
  393. : 'border-white/30 bg-black/30 hover:border-bambu-green/50'
  394. }`}
  395. >
  396. {isSelected && <Check className="w-4 h-4" />}
  397. </button>
  398. )}
  399. {/* Drag handle or position number - hidden on mobile */}
  400. {isPending ? (
  401. <div
  402. {...attributes}
  403. {...listeners}
  404. 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"
  405. >
  406. <GripVertical className="w-4 h-4 text-bambu-gray" />
  407. </div>
  408. ) : position !== undefined ? (
  409. <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">
  410. #{position}
  411. </div>
  412. ) : (
  413. <div className="hidden sm:block w-8 shrink-0" />
  414. )}
  415. {/* Thumbnail - use plate-specific thumbnail if plate_id is set */}
  416. <div className="w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden">
  417. {item.archive_thumbnail ? (
  418. <img
  419. src={
  420. item.plate_id != null
  421. ? api.getArchivePlateThumbnail(item.archive_id!, item.plate_id)
  422. : api.getArchiveThumbnail(item.archive_id!)
  423. }
  424. alt=""
  425. className="w-full h-full object-cover"
  426. />
  427. ) : item.library_file_thumbnail ? (
  428. <img
  429. src={
  430. item.plate_id != null
  431. ? api.getLibraryFilePlateThumbnail(item.library_file_id!, item.plate_id)
  432. : api.getLibraryFileThumbnailUrl(item.library_file_id!)
  433. }
  434. alt=""
  435. className="w-full h-full object-cover"
  436. />
  437. ) : (
  438. <div className="w-full h-full flex items-center justify-center text-bambu-gray">
  439. <Layers className="w-5 h-5 sm:w-6 sm:h-6" />
  440. </div>
  441. )}
  442. </div>
  443. {/* Info */}
  444. <div className="flex-1 min-w-0">
  445. <div className="flex items-center gap-2 mb-1">
  446. <p className="text-sm sm:text-base text-white font-medium truncate">
  447. {item.archive_name || item.library_file_name || `File #${item.archive_id || item.library_file_id}`}
  448. {(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 })}`}
  449. </p>
  450. {item.archive_id ? (
  451. <Link
  452. to={`/archives?highlight=${item.archive_id}`}
  453. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  454. title={t('queue.viewArchive')}
  455. >
  456. <ExternalLink className="w-3.5 h-3.5" />
  457. </Link>
  458. ) : item.library_file_id ? (
  459. <Link
  460. to={`/library?highlight=${item.library_file_id}`}
  461. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  462. title={t('queue.viewInFileManager')}
  463. >
  464. <ExternalLink className="w-3.5 h-3.5" />
  465. </Link>
  466. ) : null}
  467. {item.batch_name && (
  468. <span className="flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-purple-500/20 text-purple-300 rounded border border-purple-500/30">
  469. {item.batch_name}
  470. </span>
  471. )}
  472. </div>
  473. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray">
  474. <span className={`flex items-center gap-1 sm:gap-1.5 ${item.printer_id === null && !item.target_model ? 'text-orange-400' : ''} ${item.target_model && !item.printer_id ? 'text-blue-400' : ''}`}>
  475. <Printer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  476. <span className="truncate max-w-[120px] sm:max-w-none">
  477. {item.target_model && !item.printer_id
  478. ? `${t('queue.filter.any')} ${item.target_model}${item.target_location ? ` @ ${item.target_location}` : ''}${item.required_filament_types?.length ? ` (${item.required_filament_types.join(', ')})` : ''}`
  479. : item.printer_id === null
  480. ? t('queue.filter.unassigned')
  481. : (item.printer_name || `${t('common.printer')} #${item.printer_id}`)}
  482. </span>
  483. </span>
  484. {item.print_time_seconds && (
  485. <span className="flex items-center gap-1 sm:gap-1.5">
  486. <Timer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  487. {formatDuration(item.print_time_seconds)}
  488. </span>
  489. )}
  490. {item.filament_used_grams && (
  491. <span className="flex items-center gap-1 sm:gap-1.5">
  492. <Weight className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  493. {formatWeight(item.filament_used_grams)}
  494. </span>
  495. )}
  496. {(() => {
  497. // Build plate badge so the user knows which plate to mount before
  498. // walking to the printer (#1281). Hidden when the 3MF doesn't
  499. // carry curr_bed_type or the slicer used an unknown label.
  500. const bed = getBedTypeInfo(item.bed_type);
  501. if (!bed) return null;
  502. return (
  503. <span className="flex items-center gap-1 sm:gap-1.5" title={bed.label}>
  504. <img src={bed.icon} alt="" className="w-3.5 h-3.5 sm:w-4 sm:h-4 object-contain" />
  505. <span className="truncate max-w-[120px]">{bed.label}</span>
  506. </span>
  507. );
  508. })()}
  509. {item.created_by_username && (
  510. <span className="hidden sm:flex items-center gap-1.5" title={t('queue.addedBy', { name: item.created_by_username })}>
  511. <User className="w-3.5 h-3.5" />
  512. {item.created_by_username}
  513. </span>
  514. )}
  515. {isPending && !item.manual_start && (
  516. <span className="flex items-center gap-1.5">
  517. <Clock className="w-3.5 h-3.5" />
  518. {item.scheduled_time
  519. ? ((parseUTCDate(item.scheduled_time)?.getTime() ?? 0) - Date.now() < -60000
  520. ? t?.('queue.time.overdue') ?? 'Overdue'
  521. : formatRelativeTime(item.scheduled_time, timeFormat, t))
  522. : t?.('queue.time.asap') ?? 'ASAP'}
  523. </span>
  524. )}
  525. </div>
  526. {/* Options badges */}
  527. <div className="flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2">
  528. {item.manual_start && (
  529. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1">
  530. <Hand className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  531. {t('queue.badges.staged')}
  532. </span>
  533. )}
  534. {item.require_previous_success && (
  535. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20">
  536. {t('queue.badges.requiresPrevious')}
  537. </span>
  538. )}
  539. {item.auto_off_after && (
  540. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1">
  541. <Power className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  542. {t('queue.badges.autoPowerOff')}
  543. </span>
  544. )}
  545. {item.gcode_injection && (
  546. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-500/10 text-emerald-400 rounded-full border border-emerald-500/20 flex items-center gap-1">
  547. <Code className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  548. {t('queue.badges.gcodeInjection')}
  549. </span>
  550. )}
  551. </div>
  552. {/* Progress bar for printing items - TODO: integrate with WebSocket */}
  553. {isPrinting && status && (() => {
  554. // Gate progress/remaining/layer on printer actually running this print.
  555. // Between dispatch and RUNNING transition (H2D/P1 MQTT lag), status.progress
  556. // is stale from the previous print — showing 100% then snapping back to 0%
  557. // once the new print starts. Only trust these fields when state is active.
  558. const isActive = status.state === 'RUNNING' || status.state === 'PAUSE';
  559. const progress = isActive ? (status.progress || 0) : 0;
  560. const remaining = isActive ? status.remaining_time : null;
  561. const layerNum = isActive ? status.layer_num : null;
  562. const totalLayers = isActive ? status.total_layers : null;
  563. return (
  564. <div className="mt-2 sm:mt-3">
  565. <div className="flex items-center justify-between text-xs sm:text-sm">
  566. <div className="flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3">
  567. <div
  568. className="bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all"
  569. style={{ width: `${progress}%` }}
  570. />
  571. </div>
  572. <span className="text-white">{Math.round(progress)}%</span>
  573. </div>
  574. <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">
  575. {remaining != null && remaining > 0 && (
  576. <>
  577. <span className="flex items-center gap-1">
  578. <Clock className="w-3 h-3" />
  579. {formatDuration(remaining * 60)}
  580. </span>
  581. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  582. ETA {formatETA(remaining, timeFormat, t)}
  583. </span>
  584. </>
  585. )}
  586. {layerNum != null && totalLayers != null && totalLayers > 0 && (
  587. <span className="flex items-center gap-1">
  588. <Layers className="w-3 h-3" />
  589. {layerNum}/{totalLayers}
  590. </span>
  591. )}
  592. </div>
  593. </div>
  594. );
  595. })()}
  596. {/* Waiting reason for model-based assignments */}
  597. {item.waiting_reason && item.status === 'pending' && (
  598. <p className="text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1">
  599. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  600. <span>{item.waiting_reason}</span>
  601. </p>
  602. )}
  603. {/* Filament-short flag from the dispatch pre-flight (#1496). */}
  604. {item.filament_short && item.status === 'pending' && (
  605. <p
  606. className="text-[10px] sm:text-xs text-yellow-400 mt-1.5 sm:mt-2 flex items-start gap-1"
  607. title={t('queue.filamentShort.rowTooltip')}
  608. >
  609. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  610. <span>{t('queue.filamentShort.rowBadge')}</span>
  611. </p>
  612. )}
  613. {/* Error message */}
  614. {item.error_message && (
  615. <p className="text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1">
  616. <AlertCircle className="w-3 h-3" />
  617. {item.error_message}
  618. </p>
  619. )}
  620. </div>
  621. {/* Status badge + Actions */}
  622. <div className="flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
  623. <StatusBadge status={item.status} waitingReason={item.waiting_reason} printerState={printerState} t={t} />
  624. <div className="flex items-center gap-0.5 sm:gap-1">
  625. {isPrinting && (
  626. <Button
  627. variant="ghost"
  628. size="sm"
  629. onClick={onStop}
  630. disabled={!hasPermission('printers:control')}
  631. title={!hasPermission('printers:control') ? t('queue.permissions.noStopPrint') : t('queue.actions.stopPrint')}
  632. className="text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2"
  633. >
  634. <StopCircle className="w-4 h-4" />
  635. </Button>
  636. )}
  637. {isPending && (
  638. <>
  639. {item.manual_start && (
  640. <Button
  641. variant="ghost"
  642. size="sm"
  643. onClick={onStart}
  644. disabled={!hasPermission('printers:control')}
  645. title={!hasPermission('printers:control') ? t('queue.permissions.noStartPrint') : t('queue.actions.startPrint')}
  646. className="text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2"
  647. >
  648. <Play className="w-4 h-4" />
  649. </Button>
  650. )}
  651. <Button
  652. variant="ghost"
  653. size="sm"
  654. onClick={onEdit}
  655. disabled={!canModify('queue', 'update', item.created_by_id)}
  656. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noEdit') : t('common.edit')}
  657. className="p-1.5 sm:p-2"
  658. >
  659. <Pencil className="w-4 h-4" />
  660. </Button>
  661. <Button
  662. variant="ghost"
  663. size="sm"
  664. onClick={onCancel}
  665. disabled={!canModify('queue', 'delete', item.created_by_id)}
  666. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noCancel') : t('common.cancel')}
  667. className="text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2"
  668. >
  669. <X className="w-4 h-4" />
  670. </Button>
  671. </>
  672. )}
  673. {isHistory && (
  674. <>
  675. <Button
  676. variant="ghost"
  677. size="sm"
  678. onClick={onRequeue}
  679. disabled={!hasPermission('queue:create')}
  680. title={!hasPermission('queue:create') ? t('queue.permissions.noRequeue') : t('queue.actions.requeue')}
  681. className="text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2"
  682. >
  683. <RefreshCw className="w-4 h-4" />
  684. </Button>
  685. <Button
  686. variant="ghost"
  687. size="sm"
  688. onClick={onRemove}
  689. disabled={!canModify('queue', 'delete', item.created_by_id)}
  690. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noRemove') : t('common.remove')}
  691. className="p-1.5 sm:p-2"
  692. >
  693. <Trash2 className="w-4 h-4" />
  694. </Button>
  695. </>
  696. )}
  697. </div>
  698. </div>
  699. </div>
  700. </div>
  701. );
  702. }
  703. export function QueuePage() {
  704. const { t } = useTranslation();
  705. const queryClient = useQueryClient();
  706. const { showToast } = useToast();
  707. const { hasPermission, hasAnyPermission, canModify } = useAuth();
  708. const [filterPrinter, setFilterPrinter] = useState<number | null>(null);
  709. const [filterStatus, setFilterStatus] = useState<string>('');
  710. const [filterLocation, setFilterLocation] = useState<string>('');
  711. const [showClearHistoryConfirm, setShowClearHistoryConfirm] = useState(false);
  712. const [editItem, setEditItem] = useState<PrintQueueItem | null>(null);
  713. const [requeueItem, setRequeueItem] = useState<PrintQueueItem | null>(null);
  714. const [confirmAction, setConfirmAction] = useState<{
  715. type: 'cancel' | 'remove' | 'stop';
  716. item: PrintQueueItem;
  717. } | null>(null);
  718. const [selectedItems, setSelectedItems] = useState<number[]>([]);
  719. const [showBulkEditModal, setShowBulkEditModal] = useState(false);
  720. const [historySortBy, setHistorySortBy] = useState<'date' | 'name' | 'printer'>(() => {
  721. const saved = localStorage.getItem('queue.historySortBy');
  722. return (saved as 'date' | 'name' | 'printer') || 'date';
  723. });
  724. const [historySortAsc, setHistorySortAsc] = useState(() => {
  725. const saved = localStorage.getItem('queue.historySortAsc');
  726. return saved !== null ? saved === 'true' : false;
  727. });
  728. const [pendingSortBy, setPendingSortBy] = useState<'position' | 'name' | 'printer' | 'time'>(() => {
  729. const saved = localStorage.getItem('queue.pendingSortBy');
  730. return (saved as 'position' | 'name' | 'printer' | 'time') || 'position';
  731. });
  732. const [pendingSortAsc, setPendingSortAsc] = useState(() => {
  733. const saved = localStorage.getItem('queue.pendingSortAsc');
  734. return saved !== null ? saved === 'true' : true;
  735. });
  736. const [historyCollapsed, setHistoryCollapsed] = useState(() => {
  737. return localStorage.getItem('queue.historyCollapsed') !== 'false';
  738. });
  739. const [viewMode, setViewMode] = useState<'list' | 'timeline'>(() => {
  740. return (localStorage.getItem('queue.viewMode') as 'list' | 'timeline') || 'list';
  741. });
  742. // Persist sort settings to localStorage
  743. useEffect(() => {
  744. localStorage.setItem('queue.historySortBy', historySortBy);
  745. }, [historySortBy]);
  746. useEffect(() => {
  747. localStorage.setItem('queue.historySortAsc', String(historySortAsc));
  748. }, [historySortAsc]);
  749. useEffect(() => {
  750. localStorage.setItem('queue.pendingSortBy', pendingSortBy);
  751. }, [pendingSortBy]);
  752. useEffect(() => {
  753. localStorage.setItem('queue.pendingSortAsc', String(pendingSortAsc));
  754. }, [pendingSortAsc]);
  755. useEffect(() => {
  756. localStorage.setItem('queue.historyCollapsed', String(historyCollapsed));
  757. }, [historyCollapsed]);
  758. useEffect(() => {
  759. localStorage.setItem('queue.viewMode', viewMode);
  760. }, [viewMode]);
  761. const sensors = useSensors(
  762. useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
  763. useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  764. );
  765. const { data: settings } = useQuery({
  766. queryKey: ['settings'],
  767. queryFn: api.getSettings,
  768. });
  769. const timeFormat: TimeFormat = settings?.time_format || 'system';
  770. const { data: queue, isLoading } = useQuery({
  771. queryKey: ['queue', filterPrinter, filterStatus],
  772. queryFn: () => api.getQueue(filterPrinter || undefined, filterStatus || undefined),
  773. refetchInterval: 5000,
  774. });
  775. const { data: printers } = useQuery({
  776. queryKey: ['printers'],
  777. queryFn: () => api.getPrinters(),
  778. });
  779. const sjfMutation = useMutation({
  780. mutationFn: (enabled: boolean) => api.updateSettings({ queue_shortest_first: enabled }),
  781. onSuccess: () => {
  782. queryClient.invalidateQueries({ queryKey: ['settings'] });
  783. },
  784. });
  785. const cancelMutation = useMutation({
  786. mutationFn: (id: number) => api.cancelQueueItem(id),
  787. onSuccess: () => {
  788. queryClient.invalidateQueries({ queryKey: ['queue'] });
  789. showToast(t('queue.toast.cancelled'));
  790. },
  791. onError: () => showToast(t('queue.toast.cancelFailed'), 'error'),
  792. });
  793. const removeMutation = useMutation({
  794. mutationFn: (id: number) => api.removeFromQueue(id),
  795. onSuccess: () => {
  796. queryClient.invalidateQueries({ queryKey: ['queue'] });
  797. showToast(t('queue.toast.removed'));
  798. },
  799. onError: () => showToast(t('queue.toast.removeFailed'), 'error'),
  800. });
  801. const stopMutation = useMutation({
  802. mutationFn: (id: number) => api.stopQueueItem(id),
  803. onSuccess: () => {
  804. queryClient.invalidateQueries({ queryKey: ['queue'] });
  805. showToast(t('queue.toast.stopped'));
  806. },
  807. onError: () => showToast(t('queue.toast.stopFailed'), 'error'),
  808. });
  809. // Filament-deficit confirmation state (#1496). When the backend returns
  810. // 409 with `code=insufficient_filament` we stash the deficit + item id
  811. // here; the modal at the bottom of the page reads it and the "Print
  812. // Anyway" path re-issues the start with `skipFilamentCheck=true`.
  813. const [filamentShortConfirm, setFilamentShortConfirm] = useState<{
  814. itemId: number;
  815. deficit: Array<{
  816. slot_id: number;
  817. required_grams: number;
  818. remaining_grams: number | null;
  819. filament_type?: string | null;
  820. }>;
  821. } | null>(null);
  822. const startMutation = useMutation({
  823. mutationFn: ({ id, skipFilamentCheck }: { id: number; skipFilamentCheck?: boolean }) =>
  824. api.startQueueItem(id, { skipFilamentCheck }),
  825. onSuccess: () => {
  826. queryClient.invalidateQueries({ queryKey: ['queue'] });
  827. showToast(t('queue.toast.released'));
  828. setFilamentShortConfirm(null);
  829. },
  830. onError: (error: unknown, variables) => {
  831. if (error instanceof ApiError && error.status === 409 && error.code === 'insufficient_filament') {
  832. const deficitRaw = (error.detail?.deficit ?? []) as Array<{
  833. slot_id: number;
  834. required_grams: number;
  835. remaining_grams: number | null;
  836. filament_type?: string | null;
  837. }>;
  838. setFilamentShortConfirm({ itemId: variables.id, deficit: deficitRaw });
  839. return;
  840. }
  841. showToast(t('queue.toast.startFailed'), 'error');
  842. },
  843. });
  844. const reorderMutation = useMutation({
  845. mutationFn: (items: { id: number; position: number }[]) => api.reorderQueue(items),
  846. onSuccess: () => {
  847. queryClient.invalidateQueries({ queryKey: ['queue'] });
  848. },
  849. onError: () => showToast(t('queue.toast.reorderFailed'), 'error'),
  850. });
  851. const clearHistoryMutation = useMutation({
  852. mutationFn: async () => {
  853. const historyItems = queue?.filter(i =>
  854. ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)
  855. ) || [];
  856. for (const item of historyItems) {
  857. await api.removeFromQueue(item.id);
  858. }
  859. return historyItems.length;
  860. },
  861. onSuccess: (count) => {
  862. queryClient.invalidateQueries({ queryKey: ['queue'] });
  863. showToast(t('queue.toast.historyCleared', { count }));
  864. },
  865. onError: () => showToast(t('queue.toast.clearHistoryFailed'), 'error'),
  866. });
  867. const bulkUpdateMutation = useMutation({
  868. mutationFn: (data: PrintQueueBulkUpdate) => api.bulkUpdateQueue(data),
  869. onSuccess: (result) => {
  870. queryClient.invalidateQueries({ queryKey: ['queue'] });
  871. setSelectedItems([]);
  872. setShowBulkEditModal(false);
  873. showToast(result.message);
  874. },
  875. onError: () => showToast(t('queue.toast.updateFailed'), 'error'),
  876. });
  877. const bulkCancelMutation = useMutation({
  878. mutationFn: async (ids: number[]) => {
  879. for (const id of ids) {
  880. await api.cancelQueueItem(id);
  881. }
  882. return ids.length;
  883. },
  884. onSuccess: (count) => {
  885. queryClient.invalidateQueries({ queryKey: ['queue'] });
  886. setSelectedItems([]);
  887. showToast(t('queue.toast.bulkCancelled', { count }));
  888. },
  889. onError: () => showToast(t('queue.toast.bulkCancelFailed'), 'error'),
  890. });
  891. const handleToggleSelect = (id: number) => {
  892. setSelectedItems(prev =>
  893. prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
  894. );
  895. };
  896. // Get unique locations from printers for the filter dropdown
  897. const uniqueLocations = useMemo(() => {
  898. const locations = new Set<string>();
  899. printers?.forEach(p => {
  900. if (p.location) locations.add(p.location);
  901. });
  902. // Also include locations from queue items (for model-based assignments)
  903. queue?.forEach(item => {
  904. if (item.target_location) locations.add(item.target_location);
  905. });
  906. return Array.from(locations).sort();
  907. }, [printers, queue]);
  908. // Helper to check if a queue item matches the location filter
  909. const matchesLocationFilter = useCallback((item: PrintQueueItem): boolean => {
  910. if (!filterLocation) return true;
  911. // For model-based assignments, check target_location
  912. if (item.target_location) return item.target_location === filterLocation;
  913. // For printer-based assignments, check the printer's location
  914. if (item.printer_id) {
  915. const printer = printers?.find(p => p.id === item.printer_id);
  916. return printer?.location === filterLocation;
  917. }
  918. return false;
  919. }, [filterLocation, printers]);
  920. const pendingItems = useMemo(() => {
  921. let items = queue?.filter(i => i.status === 'pending') || [];
  922. // Apply location filter
  923. if (filterLocation) {
  924. items = items.filter(matchesLocationFilter);
  925. }
  926. // Helper to get scheduled time as timestamp (ASAP/placeholder = 0 for earliest)
  927. const getScheduledTime = (item: PrintQueueItem): number => {
  928. if (!item.scheduled_time) return 0;
  929. const time = parseUTCDate(item.scheduled_time)?.getTime() ?? 0;
  930. // Placeholder dates (> 6 months out) are treated as ASAP
  931. const sixMonthsFromNow = Date.now() + (180 * 24 * 60 * 60 * 1000);
  932. return time > sixMonthsFromNow ? 0 : time;
  933. };
  934. // When SJF is enabled, override sort to match scheduler order
  935. if (settings?.queue_shortest_first) {
  936. return [...items].sort((a, b) => {
  937. // Group by printer first (nulls = model-based, grouped by target_model)
  938. const aPrinter = a.printer_id ?? -(a.target_model?.charCodeAt(0) ?? 0);
  939. const bPrinter = b.printer_id ?? -(b.target_model?.charCodeAt(0) ?? 0);
  940. if (aPrinter !== bPrinter) return aPrinter - bPrinter;
  941. // Within same printer/model: jumped items first (starvation guard)
  942. const aJumped = a.been_jumped ? 1 : 0;
  943. const bJumped = b.been_jumped ? 1 : 0;
  944. if (aJumped !== bJumped) return bJumped - aJumped;
  945. // Shortest print time next (nulls last)
  946. const aTime = a.print_time_seconds ?? Infinity;
  947. const bTime = b.print_time_seconds ?? Infinity;
  948. if (aTime !== bTime) return aTime - bTime;
  949. // Position as tiebreaker
  950. return a.position - b.position;
  951. });
  952. }
  953. return [...items].sort((a, b) => {
  954. let cmp: number;
  955. if (pendingSortBy === 'name') {
  956. const aName = a.archive_name || a.library_file_name || '';
  957. const bName = b.archive_name || b.library_file_name || '';
  958. cmp = aName.localeCompare(bName);
  959. } else if (pendingSortBy === 'printer') {
  960. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  961. } else if (pendingSortBy === 'time') {
  962. // Sort by scheduled start time (when print will begin)
  963. cmp = getScheduledTime(a) - getScheduledTime(b);
  964. } else {
  965. cmp = a.position - b.position;
  966. }
  967. return pendingSortAsc ? cmp : -cmp;
  968. });
  969. }, [queue, pendingSortBy, pendingSortAsc, matchesLocationFilter, filterLocation, settings?.queue_shortest_first]);
  970. const handleSelectAll = () => {
  971. const allPendingIds = pendingItems.map(i => i.id);
  972. if (selectedItems.length === allPendingIds.length) {
  973. setSelectedItems([]);
  974. } else {
  975. setSelectedItems(allPendingIds);
  976. }
  977. };
  978. const activeItems = useMemo(() => {
  979. let items = queue?.filter(i => i.status === 'printing') || [];
  980. if (filterLocation) {
  981. items = items.filter(matchesLocationFilter);
  982. }
  983. return items;
  984. }, [queue, filterLocation, matchesLocationFilter]);
  985. // Get unique printer IDs from active items to fetch their statuses
  986. const activePrinterIds = useMemo(() => {
  987. const ids = new Set<number>();
  988. activeItems.forEach(item => {
  989. if (item.printer_id) ids.add(item.printer_id);
  990. });
  991. return Array.from(ids);
  992. }, [activeItems]);
  993. // Fetch printer statuses for printers with active jobs
  994. const printerStatusQueries = useQueries({
  995. queries: activePrinterIds.map(printerId => ({
  996. queryKey: ['printerStatus', printerId],
  997. queryFn: () => api.getPrinterStatus(printerId),
  998. refetchInterval: 5000,
  999. })),
  1000. });
  1001. // Build a map of printer_id -> state for quick lookup
  1002. const printerStateMap = useMemo(() => {
  1003. const map: Record<number, string | null> = {};
  1004. activePrinterIds.forEach((printerId, index) => {
  1005. const result = printerStatusQueries[index];
  1006. if (result?.data?.state) {
  1007. map[printerId] = result.data.state;
  1008. }
  1009. });
  1010. return map;
  1011. }, [activePrinterIds, printerStatusQueries]);
  1012. // Build a map of printer_id -> full status for timeline view
  1013. const printerStatusMap = useMemo(() => {
  1014. const map: Record<number, { progress?: number; remaining_time?: number; state?: string }> = {};
  1015. activePrinterIds.forEach((printerId, index) => {
  1016. const result = printerStatusQueries[index];
  1017. if (result?.data) {
  1018. map[printerId] = {
  1019. progress: result.data.progress ?? undefined,
  1020. remaining_time: result.data.remaining_time ?? undefined,
  1021. state: result.data.state ?? undefined,
  1022. };
  1023. }
  1024. });
  1025. return map;
  1026. }, [activePrinterIds, printerStatusQueries]);
  1027. const historyItems = useMemo(() => {
  1028. let items = queue?.filter(i => ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)) || [];
  1029. if (filterLocation) {
  1030. items = items.filter(matchesLocationFilter);
  1031. }
  1032. return [...items].sort((a, b) => {
  1033. let cmp: number;
  1034. if (historySortBy === 'name') {
  1035. const aName = a.archive_name || a.library_file_name || '';
  1036. const bName = b.archive_name || b.library_file_name || '';
  1037. cmp = aName.localeCompare(bName);
  1038. } else if (historySortBy === 'printer') {
  1039. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  1040. } else {
  1041. // Default: by date - most recent first (desc) is the natural order
  1042. cmp = (parseUTCDate(b.completed_at || b.created_at)?.getTime() ?? 0) - (parseUTCDate(a.completed_at || a.created_at)?.getTime() ?? 0);
  1043. }
  1044. return historySortAsc ? -cmp : cmp;
  1045. });
  1046. }, [queue, historySortBy, historySortAsc, matchesLocationFilter, filterLocation]);
  1047. // Calculate total queue time
  1048. const totalQueueTime = useMemo(() => {
  1049. return pendingItems.reduce((acc, item) => acc + (item.print_time_seconds || 0), 0);
  1050. }, [pendingItems]);
  1051. // Calculate total material weight
  1052. const totalWeight = useMemo(() => {
  1053. return pendingItems.reduce((acc, item) => acc + (item.filament_used_grams || 0), 0);
  1054. }, [pendingItems]);
  1055. const handleDragEnd = (event: DragEndEvent) => {
  1056. const { active, over } = event;
  1057. if (!over || active.id === over.id) return;
  1058. const oldIndex = pendingItems.findIndex(i => i.id === active.id);
  1059. const newIndex = pendingItems.findIndex(i => i.id === over.id);
  1060. if (oldIndex !== -1 && newIndex !== -1) {
  1061. const reordered = arrayMove(pendingItems, oldIndex, newIndex);
  1062. const updates = reordered.map((item, index) => ({
  1063. id: item.id,
  1064. position: index + 1,
  1065. }));
  1066. reorderMutation.mutate(updates);
  1067. }
  1068. };
  1069. return (
  1070. <div className="p-4 md:p-8">
  1071. {/* Header */}
  1072. <div className="flex items-center justify-between mb-8">
  1073. <div>
  1074. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  1075. <ListOrdered className="w-7 h-7 text-bambu-green" />
  1076. {t('queue.title')}
  1077. </h1>
  1078. <p className="text-bambu-gray mt-1">{t('queue.subtitle')}</p>
  1079. </div>
  1080. </div>
  1081. {/* Summary Stats */}
  1082. <QueueStatsBar
  1083. activeCount={activeItems.length}
  1084. pendingCount={pendingItems.length}
  1085. totalTime={totalQueueTime}
  1086. totalWeight={totalWeight}
  1087. historyCount={historyItems.length}
  1088. t={t}
  1089. />
  1090. {/* Filters */}
  1091. <div className="flex flex-wrap items-center gap-2 sm:gap-4 mb-6">
  1092. <select
  1093. 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"
  1094. value={filterPrinter === -1 ? 'unassigned' : (filterPrinter || '')}
  1095. onChange={(e) => {
  1096. const val = e.target.value;
  1097. if (val === 'unassigned') setFilterPrinter(-1);
  1098. else if (val === '') setFilterPrinter(null);
  1099. else setFilterPrinter(Number(val));
  1100. }}
  1101. >
  1102. <option value="">{t('queue.filter.allPrinters')}</option>
  1103. <option value="unassigned">{t('queue.filter.unassigned')}</option>
  1104. {printers?.map((p) => (
  1105. <option key={p.id} value={p.id}>{p.name}</option>
  1106. ))}
  1107. </select>
  1108. <select
  1109. 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"
  1110. value={filterStatus}
  1111. onChange={(e) => setFilterStatus(e.target.value)}
  1112. >
  1113. <option value="">{t('queue.filter.allStatus')}</option>
  1114. <option value="pending">{t('queue.status.pending')}</option>
  1115. <option value="printing">{t('queue.status.printing')}</option>
  1116. <option value="completed">{t('queue.status.completed')}</option>
  1117. <option value="failed">{t('queue.status.failed')}</option>
  1118. <option value="skipped">{t('queue.status.skipped')}</option>
  1119. <option value="cancelled">{t('queue.status.cancelled')}</option>
  1120. </select>
  1121. {uniqueLocations.length > 0 && (
  1122. <select
  1123. 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"
  1124. value={filterLocation}
  1125. onChange={(e) => setFilterLocation(e.target.value)}
  1126. >
  1127. <option value="">{t('queue.filter.allLocations')}</option>
  1128. {uniqueLocations.map((loc) => (
  1129. <option key={loc} value={loc}>{loc}</option>
  1130. ))}
  1131. </select>
  1132. )}
  1133. <div className="hidden sm:block flex-1" />
  1134. {historyItems.length > 0 && (
  1135. <Button
  1136. className="w-full sm:w-auto"
  1137. variant="secondary"
  1138. size="sm"
  1139. onClick={() => setShowClearHistoryConfirm(true)}
  1140. disabled={!hasPermission('queue:delete_all')}
  1141. title={!hasPermission('queue:delete_all') ? t('queue.permissions.noClearHistory') : undefined}
  1142. >
  1143. <Trash2 className="w-4 h-4" />
  1144. {t('queue.clearHistory')}
  1145. </Button>
  1146. )}
  1147. </div>
  1148. {/* View Mode Toggle + SJF */}
  1149. <div className="flex items-center gap-3 mb-6">
  1150. <div className="hidden sm:flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden">
  1151. <button
  1152. className={`p-2 transition-colors ${viewMode === 'list' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  1153. onClick={() => setViewMode('list')}
  1154. title={t('queue.timeline.listView')}
  1155. >
  1156. <List className="w-4 h-4" />
  1157. </button>
  1158. <button
  1159. className={`p-2 transition-colors ${viewMode === 'timeline' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  1160. onClick={() => setViewMode('timeline')}
  1161. title={t('queue.timeline.timelineView')}
  1162. >
  1163. <GanttChart className="w-4 h-4" />
  1164. </button>
  1165. </div>
  1166. <button
  1167. onClick={() => {
  1168. const newValue = !(settings?.queue_shortest_first ?? false);
  1169. sjfMutation.mutate(newValue);
  1170. }}
  1171. className={`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${
  1172. settings?.queue_shortest_first
  1173. ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
  1174. : 'bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  1175. }`}
  1176. title={t('queue.sjf.tooltip', 'Shortest Job First — scheduler prioritizes shorter prints')}
  1177. >
  1178. <Snail className="w-4 h-4" />
  1179. <span className="hidden sm:inline">{t('queue.sjf.label', 'SJF')}</span>
  1180. <span className={`w-1.5 h-1.5 rounded-full ${settings?.queue_shortest_first ? 'bg-bambu-green' : 'bg-bambu-gray'}`} />
  1181. </button>
  1182. </div>
  1183. {isLoading ? (
  1184. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  1185. ) : queue?.length === 0 ? (
  1186. <Card className="p-12 text-center border-dashed">
  1187. <Calendar className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  1188. <h3 className="text-xl font-medium text-white mb-2">{t('queue.empty.title')}</h3>
  1189. <p className="text-bambu-gray max-w-md mx-auto">
  1190. {t('queue.empty.description')}
  1191. </p>
  1192. </Card>
  1193. ) : viewMode === 'timeline' ? (
  1194. <QueueTimelineView
  1195. queueItems={queue || []}
  1196. printerStatuses={printerStatusMap}
  1197. onItemClick={(item) => {
  1198. if (['completed', 'failed', 'skipped', 'cancelled'].includes(item.status)) {
  1199. setRequeueItem(item);
  1200. } else if (item.status === 'pending') {
  1201. setEditItem(item);
  1202. } else if (item.status === 'printing') {
  1203. setConfirmAction({ type: 'stop', item });
  1204. }
  1205. }}
  1206. t={t}
  1207. />
  1208. ) : (
  1209. <div className="space-y-6 sm:space-y-8">
  1210. {/* Active Prints */}
  1211. {activeItems.length > 0 && (
  1212. <div>
  1213. <h2 className="text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2">
  1214. <div className="w-2 h-2 rounded-full bg-blue-400 animate-pulse" />
  1215. {t('queue.sections.currentlyPrinting')}
  1216. </h2>
  1217. <div className="space-y-2 sm:space-y-3">
  1218. {activeItems.map((item) => (
  1219. <SortableQueueItem
  1220. key={item.id}
  1221. item={item}
  1222. onEdit={() => {}}
  1223. onCancel={() => {}}
  1224. onRemove={() => {}}
  1225. onStop={() => setConfirmAction({ type: 'stop', item })}
  1226. onRequeue={() => {}}
  1227. onStart={() => {}}
  1228. timeFormat={timeFormat}
  1229. hasPermission={hasPermission}
  1230. canModify={canModify}
  1231. printerState={item.printer_id ? printerStateMap[item.printer_id] : null}
  1232. t={t}
  1233. />
  1234. ))}
  1235. </div>
  1236. </div>
  1237. )}
  1238. {/* Pending Queue */}
  1239. {pendingItems.length > 0 && (
  1240. <div>
  1241. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  1242. <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
  1243. <Clock className="w-4 h-4 sm:w-5 sm:h-5 text-yellow-400" />
  1244. {t('queue.sections.queued')}
  1245. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  1246. ({t('queue.itemCount', { count: pendingItems.length })})
  1247. </span>
  1248. <span className="hidden sm:inline text-xs text-bambu-gray ml-2" title={t('queue.reorderHint')}>
  1249. {t('queue.dragToReorder')}
  1250. </span>
  1251. </h2>
  1252. <div className="flex items-center gap-2">
  1253. <select
  1254. 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"
  1255. value={pendingSortBy}
  1256. onChange={(e) => setPendingSortBy(e.target.value as 'position' | 'name' | 'printer' | 'time')}
  1257. >
  1258. <option value="position">{t('queue.sort.byPosition')}</option>
  1259. <option value="name">{t('queue.sort.byName')}</option>
  1260. <option value="printer">{t('queue.sort.byPrinter')}</option>
  1261. <option value="time">{t('queue.sort.bySchedule')}</option>
  1262. </select>
  1263. <Button
  1264. variant="ghost"
  1265. size="sm"
  1266. onClick={() => setPendingSortAsc(!pendingSortAsc)}
  1267. title={pendingSortAsc ? t('common.ascending') : t('common.descending')}
  1268. className="px-2"
  1269. >
  1270. {pendingSortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  1271. </Button>
  1272. </div>
  1273. </div>
  1274. {/* Bulk action toolbar */}
  1275. <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">
  1276. <Button
  1277. variant="ghost"
  1278. size="sm"
  1279. onClick={handleSelectAll}
  1280. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm"
  1281. >
  1282. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? (
  1283. <CheckSquare className="w-4 h-4 text-bambu-green" />
  1284. ) : (
  1285. <Square className="w-4 h-4" />
  1286. )}
  1287. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? t('queue.bulkEdit.deselectAll') : t('queue.bulkEdit.selectAll')}
  1288. </Button>
  1289. {selectedItems.length > 0 && (
  1290. <>
  1291. <span className="text-xs sm:text-sm text-bambu-gray">
  1292. {t('queue.bulkEdit.selected', { count: selectedItems.length })}
  1293. </span>
  1294. <div className="hidden sm:block h-4 w-px bg-bambu-dark-tertiary" />
  1295. <Button
  1296. variant="ghost"
  1297. size="sm"
  1298. onClick={() => setShowBulkEditModal(true)}
  1299. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light"
  1300. disabled={!hasAnyPermission('queue:update_own', 'queue:update_all')}
  1301. title={!hasAnyPermission('queue:update_own', 'queue:update_all') ? t('queue.permissions.noEditItems') : t('queue.bulkEdit.editSelected')}
  1302. >
  1303. <Pencil className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  1304. <span className="hidden sm:inline">{t('queue.bulkEdit.editSelected')}</span>
  1305. </Button>
  1306. <Button
  1307. variant="ghost"
  1308. size="sm"
  1309. onClick={() => bulkCancelMutation.mutate(selectedItems)}
  1310. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300"
  1311. disabled={bulkCancelMutation.isPending || !hasAnyPermission('queue:delete_own', 'queue:delete_all')}
  1312. title={!hasAnyPermission('queue:delete_own', 'queue:delete_all') ? t('queue.permissions.noCancelItems') : t('queue.bulkEdit.cancelSelected')}
  1313. >
  1314. <X className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  1315. <span className="hidden sm:inline">{t('queue.bulkEdit.cancelSelected')}</span>
  1316. </Button>
  1317. </>
  1318. )}
  1319. </div>
  1320. <DndContext
  1321. sensors={sensors}
  1322. collisionDetection={closestCenter}
  1323. onDragEnd={handleDragEnd}
  1324. >
  1325. <SortableContext
  1326. items={pendingItems.map(i => i.id)}
  1327. strategy={verticalListSortingStrategy}
  1328. >
  1329. <div className="space-y-2 sm:space-y-3">
  1330. {pendingItems.map((item, index) => (
  1331. <SortableQueueItem
  1332. key={item.id}
  1333. item={item}
  1334. position={index + 1}
  1335. onEdit={() => setEditItem(item)}
  1336. onCancel={() => setConfirmAction({ type: 'cancel', item })}
  1337. onRemove={() => {}}
  1338. onStop={() => {}}
  1339. onRequeue={() => {}}
  1340. onStart={() => startMutation.mutate({ id: item.id })}
  1341. timeFormat={timeFormat}
  1342. isSelected={selectedItems.includes(item.id)}
  1343. onToggleSelect={() => handleToggleSelect(item.id)}
  1344. hasPermission={hasPermission}
  1345. canModify={canModify}
  1346. t={t}
  1347. />
  1348. ))}
  1349. </div>
  1350. </SortableContext>
  1351. </DndContext>
  1352. </div>
  1353. )}
  1354. {/* History */}
  1355. {historyItems.length > 0 && (
  1356. <div>
  1357. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  1358. <button
  1359. onClick={() => setHistoryCollapsed(!historyCollapsed)}
  1360. className="text-base sm:text-lg font-semibold text-white flex items-center gap-2 hover:text-bambu-green transition-colors"
  1361. >
  1362. {historyCollapsed ? <ChevronRight className="w-4 h-4 sm:w-5 sm:h-5" /> : <ChevronDown className="w-4 h-4 sm:w-5 sm:h-5" />}
  1363. {t('queue.sections.history')}
  1364. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  1365. ({t('queue.itemCount', { count: historyItems.length })})
  1366. </span>
  1367. </button>
  1368. {!historyCollapsed && (
  1369. <div className="flex items-center gap-2">
  1370. <select
  1371. 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"
  1372. value={historySortBy}
  1373. onChange={(e) => setHistorySortBy(e.target.value as 'date' | 'name' | 'printer')}
  1374. >
  1375. <option value="date">{t('queue.sort.byDate')}</option>
  1376. <option value="name">{t('queue.sort.byName')}</option>
  1377. <option value="printer">{t('queue.sort.byPrinter')}</option>
  1378. </select>
  1379. <Button
  1380. variant="ghost"
  1381. size="sm"
  1382. onClick={() => setHistorySortAsc(!historySortAsc)}
  1383. title={historySortAsc ? t('queue.sort.ascendingOldest') : t('queue.sort.descendingNewest')}
  1384. className="px-2"
  1385. >
  1386. {historySortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  1387. </Button>
  1388. </div>
  1389. )}
  1390. </div>
  1391. {!historyCollapsed && (
  1392. <div className="space-y-1.5 sm:space-y-2">
  1393. {historyItems.slice(0, 50).map((item) => (
  1394. <CompactHistoryRow
  1395. key={item.id}
  1396. item={item}
  1397. onRemove={() => setConfirmAction({ type: 'remove', item })}
  1398. onRequeue={() => setRequeueItem(item)}
  1399. timeFormat={timeFormat}
  1400. hasPermission={hasPermission}
  1401. canModify={canModify}
  1402. t={t}
  1403. />
  1404. ))}
  1405. </div>
  1406. )}
  1407. </div>
  1408. )}
  1409. </div>
  1410. )}
  1411. {/* Edit Modal */}
  1412. {editItem && (
  1413. <PrintModal
  1414. mode="edit-queue-item"
  1415. archiveId={editItem.archive_id ?? undefined}
  1416. libraryFileId={editItem.library_file_id ?? undefined}
  1417. archiveName={editItem.archive_name || editItem.library_file_name || `File #${editItem.archive_id || editItem.library_file_id}`}
  1418. queueItem={editItem}
  1419. onClose={() => setEditItem(null)}
  1420. />
  1421. )}
  1422. {/* Re-queue Modal */}
  1423. {requeueItem && (
  1424. <PrintModal
  1425. mode="add-to-queue"
  1426. archiveId={requeueItem.archive_id ?? undefined}
  1427. libraryFileId={requeueItem.library_file_id ?? undefined}
  1428. archiveName={requeueItem.archive_name || requeueItem.library_file_name || `File #${requeueItem.archive_id || requeueItem.library_file_id}`}
  1429. onClose={() => setRequeueItem(null)}
  1430. />
  1431. )}
  1432. {/* Confirm Action Modal */}
  1433. {filamentShortConfirm && (
  1434. <ConfirmModal
  1435. title={t('queue.filamentShort.confirmTitle')}
  1436. message={
  1437. t('queue.filamentShort.confirmIntro') + '\n\n' +
  1438. filamentShortConfirm.deficit
  1439. .map((d) =>
  1440. t('queue.filamentShort.lineItem', {
  1441. slot: d.slot_id,
  1442. required: Math.round(d.required_grams),
  1443. remaining:
  1444. d.remaining_grams == null
  1445. ? t('queue.filamentShort.unknown')
  1446. : Math.round(d.remaining_grams),
  1447. }),
  1448. )
  1449. .join('\n')
  1450. }
  1451. confirmText={t('queue.filamentShort.printAnyway')}
  1452. variant="warning"
  1453. onConfirm={() => {
  1454. startMutation.mutate({ id: filamentShortConfirm.itemId, skipFilamentCheck: true });
  1455. }}
  1456. onCancel={() => setFilamentShortConfirm(null)}
  1457. />
  1458. )}
  1459. {confirmAction && (
  1460. <ConfirmModal
  1461. title={
  1462. confirmAction.type === 'cancel' ? t('queue.confirm.cancelTitle') :
  1463. confirmAction.type === 'stop' ? t('queue.confirm.stopTitle') :
  1464. t('queue.confirm.removeTitle')
  1465. }
  1466. message={
  1467. confirmAction.type === 'cancel'
  1468. ? t('queue.confirm.cancelMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  1469. : confirmAction.type === 'stop'
  1470. ? t('queue.confirm.stopMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  1471. : t('queue.confirm.removeMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisItem') })
  1472. }
  1473. confirmText={
  1474. confirmAction.type === 'cancel' ? t('queue.confirm.cancelButton') :
  1475. confirmAction.type === 'stop' ? t('queue.confirm.stopButton') :
  1476. t('common.remove')
  1477. }
  1478. variant="danger"
  1479. onConfirm={() => {
  1480. if (confirmAction.type === 'cancel') {
  1481. cancelMutation.mutate(confirmAction.item.id);
  1482. } else if (confirmAction.type === 'stop') {
  1483. stopMutation.mutate(confirmAction.item.id);
  1484. } else {
  1485. removeMutation.mutate(confirmAction.item.id);
  1486. }
  1487. setConfirmAction(null);
  1488. }}
  1489. onCancel={() => setConfirmAction(null)}
  1490. />
  1491. )}
  1492. {/* Clear History Confirm Modal */}
  1493. {showClearHistoryConfirm && (
  1494. <ConfirmModal
  1495. title={t('queue.confirm.clearHistoryTitle')}
  1496. message={t('queue.confirm.clearHistoryMessage', { count: historyItems.length })}
  1497. confirmText={t('queue.clearHistory')}
  1498. variant="danger"
  1499. onConfirm={() => {
  1500. clearHistoryMutation.mutate();
  1501. setShowClearHistoryConfirm(false);
  1502. }}
  1503. onCancel={() => setShowClearHistoryConfirm(false)}
  1504. />
  1505. )}
  1506. {/* Bulk Edit Modal */}
  1507. {showBulkEditModal && (
  1508. <BulkEditModal
  1509. selectedCount={selectedItems.length}
  1510. printers={printers?.map(p => ({ id: p.id, name: p.name, nozzle_count: p.nozzle_count })) || []}
  1511. onSave={(data) => {
  1512. if (Object.keys(data).length > 0) {
  1513. bulkUpdateMutation.mutate({ item_ids: selectedItems, ...data });
  1514. }
  1515. }}
  1516. onClose={() => setShowBulkEditModal(false)}
  1517. isSaving={bulkUpdateMutation.isPending}
  1518. canControlPrinter={hasPermission('printers:control')}
  1519. t={t}
  1520. />
  1521. )}
  1522. </div>
  1523. );
  1524. }