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