@openmrs/esm-stock-management-app 3.3.2-pre.447 → 3.3.2-pre.458

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/228.js +3 -3
  2. package/dist/228.js.map +1 -1
  3. package/dist/5117.js +1 -1
  4. package/dist/5117.js.map +1 -1
  5. package/dist/8071.js +1 -1
  6. package/dist/8071.js.map +1 -1
  7. package/dist/8359.js +1 -1
  8. package/dist/8359.js.map +1 -1
  9. package/dist/openmrs-esm-stock-management-app.js +1 -1
  10. package/dist/routes.json +1 -1
  11. package/package.json +1 -1
  12. package/src/core/api/types/stockOperation/StockOperationType.ts +0 -12
  13. package/src/stock-operations/stock-operations-forms/hooks/useStockItemBatchNumbers.test.ts +29 -0
  14. package/src/stock-operations/stock-operations-forms/hooks/useStockItemBatchNumbers.ts +6 -2
  15. package/src/stock-operations/stock-operations-forms/input-components/batch-no-selector.component.tsx +51 -17
  16. package/src/stock-operations/stock-operations-forms/input-components/batch-no-selector.test.tsx +325 -3
  17. package/src/stock-operations/stock-operations-forms/step2.test.tsx +1 -0
  18. package/src/stock-operations/stock-operations-forms/step3.test.tsx +1 -0
  19. package/src/stock-operations/stock-operations-forms/steps/stock-availability-cell.component.tsx +9 -7
  20. package/src/stock-operations/stock-operations-forms/steps/stock-availability-cell.test.tsx +3 -3
  21. package/src/stock-operations/stock-operations-forms/steps/stock-operation-items-form-step.component.tsx +25 -19
  22. package/src/stock-operations/stock-operations-forms/steps/stock-operation-items-form-step.test.tsx +139 -0
  23. package/src/stock-operations/stock-operations-forms/stock-item-form/stock-item-form.test.tsx +57 -0
  24. package/src/stock-operations/stock-operations-forms/stock-item-form/stock-item-form.workspace.tsx +15 -1
  25. package/src/stock-operations/stock-operations-forms/stock-operation-form.component.tsx +1 -0
  26. package/src/stock-operations/stock-operations-forms/stock-operation-form.test.tsx +28 -5
  27. package/translations/en.json +2 -0
  28. package/translations/ru_RU.json +22 -0
  29. package/src/core/api/types/stockOperation/StockOperationType.test.ts +0 -24
