QueuePage.tsx 104 KB

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