AccessionListPage.tsx 9.44 KB
Newer Older
Matija Obreza's avatar
Matija Obreza committed
1
2
3
import React from 'react';
import { Link } from 'react-router-dom';
import { parse } from 'query-string';
Oleksii Savran's avatar
Redux    
Oleksii Savran committed
4
import { connect } from 'react-redux';
Matija Obreza's avatar
Matija Obreza committed
5
6
7
8
9

import { AccessionService } from '@genesys/client/service';
import AccessionFilter from '@genesys/client/model/accession/AccessionFilter';
import Accession from '@genesys/client/model/accession/Accession';
import FilteredPage, { IPageRequest } from '@genesys/client/model/FilteredPage';
Oleksii Savran's avatar
Oleksii Savran committed
10
import Pagination from 'ui/common/Pagination';
Matija Obreza's avatar
Matija Obreza committed
11
import { AccessionFilters } from './AccessionFilters';
Matija Obreza's avatar
Matija Obreza committed
12
import { withTranslation, WithTranslation } from 'react-i18next';
Matija Obreza's avatar
Matija Obreza committed
13
import { canAddToCart, LocalStorageCart } from 'utilities';
14
import { WithConfig } from 'config/config';
Maksym Tishchenko's avatar
Maksym Tishchenko committed
15
import Loading from 'ui/common/Loading';
Maksym Tishchenko's avatar
Maksym Tishchenko committed
16
import PageTitle from 'ui/common/PageTitle';
Maksym Tishchenko's avatar
Maksym Tishchenko committed
17
import { CountryName } from 'ui/common/CountryName';
Matija Obreza's avatar
Matija Obreza committed
18
19
20
21

interface IAccessionListPageState {
  filter: AccessionFilter;
  accessions: FilteredPage<Accession>;
Oleksii Savran's avatar
Oleksii Savran committed
22
  selected: string[];
Maksym Tishchenko's avatar
Maksym Tishchenko committed
23
  cartItems: string[];
Oleksii Savran's avatar
Oleksii Savran committed
24
  isAllSelected: boolean;
Matija Obreza's avatar
Matija Obreza committed
25
26
27
28
29
30
}

interface IAccessionListPageProps {
  location: any;
}

31
class AccessionListPage extends React.Component<IAccessionListPageProps & WithTranslation & WithConfig, IAccessionListPageState> {
Matija Obreza's avatar
Matija Obreza committed
32
33
34
35
  public constructor(props) {
    super(props);

    this.state = {
36
      filter: this.props.appConfig.filter,
Matija Obreza's avatar
Matija Obreza committed
37
      accessions: null,
Oleksii Savran's avatar
Oleksii Savran committed
38
39
      selected: [],
      isAllSelected: false,
Maksym Tishchenko's avatar
Maksym Tishchenko committed
40
      cartItems: LocalStorageCart.getCartItemsLS(),
Matija Obreza's avatar
Matija Obreza committed
41
42
43
44
45
46
    }
  }

  public componentDidMount() {
    const { current, filterCode } = this.parseLocationSearch(this.props.location);
    this.loadData(filterCode || this.state.filter, current ? { page: current } : {});
Maksym Tishchenko's avatar
Maksym Tishchenko committed
47
48
49
50
    if (typeof window !== 'undefined') {
      window.addEventListener('storage', this.handleLocalStorageUpdate);
      this.receiveData();
    }
Matija Obreza's avatar
Matija Obreza committed
51
52
  }

Maksym Tishchenko's avatar
Maksym Tishchenko committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
  public componentWillUnmount() {
    if (typeof window !== 'undefined') {
      window.removeEventListener('storage', this.handleLocalStorageUpdate);
    }
  }

  private handleLocalStorageUpdate = (e: StorageEvent) => {
    if (e.key === LocalStorageCart.LS_KEY) {
      this.receiveData();
    }
  };

  private receiveData = () => {
    this.setState({ cartItems: LocalStorageCart.getCartItemsLS() });
  };

Matija Obreza's avatar
Matija Obreza committed
69
70
71
72
73
74
  public componentDidUpdate(prevProps) {
    const { current: currentPage, filterCode } = this.parseLocationSearch(this.props.location);
    const { current: prevPage, filterCode: prevFilterCode } = this.parseLocationSearch(prevProps.location);

    if (prevPage !== undefined && currentPage === 0 && prevFilterCode !== undefined && filterCode === undefined) {
      // console.log('did update, reset filter);
75
      this.loadData(this.props.appConfig.filter, {});
Matija Obreza's avatar
Matija Obreza committed
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
    }
  }

  private parseLocationSearch = (location) => {
    const current = +parse(location.search).p || 0;
    const filterCode = parse(location.search).filter && parse(location.search).filter.toString();
    // const size = +parse(location.search).l || 20;
    // const sort = parse(location.search).s;
    // const dir = parse(location.search).d;

    return { current, filterCode /* , size, sort, dir, */ };
  };