package/dist/routes.json CHANGED
@@ -1 +1 @@
1
- {"$schema":"https://json.openmrs.org/routes.schema.json","backendDependencies":{"fhir2":">=1.2","webservices.rest":">=2.2.0"},"extensions":[{"name":"stock-nav-menu","slot":"stock-sidebar-slot","component":"stockNavMenu","online":true,"offline":true},{"name":"overview-db-link","slot":"stock-page-dashboard-slot","component":"stockOverviewLink","meta":{"name":"overview","slot":"overview-dashboard-slot","title":"overview"},"order":0,"online":true,"offline":true},{"name":"stock-overview-db","slot":"overview-dashboard-slot","component":"stockOverview"},{"name":"operations-db-link","slot":"stock-page-dashboard-slot","component":"stockOperationsLink","meta":{"name":"operations","slot":"operations-dashboard-slot","title":"operations"},"order":2,"online":true,"offline":true},{"name":"stock-operations-db","slot":"operations-dashboard-slot","component":"stockOperations"},{"name":"items-db-link","slot":"stock-page-dashboard-slot","component":"stockItemsLink","meta":{"name":"items","slot":"items-dashboard-slot","title":"items"},"order":1,"online":true,"offline":true},{"name":"stock-items-db","slot":"items-dashboard-slot","component":"stockItems"},{"name":"user-scopes-db-link","slot":"stock-page-dashboard-slot","component":"stockUserScopesLink","meta":{"name":"user-scopes","slot":"user-scopes-dashboard-slot","title":"user-scopes"},"order":3,"online":true,"offline":true},{"name":"stock-user-scopes-db","slot":"user-scopes-dashboard-slot","component":"stockUserScopes"},{"name":"sources-db-link","slot":"stock-page-dashboard-slot","component":"stockSourcesLink","meta":{"name":"sources","slot":"sources-dashboard-slot","title":"Sources"},"order":2,"online":true,"offline":true},{"name":"stock-sources-db","slot":"sources-dashboard-slot","component":"stockSources"},{"name":"reports-db-link","slot":"stock-page-dashboard-slot","component":"stockReportsLink","meta":{"name":"reports","slot":"reports-dashboard-slot","title":"Reports"},"order":5,"privileges":"App: stockmanagement.reports","online":true,"offline":true},{"name":"stock-reports-db","slot":"reports-dashboard-slot","component":"stockReports"},{"name":"stock-management-admin-card-link","slot":"system-admin-page-card-link-slot","component":"stockManagementAdminCardLink"},{"name":"stock-management-app-menu-item","component":"stockManagementAppMenuItem","slot":"app-menu-slot","meta":{"name":"Stock Management"}},{"name":"delete-packaging-unit-button","component":"deletePackagingUnitButton"}],"modals":[{"name":"delete-stock-modal","component":"deleteStockModal"},{"name":"delete-stock-user-scope-modal","component":"deleteUserScopeModal"},{"name":"delete-stock-rule-modal","component":"deleteStockRuleModal"},{"name":"delete-packaging-unit-modal","component":"deletePackagingUnitModal"},{"name":"expired-stock-modal","component":"expiredStockModal"},{"name":"import-bulk-stock-items","component":"importBulkStockItemsModal"},{"name":"issuing-stock-modal","component":"issuingStockModal"},{"name":"receiving-stock-modal","component":"receivingStockModal"},{"name":"stock-operations-modal","component":"stockOperationsModal"},{"name":"transactions-print-bincard-preview-modal","component":"transactionBincardPrintPreviewModal"},{"name":"transactions-print-stockcard-preview-modal","component":"transactionStockcardPrintPreviewModal"},{"name":"stock-create-location-modal","component":"createLocationModal"}],"workspaceGroups2":[{"name":"stock-management-group","overlay":true}],"workspaceWindows2":[{"name":"stock-operation-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-item-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-sources-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-user-role-scopes-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-reports-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"}],"workspaces2":[{"name":"stock-operation-form-workspace","component":"stockOperationFormWorkspace","window":"stock-operation-form-window"},{"name":"stock-item-form-workspace","component":"stockItemFormWorkspace","window":"stock-item-form-window"},{"name":"stock-item-rules-form-workspace","component":"stockItemRulesFormWorkspace","window":"stock-item-form-window"},{"name":"stock-sources-form-workspace","component":"stockSourcesFormWorkspace","window":"stock-sources-form-window"},{"name":"stock-user-role-scopes-form-workspace","component":"stockUserScopesFormWorkspace","window":"stock-user-role-scopes-form-window"},{"name":"stock-reports-form-workspace","component":"stockReportsFormWorkspace","window":"stock-reports-form-window"}],"pages":[{"component":"root","route":"stock-management"}],"version":"3.3.2-pre.447"}
1
+ {"$schema":"https://json.openmrs.org/routes.schema.json","backendDependencies":{"fhir2":">=1.2","webservices.rest":">=2.2.0"},"extensions":[{"name":"stock-nav-menu","slot":"stock-sidebar-slot","component":"stockNavMenu","online":true,"offline":true},{"name":"overview-db-link","slot":"stock-page-dashboard-slot","component":"stockOverviewLink","meta":{"name":"overview","slot":"overview-dashboard-slot","title":"overview"},"order":0,"online":true,"offline":true},{"name":"stock-overview-db","slot":"overview-dashboard-slot","component":"stockOverview"},{"name":"operations-db-link","slot":"stock-page-dashboard-slot","component":"stockOperationsLink","meta":{"name":"operations","slot":"operations-dashboard-slot","title":"operations"},"order":2,"online":true,"offline":true},{"name":"stock-operations-db","slot":"operations-dashboard-slot","component":"stockOperations"},{"name":"items-db-link","slot":"stock-page-dashboard-slot","component":"stockItemsLink","meta":{"name":"items","slot":"items-dashboard-slot","title":"items"},"order":1,"online":true,"offline":true},{"name":"stock-items-db","slot":"items-dashboard-slot","component":"stockItems"},{"name":"user-scopes-db-link","slot":"stock-page-dashboard-slot","component":"stockUserScopesLink","meta":{"name":"user-scopes","slot":"user-scopes-dashboard-slot","title":"user-scopes"},"order":3,"online":true,"offline":true},{"name":"stock-user-scopes-db","slot":"user-scopes-dashboard-slot","component":"stockUserScopes"},{"name":"sources-db-link","slot":"stock-page-dashboard-slot","component":"stockSourcesLink","meta":{"name":"sources","slot":"sources-dashboard-slot","title":"Sources"},"order":2,"online":true,"offline":true},{"name":"stock-sources-db","slot":"sources-dashboard-slot","component":"stockSources"},{"name":"reports-db-link","slot":"stock-page-dashboard-slot","component":"stockReportsLink","meta":{"name":"reports","slot":"reports-dashboard-slot","title":"Reports"},"order":5,"privileges":"App: stockmanagement.reports","online":true,"offline":true},{"name":"stock-reports-db","slot":"reports-dashboard-slot","component":"stockReports"},{"name":"stock-management-admin-card-link","slot":"system-admin-page-card-link-slot","component":"stockManagementAdminCardLink"},{"name":"stock-management-app-menu-item","component":"stockManagementAppMenuItem","slot":"app-menu-slot","meta":{"name":"Stock Management"}},{"name":"delete-packaging-unit-button","component":"deletePackagingUnitButton"}],"modals":[{"name":"delete-stock-modal","component":"deleteStockModal"},{"name":"delete-stock-user-scope-modal","component":"deleteUserScopeModal"},{"name":"delete-stock-rule-modal","component":"deleteStockRuleModal"},{"name":"delete-packaging-unit-modal","component":"deletePackagingUnitModal"},{"name":"expired-stock-modal","component":"expiredStockModal"},{"name":"import-bulk-stock-items","component":"importBulkStockItemsModal"},{"name":"issuing-stock-modal","component":"issuingStockModal"},{"name":"receiving-stock-modal","component":"receivingStockModal"},{"name":"stock-operations-modal","component":"stockOperationsModal"},{"name":"transactions-print-bincard-preview-modal","component":"transactionBincardPrintPreviewModal"},{"name":"transactions-print-stockcard-preview-modal","component":"transactionStockcardPrintPreviewModal"},{"name":"stock-create-location-modal","component":"createLocationModal"}],"workspaceGroups2":[{"name":"stock-management-group","overlay":true}],"workspaceWindows2":[{"name":"stock-operation-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-item-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-sources-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-user-role-scopes-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"},{"name":"stock-reports-form-window","group":"stock-management-group","canMaximize":true,"width":"extra-wide"}],"workspaces2":[{"name":"stock-operation-form-workspace","component":"stockOperationFormWorkspace","window":"stock-operation-form-window"},{"name":"stock-item-form-workspace","component":"stockItemFormWorkspace","window":"stock-item-form-window"},{"name":"stock-item-rules-form-workspace","component":"stockItemRulesFormWorkspace","window":"stock-item-form-window"},{"name":"stock-sources-form-workspace","component":"stockSourcesFormWorkspace","window":"stock-sources-form-window"},{"name":"stock-user-role-scopes-form-workspace","component":"stockUserScopesFormWorkspace","window":"stock-user-role-scopes-form-window"},{"name":"stock-reports-form-workspace","component":"stockReportsFormWorkspace","window":"stock-reports-form-window"}],"pages":[{"component":"root","route":"stock-management"}],"version":"3.3.2-pre.458"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openmrs/esm-stock-management-app",
3
- "version": "3.3.2-pre.447",
3
+ "version": "3.3.2-pre.458",
4
4
  "license": "MPL-2.0",
5
5
  "description": "Stock management microfrontend for OpenMRS 3.x",
6
6
  "browser": "dist/openmrs-esm-stock-management-app.js",
@@ -123,15 +123,3 @@ export const StockOperationTypeIsStockIssue = (operationType: OperationType) =>
123
123
  export const StockOperationPrintHasItemCosts = (operationType: OperationType) => {
124
124
  return StockOperationTypeIsStockIssue(operationType) || StockOperationTypeIsTransferOut(operationType);
125
125
  };
126
-
127
- // Operations where the source is a location the stock is taken from or adjusted at,
128
- // so "available" should be scoped to it. For a Receipt the source is a supplier.
129
- export const StockOperationTypeTakesStockFromSource = (operationType?: OperationType) => {
130
- return (
131
- operationType === OperationType.TRANSFER_OUT_OPERATION_TYPE ||
132
- operationType === OperationType.STOCK_ISSUE_OPERATION_TYPE ||
133
- operationType === OperationType.DISPOSED_OPERATION_TYPE ||
134
- operationType === OperationType.ADJUSTMENT_OPERATION_TYPE ||
135
- operationType === OperationType.STOCK_TAKE_OPERATION_TYPE
136
- );
137
- };
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { renderHook } from '@testing-library/react';
3
+ import { useStockBatches } from '../../../stock-items/stock-items.resource';
4
+ import { useStockItemBatchNumbers } from './useStockItemBatchNumbers';
5
+
6
+ vi.mock('../../../stock-items/stock-items.resource', () => ({
7
+ useStockBatches: vi.fn().mockReturnValue({ items: { results: [] }, isLoading: false, error: null }),
8
+ }));
9
+
10
+ const mockUseStockBatches = vi.mocked(useStockBatches);
11
+
12
+ describe('useStockItemBatchNumbers', () => {
13
+ it('asks stockbatch to leave out expired batches when told to', () => {
14
+ renderHook(() => useStockItemBatchNumbers('item-uuid', true));
15
+
16
+ expect(mockUseStockBatches).toHaveBeenLastCalledWith(
17
+ expect.objectContaining({ stockItemUuid: 'item-uuid', excludeExpired: true }),
18
+ );
19
+ });
20
+
21
+ it("returns the batch request's error", () => {
22
+ const error = new Error('Forbidden');
23
+ mockUseStockBatches.mockReturnValue({ items: {}, isLoading: false, error } as ReturnType<typeof useStockBatches>);
24
+
25
+ const { result } = renderHook(() => useStockItemBatchNumbers('item-uuid'));
26
+
27
+ expect(result.current.error).toBe(error);
28
+ });
29
+ });
@@ -2,17 +2,19 @@ import { useEffect, useState } from 'react';
2
2
  import { ResourceRepresentation } from '../../../core/api/api';
3
3
  import { type StockBatchFilter, useStockBatches } from '../../../stock-items/stock-items.resource';
4
4
 
5
- export function useStockItemBatchNumbers(stockItemUuid: string) {
5
+ export function useStockItemBatchNumbers(stockItemUuid: string, excludeExpired = false) {
6
6
  const [conceptFilter, setConceptFilter] = useState<StockBatchFilter>({
7
7
  v: ResourceRepresentation.Default,
8
8
  limit: 10,
9
9
  startIndex: 0,
10
10
  stockItemUuid,
11
+ excludeExpired: excludeExpired || undefined,
11
12
  });
12
13
 
13
14
  const {
14
15
  items: { results: stockItemBatchNos },
15
16
  isLoading,
17
+ error,
16
18
  } = useStockBatches(conceptFilter);
17
19
 
18
20
  const [searchString, setSearchString] = useState(null);
@@ -28,8 +30,9 @@ export function useStockItemBatchNumbers(stockItemUuid: string) {
28
30
  limit: limit,
29
31
  q: searchString,
30
32
  stockItemUuid,
33
+ excludeExpired: excludeExpired || undefined,
31
34
  });
32
- }, [searchString, limit, representation, stockItemUuid]);
35
+ }, [searchString, limit, representation, stockItemUuid, excludeExpired]);
33
36
 
