@openmrs/esm-stock-management-app 3.3.2-pre.21 → 3.3.2-pre.210

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 (240) hide show
  1. package/README.md +20 -0
  2. package/dist/1164.js +1 -1
  3. package/dist/1164.js.map +1 -1
  4. package/dist/1207.js +1 -0
  5. package/dist/1207.js.map +1 -0
  6. package/dist/1209.js +1 -0
  7. package/dist/1209.js.map +1 -0
  8. package/dist/1480.js +1 -1
  9. package/dist/1480.js.map +1 -1
  10. package/dist/1600.js +1 -1
  11. package/dist/1600.js.map +1 -1
  12. package/dist/1646.js +1 -1
  13. package/dist/1646.js.map +1 -1
  14. package/dist/1869.js +1 -1
  15. package/dist/1869.js.map +1 -1
  16. package/dist/1877.js +1 -1
  17. package/dist/1877.js.map +1 -1
  18. package/dist/1878.js +1 -1
  19. package/dist/1878.js.map +1 -1
  20. package/dist/2317.js +1 -1
  21. package/dist/2317.js.map +1 -1
  22. package/dist/2392.js +11 -11
  23. package/dist/2392.js.map +1 -1
  24. package/dist/2416.js +1 -1
  25. package/dist/2416.js.map +1 -1
  26. package/dist/2713.js +1 -1
  27. package/dist/2713.js.map +1 -1
  28. package/dist/282.js +1 -1
  29. package/dist/282.js.map +1 -1
  30. package/dist/2881.js +1 -1
  31. package/dist/2881.js.map +1 -1
  32. package/dist/3378.js +1 -1
  33. package/dist/3378.js.map +1 -1
  34. package/dist/3576.js +2 -2
  35. package/dist/3576.js.map +1 -1
  36. package/dist/3588.js +1 -0
  37. package/dist/3588.js.map +1 -0
  38. package/dist/3963.js +1 -1
  39. package/dist/3963.js.map +1 -1
  40. package/dist/4106.js +1 -1
  41. package/dist/4106.js.map +1 -1
  42. package/dist/4111.js +1 -1
  43. package/dist/4111.js.map +1 -1
  44. package/dist/4214.js +1 -1
  45. package/dist/4214.js.map +1 -1
  46. package/dist/434.js +1 -1
  47. package/dist/434.js.map +1 -1
  48. package/dist/4348.js +1 -1
  49. package/dist/4348.js.map +1 -1
  50. package/dist/4383.js +1 -1
  51. package/dist/4383.js.map +1 -1
  52. package/dist/4658.js +1 -1
  53. package/dist/4658.js.map +1 -1
  54. package/dist/4869.css +1 -0
  55. package/dist/4869.css.map +1 -0
  56. package/dist/4869.js +1048 -0
  57. package/dist/4869.js.map +1 -0
  58. package/dist/4928.js +1 -1
  59. package/dist/4928.js.map +1 -1
  60. package/dist/5117.js +1 -1
  61. package/dist/5117.js.map +1 -1
  62. package/dist/5132.js +1 -1
  63. package/dist/5132.js.map +1 -1
  64. package/dist/5145.js +1 -1
  65. package/dist/5145.js.map +1 -1
  66. package/dist/5503.js +1 -1
  67. package/dist/5503.js.map +1 -1
  68. package/dist/556.js +1 -1
  69. package/dist/556.js.map +1 -1
  70. package/dist/5644.js +1 -1
  71. package/dist/5644.js.map +1 -1
  72. package/dist/5838.js +1 -1
  73. package/dist/5838.js.map +1 -1
  74. package/dist/5940.js +1 -1
  75. package/dist/5940.js.map +1 -1
  76. package/dist/5996.js +1 -1
  77. package/dist/5996.js.map +1 -1
  78. package/dist/6047.js +1 -1
  79. package/dist/6047.js.map +1 -1
  80. package/dist/6105.js +1 -1
  81. package/dist/6105.js.map +1 -1
  82. package/dist/6371.js +1 -1
  83. package/dist/6371.js.map +1 -1
  84. package/dist/6377.js +1 -1
  85. package/dist/6377.js.map +1 -1
  86. package/dist/6444.js +1 -1
  87. package/dist/6444.js.map +1 -1
  88. package/dist/6508.js +1 -1
  89. package/dist/6508.js.map +1 -1
  90. package/dist/6724.js +1 -1
  91. package/dist/6724.js.map +1 -1
  92. package/dist/6904.js +1 -1
  93. package/dist/6904.js.map +1 -1
  94. package/dist/6981.js +1 -1
  95. package/dist/6981.js.map +1 -1
  96. package/dist/7037.js +1 -1
  97. package/dist/7045.js +1 -1
  98. package/dist/7045.js.map +1 -1
  99. package/dist/7175.js +1 -1
  100. package/dist/7175.js.map +1 -1
  101. package/dist/7182.js +1 -1
  102. package/dist/7182.js.map +1 -1
  103. package/dist/7742.js +1 -1
  104. package/dist/7742.js.map +1 -1
  105. package/dist/7912.js +1 -1
  106. package/dist/7912.js.map +1 -1
  107. package/dist/8156.js +1 -1
  108. package/dist/8156.js.map +1 -1
  109. package/dist/822.js +1 -1
  110. package/dist/822.js.map +1 -1
  111. package/dist/8358.js +1 -1
  112. package/dist/8358.js.map +1 -1
  113. package/dist/8359.js +1 -1
  114. package/dist/8359.js.map +1 -1
  115. package/dist/8473.js +1 -0
  116. package/dist/8473.js.map +1 -0
  117. package/dist/854.js +1 -0
  118. package/dist/854.js.map +1 -0
  119. package/dist/8661.js +1 -1
  120. package/dist/8661.js.map +1 -1
  121. package/dist/8695.js +1 -1
  122. package/dist/8695.js.map +1 -1
  123. package/dist/8990.js +1 -1
  124. package/dist/8990.js.map +1 -1
  125. package/dist/903.js +1 -1
  126. package/dist/903.js.map +1 -1
  127. package/dist/9072.js +1 -1
  128. package/dist/9072.js.map +1 -1
  129. package/dist/9154.js +1 -1
  130. package/dist/9154.js.map +1 -1
  131. package/dist/9191.js +1 -1
  132. package/dist/9191.js.map +1 -1
  133. package/dist/9806.js +1 -1
  134. package/dist/9806.js.map +1 -1
  135. package/dist/openmrs-esm-stock-management-app.js +2 -2
  136. package/dist/openmrs-esm-stock-management-app.js.map +1 -1
  137. package/dist/routes.json +1 -1
  138. package/package.json +1 -1
  139. package/src/config-schema.ts +38 -0
  140. package/src/constants.ts +0 -56
  141. package/src/routes.json +6 -2
  142. package/src/stock-app-menu-item/item.component.tsx +9 -11
  143. package/src/stock-app-menu-item/item.test.tsx +18 -0
  144. package/src/stock-home/expired-stock.modal.tsx +2 -6
  145. package/src/stock-home/expired-stock.test.tsx +23 -0
  146. package/src/stock-home/issuing-stock.modal.tsx +18 -16
  147. package/src/stock-home/issuing-stock.test.tsx +41 -0
  148. package/src/stock-items/add-stock-item/add-stock-item.component.tsx +10 -1
  149. package/src/stock-items/add-stock-item/add-stock-item.integration.test.tsx +45 -1
  150. package/src/stock-items/add-stock-item/add-stock-item.test.tsx +20 -1
  151. package/src/stock-items/add-stock-item/stock-item-details/stock-item-details.component.tsx +13 -4
  152. package/src/stock-items/add-stock-item/stock-item-units-edit/stock-item-units-edit.component.test.tsx +69 -0
  153. package/src/stock-items/add-stock-item/stock-item-units-edit/stock-item-units-edit.component.tsx +1 -1
  154. package/src/stock-items/stock-items.resource.test.ts +79 -0
  155. package/src/stock-items/stock-items.resource.ts +25 -3
  156. package/src/stock-items/validationSchema.test.ts +51 -0
  157. package/src/stock-items/validationSchema.ts +10 -1
  158. package/src/stock-locations/stock-locations-table.resource.test.ts +24 -2
  159. package/src/stock-lookups/stock-lookups.resource.ts +12 -22
  160. package/src/stock-operations/stock-operation-types-selector/stock-operation-types-selector.component.tsx +4 -1
  161. package/src/stock-operations/stock-operation-types-selector/stock-operation-types-selector.test.tsx +46 -0
  162. package/src/stock-operations/stock-operations-forms/hooks/useFilteredOperationTypesByRoles.test.tsx +77 -0
  163. package/src/stock-operations/stock-operations-forms/hooks/useFilteredOperationTypesByRoles.ts +20 -9
  164. package/src/stock-operations/stock-operations-forms/steps/base-operation-details-form-step.test.tsx +64 -0
  165. package/src/stock-operations/stock-operations-forms/steps/base-operation-details-form-step.tsx +16 -5
  166. package/src/stock-operations/stock-operations-forms/steps/stock-operation-item-cell.component.tsx +2 -7
  167. package/src/stock-operations/stock-operations-forms/steps/stock-operation-submission-form-step.component.tsx +11 -3
  168. package/src/stock-operations/stock-operations-forms/steps/stock-operation-submission-form-step.test.tsx +146 -0
  169. package/src/stock-operations/stock-operations-forms/stock-operation-form.component.tsx +4 -2
  170. package/src/stock-operations/stock-operations-forms/stock-operation-form.test.tsx +135 -0
  171. package/src/stock-operations/stock-operations-modal/stock-operations.modal.test.tsx +69 -0
  172. package/src/stock-operations/stock-operations-modal/stock-operations.modal.tsx +12 -2
  173. package/src/stock-operations/stock-operations-table.component.tsx +8 -2
  174. package/src/stock-operations/stock-operations-table.test.tsx +48 -0
  175. package/src/stock-operations/stock-print-reports/StockOperationReport.test.ts +15 -0
  176. package/src/stock-operations/stock-print-reports/StockOperationReport.tsx +5 -2
  177. package/src/stock-reports/ReportType.ts +0 -14
  178. package/src/stock-reports/generate-report/create-stock-report.test.tsx +191 -0
  179. package/src/stock-reports/generate-report/create-stock-report.workspace.tsx +63 -37
  180. package/src/stock-reports/report-list/stock-reports.component.tsx +3 -4
  181. package/src/stock-reports/report-validation-schema.ts +13 -2
  182. package/src/stock-reports/stock-reports.resource.test.ts +50 -0
  183. package/src/stock-reports/stock-reports.resource.ts +23 -13
  184. package/src/stock-sources/add-stock-sources/add-stock-sources.test.tsx +30 -0
  185. package/src/stock-sources/add-stock-sources/add-stock-sources.workspace.tsx +2 -8
  186. package/src/stock-sources/stock-sources-items-table.resource.test.ts +40 -0
  187. package/src/stock-sources/stock-sources-items-table.resource.ts +2 -1
  188. package/src/stock-user-role-scopes/add-stock-user-scope/add-stock-user-role-scope.test.tsx +49 -0
  189. package/src/stock-user-role-scopes/add-stock-user-scope/add-stock-user-role-scope.workspace.tsx +6 -21
  190. package/src/stock-user-role-scopes/stock-user-role-scopes-items-table.component.tsx +1 -10
  191. package/src/stock-user-role-scopes/stock-user-role-scopes-items-table.test.tsx +65 -0
  192. package/translations/am.json +6 -1
  193. package/translations/ar.json +6 -1
  194. package/translations/ar_SY.json +6 -1
  195. package/translations/bn.json +6 -1
  196. package/translations/cs.json +6 -1
  197. package/translations/de.json +6 -1
  198. package/translations/en.json +6 -1
  199. package/translations/en_US.json +6 -1
  200. package/translations/es.json +6 -1
  201. package/translations/es_MX.json +6 -1
  202. package/translations/fr.json +6 -1
  203. package/translations/he.json +6 -1
  204. package/translations/hi.json +6 -1
  205. package/translations/hi_IN.json +6 -1
  206. package/translations/id.json +6 -1
  207. package/translations/it.json +6 -1
  208. package/translations/ka.json +6 -1
  209. package/translations/km.json +6 -1
  210. package/translations/ku.json +6 -1
  211. package/translations/ky.json +6 -1
  212. package/translations/lg.json +6 -1
  213. package/translations/ne.json +6 -1
  214. package/translations/pl.json +6 -1
  215. package/translations/pt.json +6 -1
  216. package/translations/pt_BR.json +6 -1
  217. package/translations/qu.json +6 -1
  218. package/translations/ro_RO.json +6 -1
  219. package/translations/ru_RU.json +6 -1
  220. package/translations/si.json +6 -1
  221. package/translations/sq.json +6 -1
  222. package/translations/sw.json +6 -1
  223. package/translations/sw_KE.json +6 -1
  224. package/translations/tr.json +6 -1
  225. package/translations/tr_TR.json +6 -1
  226. package/translations/uk.json +6 -1
  227. package/translations/uz.json +6 -1
  228. package/translations/uz@Latn.json +6 -1
  229. package/translations/uz_UZ.json +6 -1
  230. package/translations/vi.json +6 -1
  231. package/translations/zh.json +6 -1
  232. package/translations/zh_CN.json +6 -1
  233. package/translations/zh_TW.json +6 -1
  234. package/dist/138.js +0 -1
  235. package/dist/138.js.map +0 -1
  236. package/dist/3936.css +0 -1
  237. package/dist/3936.css.map +0 -1
  238. package/dist/3936.js +0 -1048
  239. package/dist/3936.js.map +0 -1
  240. package/src/stock-app-menu-item/item.scss +0 -14
