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