34
37
  return {
35
38
  stockItemBatchNos,
@@ -37,5 +40,6 @@ export function useStockItemBatchNumbers(stockItemUuid: string) {
37
40
  setRepresentation,
38
41
  setSearchString,
39
42
  isLoading,
43
+ error,
40
44
  };
41
45
  }
@@ -2,13 +2,18 @@ import React, { useCallback, useEffect, useMemo } from 'react';
2
2
  import { useTranslation } from 'react-i18next';
3
3
  import { ComboBox, SelectSkeleton } from '@carbon/react';
4
4
  import { type StockBatchWithUoM } from '../../../core/api/types/stockItem/StockBatchDTO';
5
- import { formatForDatePicker } from '../../../constants';
5
+ import { APP_STOCKMANAGEMENT_STOCKITEMS, formatForDatePicker } from '../../../constants';
6
6
  import { parseStockExpiryDate } from '../../expiry-date.utils';
7
7
  import { useStockItemBatchInformationHook } from '../../../stock-items/add-stock-item/batch-information/batch-information.resource';
8
+ import { useStockManagementSession } from '../../../stock-lookups/stock-lookups.resource';
8
9
  import { useStockItemBatchNumbers } from '../hooks/useStockItemBatchNumbers';
9
10
 
10
11
  interface BatchNoSelectorProps {
11
12
  stockItemUuid: string;
13
+ /** The party the stock is drawn from. Only batches with stock there are listed. */
14
+ partyUuid?: string;
15
+ /** Also list batches with no stock at the party, for operations that correct a recorded balance. */
16
+ includeEmptyBatches?: boolean;
12
17
  /** Also list expired batches that have stock, for operation types that allow them (Disposal on the RefApp). */
13
18
  includeExpiredBatches?: boolean;
14
19
  initialValue?: string;
@@ -18,48 +23,72 @@ interface BatchNoSelectorProps {
18
23
 
19
24
  const BatchNoSelector: React.FC<BatchNoSelectorProps> = ({
20
25
  stockItemUuid,
26
+ partyUuid,
27
+ includeEmptyBatches = false,
21
28
  includeExpiredBatches = false,
22
29
  error,
23
30
  initialValue,
24
31
  onValueChange,
25
32
  }) => {
26
- const { isLoading, stockItemBatchNos } = useStockItemBatchNumbers(stockItemUuid);
33
+ // Unless expired batches are asked for, inventory leaves them out, so an expired batch would show
34
+ // here with no stock at all.
35
+ const {
36
+ isLoading,
37
+ stockItemBatchNos,
38
+ error: batchesError,
39
+ } = useStockItemBatchNumbers(stockItemUuid, includeEmptyBatches && !includeExpiredBatches);
27
40
  const { t } = useTranslation();
28
41
  const {
29
42
  items,
30
43
  setStockItemUuid,
44
+ setPartyUuid,
31
45
  isLoading: isLoadingBatchinfo,
32
- } = useStockItemBatchInformationHook({ excludeExpired: includeExpiredBatches ? false : undefined });
46
+ error: inventoryError,
47
+ } = useStockItemBatchInformationHook({ partyUuid, excludeExpired: includeExpiredBatches ? false : undefined });
33
48
 
34
49
  useEffect(() => {
35
50
  setStockItemUuid(stockItemUuid);
36
51
  }, [stockItemUuid, setStockItemUuid]);
37
52
 
53
+ useEffect(() => {
54
+ setPartyUuid(partyUuid);
55
+ }, [partyUuid, setPartyUuid]);
56
+
57
+ // Inventory leaves out stock the user can't see, so only call a batch empty where they can see the stock.
58
+ const { privilegeScopes } = useStockManagementSession();
59
+ const canSeeStock = privilegeScopes?.some(
60
+ (scope) => scope.partyUuid === partyUuid && scope.privilege === APP_STOCKMANAGEMENT_STOCKITEMS,
61
+ );
62
+
38
63
  const stockItemBatchesInfo = useMemo(() => {
39
- if (!stockItemBatchNos) return [];
64
+ // Without the inventory every quantity is unknown, so list no batches rather than show them as empty.
65
+ if (!stockItemBatchNos || inventoryError) return [];
40
66
 
41
67
  return stockItemBatchNos.map((item) => {
42
- const matchingBatch = items?.find((batch) => batch.batchNumber === item.batchNo);
43
-
44
- return matchingBatch
45
- ? ({
46
- ...item,
47
- ...matchingBatch,
48
- quantity: String(matchingBatch.quantity),
49
- } as StockBatchWithUoM)
50
- : (item as StockBatchWithUoM);
68
+ const matchingBatch = items?.find((batch) => batch.stockBatchUuid === item.uuid);
69
+
70
+ if (matchingBatch) {
71
+ return {
72
+ ...item,
73
+ ...matchingBatch,
74
+ quantity: String(matchingBatch.quantity),
75
+ } as StockBatchWithUoM;
76
+ }
77
+
78
+ return (includeEmptyBatches && canSeeStock ? { ...item, quantity: '0' } : item) as StockBatchWithUoM;
51
79
  });
52
- }, [stockItemBatchNos, items]);
80
+ }, [stockItemBatchNos, items, includeEmptyBatches, inventoryError, canSeeStock]);
53
81
 
