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

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
@@ -30,15 +30,9 @@ import {
30
30
  Workspace2,
31
31
  type Workspace2DefinitionProps,
32
32
  } from '@openmrs/esm-framework';
33
- import { Controller, useForm } from 'react-hook-form';
33
+ import { Controller, type FieldErrors, useForm } from 'react-hook-form';
34
34
  import { zodResolver } from '@hookform/resolvers/zod';
35
- import {
36
- getParamDefaultLimit,
37
- getReportEndDateLabel,
38
- getReportLimitLabel,
39
- getReportStartDateLabel,
40
- ReportParameter,
41
- } from '../ReportType';
35
+ import { getParamDefaultLimit, isForecastReport, ReportParameter } from '../ReportType';
42
36
  import { DATE_PICKER_CONTROL_FORMAT, DATE_PICKER_FORMAT, formatForDatePicker, today } from '../../constants';
43
37
  import { BatchJobTypeReport } from '../../core/api/types/BatchJob';
44
38
  import { createBatchJob } from '../../stock-batch/stock-batch.resource';
@@ -47,7 +41,7 @@ import { useHandleMutate } from '../../utils';
47
41
  import { type Concept } from '../../core/api/types/concept/Concept';
48
42
  import { type Patient } from '../../core/api/types/identity/Patient';
49
43
  import { type StockItemDTO } from '../../core/api/types/stockItem/StockItem';
50
- import { type StockReportSchema, reportSchema } from '../report-validation-schema';
44
+ import { type StockReportSchema, getReportSchema } from '../report-validation-schema';
51
45
  import { useConcept, useStockTagLocations } from '../../stock-lookups/stock-lookups.resource';
52
46
  import { ResourceRepresentation } from '../../core/api/api';
53
47
  import { useReportTypes } from '../stock-reports.resource';
@@ -82,7 +76,6 @@ export interface ReportModel {
82
76
  patientName?: string;
83
77
  limit?: number | null;
84
78
  mostLeastMoving?: string;
85
- mostLeastMovingName?: string;
86
79
  fullFillment?: string[];
87
80
  }
88
81
 
@@ -254,7 +247,7 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
254
247
  setValue,
255
248
  } = useForm<StockReportSchema>({
256
249
  mode: 'all',
257
- resolver: zodResolver(reportSchema),
250
+ resolver: zodResolver(getReportSchema(displayLocation)),
258
251
  });
259
252
 
260
253
  if (isLoading) {
@@ -275,17 +268,6 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
275
268
  return;
276
269
  }
277
270
 
278
- const reportType = Array.isArray(reportTypes) ? reportTypes.find((p) => p.systemName === reportSystemName) : null;
279
-
280
- if (reportType?.parameters?.includes(ReportParameter.Location) && !report.locationUuid) {
281
- showSnackbar({
282
- title: t('error', 'Error'),
283
- kind: 'error',
284
- subtitle: t('locationRequired', 'Location is required for this report type.'),
285
- });
286
- return;
287
- }
288
-
289
271
  let hideSplash = true;
290
272
  try {
291
273
  const newLine = '\r\n';
@@ -384,8 +366,8 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
384
366
  parameters += getReportParameter(
385
367
  ReportParameter.MostLeastMoving,
386
368
  report.mostLeastMoving ?? 'MostMoving',
387
- report.mostLeastMovingName?.trim() ?? 'Most Moving',
388
- t('mostMoving', 'Most moving'),
369
+ report.mostLeastMoving === 'LeastMoving' ? t('leastMoving', 'Least Moving') : t('mostMoving', 'Most moving'),
370
+ t('rank', 'Rank'),
389
371
  newLine,
390
372
  );
391
373
  }
@@ -394,7 +376,7 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
394
376
  ReportParameter.Limit,
395
377
  (report.limit ?? getParamDefaultLimit(reportSystemName) ?? 20).toString(),
396
378
  (report.limit ?? getParamDefaultLimit(reportSystemName) ?? 20).toString(),
397
- t(getReportLimitLabel(reportSystemName)),
379
+ isForecastReport(reportSystemName) ? t('months', 'Months') : t('limit', 'Limit'),
398
380
  newLine,
