AccessionListPage.tsx 9.21 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';
Matija Obreza's avatar
Matija Obreza committed
14
15
16
17

interface IAccessionListPageState {
  filter: AccessionFilter;
  accessions: FilteredPage<Accession>;
Oleksii Savran's avatar
Oleksii Savran committed
18
  selected: string[];
Maksym Tishchenko's avatar
Maksym Tishchenko committed
19
  cartItems: string[];
Oleksii Savran's avatar
Oleksii Savran committed
20
  isAllSelected: boolean;
Matija Obreza's avatar
Matija Obreza committed
21
22
23
24
25
}

interface IAccessionListPageProps {
  filter: AccessionFilter;
  location: any;
26
  cartEnabled: boolean;
Matija Obreza's avatar
Matija Obreza committed
27
28
}

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

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

  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
45
46
47
48
    if (typeof window !== 'undefined') {
      window.addEventListener('storage', this.handleLocalStorageUpdate);
      this.receiveData();
    }
Matija Obreza's avatar
Matija Obreza committed
49
50
  }

Maksym Tishchenko's avatar
Maksym Tishchenko committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
  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
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
  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);
      this.loadData(this.props.filter, {});
    }
  }

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

  private addSelectedToCart = () => {
    LocalStorageCart.addToCart(this.state.selected);
Maksym Tishchenko's avatar
Maksym Tishchenko committed
116
117
118
119
120
    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
121
  };
Maksym Tishchenko's avatar
Maksym Tishchenko committed
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
  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
158
159
160
161

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

Matija Obreza's avatar
Matija Obreza committed
166
  public render() {
Oleksii Savran's avatar
Oleksii Savran committed
167
    const { accessions, selected, isAllSelected } = this.state;
168
    const { t, cartEnabled } = this.props;
Oleksii Savran's avatar
Oleksii Savran committed
169
170
    const selectedUUIDs = new Set();
    selected.forEach((uuid) => selectedUUIDs.add(uuid));
Oleksii Savran's avatar
Oleksii Savran committed
171

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

Oleksii Savran's avatar
Redux    
Oleksii Savran committed
251
252
const mapStateToProps = (state) => ({
  filter: state.appConfig.config.filter,
253
  cartEnabled: state.appConfig.config.request.enabled,
Oleksii Savran's avatar
Redux    
Oleksii Savran committed
254
255
256
});

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