54
82
  const filteredBatches = useMemo(() => {
55
83
  if (!stockItemBatchesInfo) return [];
84
+ if (includeEmptyBatches) return stockItemBatchesInfo;
56
85
 
57
86
  return stockItemBatchesInfo.filter((batch) => {
58
87
  const quantity = typeof batch.quantity === 'string' ? parseFloat(batch.quantity) : batch.quantity;
59
88
 
60
89
  return !isNaN(quantity) && quantity > 0;
61
90
  });
62
- }, [stockItemBatchesInfo]);
91
+ }, [stockItemBatchesInfo, includeEmptyBatches]);
63
92
 
64
93
  const initialSelectedItem = useMemo(
65
94
  () => filteredBatches.find((batch) => batch.uuid === initialValue) ?? null,
@@ -116,8 +145,13 @@ const BatchNoSelector: React.FC<BatchNoSelectorProps> = ({
116
145
  return (
117
146
  <ComboBox
118
147
  id="stockBatchUuid"
119
- invalid={!!error}
120
- invalidText={error}
148
+ invalid={!!error || !!batchesError || !!inventoryError}
149
+ invalidText={
150
+ error ||
151
+ (batchesError
152
+ ? t('batchesLoadError', "Couldn't load this item's batches")
153
+ : t('batchQuantitiesLoadError', "Couldn't load the stock held at this location"))
154
+ }
121
155
  items={filteredBatches}
122
156
  itemToString={itemToString}
123
157
  name="stockBatchUuid"
@@ -4,8 +4,14 @@ import userEvent from '@testing-library/user-event';
4
4
  import { render, screen } from '@testing-library/react';
5
5
  import { type StockBatchDTO } from '../../../core/api/types/stockItem/StockBatchDTO';
6
6
  import { type StockItemInventory } from '../../../core/api/types/stockItem/StockItemInventory';
7
- import { formatForDatePicker } from '../../../constants';
7
+ import {
8
+ APP_STOCKMANAGEMENT_STOCKITEMS,
9
+ TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE,
10
+ formatForDatePicker,
11
+ } from '../../../constants';
12
+ import { type PrivilegeScope } from '../../../core/api/types/identity/PriviledgeScope';
8
13
  import { useStockItemBatchInformationHook } from '../../../stock-items/add-stock-item/batch-information/batch-information.resource';
14
+ import { useStockManagementSession } from '../../../stock-lookups/stock-lookups.resource';
9
15
  import { useStockItemBatchNumbers } from '../hooks/useStockItemBatchNumbers';
10
16
  import BatchNoSelector from './batch-no-selector.component';
11
17
 
@@ -17,7 +23,12 @@ vi.mock('../../../stock-items/add-stock-item/batch-information/batch-information
17
23
  useStockItemBatchInformationHook: vi.fn(),
18
24
  }));
19
25
 
26
+ vi.mock('../../../stock-lookups/stock-lookups.resource', () => ({
27
+ useStockManagementSession: vi.fn(),
28
+ }));
29
+
20
30
  const mockUseStockItemBatchNumbers = vi.mocked(useStockItemBatchNumbers);
31
+ const mockUseStockManagementSession = vi.mocked(useStockManagementSession);
21
32
  const mockUseStockItemBatchInformationHook = vi.mocked(useStockItemBatchInformationHook);
22
33
 
23
34
  describe('BatchNoSelector', () => {
@@ -26,6 +37,13 @@ describe('BatchNoSelector', () => {
26
37
  const mockExpiration = new Date();
27
38
 
28
39
  beforeEach(() => {
40
+ mockUseStockManagementSession.mockReturnValue({
41
+ privilegeScopes: [
42
+ { partyUuid: 'main-store', privilege: APP_STOCKMANAGEMENT_STOCKITEMS },
43
+ ] as Array<PrivilegeScope>,
44
+ isLoading: false,
45
+ error: undefined,
46
+ });
29
47
  mockUseStockItemBatchNumbers.mockReturnValue({
30
48
  isLoading: false,
31
49
  stockItemBatchNos: [
@@ -49,12 +67,13 @@ describe('BatchNoSelector', () => {
49
67
  setLimit: vi.fn(),
50
68
  setRepresentation: vi.fn(),
51
69
  setSearchString: vi.fn(),
70
+ error: null,
52
71
  });
53
72
 
54
73
  mockUseStockItemBatchInformationHook.mockReturnValue({
55
74
  items: [
56
- { batchNumber: 'BATCH-001', quantity: 10 },
57
- { batchNumber: 'BATCH-002', quantity: 20 },
75
+ { stockBatchUuid: '1', batchNumber: 'BATCH-001', quantity: 10 },
76
+ { stockBatchUuid: '2', batchNumber: 'BATCH-002', quantity: 20 },
58
77
  ] as StockItemInventory[],
59
78
  totalCount: 2,
60
79
  currentPage: 1,
@@ -79,6 +98,7 @@ describe('BatchNoSelector', () => {
79
98
  setLimit: vi.fn(),
80
99
  setRepresentation: vi.fn(),
81
100
  setSearchString: vi.fn(),
101
+ error: null,
82
102
  });
83
103
 
84
104
  mockUseStockItemBatchInformationHook.mockReturnValue({
@@ -134,6 +154,306 @@ describe('BatchNoSelector', () => {
134
154
  expect(screen.getByText(errorMessage)).toBeInTheDocument();
135
155
  });
136
156
 
157
+ it("shows the quantity at the operation's source when another location holds the same batch", async () => {
158
+ const user = userEvent.setup();
159
+ const inventory = [
160
+ { partyUuid: 'main-pharmacy', stockBatchUuid: '1', batchNumber: 'BATCH-001', quantity: 20 },
161
+ { partyUuid: 'main-store', stockBatchUuid: '1', batchNumber: 'BATCH-001', quantity: 500 },
162
+ ] as StockItemInventory[];
163
+ mockUseStockItemBatchInformationHook.mockImplementation((filter) => ({
164
+ items: inventory.filter((row) => !filter?.partyUuid || row.partyUuid === filter.partyUuid),
165
+ totalCount: 1,
166
+ currentPage: 1,
167
+ currentPageSize: 10,
168
+ setCurrentPage: vi.fn(),
169
+ setStockBatchUuid: vi.fn(),
170
+ setStockItemUuid: vi.fn(),
171
+ setPageSize: vi.fn(),
172
+ pageSizes: [10, 20, 50],
173
+ isLoading: false,
174
+ error: null,
175
+ setLocationUuid: vi.fn(),
176
+ setPartyUuid: vi.fn(),
177
+ setSearchString: vi.fn(),
178
+ }));
179
+
180
+ render(
181
+ <BatchNoSelector stockItemUuid={mockStockItemUuid} partyUuid="main-store" onValueChange={mockOnValueChange} />,
182
+ );
183
+
184
+ await user.click(screen.getByRole('combobox'));
185
+
186
+ expect(
187
+ screen.getByText(`BATCH-001 | Qty: 500 | Expiry: ${formatForDatePicker(mockExpiration)}`),
188
+ ).toBeInTheDocument();
189
+ });
190
+
191
+ it('lists batches with no stock at the party only when includeEmptyBatches is set', async () => {
192
+ const user = userEvent.setup();
193
+ mockUseStockItemBatchNumbers.mockReturnValue({
194
+ isLoading: false,
195
+ stockItemBatchNos: [
196
+ {
197
+ uuid: '1',
198
+ batchNo: 'BATCH-001',
199
+ quantity: undefined,
200
+ expiration: mockExpiration,
201
+ stockItemUuid: 'item1',
202
+ voided: false,
203
+ },
204
+ {
205
+ uuid: '2',
206
+ batchNo: 'BATCH-002',
207
+ quantity: undefined,
208
+ expiration: mockExpiration,
209
+ stockItemUuid: 'item1',
210
+ voided: false,
211
+ },
212
+ ],
213
+ setLimit: vi.fn(),
214
+ setRepresentation: vi.fn(),
215
+ setSearchString: vi.fn(),
216
+ error: null,
217
+ });
218
+ mockUseStockItemBatchInformationHook.mockReturnValue({
219
+ items: [
220
+ { partyUuid: 'main-store', stockBatchUuid: '1', batchNumber: 'BATCH-001', quantity: 500 },
221
+ ] as StockItemInventory[],
222
+ totalCount: 1,
223
+ currentPage: 1,
224
+ currentPageSize: 10,
225
+ setCurrentPage: vi.fn(),
226
+ setStockBatchUuid: vi.fn(),
227
+ setStockItemUuid: vi.fn(),
228
+ setPageSize: vi.fn(),
229
+ pageSizes: [10, 20, 50],
230
+ isLoading: false,
231
+ error: null,
232
+ setLocationUuid: vi.fn(),
233
+ setPartyUuid: vi.fn(),
234
+ setSearchString: vi.fn(),
235
+ });
236
+ const emptyBatchOption = `BATCH-002 | Qty: 0 | Expiry: ${formatForDatePicker(mockExpiration)}`;
237
+
238
+ const { unmount } = render(
239
+ <BatchNoSelector stockItemUuid={mockStockItemUuid} partyUuid="main-store" onValueChange={mockOnValueChange} />,
240
+ );
241
+ await user.click(screen.getByRole('combobox'));
242
+ expect(screen.queryByText(/BATCH-002/)).not.toBeInTheDocument();
243
+ unmount();
244
+
245
+ render(
246
+ <BatchNoSelector
247
+ stockItemUuid={mockStockItemUuid}
248
+ partyUuid="main-store"
249
+ includeEmptyBatches
250
+ onValueChange={mockOnValueChange}
251
+ />,
252
+ );
253
+ await user.click(screen.getByRole('combobox'));
254
+ expect(screen.getByText(emptyBatchOption)).toBeInTheDocument();
255
+ // Expired batches have no inventory row, so the batch list must leave them out instead of showing them empty.
256
+ expect(mockUseStockItemBatchNumbers).toHaveBeenLastCalledWith(mockStockItemUuid, true);
257
+ });
258
+
259
+ it("doesn't call a batch empty where the user can't see the party's stock", async () => {
260
+ const user = userEvent.setup();
261
+ // Inventory comes back empty for a party outside the user's stock scopes. Seeing stock elsewhere, or
262
+ // holding another privilege here, doesn't count.
263
+ mockUseStockManagementSession.mockReturnValue({
264
+ privilegeScopes: [
265
+ { partyUuid: 'main-pharmacy', privilege: APP_STOCKMANAGEMENT_STOCKITEMS },
266
+ { partyUuid: 'main-store', privilege: TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE },
267
+ ] as Array<PrivilegeScope>,
268
+ isLoading: false,
269
+ error: undefined,
270
+ });
271
+ mockUseStockItemBatchNumbers.mockReturnValue({
272
+ isLoading: false,
273
+ stockItemBatchNos: [
274
+ {
275
+ uuid: '1',
276
+ batchNo: 'BATCH-001',
277
+ quantity: undefined,
278
+ expiration: mockExpiration,
279
+ stockItemUuid: 'item1',
280
+ voided: false,
281
+ },
282
+ ],
283
+ setLimit: vi.fn(),
284
+ setRepresentation: vi.fn(),
285
+ setSearchString: vi.fn(),
286
+ error: null,
287
+ });
288
+ mockUseStockItemBatchInformationHook.mockReturnValue({
289
+ items: [] as StockItemInventory[],
290
+ totalCount: 0,
291
+ currentPage: 1,
292
+ currentPageSize: 10,
293
+ setCurrentPage: vi.fn(),
294
+ setStockBatchUuid: vi.fn(),
295
+ setStockItemUuid: vi.fn(),
296
+ setPageSize: vi.fn(),
297
+ pageSizes: [10, 20, 50],
298
+ isLoading: false,
299
+ error: null,
300
+ setLocationUuid: vi.fn(),
301
+ setPartyUuid: vi.fn(),
302
+ setSearchString: vi.fn(),
303
+ });
304
+
305
+ render(
306
+ <BatchNoSelector
307
+ stockItemUuid={mockStockItemUuid}
308
+ partyUuid="main-store"
309
+ includeEmptyBatches
310
+ onValueChange={mockOnValueChange}
311
+ />,
312
+ );
313
+ await user.click(screen.getByRole('combobox'));
314
+
315
+ expect(
316
+ screen.getByText(`BATCH-001 | Qty: Unknown | Expiry: ${formatForDatePicker(mockExpiration)}`),
317
+ ).toBeInTheDocument();
318
+ expect(screen.queryByText(/Qty: 0/)).not.toBeInTheDocument();
319
+ });
320
+
321
+ it('keeps the batch list unfiltered by expiry when empty batches are hidden', () => {
322
+ render(<BatchNoSelector stockItemUuid={mockStockItemUuid} onValueChange={mockOnValueChange} />);
323
+
324
+ expect(mockUseStockItemBatchNumbers).toHaveBeenLastCalledWith(mockStockItemUuid, false);
325
+ });
326
+
327
+ it('keeps expired batches in the list when both empty and expired batches are asked for', () => {
328
+ render(
329
+ <BatchNoSelector
330
+ stockItemUuid={mockStockItemUuid}
331
+ partyUuid="main-store"
332
+ includeEmptyBatches
333
+ includeExpiredBatches
334
+ onValueChange={mockOnValueChange}
335
+ />,
336
+ );
337
+
338
+ expect(mockUseStockItemBatchNumbers).toHaveBeenLastCalledWith(mockStockItemUuid, false);
339
+ expect(mockUseStockItemBatchInformationHook).toHaveBeenLastCalledWith({
340
+ partyUuid: 'main-store',
341
+ excludeExpired: false,
342
+ });
343
+ });
344
+
345
+ it('offers no batches and shows an error when the inventory fails to load', async () => {
346
+ const user = userEvent.setup();
347
+ mockUseStockItemBatchInformationHook.mockReturnValue({
348
+ items: [],
349
+ totalCount: 0,
350
+ currentPage: 1,
351
+ currentPageSize: 10,
352
+ setCurrentPage: vi.fn(),
353
+ setStockBatchUuid: vi.fn(),
354
+ setStockItemUuid: vi.fn(),
355
+ setPageSize: vi.fn(),
356
+ pageSizes: [10, 20, 50],
357
+ isLoading: false,
358
+ error: new Error('Forbidden'),
359
+ setLocationUuid: vi.fn(),
360
+ setPartyUuid: vi.fn(),
361
+ setSearchString: vi.fn(),
362
+ });
363
+
364
+ render(
365
+ <BatchNoSelector
366
+ stockItemUuid={mockStockItemUuid}
367
+ partyUuid="main-store"
368
+ includeEmptyBatches
369
+ onValueChange={mockOnValueChange}
370
+ />,
371
+ );
372
+ await user.click(screen.getByRole('combobox'));
373
+
374
+ expect(screen.queryAllByRole('option')).toHaveLength(0);
375
+ expect(screen.getByText("Couldn't load the stock held at this location")).toBeInTheDocument();
376
+ });
377
+
378
+ it('offers no batches and shows an error when the batch list fails to load', async () => {
379
+ const user = userEvent.setup();
380
+ mockUseStockItemBatchNumbers.mockReturnValue({
381
+ isLoading: false,
382
+ stockItemBatchNos: undefined,
383
+ error: new Error('Forbidden'),
384
+ setLimit: vi.fn(),
385
+ setRepresentation: vi.fn(),
386
+ setSearchString: vi.fn(),
387
+ });
388
+
389
+ render(
390
+ <BatchNoSelector stockItemUuid={mockStockItemUuid} partyUuid="main-store" onValueChange={mockOnValueChange} />,
391
+ );
392
+ await user.click(screen.getByRole('combobox'));
393
+
394
+ expect(screen.queryAllByRole('option')).toHaveLength(0);
395
+ expect(screen.getByText("Couldn't load this item's batches")).toBeInTheDocument();
396
+ });
397
+
398
+ it('matches each batch to its own inventory row when two batches share a number', async () => {
399
+ const user = userEvent.setup();
400
+ const laterExpiration = new Date(mockExpiration.getTime() + 365 * 24 * 60 * 60 * 1000);
401
+ mockUseStockItemBatchNumbers.mockReturnValue({
402
+ isLoading: false,
403
+ stockItemBatchNos: [
404
+ {
405
+ uuid: '1',
406
+ batchNo: 'BATCH-001',
407
+ quantity: undefined,
408
+ expiration: mockExpiration,
409
+ stockItemUuid: 'item1',
410
+ voided: false,
411
+ },
412
+ {
413
+ uuid: '2',
414
+ batchNo: 'BATCH-001',
415
+ quantity: undefined,
416
+ expiration: laterExpiration,
417
+ stockItemUuid: 'item1',
418
+ voided: false,
419
+ },
420
+ ],
421
+ setLimit: vi.fn(),
422
+ setRepresentation: vi.fn(),
423
+ setSearchString: vi.fn(),
424
+ error: null,
425
+ });
426
+ mockUseStockItemBatchInformationHook.mockReturnValue({
427
+ items: [
428
+ { stockBatchUuid: '1', batchNumber: 'BATCH-001', quantity: 10, expiration: mockExpiration },
429
+ { stockBatchUuid: '2', batchNumber: 'BATCH-001', quantity: 5, expiration: laterExpiration },
430
+ ] as StockItemInventory[],
431
+ totalCount: 2,
432
+ currentPage: 1,
433
+ currentPageSize: 10,
434
+ setCurrentPage: vi.fn(),
435
+ setStockBatchUuid: vi.fn(),
436
+ setStockItemUuid: vi.fn(),
437
+ setPageSize: vi.fn(),
438
+ pageSizes: [10, 20, 50],
439
+ isLoading: false,
440
+ error: null,
441
+ setLocationUuid: vi.fn(),
442
+ setPartyUuid: vi.fn(),
443
+ setSearchString: vi.fn(),
444
+ });
445
+
446
+ render(<BatchNoSelector stockItemUuid={mockStockItemUuid} onValueChange={mockOnValueChange} />);
447
+ await user.click(screen.getByRole('combobox'));
448
+
449
+ expect(
450
+ screen.getByText(`BATCH-001 | Qty: 10 | Expiry: ${formatForDatePicker(mockExpiration)}`),
451
+ ).toBeInTheDocument();
452
+ expect(
453
+ screen.getByText(`BATCH-001 | Qty: 5 | Expiry: ${formatForDatePicker(laterExpiration)}`),
454
+ ).toBeInTheDocument();
455
+ });
456
+
137
457
  it('should filter out batches with zero or undefined quantity', async () => {
138
458
  const user = userEvent.setup();
139
459
 
@@ -168,6 +488,7 @@ describe('BatchNoSelector', () => {
168
488
  setLimit: vi.fn(),
169
489
  setRepresentation: vi.fn(),
170
490
  setSearchString: vi.fn(),
491
+ error: null,
171
492
  });
172
493
 
173
494
  render(<BatchNoSelector stockItemUuid={mockStockItemUuid} onValueChange={mockOnValueChange} />);
@@ -214,6 +535,7 @@ describe('BatchNoSelector', () => {
214
535
  setLimit: vi.fn(),
215
536
  setRepresentation: vi.fn(),
216
537
  setSearchString: vi.fn(),
538
+ error: null,
217
539
  });
218
540
 
219
541
  try {
@@ -28,6 +28,7 @@ vi.mock('../../stock-lookups/stock-lookups.resource', () => ({
28
28
  useStockOperationTypes: vi.fn(),
29
29
  useUsers: vi.fn().mockReturnValue({ items: { results: [] }, isLoading: false }),
30
30
  useUser: vi.fn().mockReturnValue({ data: { display: 'Test User' }, isLoading: false, error: null }),
31
+ useStockManagementSession: vi.fn().mockReturnValue({ privilegeScopes: [], isLoading: false, error: undefined }),
31
32
  }));
32
33
 
33
34
  vi.mock('../stock-operations.resource', () => ({
@@ -24,6 +24,7 @@ vi.mock('../../stock-lookups/stock-lookups.resource', () => ({
24
24
  useStockOperationTypes: vi.fn(),
25
25
  useUsers: vi.fn().mockReturnValue({ items: { results: [] }, isLoading: false }),
26
26
  useUser: vi.fn().mockReturnValue({ data: { display: 'Test User' }, isLoading: false, error: null }),
27
+ useStockManagementSession: vi.fn().mockReturnValue({ privilegeScopes: [], isLoading: false, error: undefined }),
27
28
  }));
28
29
 
29
30
  vi.mock('../stock-operations.resource', () => ({