399
381
  );
400
382
  }
@@ -412,7 +394,9 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
412
394
  ReportParameter.StartDate,
413
395
  report.startDate ? JSON.stringify(report.startDate).replaceAll('"', '') : '',
414
396
  formatDisplayDate(report.startDate) ?? '',
415
- t(getReportStartDateLabel(reportSystemName)),
397
+ isForecastReport(reportSystemName)
398
+ ? t('historicalStartDate', 'Historical start date')
399
+ : t('startDate', 'Start date'),
416
400
  newLine,
417
401
  );
418
402
  }
@@ -421,7 +405,7 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
421
405
  ReportParameter.EndDate,
422
406
  report.endDate ? JSON.stringify(report.endDate).replaceAll('"', '') : '',
423
407
  formatDisplayDate(report.endDate) ?? '',
424
- t(getReportEndDateLabel(reportSystemName)),
408
+ isForecastReport(reportSystemName) ? t('historicalEndDate', 'Historical end date') : t('endDate', 'End date'),
425
409
  newLine,
426
410
  );
427
411
  }
@@ -467,6 +451,38 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
467
451
  }
468
452
  };
469
453
 
454
+ const handleInvalid = (fieldErrors: FieldErrors<StockReportSchema>) => {
455
+ const fieldLabels: Partial<Record<keyof StockReportSchema, string>> = {
456
+ reportName: t('reportName', 'Report name'),
457
+ date: t('date', 'Date'),
458
+ startDate: t('startDate', 'Start date'),
459
+ endDate: t('endDate', 'End date'),
460
+ inventoryGroupBy: t('inventoryBy', 'Inventory by'),
461
+ locationUuid: t('location', 'Location'),
462
+ };
463
+ const missingFields = Object.keys(fieldErrors)
464
+ .map((field) => fieldLabels[field])
465
+ .filter(Boolean);
466
+
467
+ showSnackbar({
468
+ title: t('reportNotSaved', 'Report not saved'),
469
+ kind: 'error',
470
+ isLowContrast: true,
471
+ subtitle: t('completeRequiredFields', 'Complete the required fields: {{fields}}', {
472
+ fields: missingFields.join(', '),
473
+ }),
474
+ });
475
+ };
476
+
477
+ // Enter in a date field commits the typed date, it shouldn't also submit the form. This has to run in the
478
+ // capture phase because Carbon's DatePicker stops the keydown from bubbling.
479
+ const handleFormKeyDown = (event: React.KeyboardEvent<HTMLFormElement>) => {
480
+ const isDateField = ['date', 'startDate', 'endDate'].includes((event.target as HTMLElement).id);
481
+ if (event.key === 'Enter' && isDateField) {
482
+ event.preventDefault();
483
+ }
484
+ };
485
+
470
486
  const getReportParameter = (
471
487
  name: string,
472
488
  value: string,
@@ -479,7 +495,11 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
479
495
 
480
496
  return (
481
497
  <Workspace2 title={t('newReport', 'New Report')}>
482
- <Form className={styles.container} onSubmit={handleSubmit(handleSave)}>
498
+ <Form
499
+ className={styles.container}
500
+ onKeyDownCapture={handleFormKeyDown}
501
+ onSubmit={handleSubmit(handleSave, handleInvalid)}
502
+ >
483
503
  <Stack className={styles.form} gap={5}>
484
504
  <>
485
505
  <FormGroup legendText={t('reportName', 'Report name')}>
@@ -489,6 +509,8 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
489
509
  render={({ field: { onChange } }) => (
490
510
  <ComboBox
491
511
  id="report"
512
+ invalid={!!errors?.reportName?.message}
513
+ invalidText={errors?.reportName?.message}
492
514
  titleText={t('reportName', 'Report name')}
493
515
  items={Array.isArray(reportTypes) ? reportTypes : [reportTypes]}
494
516
  itemToString={(item) => `${item?.name ?? item?.name ?? ''}`}
@@ -537,6 +559,7 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
537
559
  maxDate={formatForDatePicker(today())}
538
560
  locale="en"
539
561
  dateFormat={DATE_PICKER_CONTROL_FORMAT}
562
+ invalid={!!errors?.startDate?.message}
540
563
  onChange={onChange}
541
564
  value={value}
542
565
  >
@@ -544,7 +567,6 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
544
567
  id="startDate"
545
568
  placeholder={DATE_PICKER_FORMAT}
546
569
  labelText={t('startDate', 'Start date')}
547
- invalid={!!errors?.startDate?.message}
548
570
  invalidText={errors?.startDate?.message}
549
571
  />
550
572
  </DatePicker>
@@ -561,6 +583,7 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
561
583
  maxDate={formatForDatePicker(today())}
562
584
  locale="en"
563
585
  dateFormat={DATE_PICKER_CONTROL_FORMAT}
586
+ invalid={!!errors?.endDate?.message}
564
587
  onChange={onChange}
565
588
  value={value}
566
589
  >
@@ -568,7 +591,6 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
568
591
  id="endDate"
569
592
  placeholder={DATE_PICKER_FORMAT}
570
593
  labelText={t('endDate', 'End date')}
571
- invalid={!!errors?.endDate?.message}
572
594
  invalidText={errors?.endDate?.message}
573
595
  />
574
596
  </DatePicker>
@@ -582,7 +604,11 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
582
604
  invalid={!!errors?.inventoryGroupBy?.message}
583
605
  invalidText={errors?.inventoryGroupBy?.message}
584
606
  labelText={t('inventoryBy', 'Inventory by')}
585
- onChange={(e) => setValue('inventoryGroupBy', e.target.value)}
607
+ onChange={(e) => {
608
+ const selectedOption = e.target.selectedOptions[0];
609
+ setValue('inventoryGroupBy', e.target.value, { shouldValidate: true });
610
+ setValue('inventoryGroupByName', selectedOption?.text ?? '');
611
+ }}
586
612
  >
587
613
  <SelectItem value="" text={t('selectOption', 'Select an option')} />
588
614
  <SelectItem value="StockItemOnly" text={t('stockItem', 'Stock Item')} />
@@ -659,12 +685,12 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
659
685
  id="location"
660
686
  onChange={(e) => {
661
687
  const selectedLocation = stockLocations?.find((loc) => loc.id === e.target.value);
662
- setValue('locationUuid', e.target.value);
688
+ setValue('locationUuid', e.target.value, { shouldValidate: true });
663
689
  setValue('location', selectedLocation?.name || '');
664
690
  }}
665
691
  defaultValue=""
666
- invalid={!!errors?.location?.message}
667
- invalidText={errors?.location?.message}
692
+ invalid={!!errors?.locationUuid?.message}
693
+ invalidText={errors?.locationUuid?.message}
668
694
  >
669
695
  <SelectItem disabled hidden value="" text={t('chooseALocation', 'Choose a location')} />
670
696
  {(stockLocations ?? [])?.map((loc) => {
@@ -717,8 +743,8 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
717
743
  allowEmpty
718
744
  disableWheel
719
745
  hideSteppers
720
- value={value}
721
- onChange={onChange}
746
+ value={value ?? ''}
747
+ onChange={(_, { value: limit }) => onChange(limit === '' ? undefined : Number(limit))}
722
748
  label={t('limit', 'Limit')}
723
749
  />
724
750
  )}
@@ -798,6 +824,7 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
798
824
  maxDate={formatForDatePicker(today())}
799
825
  locale="en"
800
826
  dateFormat={DATE_PICKER_CONTROL_FORMAT}
827
+ invalid={!!errors?.date?.message}
801
828
  onChange={onChange}
802
829
  value={value}
803
830
  >
@@ -805,7 +832,6 @@ const CreateReport: React.FC<Workspace2DefinitionProps<CreateReportProps>> = ({
805
832
  id="date"
806
833
  placeholder={DATE_PICKER_FORMAT}
807
834
  labelText={t('date', 'Date')}
808
- invalid={!!errors?.date?.message}
809
835
  invalidText={errors?.date?.message}
810
836
  />
811
837
  </DatePicker>
@@ -139,7 +139,7 @@ const StockReports: React.FC = () => {
139
139
  uuid: `${batchJob?.uuid}`,
140
140
  batchJobType: batchJob?.batchJobType,
141
141
  dateRequested: formatDisplayDateTime(batchJob.dateCreated),
142
- parameters: <StockReportParameters model={reports[index]} />,
142
+ parameters: <StockReportParameters model={batchJob} />,
143
143
  report: batchJob?.description,
144
144
  requestedBy: batchJob?.owners?.map((p, index) => (
145
145
  <div key={`${batchJob.uuid}-owner-${index}`}>{`${p.ownerFamilyName} ${p.ownerGivenName}`}</div>
@@ -294,7 +294,7 @@ const StockReports: React.FC = () => {
294
294
 
295
295
  {row.isExpanded ? (
296
296
  <TableExpandedRow colSpan={headers.length + 2}>
297
- <StockReportStatus model={reports[index]} />
297
+ <StockReportStatus model={reports.find((report) => report.uuid === row.id)} />
298
298
  </TableExpandedRow>
299
299
  ) : (
300
300
  <TableExpandedRow className={styles.hiddenRow} colSpan={headers.length + 2} />
@@ -330,8 +330,7 @@ const StockReports: React.FC = () => {
330
330
  onChange={({ pageSize, page }) => {
331
331
  if (pageSize !== currentPageSize) {
332
332
  setPageSize(pageSize);
333
- }
334
- if (page !== currentPage) {
333
+ } else if (page !== currentPage) {
335
334
  goTo(page);
336
335
  }
337
336
  }}
@@ -9,7 +9,6 @@ export const reportSchema = z
9
9
  message: 'Report Name Required',
10
10
  }),
11
11
  mostLeastMoving: z.string().optional(),
12
- mostLeastMovingName: z.string().optional(),
13
12
  stockItemUuid: z.string().optional(),
14
13
  stockItemName: z.string().optional(),
15
14
  patientUuid: z.string().optional(),
@@ -27,7 +26,7 @@ export const reportSchema = z
27
26
  reportSystemName: z.string().optional(),
28
27
  maxReorderLevelRatio: z.number().optional(),
29
28
  fullFillment: z.string().array().optional(),
30
- limit: z.string().optional(),
29
+ limit: z.number().optional(),
31
30
  date: z.coerce.date().optional(),
32
31
  })
33
32
  .superRefine((data, ctx) => {
@@ -65,4 +64,16 @@ export const reportSchema = z
65
64
  }
66
65
  });
67
66
 
67
+ // Which reports need a location comes from the backend's report definition
68
+ export const getReportSchema = (requiresLocation: boolean) =>
69
+ reportSchema.superRefine((data, ctx) => {
70
+ if (requiresLocation && !data.locationUuid) {
71
+ ctx.addIssue({
72
+ code: z.ZodIssueCode.custom,
73
+ message: 'Location is required',
74
+ path: ['locationUuid'],
75
+ });
76
+ }
77
+ });
78
+
68
79
  export type StockReportSchema = z.infer<typeof reportSchema>;
@@ -0,0 +1,50 @@
1
+ import { act, renderHook } from '@testing-library/react';
2
+ import useSWR from 'swr';
3
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
4
+ import { useGetReports } from './stock-reports.resource';
5
+
6
+ vi.mock('swr', () => ({ default: vi.fn() }));
7
+
8
+ const mockedUseSWR = vi.mocked(useSWR);
9
+
10
+ describe('useGetReports', () => {
11
+ beforeEach(() => {
12
+ mockedUseSWR.mockReturnValue({
13
+ data: { data: { results: [], totalCount: 13 } },
14
+ error: undefined,
15
+ isLoading: false,
16
+ mutate: vi.fn(),
17
+ } as never);
18
+ });
19
+
20
+ const lastRequestUrl = () => mockedUseSWR.mock.calls.at(-1)?.[0];
21
+
22
+ it('requests the first page and exposes the total count', () => {
23
+ const { result } = renderHook(() => useGetReports());
24
+
25
+ expect(lastRequestUrl()).toContain('/stockmanagement/batchjob');
26
+ expect(lastRequestUrl()).toContain('limit=10');
27
+ expect(lastRequestUrl()).toContain('startIndex=0');
28
+ expect(result.current.totalItems).toBe(13);
29
+ });
30
+
31
+ it('sends the zero-based page index when paging', () => {
32
+ const { result } = renderHook(() => useGetReports());
33
+
34
+ act(() => result.current.goTo(2));
35
+
36
+ expect(lastRequestUrl()).toContain('startIndex=1');
37
+ expect(result.current.currentPage).toBe(2);
38
+ });
39
+
40
+ it('resets to the first page when the page size changes', () => {
41
+ const { result } = renderHook(() => useGetReports());
42
+
43
+ act(() => result.current.goTo(3));
44
+ act(() => result.current.setPageSize(20));
45
+
46
+ expect(lastRequestUrl()).toContain('limit=20');
47
+ expect(lastRequestUrl()).toContain('startIndex=0');
48
+ expect(result.current.currentPage).toBe(1);
49
+ });
50
+ });
@@ -1,4 +1,4 @@
1
- import { openmrsFetch, restBaseUrl, usePagination } from '@openmrs/esm-framework';
1
+ import { openmrsFetch, restBaseUrl } from '@openmrs/esm-framework';
2
2
  import useSWR from 'swr';
3
3
  import { type ReportType } from './ReportType';
4
4
  import { useState } from 'react';
@@ -13,26 +13,36 @@ export function useReportTypes() {
13
13
  };
14
14
  }
15
15
  export function useGetReports(enabled = true) {
16
- const apiUrl = `${restBaseUrl}/stockmanagement/batchjob?batchJobType=Report&v=default&limit=10&totalCount=true`;
16
+ const pageSizes = [10, 20, 30, 40, 50];
17
+ const [currentPage, setCurrentPage] = useState(1);
18
+ const [currentPageSize, setCurrentPageSize] = useState(10);
19
+ const apiUrl = `${restBaseUrl}/stockmanagement/batchjob?batchJobType=Report&v=default&limit=${currentPageSize}&startIndex=${
20
+ currentPage - 1
21
+ }&totalCount=true`;
17
22
 
18
- const { data, error, isLoading, mutate } = useSWR<{ data: any }, Error>(enabled ? apiUrl : null, openmrsFetch, {
19
- refreshInterval: 15000,
20
- dedupingInterval: 10000,
21
- });
23
+ const { data, error, isLoading, mutate } = useSWR<{ data: { results?: any[]; totalCount?: number } }, Error>(
24
+ enabled ? apiUrl : null,
25
+ openmrsFetch,
26
+ {
27
+ refreshInterval: 15000,
28
+ dedupingInterval: 10000,
29
+ },
30
+ );
22
31
 
23
- const pageSizes = [10, 20, 30, 40, 50];
24
- const [currentPageSize, setPageSize] = useState(10);
25
- const { goTo, results: paginatedItems, currentPage } = usePagination(data?.data?.results, currentPageSize);
32
+ const goTo = (page: number) => setCurrentPage(page);
33
+ const setPageSize = (pageSize: number) => {
34
+ setCurrentPageSize(pageSize);
35
+ setCurrentPage(1);
36
+ };
37
+ const reports = data?.data?.results ?? [];
26
38
 
27
39
  return {
28
- reports: data?.data?.results ?? [],
40
+ reports,
29
41
  isLoading,
30
42
  error,
31
- items: paginatedItems,
32
- totalItems: data?.data?.results?.length ?? 0,
43
+ totalItems: data?.data?.totalCount ?? reports.length,
33
44
  currentPage,
34
45
  currentPageSize,
35
- paginatedItems,
36
46
  goTo,
37
47
  pageSizes,
38
48
  setPageSize,
@@ -145,6 +145,36 @@ describe('StockSourcesAddOrUpdate', () => {
145
145
  await user.click(screen.getByText(/save/i));
146
146
  });
147
147
 
148
+ it('does not change the source being edited until it is saved', async () => {
149
+ const user = userEvent.setup();
150
+ const model = { uuid: '123', name: 'SMV Donor', acronym: 'SMV' } as StockSource;
151
+
152
+ render(<StockSourcesAddOrUpdate {...mockWorkspace2Props({ model })} />);
153
+
154
+ await user.type(screen.getByLabelText(/full name/i), ' DISCARDED');
155
+ await user.type(screen.getByLabelText(/acronym\/code/i), 'X');
156
+
157
+ expect(screen.getByLabelText(/full name/i)).toHaveValue('SMV Donor DISCARDED');
158
+ expect(screen.getByLabelText(/acronym\/code/i)).toHaveValue('SMVX');
159
+ expect(model.name).toBe('SMV Donor');
160
+ expect(model.acronym).toBe('SMV');
161
+ });
162
+
163
+ it('saves the edited values of an existing source', async () => {
164
+ const user = userEvent.setup();
165
+ mockCreateOrUpdateStockSource.mockResolvedValue({ ok: true } as unknown as FetchResponse);
166
+ const model = { uuid: '123', name: 'SMV Donor', acronym: 'SMV' } as StockSource;
167
+
168
+ render(<StockSourcesAddOrUpdate {...mockWorkspace2Props({ model })} />);
169
+
170
+ await user.type(screen.getByLabelText(/full name/i), ' 2');
171
+ await user.click(screen.getByText(/save/i));
172
+
173
+ expect(mockCreateOrUpdateStockSource).toHaveBeenLastCalledWith(
174
+ expect.objectContaining({ uuid: '123', name: 'SMV Donor 2', acronym: 'SMV' }),
175
+ );
176
+ });
177
+
148
178
  it('closes workspace when cancel button is clicked', async () => {
149
179
  const user = userEvent.setup();
150
180
  render(<StockSourcesAddOrUpdate {...mockWorkspace2Props({})} />);
@@ -39,16 +39,10 @@ const StockSourcesAddOrUpdate: React.FC<Workspace2DefinitionProps<AddStockSource
39
39
  const [formModel, setFormModel] = useState<StockSource>({ ...model });
40
40
 
41
41
  const onNameChanged = (evt: React.ChangeEvent<HTMLInputElement>): void => {
42
- if (model) {
43
- model.name = evt.target.value;
44
- }
45
42
  setFormModel({ ...formModel, name: evt.target.value });
46
43
  };
47
44
 
48
45
  const onAcronymChanged = (evt: React.ChangeEvent<HTMLInputElement>): void => {
49
- if (model) {
50
- model.acronym = evt.target.value;
51
- }
52
46
  setFormModel({ ...formModel, acronym: evt.target.value });
53
47
  };
54
48
 
@@ -106,7 +100,7 @@ const StockSourcesAddOrUpdate: React.FC<Workspace2DefinitionProps<AddStockSource
106
100
  placeholder="e.g National Medical Stores"
107
101
  size="md"
108
102
  type="text"
109
- value={model?.name}
103
+ value={formModel.name ?? ''}
110
104
  />
111
105
  </FormGroup>
112
106
  <FormGroup legendText={''}>
@@ -117,7 +111,7 @@ const StockSourcesAddOrUpdate: React.FC<Workspace2DefinitionProps<AddStockSource
117
111
  placeholder="e.g NMS"
118
112
  size="md"
119
113
  type="text"
120
- value={model?.acronym}
114
+ value={formModel.acronym ?? ''}
121
115
  />
122
116
  </FormGroup>
123
117
  <Select
@@ -0,0 +1,40 @@
1
+ import { renderHook } from '@testing-library/react';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { useStockSources } from './stock-sources.resource';
4
+ import useStockSourcesPage from './stock-sources-items-table.resource';
5
+
6
+ vi.mock('./stock-sources.resource', () => ({ useStockSources: vi.fn() }));
7
+
8
+ const source = { uuid: 'source-uuid', name: 'Community' };
9
+
10
+ describe('useStockSourcesPage', () => {
11
+ it('uses the number of results as the total when the backend returns a null totalCount', () => {
12
+ vi.mocked(useStockSources).mockReturnValue({
13
+ items: { results: [source], totalCount: null },
14
+ isLoading: false,
15
+ } as never);
16
+
17
+ const { result } = renderHook(() => useStockSourcesPage({}));
18
+
19
+ expect(result.current.totalItems).toBe(1);
20
+ });
21
+
22
+ it('uses the totalCount from the backend when there is one', () => {
23
+ vi.mocked(useStockSources).mockReturnValue({
24
+ items: { results: [source], totalCount: 12 },
25
+ isLoading: false,
26
+ } as never);
27
+
28
+ const { result } = renderHook(() => useStockSourcesPage({}));
29
+
30
+ expect(result.current.totalItems).toBe(12);
31
+ });
32
+
33
+ it('returns a total of zero before the sources have loaded', () => {
34
+ vi.mocked(useStockSources).mockReturnValue({ items: {}, isLoading: true } as never);
35
+
36
+ const { result } = renderHook(() => useStockSourcesPage({}));
37
+
38
+ expect(result.current.totalItems).toBe(0);
39
+ });
40
+ });
@@ -40,7 +40,8 @@ export default function useStockSourcesPage(filter: StockOperationFilter) {
40
40
 
41
41
  return {
42
42
  items: paginatedItems,
43
- totalItems: items?.totalCount,
43
+ // The backend returns a null totalCount for an unfiltered request
44
+ totalItems: items?.totalCount ?? items?.results?.length ?? 0,
44
45
  currentPage,
45
46
  currentPageSize,
46
47
  paginatedItems,
@@ -0,0 +1,49 @@
1
+ import React from 'react';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { render, screen } from '@testing-library/react';
4
+ import userEvent from '@testing-library/user-event';
5
+ import { useConfig } from '@openmrs/esm-framework';
6
+ import { mockWorkspace2Props } from '@mocks';
7
+ import useSearchUser from '../../stock-operations/stock-operations-forms/hooks/useSearchUser';
8
+ import AddStockUserRoleScope from './add-stock-user-role-scope.workspace';
9
+
10
+ vi.mock('../../stock-lookups/stock-lookups.resource', () => ({
11
+ useRoles: vi.fn(() => ({ isLoading: false })),
12
+ useStockOperationTypes: vi.fn(() => ({ types: { results: [] }, isLoading: false })),
13
+ useStockTagLocations: vi.fn(() => ({ stockLocations: [], isLoading: false })),
14
+ useUser: vi.fn(() => ({ data: {} })),
15
+ }));
16
+ vi.mock('../../stock-operations/stock-operations-forms/hooks/useSearchUser', () => ({ default: vi.fn() }));
17
+ vi.mock('../stock-user-role-scopes.resource', () => ({ createOrUpdateUserRoleScope: vi.fn() }));
18
+ vi.mock('../../utils', () => ({ useHandleMutate: vi.fn(() => vi.fn()) }));
19
+
20
+ describe('AddStockUserRoleScope stock roles', () => {
21
+ beforeEach(() => {
22
+ vi.mocked(useConfig).mockReturnValue({ stockRoleUUIDs: ['configured-role-uuid'] });
23
+ vi.mocked(useSearchUser).mockReturnValue({
24
+ userList: [
25
+ {
26
+ uuid: 'user-uuid',
27
+ display: 'Jane Doe',
28
+ roles: [
29
+ { uuid: 'configured-role-uuid', display: 'Central Store Clerk' },
30
+ { uuid: 'other-role-uuid', display: 'Provider' },
31
+ ],
32
+ },
33
+ ],
34
+ setSearchString: vi.fn(),
35
+ isLoading: false,
36
+ } as never);
37
+ });
38
+
39
+ it('identifies stock roles by the configured role UUIDs', async () => {
40
+ const user = userEvent.setup();
41
+ render(<AddStockUserRoleScope {...mockWorkspace2Props({})} />);
42
+
43
+ await user.click(screen.getByRole('combobox', { name: 'User' }));
44
+ await user.click(screen.getByRole('option', { name: 'Jane Doe' }));
45
+
46
+ expect(screen.getByRole('option', { name: 'Central Store Clerk' })).toBeInTheDocument();
47
+ expect(screen.queryByRole('option', { name: 'Provider' })).not.toBeInTheDocument();
48
+ });
49
+ });
@@ -22,6 +22,7 @@ import {
22
22
  getCoreTranslation,
23
23
  restBaseUrl,
24
24
  showSnackbar,
25
+ useConfig,
25
26
  useLayoutType,
26
27
  useSession,
27
28
  Workspace2,
@@ -33,22 +34,13 @@ import {
33
34
  useStockTagLocations,
34
35
  useUser,
35
36
  } from '../../stock-lookups/stock-lookups.resource';
37
+ import { type ConfigObject } from '../../config-schema';
36
38
  import { ResourceRepresentation } from '../../core/api/api';
37
39
  import { type UserRoleScope } from '../../core/api/types/identity/UserRoleScope';
38
40
  import { createOrUpdateUserRoleScope } from '../stock-user-role-scopes.resource';
39
41
  import { type UserRoleScopeOperationType } from '../../core/api/types/identity/UserRoleScopeOperationType';
40
42
  import { type UserRoleScopeLocation } from '../../core/api/types/identity/UserRoleScopeLocation';
41
- import {
42
- DATE_PICKER_CONTROL_FORMAT,
43
- DATE_PICKER_FORMAT,
44
- formatForDatePicker,
45
- INVENTORY_ADMINISTRATOR_ROLE_UUID,
46
- INVENTORY_CLERK_ROLE_UUID,
47
- INVENTORY_DISPENSING_ROLE_UUID,
48
- INVENTORY_MANAGER_ROLE_UUID,
49
- INVENTORY_REPORTING_ROLE_UUID,
50
- today,
51
- } from '../../constants';
43
+ import { DATE_PICKER_CONTROL_FORMAT, DATE_PICKER_FORMAT, formatForDatePicker, today } from '../../constants';
52
44
  import { type Role } from '../../core/api/types/identity/Role';
53
45
  import { type StockOperationType } from '../../core/api/types/stockOperation/StockOperationType';
54
46
  import { type User } from '../../core/api/types/identity/User';
@@ -70,6 +62,7 @@ const AddStockUserRoleScope: React.FC<Workspace2DefinitionProps<AddStockUserRole
70
62
  }) => {
71
63
  const { model, editMode } = workspaceProps ?? {};
72
64
  const { t } = useTranslation();
65
+ const { stockRoleUUIDs } = useConfig<ConfigObject>();
73
66
  const handleMutate = useHandleMutate();
74
67
  const title = model
75
68
  ? t('editUserRoleScope', 'Edit user role scope')
@@ -117,7 +110,7 @@ const AddStockUserRoleScope: React.FC<Workspace2DefinitionProps<AddStockUserRole
117
110
  });
118
111
 
119
112
  /* Only load locations tagged to perform stock related activities.
120
- Unless a location is tag as main store, main pharmacy or dispensing, it will not be listed here.
113
+ Unless a location has one of the tags configured in `stockLocationTags`, it will not be listed here.
121
114
  */
122
115
  const { stockLocations, isLoading: isLoadingStockLocations } = useStockTagLocations();
123
116
  const onEnabledChanged = (): void => {
@@ -190,16 +183,8 @@ const AddStockUserRoleScope: React.FC<Workspace2DefinitionProps<AddStockUserRole
190
183
  };
191
184
 
192
185
  const onUserChanged = (data: { selectedItem: User }) => {
193
- const stockRolesUUIDs = [
194
- INVENTORY_CLERK_ROLE_UUID,
195
- INVENTORY_MANAGER_ROLE_UUID,
196
- INVENTORY_DISPENSING_ROLE_UUID,
197
- INVENTORY_REPORTING_ROLE_UUID,
198
- INVENTORY_ADMINISTRATOR_ROLE_UUID,
199
- ];
200
-
201
186
  const filteredStockRoles = data.selectedItem?.roles
202
- .filter((role) => stockRolesUUIDs.includes(role.uuid))
187
+ .filter((role) => stockRoleUUIDs.includes(role.uuid))
203
188
  .filter((role) => role.uuid !== loggedInUserUuid);
204
189
  setFormModel({ ...formModel, userUuid: data.selectedItem?.uuid });
205
190
  setRoles(filteredStockRoles ?? []);