BatchOrdersView.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import { useEffect, useState } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { Package, Layers, PlayCircle, XCircle, AlertTriangle, Clock, Coins } from 'lucide-react';
  4. import { api } from '../api/client';
  5. import type { PrintBatch, PrintBatchPlateProgress, Permission } from '../api/client';
  6. import { Card } from './Card';
  7. import { Button } from './Button';
  8. import { ConfirmModal } from './ConfirmModal';
  9. import { useToast } from '../contexts/ToastContext';
  10. import { formatDuration, parseUTCDate } from '../utils/date';
  11. import { getCurrencySymbol } from '../utils/currency';
  12. import { useUiSettings } from '../hooks/useUiSettings';
  13. type StatusFilter = 'active' | 'completed' | 'failed' | 'cancelled' | 'all';
  14. interface BatchOrdersViewProps {
  15. hasPermission: (p: Permission) => boolean;
  16. t: (key: string, options?: Record<string, unknown>) => string;
  17. /** A batch to scroll to and highlight (``/queue?batch=<id>``, e.g. from Bambuddy Orders). */
  18. focusBatchId?: number | null;
  19. }
  20. /**
  21. * Batch orders tab (#342).
  22. *
  23. * An order lives longer than the queue it spawned: once its runs finish they
  24. * leave the active queue entirely, so the Queue and History tabs each hold
  25. * only half the picture. This is the one place that shows what was asked for
  26. * against what has actually been produced — including the runs that failed and
  27. * are therefore still owed.
  28. */
  29. export function BatchOrdersView({ hasPermission, t, focusBatchId = null }: BatchOrdersViewProps) {
  30. const queryClient = useQueryClient();
  31. const { showToast } = useToast();
  32. // A linked batch may be finished or cancelled: show every status so it's there.
  33. const [statusFilter, setStatusFilter] = useState<StatusFilter>(focusBatchId ? 'all' : 'active');
  34. const [cancelTarget, setCancelTarget] = useState<PrintBatch | null>(null);
  35. const { data: settings } = useUiSettings();
  36. const currency = getCurrencySymbol(settings?.currency || 'USD');
  37. const { data: batches, isLoading } = useQuery({
  38. queryKey: ['batches', statusFilter],
  39. queryFn: () => api.getBatches(statusFilter === 'all' ? undefined : statusFilter),
  40. });
  41. const focusFound = focusBatchId != null && !!batches?.some((b) => b.id === focusBatchId);
  42. useEffect(() => {
  43. if (focusFound) document.getElementById(`batch-${focusBatchId}`)?.scrollIntoView({ block: 'center' });
  44. }, [focusFound, focusBatchId]);
  45. const invalidate = () => {
  46. queryClient.invalidateQueries({ queryKey: ['batches'] });
  47. queryClient.invalidateQueries({ queryKey: ['queue'] });
  48. };
  49. const dispatchMutation = useMutation({
  50. mutationFn: ({ id, plateId }: { id: number; plateId?: number | null }) =>
  51. api.dispatchBatch(id, plateId !== undefined ? { plate_id: plateId, only_plate: true } : {}),
  52. onSuccess: (batch) => {
  53. invalidate();
  54. showToast(t('queue.batchOrders.dispatched', { name: batch.name }), 'success');
  55. },
  56. onError: (error: Error) => showToast(error.message, 'error'),
  57. });
  58. const cancelMutation = useMutation({
  59. mutationFn: (id: number) => api.cancelBatch(id),
  60. onSuccess: () => {
  61. invalidate();
  62. setCancelTarget(null);
  63. showToast(t('queue.batchCancelled'), 'success');
  64. },
  65. onError: (error: Error) => showToast(error.message, 'error'),
  66. });
  67. const canDispatch = hasPermission('queue:create' as Permission);
  68. const canCancel = hasPermission('queue:delete_all' as Permission);
  69. const filters: StatusFilter[] = ['active', 'completed', 'failed', 'cancelled', 'all'];
  70. return (
  71. <div>
  72. <div className="flex flex-wrap items-center gap-2 mb-4">
  73. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  74. <h2 className="text-base sm:text-lg font-semibold text-white">{t('queue.batchOrders.title')}</h2>
  75. <div className="flex gap-1 ml-auto">
  76. {filters.map((value) => (
  77. <button
  78. key={value}
  79. type="button"
  80. onClick={() => setStatusFilter(value)}
  81. className={`text-xs px-2.5 py-1 rounded-full border transition-colors ${
  82. statusFilter === value
  83. ? 'border-bambu-green bg-bambu-green/10 text-bambu-green'
  84. : 'border-bambu-dark-tertiary text-bambu-gray hover:border-bambu-gray'
  85. }`}
  86. >
  87. {t(`queue.batchOrders.filter.${value}`)}
  88. </button>
  89. ))}
  90. </div>
  91. </div>
  92. {isLoading ? (
  93. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  94. ) : !batches?.length ? (
  95. <Card className="p-12 text-center border-dashed">
  96. <Package className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  97. <h3 className="text-xl font-medium text-white mb-2">{t('queue.batchOrders.emptyTitle')}</h3>
  98. <p className="text-bambu-gray max-w-md mx-auto">{t('queue.batchOrders.emptyDescription')}</p>
  99. </Card>
  100. ) : (
  101. <div className="space-y-4">
  102. {batches.map((batch) => (
  103. <BatchOrderCard
  104. key={batch.id}
  105. batch={batch}
  106. currency={currency}
  107. canDispatch={canDispatch}
  108. canCancel={canCancel}
  109. isDispatching={dispatchMutation.isPending && dispatchMutation.variables?.id === batch.id}
  110. highlighted={batch.id === focusBatchId}
  111. onDispatch={(plateId) => dispatchMutation.mutate({ id: batch.id, plateId })}
  112. onCancel={() => setCancelTarget(batch)}
  113. t={t}
  114. />
  115. ))}
  116. </div>
  117. )}
  118. {cancelTarget && (
  119. <ConfirmModal
  120. title={t('queue.cancelBatchConfirmTitle')}
  121. message={t('queue.cancelBatchConfirmMessage')}
  122. confirmText={t('queue.cancelBatch')}
  123. variant="warning"
  124. onConfirm={() => cancelMutation.mutate(cancelTarget.id)}
  125. onCancel={() => setCancelTarget(null)}
  126. />
  127. )}
  128. </div>
  129. );
  130. }
  131. const STATUS_STYLES: Record<string, string> = {
  132. active: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-300',
  133. completed: 'bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-300',
  134. cancelled: 'bg-bambu-dark-tertiary text-bambu-gray',
  135. // A grouping whose jobs ended in failures with nothing printed.
  136. failed: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-300',
  137. };
  138. function BatchOrderCard({
  139. batch,
  140. currency,
  141. canDispatch,
  142. canCancel,
  143. isDispatching,
  144. onDispatch,
  145. onCancel,
  146. t,
  147. highlighted = false,
  148. }: {
  149. batch: PrintBatch;
  150. currency: string;
  151. canDispatch: boolean;
  152. canCancel: boolean;
  153. isDispatching: boolean;
  154. onDispatch: (plateId?: number | null) => void;
  155. onCancel: () => void;
  156. t: (key: string, options?: Record<string, unknown>) => string;
  157. highlighted?: boolean;
  158. }) {
  159. // Progress is measured against the target, not against what was queued —
  160. // that is the whole difference between an order and a grouping.
  161. const denominator = batch.has_targets ? batch.target_count : batch.completed_count + batch.pending_count
  162. + batch.printing_count + batch.failed_count;
  163. const percent = denominator > 0 ? Math.round((batch.completed_count / denominator) * 100) : 0;
  164. // Runs the order owes that nothing can produce any more: their plate's last
  165. // queue item was deleted, so there is no configuration left to clone (#2960).
  166. const strandedCount = batch.has_targets ? batch.remaining_count - batch.dispatchable_count : 0;
  167. const dueDate = batch.due_date ? parseUTCDate(batch.due_date) : null;
  168. const isOverdue = dueDate != null && batch.status === 'active' && dueDate.getTime() < Date.now();
  169. return (
  170. <Card id={`batch-${batch.id}`} className={`p-4 ${highlighted ? 'ring-2 ring-bambu-green' : ''}`}>
  171. <div className="flex flex-wrap items-start gap-3 mb-3">
  172. <div className="min-w-0 flex-1">
  173. <div className="flex items-center gap-2 flex-wrap">
  174. <p className="text-white font-medium truncate">{batch.name}</p>
  175. <span className={`text-xs px-2 py-0.5 rounded-full ${STATUS_STYLES[batch.status] ?? STATUS_STYLES.cancelled}`}>
  176. {t(`queue.batchOrders.status.${batch.status}`)}
  177. </span>
  178. {!batch.has_targets && (
  179. <span
  180. className="text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray"
  181. title={t('queue.batchOrders.noTargetsHint')}
  182. >
  183. {t('queue.batchOrders.noTargets')}
  184. </span>
  185. )}
  186. </div>
  187. <p className="text-xs text-bambu-gray mt-1">
  188. {batch.created_by_username
  189. ? t('queue.addedBy', { name: batch.created_by_username })
  190. : null}
  191. {dueDate && (
  192. <span className={isOverdue ? 'text-orange-600 dark:text-orange-400' : ''}>
  193. {batch.created_by_username ? ' • ' : ''}
  194. {t('queue.batchOrders.due', { date: dueDate.toLocaleDateString() })}
  195. </span>
  196. )}
  197. </p>
  198. {batch.notes && <p className="text-xs text-bambu-gray mt-1 whitespace-pre-wrap">{batch.notes}</p>}
  199. </div>
  200. <div className="flex items-center gap-2 flex-shrink-0">
  201. {batch.has_targets && batch.dispatchable_count > 0 && batch.status !== 'cancelled' && canDispatch && (
  202. <Button variant="primary" size="sm" onClick={() => onDispatch()} disabled={isDispatching}>
  203. <PlayCircle className="w-4 h-4 mr-1" />
  204. {t('queue.batchOrders.dispatchRemaining', { count: batch.dispatchable_count })}
  205. </Button>
  206. )}
  207. {/* Cancel is the only way to close an order out, so it must not be
  208. gated on there being pending items to cancel: an order whose runs
  209. were all deleted has none, and is exactly the one that needs
  210. closing (#2960). */}
  211. {batch.status === 'active' && canCancel && (
  212. <Button variant="ghost" size="sm" onClick={onCancel}>
  213. <XCircle className="w-4 h-4 mr-1" />
  214. {t('queue.cancelBatch')}
  215. </Button>
  216. )}
  217. </div>
  218. </div>
  219. <div className="flex items-center gap-3 mb-2">
  220. <div className="flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden">
  221. <div
  222. className={`h-full rounded-full transition-all ${
  223. batch.status === 'completed' ? 'bg-bambu-green' : batch.status === 'failed' ? 'bg-red-500' : 'bg-blue-500'
  224. }`}
  225. style={{ width: `${Math.min(100, percent)}%` }}
  226. />
  227. </div>
  228. <span className="text-xs text-bambu-gray whitespace-nowrap tabular-nums">
  229. {t('queue.batchProgress', { completed: batch.completed_count, total: denominator })}
  230. </span>
  231. </div>
  232. <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-bambu-gray mb-1">
  233. {batch.printing_count > 0 && <span>{t('queue.batchOrders.printing', { count: batch.printing_count })}</span>}
  234. {batch.pending_count > 0 && <span>{t('queue.batch.pendingCount', { count: batch.pending_count })}</span>}
  235. {batch.failed_count > 0 && (
  236. <span className="text-orange-600 dark:text-orange-400 flex items-center gap-1">
  237. <AlertTriangle className="w-3 h-3" />
  238. {t('queue.batchOrders.failed', { count: batch.failed_count })}
  239. </span>
  240. )}
  241. {batch.has_targets && batch.remaining_count > 0 && (
  242. <span>{t('queue.batchOrders.remaining', { count: batch.remaining_count })}</span>
  243. )}
  244. {batch.print_time_seconds > 0 && (
  245. <span className="flex items-center gap-1">
  246. <Clock className="w-3 h-3" />
  247. {formatDuration(batch.print_time_seconds)}
  248. </span>
  249. )}
  250. {batch.actual_cost != null && (
  251. <span className="flex items-center gap-1">
  252. <Coins className="w-3 h-3" />
  253. <span>
  254. {t('queue.batchOrders.costSoFar', {
  255. amount: `${currency} ${batch.actual_cost.toFixed(2)}`,
  256. })}
  257. </span>
  258. {batch.estimated_remaining_cost != null && batch.estimated_remaining_cost > 0 && (
  259. <span>
  260. {t('queue.batchOrders.costRemaining', {
  261. amount: `${currency} ${batch.estimated_remaining_cost.toFixed(2)}`,
  262. })}
  263. </span>
  264. )}
  265. </span>
  266. )}
  267. </div>
  268. {strandedCount > 0 && batch.status !== 'cancelled' && (
  269. <p className="flex items-start gap-1.5 text-xs text-orange-600 dark:text-orange-400 mb-1">
  270. <AlertTriangle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  271. <span>{t('queue.batchOrders.strandedNotice', { runs: strandedCount, owed: batch.remaining_count })}</span>
  272. </p>
  273. )}
  274. {batch.has_targets && batch.plates.length > 0 && (
  275. <div className="mt-3 border-t border-bambu-dark-tertiary pt-3 space-y-1.5">
  276. {batch.plates.map((plate) => (
  277. <PlateRow
  278. key={`${plate.plate_id ?? 'file'}`}
  279. plate={plate}
  280. batchStatus={batch.status}
  281. currency={currency}
  282. canDispatch={canDispatch}
  283. isDispatching={isDispatching}
  284. onDispatch={() => onDispatch(plate.plate_id)}
  285. t={t}
  286. />
  287. ))}
  288. </div>
  289. )}
  290. </Card>
  291. );
  292. }
  293. function PlateRow({
  294. plate,
  295. batchStatus,
  296. currency,
  297. canDispatch,
  298. isDispatching,
  299. onDispatch,
  300. t,
  301. }: {
  302. plate: PrintBatchPlateProgress;
  303. batchStatus: string;
  304. currency: string;
  305. canDispatch: boolean;
  306. isDispatching: boolean;
  307. onDispatch: () => void;
  308. t: (key: string, options?: Record<string, unknown>) => string;
  309. }) {
  310. const label = plate.plate_name
  311. || (plate.plate_id != null ? t('queue.plateNumber', { index: plate.plate_id }) : t('queue.batchOrders.wholeFile'));
  312. return (
  313. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
  314. <Layers className="w-3.5 h-3.5 text-bambu-gray flex-shrink-0" />
  315. <span className="text-white min-w-0 truncate">{label}</span>
  316. <span className="text-bambu-gray tabular-nums">
  317. {t('queue.batchOrders.plateProgress', {
  318. completed: plate.completed_count,
  319. target: plate.quantity_target,
  320. })}
  321. </span>
  322. {plate.failed_count > 0 && (
  323. <span className="text-orange-600 dark:text-orange-400">
  324. {t('queue.batchOrders.failed', { count: plate.failed_count })}
  325. </span>
  326. )}
  327. {plate.actual_cost != null && (
  328. <span className="text-bambu-gray tabular-nums">{`${currency} ${plate.actual_cost.toFixed(2)}`}</span>
  329. )}
  330. {plate.remaining > 0 && batchStatus !== 'cancelled' && (
  331. <span className="ml-auto flex items-center gap-2">
  332. <span className="text-bambu-gray">
  333. {t('queue.batchOrders.remaining', { count: plate.remaining })}
  334. </span>
  335. {!plate.can_dispatch ? (
  336. <span className="text-orange-600 dark:text-orange-400">
  337. {t('queue.batchOrders.strandedPlate')}
  338. </span>
  339. ) : (
  340. canDispatch && (
  341. <button
  342. type="button"
  343. onClick={onDispatch}
  344. disabled={isDispatching}
  345. className="text-bambu-green hover:underline disabled:opacity-50"
  346. >
  347. {t('queue.batchOrders.dispatchPlate')}
  348. </button>
  349. )
  350. )}
  351. </span>
  352. )}
  353. </div>
  354. );
  355. }