  private loadData = (filter: string | AccessionFilter, pageR: IPageRequest): Promise<any> => {
    return AccessionService
      .list(filter, pageR)
      .then((data) => {
        // console.log('accessions: ', data);
        this.setState({ accessions: data, filter: data.filter });
        return data;
      })
      .catch((e) => {
        console.log('Api call failed: ', e);
      });
  };

  private applyFilter = (filter: AccessionFilter) => {
    this.loadData({ ...this.state.filter, ...filter }, {});
  };

Oleksii Savran's avatar
Oleksii Savran committed
106
107
  private toggleRowSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { selected } = this.state;
Oleksii Savran's avatar
Oleksii Savran committed
108
109
    const { uuid } = (e.currentTarget as HTMLElement).dataset;
    const updated = selected.filter((selectedUuid) => selectedUuid !== uuid);
Oleksii Savran's avatar
Oleksii Savran committed
110
    if (updated.length === selected.length) {
Oleksii Savran's avatar
Oleksii Savran committed
111
      updated.push(uuid);
Oleksii Savran's avatar
Oleksii Savran committed
112
113
114
115
116
117
    }
    this.setState({ selected: updated });
  };

  private addSelectedToCart = () => {
    LocalStorageCart.addToCart(this.state.selected);
Maksym Tishchenko's avatar
Maksym Tishchenko committed
118
119
120
121
122
    this.setState({ selected: [], isAllSelected: false, cartItems: LocalStorageCart.getCartItemsLS() });
  };
  private addToCart = (e: React.MouseEvent<HTMLButtonElement>) => {
    LocalStorageCart.addToCart(e.currentTarget.getAttribute('data-uuid'));
    this.setState( { cartItems: LocalStorageCart.getCartItemsLS() } )
Oleksii Savran's avatar
Oleksii Savran committed
123
  };
Maksym Tishchenko's avatar
Maksym Tishchenko committed
124
125
126
127
128
129
130
131
  private removeFromCart = (e: React.MouseEvent<HTMLButtonElement>) => {
    LocalStorageCart.removeFromCart(e.currentTarget.getAttribute('data-uuid'));
    this.setState( { cartItems: LocalStorageCart.getCartItemsLS() } )
  }

  private renderCartButton = (accession, i) => {
    const { t } = this.props;
    const { cartItems } = this.state;
Matija Obreza's avatar
Matija Obreza committed
132
    if (!canAddToCart(accession)) {
Maksym Tishchenko's avatar
Maksym Tishchenko committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
      return <span>{t('list.notAvailable')}</span>
    }
    if ( cartItems.includes(accession.uuid)) {
      return <button
        type="button"
        name={ `button-remove-${accession.uuid}-${i}` }
        data-uuid={ accession.uuid }
        onClick={ this.removeFromCart }
        className="btn btn-primary"
      >
        { t('cart.removeFromCart') }
      </button>
    }
    return <button
      type="button"
      name={ `button-add-${accession.uuid}-${i}` }
      data-uuid={ accession.uuid }
      onClick={ this.addToCart }
      className="btn btn-primary"
    >
      { t('cart.addToCart') }
    </button>
  }
Oleksii Savran's avatar
Oleksii Savran committed
156
157
158
159

  private onToggleAll = () => {
    this.setState((prevState) => ({
      isAllSelected: !prevState.isAllSelected,
Matija Obreza's avatar
Matija Obreza committed
160
      selected: !prevState.isAllSelected ? prevState.accessions.content.map((acc) => canAddToCart(acc) && acc.uuid) : [],
Oleksii Savran's avatar
Oleksii Savran committed
161
162
163
    }));
  };

