ForecastPanelUsedUp.test.tsx 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. /**
  2. * Used-up spools still count towards a SKU's rate (#3399): an archived spool is
  3. * not stock, but one archived in the last 90 days adds what it was used for.
  4. * The backend's stock_forecast applies the same rule to the stock alerts.
  5. */
  6. import { describe, it, expect, vi, beforeEach } from 'vitest';
  7. import { screen, waitFor } from '@testing-library/react';
  8. import { render } from '../utils';
  9. import { ForecastPanel } from '../../components/ForecastPanel';
  10. import { api } from '../../api/client';
  11. import type { InventorySpool, SpoolUsageRecord } from '../../api/client';
  12. vi.mock('../../contexts/AuthContext', async (importOriginal) => {
  13. const actual = await importOriginal<typeof import('../../contexts/AuthContext')>();
  14. return {
  15. ...actual,
  16. useAuth: () => ({ hasPermission: () => true, hasAnyPermission: () => true, authEnabled: false, user: null }),
  17. };
  18. });
  19. vi.mock('../../api/client', async (importOriginal) => {
  20. const actual = await importOriginal<typeof import('../../api/client')>();
  21. return {
  22. ...actual,
  23. api: {
  24. ...actual.api,
  25. getSettings: vi.fn(),
  26. getUiSettings: vi.fn(),
  27. getAuthStatus: vi.fn(),
  28. getSkuSettings: vi.fn(),
  29. getAllUsageHistory: vi.fn(),
  30. getShoppingList: vi.fn(),
  31. addToShoppingList: vi.fn(),
  32. removeFromShoppingList: vi.fn(),
  33. clearShoppingList: vi.fn(),
  34. updateShoppingListStatus: vi.fn(),
  35. bulkCreateSpools: vi.fn(),
  36. upsertSkuSettings: vi.fn(),
  37. updateSettings: vi.fn(),
  38. },
  39. };
  40. });
  41. const mocked = api as unknown as Record<string, ReturnType<typeof vi.fn>>;
  42. const spool = (id: number, over: Partial<InventorySpool> = {}): InventorySpool => ({
  43. id,
  44. material: 'PLA',
  45. subtype: 'Matte',
  46. brand: 'Polymaker',
  47. color_name: 'Red',
  48. rgba: 'FF0000FF',
  49. label_weight: 750,
  50. core_weight: 250,
  51. core_weight_catalog_id: null,
  52. weight_used: 100,
  53. slicer_filament: null,
  54. slicer_filament_name: null,
  55. nozzle_temp_min: null,
  56. nozzle_temp_max: null,
  57. note: null,
  58. added_full: null,
  59. last_used: null,
  60. encode_time: null,
  61. tag_uid: null,
  62. tray_uuid: null,
  63. data_origin: 'manual',
  64. tag_type: null,
  65. archived_at: null,
  66. created_at: '2025-01-01T00:00:00Z',
  67. updated_at: '2025-01-01T00:00:00Z',
  68. k_profiles: [],
  69. cost_per_kg: null,
  70. last_scale_weight: null,
  71. last_weighed_at: null,
  72. weight_locked: false,
  73. category: 'Active',
  74. low_stock_threshold_pct: null,
  75. ...over,
  76. });
  77. const DAY = 86400000;
  78. const ago = (days: number) => new Date(Date.now() - days * DAY).toISOString();
  79. // The reporter's case: 16 g on the spool that is left, 900 g on one archived since
  80. // (with 100 g still on it, which is not stock).
  81. const stock = spool(1, { label_weight: 1000, weight_used: 16, created_at: ago(20) });
  82. const usedUp = (archivedDaysAgo: number) =>
  83. spool(2, { label_weight: 1000, weight_used: 900, created_at: ago(100), archived_at: ago(archivedDaysAgo) });
  84. const usage = (id: number, spoolId: number, daysAgo: number, grams: number): SpoolUsageRecord =>
  85. ({ id, spool_id: spoolId, created_at: ago(daysAgo), weight_used: grams }) as SpoolUsageRecord;
  86. describe('ForecastPanel: used-up spools (#3399)', () => {
  87. beforeEach(() => {
  88. vi.clearAllMocks();
  89. mocked.getSettings.mockResolvedValue({ forecast_global_lead_time_days: 0 });
  90. mocked.getUiSettings.mockResolvedValue({ forecast_global_lead_time_days: 0 });
  91. mocked.getAuthStatus.mockResolvedValue({ auth_enabled: false, requires_setup: false });
  92. mocked.getSkuSettings.mockResolvedValue([]);
  93. mocked.getAllUsageHistory.mockResolvedValue([]);
  94. mocked.getShoppingList.mockResolvedValue([]);
  95. });
  96. it('counts a spool archived 10 days ago towards the rate, not the stock', async () => {
  97. render(<ForecastPanel spools={[stock, usedUp(10)]} />);
  98. // 16 g plus the 800 of the 900 g that fall inside the last 90 days, over
  99. // those 90 days (#3407), not 16 g over 20.
  100. expect(await screen.findByText('9.1g/d')).toBeInTheDocument();
  101. expect(screen.getByText('984g')).toBeInTheDocument();
  102. });
  103. it('a spool archived over 90 days ago adds no grams', async () => {
  104. render(<ForecastPanel spools={[stock, usedUp(91)]} />);
  105. // But the SKU was in use before the window, so all 90 days count (#3407):
  106. // 16 g over 90, not over the 20 since the newer spool was added.
  107. expect(await screen.findByText('0.2g/d')).toBeInTheDocument();
  108. });
  109. it('does not forecast a SKU whose spools are all archived', async () => {
  110. render(<ForecastPanel spools={[usedUp(10)]} />);
  111. await waitFor(() => expect(mocked.getAllUsageHistory).toHaveBeenCalled());
  112. expect(screen.queryByText(/g\/d$/)).toBeNull();
  113. expect(screen.queryByText('Polymaker')).toBeNull();
  114. });
  115. it('uses the usage history of a recently archived spool', async () => {
  116. // The stock spool alone has one day of history, too little for a trend.
  117. mocked.getAllUsageHistory.mockResolvedValue([usage(1, 1, 2, 16), usage(2, 2, 20, 300), usage(3, 2, 10, 700)]);
  118. render(<ForecastPanel spools={[stock, usedUp(5)]} />);
  119. expect(await screen.findByText('Trend')).toBeInTheDocument();
  120. });
  121. });