PrinterQueueWidget.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import { useEffect } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { Clock, Calendar, ChevronRight, Loader2, CircleCheck } from 'lucide-react';
  4. import { Link } from 'react-router-dom';
  5. import { useTranslation } from 'react-i18next';
  6. import { api } from '../api/client';
  7. import { useAuth } from '../contexts/AuthContext';
  8. import { useToast } from '../contexts/ToastContext';
  9. import { formatRelativeTime } from '../utils/date';
  10. import { filterCompatibleQueueItems } from '../utils/printer';
  11. interface PrinterQueueWidgetProps {
  12. printerId: number;
  13. printerModel?: string | null;
  14. /** @deprecated use awaitingPlateClear — kept so existing callers/tests still compile */
  15. printerState?: string | null;
  16. awaitingPlateClear?: boolean;
  17. requirePlateClear?: boolean;
  18. loadedFilamentTypes?: Set<string>;
  19. loadedFilaments?: Set<string>; // "TYPE:rrggbb" pairs for filament override color matching
  20. }
  21. export function PrinterQueueWidget({ printerId, printerModel, awaitingPlateClear, requirePlateClear = false, loadedFilamentTypes, loadedFilaments }: PrinterQueueWidgetProps) {
  22. const { t } = useTranslation();
  23. const queryClient = useQueryClient();
  24. const { showToast } = useToast();
  25. const { hasPermission } = useAuth();
  26. const { data: queue } = useQuery({
  27. queryKey: ['queue', printerId, 'pending', printerModel],
  28. queryFn: () => api.getQueue(printerId, 'pending', printerModel || undefined),
  29. refetchInterval: 30000,
  30. });
  31. const clearPlateMutation = useMutation({
  32. mutationFn: () => api.clearPlate(printerId),
  33. onSuccess: () => {
  34. queryClient.invalidateQueries({ queryKey: ['queue', printerId] });
  35. queryClient.invalidateQueries({ queryKey: ['printerStatus', printerId] });
  36. showToast(t('queue.clearPlateSuccess'), 'success');
  37. },
  38. onError: (err: Error) => {
  39. showToast(err.message, 'error');
  40. },
  41. });
  42. // Reset mutation state when the awaiting flag clears so the button is clickable
  43. // again after the next finished print (fixes #912). The flag is the authoritative
  44. // signal — state alone is not reliable across power cycles (#961).
  45. useEffect(() => {
  46. if (!awaitingPlateClear) {
  47. clearPlateMutation.reset();
  48. }
  49. }, [awaitingPlateClear, clearPlateMutation]);
  50. // Filter queue to items this printer can actually print (filament type + color check)
  51. const compatibleQueue = queue ? filterCompatibleQueueItems(queue, loadedFilamentTypes, loadedFilaments) : undefined;
  52. // Split into auto-dispatchable vs staged (manual_start) items
  53. const autoDispatchQueue = compatibleQueue?.filter(item => !item.manual_start) ?? [];
  54. const totalPending = compatibleQueue?.length || 0;
  55. if (totalPending === 0) {
  56. return null;
  57. }
  58. const nextAutoItem = autoDispatchQueue[0];
  59. const nextItem = compatibleQueue?.[0];
  60. // Prompt "Clear Plate & Start Next" whenever the backend flags the printer as awaiting
  61. // acknowledgment. Don't gate on reported state: after Auto Off cycles the printer, it
  62. // boots into IDLE while still awaiting — the prompt must survive that (#961). The flag
  63. // is cleared by the backend on ack or when the next print dispatches.
  64. const needsClearPlate = requirePlateClear && !!awaitingPlateClear && autoDispatchQueue.length > 0;
  65. if (needsClearPlate) {
  66. const displayItem = nextAutoItem || nextItem;
  67. return (
  68. <div className="mb-3 p-3 bg-bambu-dark rounded-lg border border-yellow-400/30">
  69. <div className="flex items-center gap-3 mb-2">
  70. <Calendar className="w-5 h-5 text-yellow-400 flex-shrink-0" />
  71. <div className="min-w-0 flex-1">
  72. <p className="text-xs text-bambu-gray">{t('queue.nextInQueue')}</p>
  73. <p className="text-sm text-white truncate">
  74. {displayItem?.archive_name || displayItem?.library_file_name || `File #${displayItem?.archive_id || displayItem?.library_file_id}`}
  75. </p>
  76. </div>
  77. {totalPending > 1 && (
  78. <span className="text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded flex-shrink-0">
  79. +{totalPending - 1}
  80. </span>
  81. )}
  82. </div>
  83. {clearPlateMutation.isSuccess ? (
  84. <div className="w-full py-2 px-3 rounded-lg bg-bambu-green/10 border border-bambu-green/20 text-bambu-green text-sm flex items-center justify-center gap-2">
  85. <CircleCheck className="w-4 h-4" />
  86. {t('queue.plateReady')}
  87. </div>
  88. ) : (
  89. <button
  90. onClick={() => clearPlateMutation.mutate()}
  91. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  92. className="w-full py-2 px-3 rounded-lg bg-bambu-green/20 border border-bambu-green/40 text-bambu-green hover:bg-bambu-green/30 transition-colors text-sm font-medium flex items-center justify-center gap-2 disabled:opacity-50"
  93. >
  94. {clearPlateMutation.isPending ? (
  95. <Loader2 className="w-4 h-4 animate-spin" />
  96. ) : (
  97. <CircleCheck className="w-4 h-4" />
  98. )}
  99. {t('queue.clearPlate')}
  100. </button>
  101. )}
  102. </div>
  103. );
  104. }
  105. return (
  106. <Link
  107. to="/queue"
  108. className="block mb-3 p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors"
  109. >
  110. <div className="flex items-center justify-between gap-3">
  111. <div className="flex items-center gap-3 min-w-0 flex-1">
  112. <Calendar className="w-5 h-5 text-yellow-400 flex-shrink-0" />
  113. <div className="min-w-0 flex-1">
  114. <p className="text-xs text-bambu-gray">{t('queue.nextInQueue')}</p>
  115. <p className="text-sm text-white truncate">
  116. {nextItem?.archive_name || nextItem?.library_file_name || `File #${nextItem?.archive_id || nextItem?.library_file_id}`}
  117. </p>
  118. </div>
  119. </div>
  120. <div className="flex items-center gap-2 flex-shrink-0">
  121. <span className="text-xs text-bambu-gray flex items-center gap-1">
  122. <Clock className="w-3 h-3" />
  123. {nextItem?.scheduled_time ? formatRelativeTime(nextItem.scheduled_time, 'system', t) : t('time.waiting')}
  124. </span>
  125. {totalPending > 1 && (
  126. <span className="text-xs px-1.5 py-0.5 bg-yellow-400/20 text-yellow-400 rounded">
  127. +{totalPending - 1}
  128. </span>
  129. )}
  130. <ChevronRight className="w-4 h-4 text-bambu-gray" />
  131. </div>
  132. </div>
  133. </Link>
  134. );
  135. }