summaryrefslogtreecommitdiff
path: root/src/lib/ServiceList.tsx
blob: 5abae6b7d733665113b7fee3f4e12261460c69f0 (plain)
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
import React, { useContext } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import _ from 'lodash';
import Page from '../containers/Page';
import ListTable from '../components/ListTable';
import hooks from '../hooks/useAPIClient';
import ServiceContext, { Filter } from './ServiceContext';
import useQuery from '../hooks/useQuery';

const getOptionLabel = (item: any, filter: Filter) => {
  const value = _.get(item, filter.as || filter.key);
  return filter.transform ? filter.transform(value) : value;
};

const ServiceList: React.FC = () => {
  const service = useContext(ServiceContext);
  const history = useHistory();
  const location = useLocation();
  const query = useQuery();
  const { data } = hooks[service.route].useList(location.search);
  const { data: unfilteredData } = hooks[service.route].useList('', { revalidateOnMount: !!location.search });

  const actions = service.actions || [{
    name: 'Добавить',
    route: `/${service.route}/add${location.search}`,
  }];

  const filters = service.filters?.map(filter => {
    const options = _
      .uniqBy(unfilteredData, filter.key)
      .map((item: any) => ({
        key: _.get(item, filter.key),
        label: getOptionLabel(item, filter),
      }));

    // Add default option
    options?.unshift({
      key: '-',
      label: filter.label,
    });

    const value = _.get(query, filter.key);

    return { ...filter, options, value };
  });

  const handleRowClick = (item: any) => {
    const route = service.rowLink
      ? service.rowLink(item)
      : `/${service.route}/${item?._id}`;

    history.push(route);
  };

  return (
    <Page title={service.name} actions={actions} filters={filters}>
      <ListTable items={data} fields={service.tableFields} handleRowClick={handleRowClick} />
    </Page>
  );
};

export default ServiceList;