ForecastPanelWiring.test.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /**
  2. * Wiring tests for ForecastPanel's inventory-changing actions: add to
  3. * shopping list, status changes, "received" creating spools via
  4. * bulkCreateSpools, remove / clear, and per-SKU settings upserts.
  5. */
  6. import { describe, it, expect, vi, beforeEach } from 'vitest';
  7. import { screen, waitFor, within } from '@testing-library/react';
  8. import userEvent from '@testing-library/user-event';
  9. import { render } from '../utils';
  10. import { ForecastPanel } from '../../components/ForecastPanel';
  11. import { api } from '../../api/client';
  12. import type { InventorySpool, ShoppingListItem } from '../../api/client';
  13. vi.mock('../../contexts/AuthContext', async (importOriginal) => {
  14. const actual = await importOriginal<typeof import('../../contexts/AuthContext')>();
  15. return {
  16. ...actual,
  17. useAuth: () => ({ hasPermission: () => true, hasAnyPermission: () => true, authEnabled: false, user: null }),
  18. };
  19. });
  20. vi.mock('../../api/client', async (importOriginal) => {
  21. const actual = await importOriginal<typeof import('../../api/client')>();
  22. return {
  23. ...actual,
  24. api: {
  25. ...actual.api,
  26. getSettings: vi.fn(),
  27. getUiSettings: vi.fn(),
  28. getAuthStatus: vi.fn(),
  29. getSkuSettings: vi.fn(),
  30. getAllUsageHistory: vi.fn(),
  31. getShoppingList: vi.fn(),
  32. addToShoppingList: vi.fn(),
  33. removeFromShoppingList: vi.fn(),
  34. clearShoppingList: vi.fn(),
  35. updateShoppingListStatus: vi.fn(),
  36. bulkCreateSpools: vi.fn(),
  37. upsertSkuSettings: vi.fn(),
  38. updateSettings: vi.fn(),
  39. },
  40. };
  41. });
  42. const mocked = api as unknown as Record<string, ReturnType<typeof vi.fn>>;
  43. const spool = (id: number, over: Partial<InventorySpool> = {}): InventorySpool => ({
  44. id,
  45. material: 'PLA',
  46. subtype: 'Matte',
  47. brand: 'Polymaker',
  48. color_name: 'Red',
  49. rgba: 'FF0000FF',
  50. label_weight: 750,
  51. core_weight: 250,
  52. core_weight_catalog_id: null,
  53. weight_used: 100,
  54. slicer_filament: null,
  55. slicer_filament_name: null,
  56. nozzle_temp_min: null,
  57. nozzle_temp_max: null,
  58. note: null,
  59. added_full: null,
  60. last_used: null,
  61. encode_time: null,
  62. tag_uid: null,
  63. tray_uuid: null,
  64. data_origin: 'manual',
  65. tag_type: null,
  66. archived_at: null,
  67. created_at: '2025-01-01T00:00:00Z',
  68. updated_at: '2025-01-01T00:00:00Z',
  69. k_profiles: [],
  70. cost_per_kg: null,
  71. last_scale_weight: null,
  72. last_weighed_at: null,
  73. weight_locked: false,
  74. category: 'Active',
  75. low_stock_threshold_pct: null,
  76. ...over,
  77. });
  78. const spools = [spool(1), spool(2)];
  79. const listItem = (over: Partial<ShoppingListItem> = {}): ShoppingListItem => ({
  80. id: 61,
  81. material: 'PLA',
  82. subtype: 'Matte',
  83. brand: 'Polymaker',
  84. color_name: 'Red',
  85. quantity_spools: 3,
  86. note: 'cheap batch',
  87. status: 'purchased',
  88. purchased_at: null,
  89. added_at: '2025-01-01T00:00:00Z',
  90. ...over,
  91. });
  92. async function openShoppingList(user: ReturnType<typeof userEvent.setup>) {
  93. await user.click(await screen.findByRole('button', { name: /Shopping List/ }));
  94. return screen.findByText('Clear all');
  95. }
  96. describe('ForecastPanel wiring', () => {
  97. beforeEach(() => {
  98. vi.clearAllMocks();
  99. mocked.getSettings.mockResolvedValue({ forecast_global_lead_time_days: 0 });
  100. mocked.getUiSettings.mockResolvedValue({ forecast_global_lead_time_days: 0 });
  101. mocked.getAuthStatus.mockResolvedValue({ auth_enabled: false, requires_setup: false });
  102. mocked.getSkuSettings.mockResolvedValue([]);
  103. mocked.getAllUsageHistory.mockResolvedValue([]);
  104. mocked.getShoppingList.mockResolvedValue([listItem()]);
  105. mocked.addToShoppingList.mockResolvedValue({});
  106. mocked.removeFromShoppingList.mockResolvedValue({ status: 'ok' });
  107. mocked.clearShoppingList.mockResolvedValue({ deleted: 1 });
  108. mocked.updateShoppingListStatus.mockResolvedValue({});
  109. mocked.bulkCreateSpools.mockResolvedValue([]);
  110. mocked.upsertSkuSettings.mockResolvedValue({});
  111. mocked.updateSettings.mockResolvedValue({});
  112. });
  113. it('marking a purchased item received creates quantity_spools spools from the item, then removes it', async () => {
  114. const user = userEvent.setup();
  115. render(<ForecastPanel spools={spools} />);
  116. await openShoppingList(user);
  117. await user.click(screen.getByTitle(/Mark as received/));
  118. await waitFor(() => expect(mocked.bulkCreateSpools).toHaveBeenCalledTimes(1));
  119. expect(mocked.updateShoppingListStatus).toHaveBeenCalledWith(61, 'received');
  120. const [base, qty] = mocked.bulkCreateSpools.mock.calls[0];
  121. expect(qty).toBe(3);
  122. expect(base).toMatchObject({
  123. material: 'PLA',
  124. subtype: 'Matte',
  125. brand: 'Polymaker',
  126. color_name: 'Red',
  127. note: 'cheap batch',
  128. // average label weight of the SKU's existing spools
  129. label_weight: 750,
  130. weight_used: 0,
  131. category: 'Stock',
  132. data_origin: 'manual',
  133. });
  134. await waitFor(() => expect(mocked.removeFromShoppingList).toHaveBeenCalledWith(61));
  135. });
  136. it('marking a pending item purchased only updates its status (no spools created)', async () => {
  137. mocked.getShoppingList.mockResolvedValue([listItem({ id: 62, status: 'pending' })]);
  138. const user = userEvent.setup();
  139. render(<ForecastPanel spools={spools} />);
  140. await openShoppingList(user);
  141. await user.click(screen.getByTitle('Mark as purchased'));
  142. await waitFor(() => expect(mocked.updateShoppingListStatus).toHaveBeenCalledWith(62, 'purchased'));
  143. expect(mocked.bulkCreateSpools).not.toHaveBeenCalled();
  144. expect(mocked.removeFromShoppingList).not.toHaveBeenCalled();
  145. });
  146. it('reset to pending sends status pending for that item', async () => {
  147. const user = userEvent.setup();
  148. render(<ForecastPanel spools={spools} />);
  149. await openShoppingList(user);
  150. await user.click(screen.getByTitle('Reset to pending'));
  151. await waitFor(() => expect(mocked.updateShoppingListStatus).toHaveBeenCalledWith(61, 'pending'));
  152. expect(mocked.bulkCreateSpools).not.toHaveBeenCalled();
  153. });
  154. it('remove deletes exactly that item id', async () => {
  155. mocked.getShoppingList.mockResolvedValue([
  156. listItem({ id: 70, color_name: 'Red' }),
  157. listItem({ id: 71, brand: 'Sunlu', color_name: 'Blue' }),
  158. ]);
  159. const user = userEvent.setup();
  160. render(<ForecastPanel spools={spools} />);
  161. await openShoppingList(user);
  162. const row = screen.getByText('Sunlu PLA Matte Blue').closest('tr') as HTMLElement;
  163. await user.click(within(row).getByTitle('Remove'));
  164. await waitFor(() => expect(mocked.removeFromShoppingList).toHaveBeenCalledTimes(1));
  165. expect(mocked.removeFromShoppingList).toHaveBeenCalledWith(71);
  166. expect(mocked.clearShoppingList).not.toHaveBeenCalled();
  167. });
  168. // BUG: "Clear all" wipes the whole shopping list on a single click
  169. // (ForecastPanel.tsx ShoppingListPanel onClear -> api.clearShoppingList with
  170. // no ConfirmModal). Every other bulk-destructive inventory action confirms.
  171. it.skip('clear all asks for confirmation before deleting the shopping list', async () => {
  172. const user = userEvent.setup();
  173. render(<ForecastPanel spools={spools} />);
  174. await openShoppingList(user);
  175. await user.click(screen.getByText('Clear all'));
  176. // Nothing may be sent before the user confirms.
  177. expect(mocked.clearShoppingList).not.toHaveBeenCalled();
  178. const cancels = screen.getAllByRole('button', { name: 'Cancel' });
  179. await user.click(cancels[cancels.length - 1]);
  180. expect(mocked.clearShoppingList).not.toHaveBeenCalled();
  181. });
  182. it('clear all sends clearShoppingList (current behaviour, no confirm)', async () => {
  183. const user = userEvent.setup();
  184. render(<ForecastPanel spools={spools} />);
  185. await openShoppingList(user);
  186. await user.click(screen.getByText('Clear all'));
  187. await waitFor(() => expect(mocked.clearShoppingList).toHaveBeenCalledTimes(1));
  188. expect(mocked.removeFromShoppingList).not.toHaveBeenCalled();
  189. });
  190. it('add to shopping list sends the SKU from the row with the entered quantity and note', async () => {
  191. mocked.getShoppingList.mockResolvedValue([]);
  192. const user = userEvent.setup();
  193. render(<ForecastPanel spools={spools} />);
  194. await user.click(await screen.findByTitle('Add to shopping list'));
  195. const qty = await screen.findByRole('spinbutton');
  196. await user.clear(qty);
  197. await user.type(qty, '4');
  198. await user.type(screen.getByPlaceholderText(/./), 'for project X');
  199. await user.click(screen.getByRole('button', { name: 'Add 4 spools' }));
  200. await waitFor(() => expect(mocked.addToShoppingList).toHaveBeenCalledTimes(1));
  201. expect(mocked.addToShoppingList).toHaveBeenCalledWith({
  202. material: 'PLA',
  203. subtype: 'Matte',
  204. brand: 'Polymaker',
  205. color_name: 'Red',
  206. quantity_spools: 4,
  207. note: 'for project X',
  208. });
  209. });
  210. it('cancelling the add-to-list dialog sends nothing', async () => {
  211. mocked.getShoppingList.mockResolvedValue([]);
  212. const user = userEvent.setup();
  213. render(<ForecastPanel spools={spools} />);
  214. await user.click(await screen.findByTitle('Add to shopping list'));
  215. await screen.findByText('Add to Shopping List');
  216. await user.click(screen.getByRole('button', { name: 'Cancel' }));
  217. await waitFor(() => expect(screen.queryByText('Add to Shopping List')).not.toBeInTheDocument());
  218. expect(mocked.addToShoppingList).not.toHaveBeenCalled();
  219. });
  220. it('SKU lead-time override save upserts the SKU settings with the new lead time', async () => {
  221. mocked.getShoppingList.mockResolvedValue([]);
  222. mocked.getSkuSettings.mockResolvedValue([
  223. {
  224. id: 5, material: 'PLA', subtype: 'Matte', brand: 'Polymaker', color_name: 'Red',
  225. lead_time_days: 3, safety_margin_value: 20, safety_margin_unit: 'g', alerts_snoozed: false,
  226. },
  227. ]);
  228. const user = userEvent.setup();
  229. render(<ForecastPanel spools={spools} />);
  230. // Expand the SKU row.
  231. await user.click(await screen.findByText('Polymaker PLA Matte Red'));
  232. const box = (await screen.findByText('Lead Time Override')).closest('div.rounded-lg') as HTMLElement;
  233. await user.click(within(box).getByRole('button'));
  234. const input = within(box).getByRole('spinbutton');
  235. await user.clear(input);
  236. await user.type(input, '12');
  237. await user.click(within(box).getByRole('button', { name: 'Save' }));
  238. await waitFor(() => expect(mocked.upsertSkuSettings).toHaveBeenCalledTimes(1));
  239. expect(mocked.upsertSkuSettings.mock.calls[0][0]).toEqual({
  240. material: 'PLA',
  241. subtype: 'Matte',
  242. brand: 'Polymaker',
  243. color_name: 'Red',
  244. lead_time_days: 12,
  245. safety_margin_value: 20,
  246. safety_margin_unit: 'g',
  247. alerts_snoozed: false,
  248. });
  249. });
  250. it('SKU lead-time edit cancelled sends nothing', async () => {
  251. mocked.getShoppingList.mockResolvedValue([]);
  252. const user = userEvent.setup();
  253. render(<ForecastPanel spools={spools} />);
  254. await user.click(await screen.findByText('Polymaker PLA Matte Red'));
  255. const box = (await screen.findByText('Lead Time Override')).closest('div.rounded-lg') as HTMLElement;
  256. await user.click(within(box).getByRole('button'));
  257. await user.type(within(box).getByRole('spinbutton'), '9');
  258. await user.click(within(box).getByRole('button', { name: 'Cancel' }));
  259. expect(mocked.upsertSkuSettings).not.toHaveBeenCalled();
  260. });
  261. });