QueuePage.tsx 132 KB

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