QueuePage.tsx 131 KB

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