Passed
Push — master ( 4f3f28...c5d2bd )
by Guangyu
04:38 queued 11s
created

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

Complexity

Total Complexity 7
Complexity/F 0

Size

Lines of Code 286
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 7
eloc 250
mnd 7
bc 7
fnc 0
dl 0
loc 286
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
  Button,
6
  ButtonGroup,
7
  Card,
8
  CardBody,
9
  Col,
10
  DropdownItem,
11
  DropdownMenu,
12
  DropdownToggle,
13
  Form,
14
  FormGroup,
15
  Input,
16
  Label,
17
  Media,
18
  Row,
19
  UncontrolledDropdown,
20
} from 'reactstrap';
21
import uuid from 'uuid/v1';
22
import Cascader from 'rc-cascader';
23
import loadable from '@loadable/component';
24
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
25
import { Link } from 'react-router-dom';
26
import Flex from '../../common/Flex';
27
import { getCookieValue, createCookie } from '../../../helpers/utils';
28
import withRedirect from '../../../hoc/withRedirect';
29
import { withTranslation } from 'react-i18next';
30
import { toast } from 'react-toastify';
31
import { APIBaseURL } from '../../../config';
32
33
34
const EquipmentTracking = ({ setRedirect, setRedirectUrl, t }) => {
35
  useEffect(() => {
36
    let is_logged_in = getCookieValue('is_logged_in');
37
    let user_name = getCookieValue('user_name');
38
    let user_display_name = getCookieValue('user_display_name');
39
    let user_uuid = getCookieValue('user_uuid');
40
    let token = getCookieValue('token');
41
    if (is_logged_in === null || !is_logged_in) {
42
      setRedirectUrl(`/authentication/basic/login`);
43
      setRedirect(true);
44
    } else {
45
      //update expires time of cookies
46
      createCookie('is_logged_in', true, 1000 * 60 * 60 * 8);
47
      createCookie('user_name', user_name, 1000 * 60 * 60 * 8);
48
      createCookie('user_display_name', user_display_name, 1000 * 60 * 60 * 8);
49
      createCookie('user_uuid', user_uuid, 1000 * 60 * 60 * 8);
50
      createCookie('token', token, 1000 * 60 * 60 * 8);
51
    }
52
  });
53
  let table = createRef();
54
 
55
  // State
56
  const [selectedSpaceName, setSelectedSpaceName] = useState(undefined);
57
  const [cascaderOptions, setCascaderOptions] = useState(undefined);
58
  const [equipmentList, setEquipmentList] = useState([]);
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
            console.log(equipments);
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
    // begin of getting equipment list
208
    let isResponseOK = false;
209
    fetch(APIBaseURL + '/reports/equipmenttracking?' +
210
      'spaceid=' + selectedSpaceID, {
211
      method: 'GET',
212
      headers: {
213
        "Content-type": "application/json",
214
        "User-UUID": getCookieValue('user_uuid'),
215
        "Token": getCookieValue('token')
216
      },
217
      body: null,
218
219
    }).then(response => {
220
      if (response.ok) {
221
        isResponseOK = true;
222
      }
223
      return response.json();
224
    }).then(json => {
225
      if (isResponseOK) {
226
        json = JSON.parse(JSON.stringify([json]).split('"id":').join('"value":').split('"name":').join('"label":'));
227
        console.log(json)
228
        let equipments = [];
229
        json[0].forEach((currentValue, index) => {
230
          equipments.push({
231
            'key': index,
232
            'id': currentValue['id'],
233
            'name': currentValue['equipment_name'],
234
            'space': currentValue['space_name'],
235
            'costcenter': currentValue['cost_center_name'],
236
            'description': currentValue['description']});
237
        });
238
        setEquipmentList(equipments);
239
        console.log(equipments);
240
      } else {
241
        toast.error(json.description)
242
      }
243
    }).catch(err => {
244
      console.log(err);
245
    });
246
    // end of getting equipment list
247
  }
248
249
  return (
250
    <Fragment>
251
      <div>
252
        <Breadcrumb>
253
          <BreadcrumbItem>{t('Equipment Data')}</BreadcrumbItem><BreadcrumbItem active>{t('Equipment Tracking')}</BreadcrumbItem>
254
        </Breadcrumb>
255
      </div>
256
      <Card className="bg-light mb-3">
257
        <CardBody className="p-3">
258
          <Form >
259
            <Row form>
260
              <Col xs="auto">
261
                <FormGroup className="form-group">
262
                  <Label className={labelClasses} for="space">
263
                    {t('Space')}
264
                  </Label>
265
                  <br />
266
                  <Cascader options={cascaderOptions}
267
                    onChange={onSpaceCascaderChange}
268
                    changeOnSelect
269
                    expandTrigger="hover">
270
                    <Input value={selectedSpaceName || ''} readOnly />
271
                  </Cascader>
272
                </FormGroup>
273
              </Col>
274
            </Row>
275
          </Form>
276
        </CardBody>
277
      </Card>
278
      <DetailedDataTable data={equipmentList} title={t('Equipment List')} columns={columns} pagesize={10} >
279
      </DetailedDataTable>
280
281
    </Fragment>
282
  );
283
};
284
285
export default withTranslation()(withRedirect(EquipmentTracking));
286