QueuePage.tsx 121 KB

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