Matija Obreza's avatar
Matija Obreza committed
164
  public render() {
Oleksii Savran's avatar
Oleksii Savran committed
165
    const { accessions, selected, isAllSelected } = this.state;
Maksym Tishchenko's avatar
Maksym Tishchenko committed
166
    const { t, appConfig: { shoppingCart } } = this.props;
Oleksii Savran's avatar
Oleksii Savran committed
167
168
    const selectedUUIDs = new Set();
    selected.forEach((uuid) => selectedUUIDs.add(uuid));
Oleksii Savran's avatar
Oleksii Savran committed
169

Matija Obreza's avatar
Matija Obreza committed
170
171
    if (accessions === null) {
      return (
Maksym Tishchenko's avatar
Maksym Tishchenko committed
172
173
174
175
        <>
          <PageTitle title={ t('pagetitle.accessionList') }/>
          <Loading/>
        </>
Matija Obreza's avatar
Matija Obreza committed
176
177
178
179
      );
    } else {
      return (
        <>
Maksym Tishchenko's avatar
Maksym Tishchenko committed
180
          <PageTitle title={ t('pagetitle.accessionList') }/>
Oleksii Savran's avatar
Oleksii Savran committed
181
182
183
184
185
186
187
188
          <h1 className="d-flex justify-content-between align-items-center">
            { t('estimatedNumberOfItems', { count: accessions.totalElements, what: t('accession.model', { count: accessions.totalElements }) }) }
            { selected.length !== 0 &&
              <button type="button" className="btn btn-primary" onClick={ this.addSelectedToCart }>
                { t('cart.addToCart') }
              </button>
            }
          </h1>
Matija Obreza's avatar
Matija Obreza committed
189
190
191
192
          <AccessionFilters filter={ this.state.filter } applyFilter={ this.applyFilter } key={ `filters-${accessions.filterCode}` }/>
          <Pagination loadData={ this.loadData } paged={ accessions }>
            <table className="table table-striped">
              <thead className="thead-dark">
Oleksii Savran's avatar
Oleksii Savran committed
193
                <tr>
194
                  { shoppingCart.enabled && (
195
196
197
198
199
200
201
202
203
204
                    <th>
                      <input
                        type="checkbox"
                        name="select-all"
                        checked={ isAllSelected }
                        onChange={ this.onToggleAll }
                        className="align-middle"
                      />
                    </th>
                  ) }
Oleksii Savran's avatar
Oleksii Savran committed
205
206
207
                  <th>{ t('accession.crop') }</th>
                  <th>{ t('accession.acceNumb') }</th>
                  <th>{ t('accession.accessionName') }</th>
208
                  <th>{ t('accession.taxonomy.scientificName') }</th>
Oleksii Savran's avatar
Oleksii Savran committed
209
210
                  <th>{ t('accession.countryOfOrigin') }</th>
                  <th>{ t('accession.sampStat') }</th>
211
                  { shoppingCart.enabled && ( <th>{ t('list.availability') }</th> ) }
Oleksii Savran's avatar
Oleksii Savran committed
212
                </tr>
Matija Obreza's avatar
Matija Obreza committed
213
214
              </thead>
              <tbody>
Oleksii Savran's avatar
Oleksii Savran committed
215
                { accessions.content.map((a, i) => (
Oleksii Savran's avatar
Oleksii Savran committed
216
                  <tr key={ a.id } className={ selectedUUIDs.has(a.uuid) ? 'table-primary' : '' }>
217
                    { shoppingCart.enabled && (
218
                      <td>
Matija Obreza's avatar
Matija Obreza committed
219
                        { canAddToCart(a) &&
220
221
222
223
224
225
226
227
228
229
230
                          <input
                            type="checkbox"
                            name={ `checkbox-${a.uuid}-${i}` }
                            data-uuid={ a.uuid }
                            checked={ selectedUUIDs.has(a.uuid) }
                            onChange={ this.toggleRowSelect }
                            className="align-middle"
                          />
                        }
                      </td>
                    ) }
231
                    <td>{ a.crop && a.crop.name || a.cropName }</td>
Oleksii Savran's avatar
Oleksii Savran committed
232
                    <td><Link to={ `/a/${a.uuid}` }>{ a.accessionNumber }</Link></td>
233
                    <td>{ a.accessionName && <b>{ a.accessionName }</b> }</td>
Oleksii Savran's avatar
Oleksii Savran committed
234
                    <td><span dangerouslySetInnerHTML={ { __html: a.taxonomy.taxonNameHtml } } /></td>
Maksym Tishchenko's avatar
Maksym Tishchenko committed
235
                    <td>{ a.countryOfOrigin && (<CountryName code3={ a.countryOfOrigin.code3 } /> || a.countryOfOrigin.name) }</td>
Oleksii Savran's avatar
Oleksii Savran committed
236
                    <td>{ a.sampStat && t(`accession.sampleStatus.${a.sampStat}`) }</td>
237
                    { shoppingCart.enabled &&
238
239
240
241
                      <td>
                        { this.renderCartButton(a, i) }
                      </td>
                    }
Oleksii Savran's avatar
Oleksii Savran committed
242
243
                  </tr>
                )) }
Matija Obreza's avatar
Matija Obreza committed
244
245
246
247
248
249
250
251
              </tbody>
            </table>
          </Pagination>
        </>
      );
    }
  };
}
Matija Obreza's avatar
Matija Obreza committed
252

Oleksii Savran's avatar
Redux    
Oleksii Savran committed
253
const mapStateToProps = (state) => ({
254
  appConfig: state.appConfig.config,
Oleksii Savran's avatar
Redux    
Oleksii Savran committed
255
256
257
});

export default connect(mapStateToProps)(withTranslation()(AccessionListPage));