AccessionListPage.tsx 9.62 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';
Oleksii Savran's avatar
Oleksii Savran committed
13
import { 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
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
  private removeFromCart = (e: React.MouseEvent<HTMLButtonElement>) => {
    LocalStorageCart.removeFromCart(e.currentTarget.getAttribute('data-uuid'));
    this.setState( { cartItems: LocalStorageCart.getCartItemsLS() } )
  }

  private canAddToCart = (accession) => {
    return !(accession.historic === true || accession.available === false || accession.institute.allowMaterialRequests === true);
  }

  private renderCartButton = (accession, i) => {
    const { t } = this.props;
    const { cartItems } = this.state;
    if (!this.canAddToCart(accession)) {
      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
160
161
162
163

  private onToggleAll = () => {
    this.setState((prevState) => ({
      isAllSelected: !prevState.isAllSelected,
Maksym Tishchenko's avatar
Maksym Tishchenko committed
164
      selected: !prevState.isAllSelected ? prevState.accessions.content.map((acc) => this.canAddToCart(acc) && acc.uuid) : [],
Oleksii Savran's avatar
Oleksii Savran committed
165
166
167
    }));
  };

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

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

Oleksii Savran's avatar
Redux    
Oleksii Savran committed
257
const mapStateToProps = (state) => ({
258
  appConfig: state.appConfig.config,
Oleksii Savran's avatar
Redux    
Oleksii Savran committed
259
260
261
});

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