QueuePage.tsx 110 KB

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