All files / src/stock-items stock-items-table.component.tsx

100% Statements 32/32
74.07% Branches 20/27
100% Functions 16/16
100% Lines 31/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276                                                                                1x 19x 19x 19x   19x 1x                           19x     19x 11x     19x 2x     19x 18x     19x 7x                                                                                         19x 150x                                           1x 1x                 19x 1x     17x             23x                                 11x                                         184x                     184x 184x                           575x                 4600x                                               2x 2x                        
import React, { useMemo, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
  DataTable,
  DataTableSkeleton,
  IconButton,
  Pagination,
  Table,
  TableBatchActions,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableHeader,
  TableRow,
  TableToolbar,
  TableToolbarAction,
  TableToolbarContent,
  TableToolbarMenu,
  TableToolbarSearch,
  Tile,
} from '@carbon/react';
import { Edit } from '@carbon/react/icons';
import { isDesktop, restBaseUrl } from '@openmrs/esm-framework';
import { useHandleMutate } from '../utils';
import { launchAddOrEditStockItemWorkspace } from './stock-item.utils';
import { ResourceRepresentation } from '../core/api/api';
import { useDebounce } from '../core/hooks/debounce-hook';
import { useStockItemsPages } from './stock-items-table.resource';
import AddStockItemActionButton from './add-stock-item/add-stock-action-button.component';
import AddStockItemsBulktImportActionButton from './add-bulk-stock-item/add-stock-items-bulk-import-action-button.component';
import EditStockItemActionsMenu from './edit-stock-item/edit-stock-item-action-menu.component';
import FilterStockItems from './components/filter-stock-items/filter-stock-items.component';
import { type CustomTableHeader } from '../core/components/table/types';
import styles from './stock-items-table.scss';
 
interface StockItemsTableProps {
  from?: string;
}
 
