Passed
Push — master ( 669be3...4762c7 )
by Guangyu
19:25 queued 10s
created

src/components/MyEMS/Equipment/EquipmentTracking.js   A

Complexity

Total Complexity 7
Complexity/F 0

Size

Lines of Code 293
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 257
mnd 7
bc 7
fnc 0
dl 0
loc 293
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import React, { createRef, Fragment, useEffect, useState } from 'react';
2
import {
3
  Breadcrumb,
4
  BreadcrumbItem,
5
  Card,
6
  CardBody,
7
  Col,
8
  DropdownItem,
9
  DropdownMenu,
10
  DropdownToggle,
11
  Form,
12
  FormGroup,
13
  Input,
14
  Label,
15
  Media,
16
  Row,
17
  UncontrolledDropdown,
18
  Spinner,
19
} from 'reactstrap';
20
import uuid from 'uuid/v1';
21
import Cascader from 'rc-cascader';
22
import loadable from '@loadable/component';
23
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
24
import { Link } from 'react-router-dom';
25
import Flex from '../../common/Flex';
26
import { getCookieValue, createCookie } from '../../../helpers/utils';
27
import withRedirect from '../../../hoc/withRedirect';
28
import { withTranslation } from 'react-i18next';
29
import { toast } from 'react-toastify';
30
import { APIBaseURL } from '../../../config';
31
32
33
const EquipmentTracking = ({ setRedirect, setRedirectUrl, t }) => {
34
  useEffect(() => {
35
    let is_logged_in = getCookieValue('is_logged_in');
36
    let user_name = getCookieValue('user_name');
37
    let user_display_name = getCookieValue('user_display_name');
38
    let user_uuid = getCookieValue('user_uuid');
39
    let token = getCookieValue('token');
40
    if (is_logged_in === null || !is_logged_in) {
41
      setRedirectUrl(`/authentication/basic/login`);
42
      setRedirect(true);
43
    } else {
44
      //update expires time of cookies
45
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
46
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
47
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
48
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
49
      createCookie('token', token, 1000 * 60 * 60 * 8);
50
    }
51
  });
52
  let table = createRef();
53
 
54
  // State
55
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
56
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
57
  const [equipmentList, setEquipmentList] = useState([]);
58
  const [spinnerHidden, setSpinnerHidden] = useState(false);
59
  
60
  useEffect(() => {
61
    let isResponseOK = false;
62
    fetch(APIBaseURL + '/spaces/tree', {
63
      method: 'GET',
64
      headers: {
65
        "Content-type": "application/json",
66
        "User-UUID": getCookieValue('user_uuid'),
67
        "Token": getCookieValue('token')
68
      },
69
      body: null,
70
71
    }).then(response => {
72
      console.log(response);
73
      if (response.ok) {
74
        isResponseOK = true;
75
      }
76
      return response.json();
77
    }).then(json => {
78
      console.log(json)
79
      if (isResponseOK) {
80
        // rename keys 
81
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
82
        setCascaderOptions(json);
83
        setSelectedSpaceName([json[0]].map(o => o.label));
84
        let selectedSpaceID  = [json[0]].map(o => o.value);
85
        // begin of getting equipment list
86
        let isSecondResponseOK = false;
87
        fetch(APIBaseURL + '/reports/equipmenttracking?' +
88
          'spaceid=' + selectedSpaceID, {
89
          method: 'GET',
90
          headers: {
91
            "Content-type": "application/json",
92
            "User-UUID": getCookieValue('user_uuid'),
93
            "Token": getCookieValue('token')
94
          },
95
          body: null,
96
97
        }).then(response => {
98
          if (response.ok) {
99
            isSecondResponseOK = true;
100
          }
101
          return response.json();
102
        }).then(json => {
103
          if (isSecondResponseOK) {
104
            json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
105
            console.log(json)
106
            let equipments = [];
107
            json[0].forEach((currentValue, index) => {
108
              equipments.push({
109
                'key': index,
110
                'id': currentValue['id'],
111
                'name': currentValue['equipment_name'],
112
                'space': currentValue['space_name'],
113
                'costcenter': currentValue['cost_center_name'],
114
                'description': currentValue['description']});
115
            });
116
            setEquipmentList(equipments);
117
            setSpinnerHidden(true);
118
          } else {
119
            toast.error(json.description)
120
          }
121
        }).catch(err => {
122
          console.log(err);
123
        });
124
        // end of getting equipment list
125
      } else {
126
        toast.error(json.description);
127
      }
128
    }).catch(err => {
129
      console.log(err);
130
    });
131
132
  }, []);
133
  const DetailedDataTable = loadable(() => import('../common/DetailedDataTable'));
134
135
  const nameFormatter = (dataField, { name }) => (
136
    <Link to="#">
137
      <Media tag={Flex} align="center">
138
        <Media body className="ml-2">
139
          <h5 className="mb-0 fs--1">{name}</h5>
140
        </Media>
141
      </Media>
142
    </Link>
143
  );
144
145
  const actionFormatter = (dataField, { id }) => (
146
    // Control your row with this id
147
    <UncontrolledDropdown>
148
      <DropdownToggle color="link" size="sm" className="text-600 btn-reveal mr-3">
149
        <FontAwesomeIcon icon="ellipsis-h" className="fs--1" />
150
      </DropdownToggle>
151
      <DropdownMenu right className="border py-2">
152
      <DropdownItem onClick={() => console.log('Edit: ', id)}>{t('Edit Equipment')}</DropdownItem>
153
      </DropdownMenu>
154
    </UncontrolledDropdown>
155
  );
156
157
  const columns = [
158
    {
159
      key: "a0",
160
      dataField: 'equipmentname',
161
      headerClasses: 'border-0',
162
      text: t('Name'),
163
      classes: 'border-0 py-2 align-middle',
164
      formatter: nameFormatter,
165
      sort: true
166
    },
167
    {
168
      key: "a1",
169
      dataField: 'space',
170
      headerClasses: 'border-0',
171
      text: t('Space'),
172
      classes: 'border-0 py-2 align-middle',
173
      sort: true
174
    },
175
    {
176
      key: "a2",
177
      dataField: 'costcenter',
178
      headerClasses: 'border-0',
179
      text: t('Cost Center'),
180
      classes: 'border-0 py-2 align-middle',
181
      sort: true
182
    },
183
    {
184
      key: "a3",
185
      dataField: 'description',
186
      headerClasses: 'border-0',
187
      text: t('Description'),
188
      classes: 'border-0 py-2 align-middle',
189
      sort: true
190
    },
191
    {
192
      key: "a4",
193
      dataField: '',
194
      headerClasses: 'border-0',
195
      text: '',
196
      classes: 'border-0 py-2 align-middle',
197
      formatter: actionFormatter,
198
      align: 'right'
199
    }
200
  ];
201
202
  const labelClasses = 'ls text-uppercase text-600 font-weight-semi-bold mb-0';
203
204
  let onSpaceCascaderChange = (value, selectedOptions) => {
205
    setSelectedSpaceName(selectedOptions.map(o => o.label).join('/'));
206
    let selectedSpaceID = value[value.length - 1];
207
    setSpinnerHidden(false);
208
    // begin of getting equipment list
209
    let isResponseOK = false;
210
    fetch(APIBaseURL + '/reports/equipmenttracking?' +
211
      'spaceid=' + selectedSpaceID, {
212
      method: 'GET',
213
      headers: {
214
        "Content-type": "application/json",
215
        "User-UUID": getCookieValue('user_uuid'),
216
        "Token": getCookieValue('token')
217
      },
218
      body: null,
219
220
    }).then(response => {
221
      if (response.ok) {
222
        isResponseOK = true;
223
      }
224
      return response.json();
225
    }).then(json => {
226
      if (isResponseOK) {
227
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
228
        console.log(json)
229
        let equipments = [];
230
        json[0].forEach((currentValue, index) => {
231
          equipments.push({
232
            'key': index,
233
            'id': currentValue['id'],
234
            'name': currentValue['equipment_name'],
235
            'space': currentValue['space_name'],
236
            'costcenter': currentValue['cost_center_name'],
237
            'description': currentValue['description']});
238
        });
239
        setEquipmentList(equipments);
240
        setSpinnerHidden(true);
241
      } else {
242
        toast.error(json.description)
243
      }
244
    }).catch(err => {
245
      console.log(err);
246
    });
247
    // end of getting equipment list
248
  }
249
250
  return (
251
    <Fragment>
252
      <div>
253
        <Breadcrumb>
254
          <BreadcrumbItem>{t('Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Equipment Tracking')}</BreadcrumbItem>
255
        </Breadcrumb>
256
      </div>
257
      <Card className="bg-light mb-3">
258
        <CardBody className="p-3">
259
          <Form >
260
            <Row form>
261
              <Col xs="auto">
262
                <FormGroup className="form-group">
263
                  <Label className={labelClasses} for="space">
264
                    {t('Space')}
265
                  </Label>
266
                  <br />
267
                  <Cascader options={cascaderOptions}
268
                    onChange={onSpaceCascaderChange}
269
                    changeOnSelect
270
                    expandTrigger="hover">
271
                    <Input value={selectedSpaceName || ''} readOnly />
272
                  </Cascader>
273
                </FormGroup>
274
              </Col>
275
              <Col xs="auto">
276
                <FormGroup>
277
                  <br></br>
278
                  <Spinner color="primary" hidden={spinnerHidden}  />
279
                </FormGroup>
280
              </Col>  
281
            </Row>
282
          </Form>
283
        </CardBody>
284
      </Card>
285
      <DetailedDataTable data={equipmentList} title={t('Equipment List')} columns={columns} pagesize={10} >
286
      </DetailedDataTable>
287
288
    </Fragment>
289
  );
290
};
291
292
export default withTranslation()(withRedirect(EquipmentTracking));
293