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