@@ -1,8 +1,13 @@
1
1
  import { renderHook } from '@testing-library/react';
2
- import { expect, it, vi } from 'vitest';
3
- import { useFhirFetchAll } from '@openmrs/esm-framework';
2
+ import { beforeEach, expect, it, vi } from 'vitest';
3
+ import { getDefaultsFromConfigSchema, useConfig, useFhirFetchAll } from '@openmrs/esm-framework';
4
+ import { configSchema } from '../config-schema';
4
5
  import { useStockLocationPages } from './stock-locations-table.resource';
5
6
 
7
+ beforeEach(() => {
8
+ vi.mocked(useConfig).mockReturnValue(getDefaultsFromConfigSchema(configSchema));
9
+ });
10
+
6
11
  it('exposes the FHIR list mutator through the location pagination hook', async () => {
7
12
  const mutate = vi.fn();
8
13
  vi.mocked(useFhirFetchAll).mockReturnValue({
@@ -21,3 +26,20 @@ it('exposes the FHIR list mutator through the location pagination hook', async (
21
26
  await result.current.mutate();
22
27
  expect(mutate).toHaveBeenCalledOnce();
23
28
  });
29
+
30
+ it('fetches locations with the default RefApp stock location tags', () => {
31
+ vi.mocked(useFhirFetchAll).mockReturnValue({ data: [], isLoading: false } as never);
32
+ renderHook(() => useStockLocationPages({}));
33
+ expect(useFhirFetchAll).toHaveBeenCalledWith(
34
+ expect.stringMatching(/\/Location\?_summary=data&_tag=Main%20Store,Main%20Pharmacy,Dispensary$/),
35
+ );
36
+ });
37
+
38
+ it('fetches locations with the configured stock location tags', () => {
39
+ vi.mocked(useConfig).mockReturnValue({ stockLocationTags: ['Central Store', 'Ward'] });
40
+ vi.mocked(useFhirFetchAll).mockReturnValue({ data: [], isLoading: false } as never);
41
+ renderHook(() => useStockLocationPages({}));
42
+ expect(useFhirFetchAll).toHaveBeenCalledWith(
43
+ expect.stringMatching(/\/Location\?_summary=data&_tag=Central%20Store,Ward$/),
44
+ );
45
+ });
@@ -3,13 +3,13 @@ import { uniqBy } from 'lodash-es';
3
3
  import useSWR from 'swr';
4
4
  import {
5
5
  type FetchResponse,
6
- type OpenmrsResource,
7
6
  fhirBaseUrl,
8
7
  openmrsFetch,
9
- useSession,
10
8
  restBaseUrl,
9
+ useConfig,
11
10
  useFhirFetchAll,
12
11
  } from '@openmrs/esm-framework';
12
+ import { type ConfigObject } from '../config-schema';
13
13
  import { type Concept } from '../core/api/types/concept/Concept';
14
14
  import { type Drug } from '../core/api/types/concept/Drug';
15
15
  import { type OpenMRSLocation, type OpenMRSLocationTag } from '../core/api/types/Location';
@@ -18,6 +18,7 @@ import { type Party } from '../core/api/types/Party';
18
18
  import { type Patient } from '../core/api/types/identity/Patient';
19
19
  import { type ResourceFilterCriteria, type ResourceRepresentation, toQueryParams } from '../core/api/api';
20
20
  import { type Role } from '../core/api/types/identity/Role';
21
+ import { type StockManagementSession } from '../core/api/types/identity/Session';
21
22
  import { type StockOperationType } from '../core/api/types/stockOperation/StockOperationType';
22
23
  import { type User } from '../core/api/types/identity/User';
23
24
  import { type UserRoleScope } from '../core/api/types/identity/UserRoleScope';
@@ -51,10 +52,12 @@ export function useStockLocations(filter: LocationFilterCriteria) {
51
52
  };
52
53
  }
53
54
  /* Get locations tagged to perform stock related activities.
54
- Unless a location is tag as main store, main pharmacy or dispensing, it will not be fetched.
55
+ Unless a location has one of the tags configured in `stockLocationTags`, it will not be fetched.
55
56
  */
56
57
  export function useStockTagLocations() {
57
- const apiUrl = `${fhirBaseUrl}/Location?_summary=data&_tag=main store,main pharmacy,dispensary `;
58
+ const { stockLocationTags } = useConfig<ConfigObject>();
59
+ const tags = stockLocationTags.map((tag) => encodeURIComponent(tag)).join(',');
60
+ const apiUrl = `${fhirBaseUrl}/Location?_summary=data&_tag=${tags}`;
58
61
  const { data, error, isLoading, mutate } = useFhirFetchAll<fhir.Location>(apiUrl);
59
62
 
60
63
  return {
@@ -275,25 +278,12 @@ export function usePatient(patientUuid: string) {
275
278
  return { isLoading, error, patient: data?.data };
276
279
  }
277
280
 
278
- type UserRole = {
279
- results: Array<{
280
- userUuid: string;
281
- locations: Array<OpenmrsResource>;
282
- operationTypes: Array<{
283
- uuid: string;
284
- operationTypeName: string;
285
- operationTypeUuid: string;
286
- }>;
287
- }>;
288
- };
289
-
290
- export const useUserRoles = () => {
291
- const { user: loggedInUser } = useSession();
292
- const url = `${restBaseUrl}/stockmanagement/userrolescope`;
293
- const { data, isLoading, error } = useSWR<{ data: UserRole }>(url, openmrsFetch);
294
- const currentUserRoles = data?.data?.results.find((user) => user.userUuid === loggedInUser.uuid);
281
+ // The current user's active privilege scopes. Any signed-in user can read these.
282
+ export const useStockManagementSession = () => {
283
+ const url = `${restBaseUrl}/stockmanagement/session`;
284
+ const { data, isLoading, error } = useSWR<{ data: StockManagementSession }>(url, openmrsFetch);
295
285
  return {
296
- userRoles: currentUserRoles,
286
+ privilegeScopes: data?.data?.privileges,
297
287
  isLoading,
298
288
  error,
299
289
  };
@@ -3,13 +3,16 @@ import { ButtonSkeleton, OverflowMenu, OverflowMenuItem } from '@carbon/react';
3
3
  import { OverflowMenuVertical } from '@carbon/react/icons';
4
4
  import { useTranslation } from 'react-i18next';
5
5
  import { showSnackbar } from '@openmrs/esm-framework';
6
+ import { TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE } from '../../constants';
6
7
  import { OperationType, type StockOperationType } from '../../core/api/types/stockOperation/StockOperationType';
7
8
  import { launchStockoperationAddOrEditWorkSpace } from '../stock-operation.utils';
8
9
  import useFilteredOperationTypesByRoles from '../stock-operations-forms/hooks/useFilteredOperationTypesByRoles';
9
10
 
10
11
  const StockOperationTypesSelector = () => {
11
12
  const { t } = useTranslation();
12
- const { error, isLoading, operationTypes } = useFilteredOperationTypesByRoles();
13
+ const { error, isLoading, operationTypes } = useFilteredOperationTypesByRoles(
14
+ TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE,
15
+ );
13
16
 
14
17
  const handleSelect = useCallback((stockOperationType: StockOperationType) => {
15
18
  const isStockIssueOperation = stockOperationType.operationType === OperationType.STOCK_ISSUE_OPERATION_TYPE;
@@ -0,0 +1,46 @@
1
+ import React from 'react';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { render, screen } from '@testing-library/react';
4
+ import userEvent from '@testing-library/user-event';
5
+ import { SWRConfig } from 'swr';
6
+ import { type FetchResponse, openmrsFetch } from '@openmrs/esm-framework';
7
+ import {
8
+ TASK_STOCKMANAGEMENT_STOCKOPERATIONS_APPROVE,
9
+ TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE,
10
+ } from '../../constants';
11
+ import StockOperationTypesSelector from './stock-operation-types-selector.component';
12
+
13
+ const mockOpenmrsFetch = vi.mocked(openmrsFetch);
14
+
15
+ describe('StockOperationTypesSelector', () => {
16
+ it('only offers the operation types the user can create', async () => {
17
+ const user = userEvent.setup();
18
+ mockOpenmrsFetch.mockImplementation((url: string) =>
19
+ Promise.resolve({
20
+ data: url.includes('/stockmanagement/session')
21
+ ? {
22
+ privileges: [
23
+ { privilege: TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE, operationTypeUuid: 'receipt-uuid' },
24
+ { privilege: TASK_STOCKMANAGEMENT_STOCKOPERATIONS_APPROVE, operationTypeUuid: 'disposal-uuid' },
25
+ ],
26
+ }
27
+ : {
28
+ results: [
29
+ { uuid: 'receipt-uuid', name: 'Receipt' },
30
+ { uuid: 'disposal-uuid', name: 'Disposal' },
31
+ ],
32
+ },
33
+ } as FetchResponse),
34
+ );
35
+
36
+ render(
37
+ <SWRConfig value={{ provider: () => new Map() }}>
38
+ <StockOperationTypesSelector />
39
+ </SWRConfig>,
40
+ );
41
+ await user.click(await screen.findByText(/Start New/));
42
+
43
+ expect(screen.getByText('Receipt')).toBeInTheDocument();
44
+ expect(screen.queryByText('Disposal')).not.toBeInTheDocument();
45
+ });
46
+ });
@@ -0,0 +1,77 @@
1
+ import React from 'react';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { renderHook, waitFor } from '@testing-library/react';
4
+ import { SWRConfig } from 'swr';
5
+ import { type FetchResponse, openmrsFetch } from '@openmrs/esm-framework';
6
+ import {
7
+ TASK_STOCKMANAGEMENT_STOCKOPERATIONS_APPROVE,
8
+ TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE,
9
+ } from '../../../constants';
10
+ import useFilteredOperationTypesByRoles from './useFilteredOperationTypesByRoles';
11
+
12
+ const mockOpenmrsFetch = vi.mocked(openmrsFetch);
13
+
14
+ const receipt = { uuid: 'receipt-type-uuid', name: 'Receipt' };
15
+ const disposal = { uuid: 'disposal-type-uuid', name: 'Disposal' };
16
+ const transferOut = { uuid: 'transfer-out-type-uuid', name: 'Transfer Out' };
17
+
18
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
19
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>{children}</SWRConfig>
20
+ );
21
+
22
+ describe('useFilteredOperationTypesByRoles', () => {
23
+ it("lists the operation types in all of a non-admin user's scopes", async () => {
24
+ mockOpenmrsFetch.mockImplementation((url: string) => {
25
+ if (url.includes('/stockmanagement/stockoperationtype')) {
26
+ return Promise.resolve({ data: { results: [receipt, disposal, transferOut] } } as FetchResponse);
27
+ }
28
+ if (url.includes('/stockmanagement/session')) {
29
+ return Promise.resolve({
30
+ data: {
31
+ privileges: [
32
+ { privilege: 'Task: stockmanagement.stockoperations.mutate', operationTypeUuid: receipt.uuid },
33
+ { privilege: 'Task: stockmanagement.stockoperations.mutate', operationTypeUuid: disposal.uuid },
34
+ ],
35
+ },
36
+ } as FetchResponse);
37
+ }
38
+ // Only Inventory Administrators can list role scopes.
39
+ return Promise.reject(new Error('403 Forbidden'));
40
+ });
41
+
42
+ const { result } = renderHook(() => useFilteredOperationTypesByRoles(), { wrapper });
43
+
44
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
45
+
46
+ expect(result.current.error).toBeUndefined();
47
+ expect(result.current.operationTypes.map((type) => type.name)).toEqual(['Receipt', 'Disposal']);
48
+ });
49
+
50
+ it('only counts scopes that grant the requested privilege', async () => {
51
+ mockOpenmrsFetch.mockImplementation((url: string) => {
52
+ if (url.includes('/stockmanagement/stockoperationtype')) {
53
+ return Promise.resolve({ data: { results: [receipt, disposal, transferOut] } } as FetchResponse);
54
+ }
55
+ return Promise.resolve({
56
+ data: {
57
+ privileges: [
58
+ { privilege: TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE, operationTypeUuid: receipt.uuid },
59
+ { privilege: TASK_STOCKMANAGEMENT_STOCKOPERATIONS_APPROVE, operationTypeUuid: disposal.uuid },
60
+ ],
61
+ },
62
+ } as FetchResponse);
63
+ });
64
+
65
+ const { result: mutable } = renderHook(
66
+ () => useFilteredOperationTypesByRoles(TASK_STOCKMANAGEMENT_STOCKOPERATIONS_MUTATE),
67
+ { wrapper },
68
+ );
69
+ const { result: viewable } = renderHook(() => useFilteredOperationTypesByRoles(), { wrapper });
70
+
71
+ await waitFor(() => expect(mutable.current.isLoading).toBe(false));
72
+ await waitFor(() => expect(viewable.current.isLoading).toBe(false));
73
+
74
+ expect(mutable.current.operationTypes.map((type) => type.name)).toEqual(['Receipt']);
75
+ expect(viewable.current.operationTypes.map((type) => type.name)).toEqual(['Receipt', 'Disposal']);
76
+ });
77
+ });
@@ -1,24 +1,35 @@
1
1
  import { useMemo } from 'react';
2
- import { useStockOperationTypes, useUserRoles } from '../../../stock-lookups/stock-lookups.resource';
2
+ import { useStockManagementSession, useStockOperationTypes } from '../../../stock-lookups/stock-lookups.resource';
3
3
 
4
- const useFilteredOperationTypesByRoles = () => {
4
+ /**
5
+ * Returns the operation types in the current user's privilege scopes.
6
+ * @param privilege Only count scopes that grant this privilege. Leave it out to count every scope.
7
+ */
8
+ const useFilteredOperationTypesByRoles = (privilege?: string) => {
5
9
  const {
6
10
  types: { results },
7
11
  isLoading: isStockOperationTypesLoading,
8
12
  error: stockOperationTypesError,
9
13
  } = useStockOperationTypes();
10
14
 
11
- const { userRoles, isLoading: isUserRolesLoading, error: userRolesError } = useUserRoles();
15
+ const {
16
+ privilegeScopes,
17
+ isLoading: isPrivilegeScopesLoading,
18
+ error: privilegeScopesError,
19
+ } = useStockManagementSession();
12
20
 
13
21
  const operationTypes = useMemo(() => {
14
- const applicablePrivilegeScopes = userRoles?.operationTypes?.map((p) => p.operationTypeUuid) || [];
15
- const uniqueApplicablePrivilegeScopes = [...new Set(applicablePrivilegeScopes)];
22
+ const applicableOperationTypeUuids = new Set(
23
+ privilegeScopes
24
+ ?.filter((scope) => !privilege || scope.privilege === privilege)
25
+ .map((scope) => scope.operationTypeUuid),
26
+ );
16
27
 
17
- return results?.filter((p) => uniqueApplicablePrivilegeScopes.includes(p.uuid)) || [];
18
- }, [results, userRoles]);
28
+ return results?.filter((p) => applicableOperationTypeUuids.has(p.uuid)) || [];
29
+ }, [results, privilegeScopes, privilege]);
19
30
 
20
- const isLoading = isStockOperationTypesLoading || isUserRolesLoading;
21
- const error = stockOperationTypesError || userRolesError;
31
+ const isLoading = isStockOperationTypesLoading || isPrivilegeScopesLoading;
32
+ const error = stockOperationTypesError || privilegeScopesError;
22
33
 
23
34
  return {
24
35
  operationTypes,
@@ -0,0 +1,64 @@
1
+ import React from 'react';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { render } from '@testing-library/react';
4
+ import { FormProvider, useForm, type UseFormReturn } from 'react-hook-form';
5
+ import { useConfig } from '@openmrs/esm-framework';
6
+ import { requisitionOperationTypeMock } from '@mocks';
7
+ import { type StockOperationType } from '../../../core/api/types/stockOperation/StockOperationType';
8
+ import { type StockOperationItemDtoSchema } from '../../validation-schema';
9
+ import useParties from '../hooks/useParties';
10
+ import BaseOperationDetailsFormStep from './base-operation-details-form-step';
11
+
12
+ vi.mock('../hooks/useParties', () => ({ default: vi.fn() }));
13
+ vi.mock('../hooks/useOperationTypePermisions', () => ({ default: vi.fn(() => ({})) }));
14
+ vi.mock('../input-components/users-selector.component', () => ({ default: () => null }));
15
+ vi.mock('../input-components/stock-operation-reason-selector.component', () => ({ default: () => null }));
16
+
17
+ const stockOperationType = {
18
+ ...requisitionOperationTypeMock,
19
+ hasSource: true,
20
+ hasDestination: true,
21
+ } as unknown as StockOperationType;
22
+
23
+ function setupStep(tag: string) {
24
+ vi.mocked(useParties).mockReturnValue({
25
+ sourceTags: [tag],
26
+ destinationTags: [tag],
27
+ sourceParties: [{ uuid: 'source-party-uuid' }],
28
+ destinationParties: [{ uuid: 'destination-party-uuid' }],
29
+ isLoading: false,
30
+ error: undefined,
31
+ } as never);
32
+
33
+ let form: UseFormReturn<StockOperationItemDtoSchema>;
34
+ const Wrapper = () => {
35
+ form = useForm<StockOperationItemDtoSchema>();
36
+ return (
37
+ <FormProvider {...form}>
38
+ <BaseOperationDetailsFormStep stockOperationType={stockOperationType} />
39
+ </FormProvider>
40
+ );
41
+ };
42
+ render(<Wrapper />);
43
+ return form;
44
+ }
45
+
46
+ describe('BaseOperationDetailsFormStep', () => {
47
+ beforeEach(() => {
48
+ vi.mocked(useConfig).mockReturnValue({ mainStoreLocationTag: 'Central Store' });
49
+ });
50
+
51
+ it('prefills the source and destination when the only allowed tag is the configured main store tag', () => {
52
+ const form = setupStep('Central Store');
53
+
54
+ expect(form.getValues('sourceUuid')).toBe('source-party-uuid');
55
+ expect(form.getValues('destinationUuid')).toBe('destination-party-uuid');
56
+ });
57
+
58
+ it('does not prefill the source and destination for any other tag', () => {
59
+ const form = setupStep('Main Store');
60
+
61
+ expect(form.getValues('sourceUuid')).toBeUndefined();
62
+ expect(form.getValues('destinationUuid')).toBeUndefined();
63
+ });
64
+ });
@@ -13,8 +13,9 @@ import {
13
13
  import { ArrowRight } from '@carbon/react/icons';
14
14
  import { Controller, useFormContext } from 'react-hook-form';
15
15
  import { useTranslation } from 'react-i18next';
16
- import { ErrorState } from '@openmrs/esm-framework';
17
- import { DATE_PICKER_CONTROL_FORMAT, DATE_PICKER_FORMAT, MAIN_STORE_LOCATION_TAG } from '../../../constants';
16
+ import { ErrorState, useConfig } from '@openmrs/esm-framework';
17
+ import { type ConfigObject } from '../../../config-schema';
18
+ import { DATE_PICKER_CONTROL_FORMAT, DATE_PICKER_FORMAT } from '../../../constants';
18
19
  import { type Party } from '../../../core/api/types/Party';
19
20
  import { type StockOperationDTO } from '../../../core/api/types/stockOperation/StockOperationDTO';
20
21
  import { OperationType, type StockOperationType } from '../../../core/api/types/stockOperation/StockOperationType';
@@ -37,6 +38,7 @@ const BaseOperationDetailsFormStep: FC<BaseOperationDetailsFormStepProps> = ({
37
38
  onNext,
38
39
  }) => {
39
40
  const { t } = useTranslation();
41
+ const { mainStoreLocationTag } = useConfig<ConfigObject>();
40
42
  const operationTypePermision = useOperationTypePermisions(stockOperationType);
41
43
  const {
42
44
  destinationParties,
@@ -71,7 +73,7 @@ const BaseOperationDetailsFormStep: FC<BaseOperationDetailsFormStepProps> = ({
71
73
  // Prefill default locaton with current location if is a new operation
72
74
  if (!stockOperation && stockOperationType.operationType !== OperationType.STOCK_ISSUE_OPERATION_TYPE) {
73
75
  if (stockOperationType?.hasSource) {
74
- const shouldLockSource = sourceTags.length === 1 && sourceTags[0] === MAIN_STORE_LOCATION_TAG;
76
+ const shouldLockSource = sourceTags.length === 1 && sourceTags[0] === mainStoreLocationTag;
75
77
  if (shouldLockSource && sourceParties?.length) {
76
78
  const party = sourceParties[0];
77
79
  form.setValue('sourceUuid', party.uuid);
@@ -79,14 +81,23 @@ const BaseOperationDetailsFormStep: FC<BaseOperationDetailsFormStepProps> = ({
79
81
  }
80
82
 
81
83
  if (stockOperationType?.hasDestination) {
82
- const shouldLockDestination = destinationTags.length === 1 && destinationTags[0] === MAIN_STORE_LOCATION_TAG;
84
+ const shouldLockDestination = destinationTags.length === 1 && destinationTags[0] === mainStoreLocationTag;
83
85
  if (shouldLockDestination && destinationParties?.length) {
84
86
  const party = destinationParties[0];
85
87
  form.setValue('destinationUuid', party.uuid);
86
88
  }
87
89
  }
88
90
  }
89
- }, [sourceParties, destinationParties, stockOperation, stockOperationType, form, destinationTags, sourceTags]);
91
+ }, [
92
+ sourceParties,
93
+ destinationParties,
94
+ stockOperation,
95
+ stockOperationType,
96
+ form,
97
+ destinationTags,
98
+ sourceTags,
99
+ mainStoreLocationTag,
100
+ ]);
90
101
 
91
102
  if (isPartiesLoading)
92
103
  return (
@@ -1,9 +1,8 @@
1
1
  import { InlineLoading } from '@carbon/react';
2
- import { ConfigurableLink, showSnackbar, useConfig } from '@openmrs/esm-framework';
2
+ import { showSnackbar, useConfig } from '@openmrs/esm-framework';
3
3
  import React, { useEffect, useMemo } from 'react';
4
4
  import { useTranslation } from 'react-i18next';
5
5
  import { type ConfigObject } from '../../../config-schema';
6
- import { URL_STOCK_ITEM } from '../../../constants';
7
6
  import { useStockItem } from '../../../stock-items/stock-items.resource';
8
7
 
9
8
  type StockOperationItemCellProps = {
@@ -39,11 +38,7 @@ const StockOperationItemCell: React.FC<StockOperationItemCellProps> = ({ stockIt
39
38
  if (isLoading) return <InlineLoading status="active" iconDescription="Loading" />;
40
39
  if (error) return <>--</>;
41
40
 
42
- return (
43
- <ConfigurableLink target={'_blank'} to={window.spaBase + URL_STOCK_ITEM(stockItemUuid)}>
44
- {useItemCommonNameAsDisplay ? commonName : drugName}
45
- </ConfigurableLink>
46
- );
41
+ return <>{useItemCommonNameAsDisplay ? commonName : drugName}</>;
47
42
  };
48
43
 
49
44
  export default StockOperationItemCell;
@@ -34,7 +34,7 @@ const StockOperationSubmissionFormStep: React.FC<StockOperationSubmissionFormSte
34
34
  const { t } = useTranslation();
35
35
  const handleMutate = useHandleMutate();
36
36
  const operationTypePermision = useOperationTypePermisions(stockOperationType);
37
- const editable = useMemo(() => !stockOperation || stockOperation.status === 'NEW', [stockOperation]);
37
+ const editable = !stockOperation || stockOperation.permission?.canEdit === true;
38
38
  const form = useFormContext<StockOperationItemDtoSchema>();
39
39
  const [approvalRequired, setApprovalRequired] = useState<boolean | null>(stockOperation?.approvalRequired);
40
40
  const isStockIssueOperation = useMemo(
@@ -46,7 +46,7 @@ const StockOperationSubmissionFormStep: React.FC<StockOperationSubmissionFormSte
46
46
  };
47
47
 
48
48
  const handleSave = useCallback(async () => {
49
- let result: StockOperationDTO; // To store the result for returning
49
+ let result: StockOperationDTO | undefined;
50
50
  await form.handleSubmit(async (formData) => {
51
51
  try {
52
52
  // Get deleted items (items in stock operation bt not i form data)
@@ -118,7 +118,6 @@ const StockOperationSubmissionFormStep: React.FC<StockOperationSubmissionFormSte
118
118
  kind: 'error',
119
119
  isLowContrast: true,
120
120
  });
121
- throw error;
122
121
  }
123
122
  })(); // Call handleSubmit to trigger validation and submission
124
123
  return result; // Return the result after handleSubmit completes
@@ -126,16 +125,25 @@ const StockOperationSubmissionFormStep: React.FC<StockOperationSubmissionFormSte
126
125
 
127
126
  const handleComplete = useCallback(() => {
128
127
  handleSave().then((operation) => {
128
+ if (!operation?.uuid?.trim()) {
129
+ return;
130
+ }
129
131
  launchStockOperationsModal('Complete', false, { ...operation, status: 'COMPLETED' });
130
132
  });
131
133
  }, [handleSave]);
132
134
  const handleSubmitForReview = useCallback(() => {
133
135
  handleSave().then((operation) => {
136
+ if (!operation?.uuid?.trim()) {
137
+ return;
138
+ }
134
139
  launchStockOperationsModal('Submit', false, { ...operation, status: 'SUBMITTED' });
135
140
  });
136
141
  }, [handleSave]);
137
142
  const handleDispatch = useCallback(() => {
138
143
  handleSave().then((operation) => {
144
+ if (!operation?.uuid?.trim()) {
145
+ return;
146
+ }
139
147
  launchStockOperationsModal('Dispatch', false, { ...operation, status: 'DISPATCHED' });
140
148
  });
141
149
  }, [handleSave]);
@@ -0,0 +1,146 @@
1
+ import React from 'react';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { render, screen, waitFor } from '@testing-library/react';
4
+ import userEvent from '@testing-library/user-event';
5
+ import { FormProvider, useForm } from 'react-hook-form';
6
+ import { zodResolver } from '@hookform/resolvers/zod';
7
+ import { z } from 'zod';
8
+ import { showSnackbar } from '@openmrs/esm-framework';
9
+ import StockOperationSubmissionFormStep from './stock-operation-submission-form-step.component';
10
+ import { launchStockOperationsModal } from '../../stock-operation.utils';
11
+ import { updateStockOperation } from '../../stock-operations.resource';
12
+ import { type StockOperationDTO } from '../../../core/api/types/stockOperation/StockOperationDTO';
13
+ import { type StockOperationType } from '../../../core/api/types/stockOperation/StockOperationType';
14
+ import { type RecordPermission } from '../../../core/api/types/RecordPermission';
15
+
16
+ vi.mock('../../stock-operation.utils', () => ({ launchStockOperationsModal: vi.fn() }));
17
+ vi.mock('../../stock-operations.resource', () => ({
18
+ updateStockOperation: vi.fn(),
19
+ createStockOperation: vi.fn(),
20
+ deleteStockOperationItem: vi.fn(),
21
+ }));
22
+ vi.mock('../../../utils', () => ({ useHandleMutate: () => vi.fn() }));
23
+
24
+ const schema = z.object({
25
+ responsiblePersonUuid: z.string().min(1),
26
+ stockOperationItems: z.array(z.object({ uuid: z.string() })),
27
+ });
28
+
29
+ function Operation({
30
+ type,
31
+ approval,
32
+ valid,
33
+ status = 'NEW',
34
+ permission = { canEdit: true },
35
+ unsaved = false,
36
+ }: {
37
+ type: string;
38
+ approval: boolean;
39
+ valid: boolean;
40
+ status?: StockOperationDTO['status'];
41
+ permission?: Partial<RecordPermission> | null;
42
+ unsaved?: boolean;
43
+ }) {
44
+ const form = useForm({
45
+ defaultValues: { responsiblePersonUuid: valid ? 'responsible-person' : '', stockOperationItems: [] },
46
+ resolver: zodResolver(schema),
47
+ });
48
+ return (
49
+ <FormProvider {...form}>
50
+ <StockOperationSubmissionFormStep
51
+ stockOperation={
52
+ unsaved
53
+ ? undefined
54
+ : ({ uuid: 'operation-being-edited', status, approvalRequired: approval, permission } as StockOperationDTO)
55
+ }
56
+ stockOperationType={{ operationType: type } as StockOperationType}
57
+ />
58
+ </FormProvider>
59
+ );
60
+ }
61
+
62
+ const actions = [
63
+ { type: 'receipt', approval: false, label: 'Complete', title: 'Complete', status: 'COMPLETED' },
64
+ { type: 'receipt', approval: true, label: 'Submit For Review', title: 'Submit', status: 'SUBMITTED' },
65
+ { type: 'stockissue', approval: false, label: 'Dispatch', title: 'Dispatch', status: 'DISPATCHED' },
66
+ ];
67
+
68
+ beforeEach(() => vi.resetAllMocks());
69
+
70
+ describe('operation identity after validation and save', () => {
71
+ it.each(actions)('$title does not open a confirmation when validation fails', async ({ type, approval, label }) => {
72
+ render(<Operation type={type} approval={approval} valid={false} />);
73
+ await userEvent.click(screen.getByRole('button', { name: label }));
74
+ expect(updateStockOperation).not.toHaveBeenCalled();
75
+ expect(launchStockOperationsModal).not.toHaveBeenCalled();
76
+ });
77
+
78
+ it.each(actions)(
79
+ '$title uses the identity returned by the save',
80
+ async ({ type, approval, label, title, status }) => {
81
+ const saved = { uuid: 'saved-operation', status: 'NEW' };
82
+ vi.mocked(updateStockOperation).mockResolvedValue({ data: saved } as never);
83
+ render(<Operation type={type} approval={approval} valid />);
84
+ await userEvent.click(screen.getByRole('button', { name: label }));
85
+ await waitFor(() => expect(launchStockOperationsModal).toHaveBeenCalledWith(title, false, { ...saved, status }));
86
+ },
87
+ );
88
+
89
+ it.each(actions.flatMap((action) => [undefined, '', ' \t'].map((uuid) => ({ ...action, uuid }))))(
90
+ '$title does not open a confirmation when the saved UUID is [$uuid]',
91
+ async ({ type, approval, label, uuid }) => {
92
+ vi.mocked(updateStockOperation).mockResolvedValue({ data: { uuid } } as never);
93
+ render(<Operation type={type} approval={approval} valid />);
94
+ await userEvent.click(screen.getByRole('button', { name: label }));
95
+ await waitFor(() => expect(updateStockOperation).toHaveBeenCalled());
96
+ expect(launchStockOperationsModal).not.toHaveBeenCalled();
97
+ },
98
+ );
99
+
100
+ it.each(actions)('$title does not open a confirmation when saving fails', async ({ type, approval, label }) => {
101
+ vi.mocked(updateStockOperation).mockRejectedValue(new Error('Save rejected'));
102
+ render(<Operation type={type} approval={approval} valid />);
103
+ await userEvent.click(screen.getByRole('button', { name: label }));
104
+ await waitFor(() => expect(showSnackbar).toHaveBeenCalledWith(expect.objectContaining({ kind: 'error' })));
105
+ expect(launchStockOperationsModal).not.toHaveBeenCalled();
106
+ expect(await screen.findByRole('button', { name: 'Save' })).toBeEnabled();
107
+ });
108
+ });
109
+
110
+ describe('editing by permission', () => {
111
+ it.each(['NEW', 'RETURNED'] as const)('shows the save and submit buttons for an editable %s operation', (status) => {
112
+ render(<Operation type="receipt" approval valid status={status} />);
113
+ expect(screen.getByRole('button', { name: 'Submit For Review' })).toBeInTheDocument();
114
+ expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
115
+ });
116
+
117
+ it('shows the save button for a new, unsaved operation', () => {
118
+ render(<Operation type="receipt" approval valid unsaved />);
119
+ expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument();
120
+ });
121
+
122
+ it.each(['NEW', 'RETURNED', 'SUBMITTED', 'DISPATCHED', 'COMPLETED', 'CANCELLED', 'REJECTED'] as const)(
123
+ 'keeps a %s operation locked when the user cannot edit it',
124
+ (status) => {
125
+ render(<Operation type="receipt" approval valid status={status} permission={{ canEdit: false }} />);
126
+ expect(screen.queryByRole('button', { name: 'Submit For Review' })).not.toBeInTheDocument();
127
+ expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();
128
+ },
129
+ );
130
+
131
+ it('keeps an operation locked when the permission is missing', () => {
132
+ render(<Operation type="receipt" approval valid permission={null} />);
133
+ expect(screen.queryByRole('button', { name: 'Submit For Review' })).not.toBeInTheDocument();
134
+ expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();
135
+ });
136
+
137
+ it('resubmits a RETURNED operation for review', async () => {
138
+ const saved = { uuid: 'saved-operation', status: 'RETURNED' };
139
+ vi.mocked(updateStockOperation).mockResolvedValue({ data: saved } as never);
140
+ render(<Operation type="receipt" approval valid status="RETURNED" />);
141
+ await userEvent.click(screen.getByRole('button', { name: 'Submit For Review' }));
142
+ await waitFor(() =>
143
+ expect(launchStockOperationsModal).toHaveBeenCalledWith('Submit', false, { ...saved, status: 'SUBMITTED' }),
144
+ );
145
+ });
146
+ });
@@ -78,7 +78,9 @@ const StockOperationForm: React.FC<Workspace2DefinitionProps<StockOperationFormP
78
78
  user: { uuid: defaultLoggedUserUuid },
79
79
  } = useSession();
80
80
  const { autoPopulateResponsiblePerson } = useConfig<ConfigObject>();
81
- const { error, items: _stockOperation, isLoading } = useStockOperationAndItems(stockRequisitionUuid);
81
+ // A requisition only prefills a new issue. A saved issue keeps its own details and lines.
82
+ const requisitionToPrefill = stockOperation ? undefined : stockRequisitionUuid;
83
+ const { error, items: _stockOperation, isLoading } = useStockOperationAndItems(requisitionToPrefill);
82
84
 
83
85
  const form = useForm<StockOperationItemDtoSchema>({
84
86
  defaultValues: {
@@ -103,7 +105,7 @@ const StockOperationForm: React.FC<Workspace2DefinitionProps<StockOperationFormP
103
105
  destinationUuid: stockOperation?.destinationUuid ?? '',
104
106
  },
105
107
  mode: 'all',
106
- values: stockRequisitionUuid
108
+ values: requisitionToPrefill
107
109
  ? {
108
110
  sourceUuid: _stockOperation?.destinationUuid,
109
111
  destinationUuid: _stockOperation?.sourceUuid,