QueuePage.tsx 108 KB

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