const StockItemsTableComponent: React.FC<StockItemsTableProps> = () => {
  const { t } = useTranslation();
  const handleMutate = useHandleMutate();
  const [searchInput, setSearchInput] = useState('');
 
  const handleRefresh = () => {
    handleMutate(`${restBaseUrl}/stockmanagement/stockitem`);
  };
 
  const {
    currentPage,
    currentPageSize,
    isDrug,
    isLoading,
    items,
    pageSizes,
    setCurrentPage,
    setDrug,
    setPageSize,
    setSearchString,
    totalCount,
  } = useStockItemsPages(ResourceRepresentation.Full);
 
  const handleSearch = (query: string) => {
    setSearchInput(query);
  };
 
  const debouncedSearch = useDebounce((query: string) => {
    setSearchString(query);
  }, 1000);
 
  useEffect(() => {
    debouncedSearch(searchInput);
  }, [searchInput, debouncedSearch]);
 
  const tableHeaders = useMemo(
    () => [
      {
        id: 0,
        header: t('type', 'Type'),
        key: 'type',
      },
      {
        id: 1,
        header: t('genericName', 'Generic name'),
        key: 'genericName',
      },
      {
        id: 2,
        header: t('commonName', 'Common name'),
        key: 'commonName',
      },
      {
        id: 3,
        header: t('tradeName', 'Trade name'),
        key: 'tradeName',
      },
      {
        id: 4,
        header: t('dispensingUnitName', 'Dispensing UoM'),
        key: 'dispensingUnitName',
      },
      {
        id: 5,
        header: t('defaultStockOperationsUoMName', 'Bulk packaging'),
        key: 'defaultStockOperationsUoMName',
      },
      {
        id: 6,
        header: t('reorderLevel', 'Reorder level'),
        key: 'reorderLevel',
      },
      {
        id: 7,
        header: t('actions', 'Actions'),
        key: 'actions',
      },
    ],
    [t],
  );
 
  const tableRows = useMemo(() => {
    return items?.map((stockItem, index) => ({
      ...stockItem,
      id: stockItem?.uuid,
      key: `key-${stockItem?.uuid}`,
      uuid: `${stockItem?.uuid}`,
      type: stockItem?.drugUuid ? t('drug', 'Drug') : t('other', 'Other'),
      genericName: <EditStockItemActionsMenu data={items[index]} />,
      commonName: stockItem?.commonName,
      tradeName: stockItem?.drugUuid ? stockItem?.conceptName : '',
      preferredVendorName: stockItem?.preferredVendorName,
      dispensingUoM: stockItem?.defaultStockOperationsUoMName,
      dispensingUnitName: stockItem?.dispensingUnitName,
      defaultStockOperationsUoMName: stockItem?.defaultStockOperationsUoMName,
      reorderLevel:
        stockItem?.reorderLevelUoMName && stockItem?.reorderLevel
          ? `${stockItem?.reorderLevel?.toLocaleString()} ${stockItem?.reorderLevelUoMName}`
          : '',
      actions: (
        <IconButton
          kind="ghost"
          label={t('editStockItem', 'Edit stock item')}
          onClick={() => {
            stockItem.isDrug = !!stockItem.drugUuid;
            launchAddOrEditStockItemWorkspace(stockItem);
          }}
        >
          <Edit size={16} />
        </IconButton>
      ),
    }));
  }, [items, t]);
 
  if (isLoading) {
    return <DataTableSkeleton role="progressbar" />;
  }
 
  return (
    <>
      <h2 className={styles.tableHeader}>
        {t('stockItemsTableHeader', 'Drugs and other stock items managed by the system.')}
      </h2>
      <DataTable rows={tableRows} headers={tableHeaders} isSortable useZebraStyles>
        {({ rows, headers, getHeaderProps, getTableProps, getRowProps, getBatchActionProps }) => (
          <TableContainer>
            <TableToolbar
              style={{
                position: 'static',
                overflow: 'visible',
                backgroundColor: 'color',
              }}
            >
              <TableBatchActions {...getBatchActionProps()} />
              <TableToolbarContent
                style={{
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                <TableToolbarSearch
                  onChange={(e) =>
                    handleSearch(typeof e === 'string' ? e : (e as React.ChangeEvent<HTMLInputElement>).target.value)
                  }
                  persistent
                  placeholder={t('searchStockItems', 'Search stock items')}
                  value={searchInput}
                />
                <FilterStockItems filterType={isDrug} changeFilterType={setDrug} />
                <AddStockItemsBulktImportActionButton />
                <TableToolbarMenu data-testid="stock-items-menu">
                  <TableToolbarAction className={styles.toolbarAction} onClick={handleRefresh}>
                    {t('refresh', 'Refresh')}
                  </TableToolbarAction>
                </TableToolbarMenu>
                <AddStockItemActionButton />
              </TableToolbarContent>
            </TableToolbar>
            <Table {...getTableProps()}>
              <TableHead>
                <TableRow>
                  {headers.map(
                    (header) =>
                      header.key !== 'details' && (
                        <TableHeader
                          {...getHeaderProps({
                            header,
                            isSortable: (header as CustomTableHeader).isSortable,
                          })}
                          className={isDesktop ? styles.desktopHeader : styles.tabletHeader}
                          key={`${header.key}`}
                          isSortable={header.key !== 'name'}
                        >
                          {(() => {
                            const customHeader = header as CustomTableHeader;
                            return typeof customHeader.header === 'object' &&
                              customHeader.header !== null &&
                              'content' in customHeader.header
                              ? (customHeader.header.content as React.ReactNode)
                              : (customHeader.header as React.ReactNode);
                          })()}
                        </TableHeader>
                      ),
                  )}
                  <TableHeader />
                </TableRow>
              </TableHead>
              <TableBody>
                {rows.map((row) => {
                  return (
                    <React.Fragment key={row.id}>
                      <TableRow
                        {...getRowProps({ row })}
                        className={isDesktop ? styles.desktopRow : styles.tabletRow}
                        key={row.id}
                      >
                        {row.cells.map(
                          (cell) =>
                            cell?.info?.header !== 'details' && <TableCell key={cell.id}>{cell.value}</TableCell>,
                        )}
                      </TableRow>
                    </React.Fragment>
                  );
                })}
              </TableBody>
            </Table>
            {rows.length === 0 ? (
              <div className={styles.tileContainer}>
                <Tile className={styles.tile}>
                  <div className={styles.tileContent}>
                    <p className={styles.content}>{t('noStockItemsToDisplay', 'No stock items to display')}</p>
                    <p className={styles.helper}>{t('checkFilters', 'Check the filters above')}</p>
                  </div>
                </Tile>
              </div>
            ) : null}
          </TableContainer>
        )}
      </DataTable>
      <Pagination
        className={styles.paginationOverride}
        onChange={({ page, pageSize }) => {
          setCurrentPage(page);
          setPageSize(pageSize);
        }}
        page={currentPage}
        pageSize={currentPageSize}
        pageSizes={pageSizes}
        totalItems={totalCount}
      />
    </>
  );
};
 
export default StockItemsTableComponent;