Compare commits

..

140 Commits

Author SHA1 Message Date
chris-cosentino
6cd1458f17 added wrapper for missed components 2020-12-08 11:09:03 -05:00
chris-cosentino
2b80c7cb82 created high order query component handling errors 2020-12-07 17:50:28 -05:00
chris-cosentino
92b522e14b checked error on all pages 2020-11-18 10:35:47 -05:00
chris-cosentino
917b949fea Merge branch 'hotfix/WIFI-905' of https://github.com/Telecominfraproject/wlan-cloud-ui into hotfix/WIFI-905 2020-11-17 19:16:25 -05:00
chris-cosentino
439ff1afbe hotfix/WIFI-905: App doesnt show error page briefly when user session expires 2020-11-17 19:13:25 -05:00
Sean Macfarlane
3f3c81f5db fixed OUI upload error 2020-11-11 10:52:47 -05:00
Sean Macfarlane
76acff8b89 fixed profile refetch 2020-11-09 16:21:40 -05:00
Sean Macfarlane
4bab1f3c1c Merge pull request #75 from Telecominfraproject/hotfix/profiles-refetch
hotfix/WIFI-735: fixed profiles refetch
2020-11-09 15:31:12 -05:00
Sean Macfarlane
2f12264af3 fixed profiles refetch 2020-11-09 15:24:35 -05:00
Sean Macfarlane
016d1ff439 update package 2020-11-07 19:07:17 -05:00
Sean Macfarlane
1f06e0b89c update version 2020-11-06 11:48:11 -05:00
Sean Macfarlane
cacb2a3833 added null check 2020-11-06 11:47:08 -05:00
Sean Macfarlane
bf39c6b6dc fixed dashboard usage 2020-11-06 11:45:38 -05:00
Sean Macfarlane
8d2de52870 update version 2020-11-06 01:08:38 -05:00
Sean Macfarlane
8b0dc34ac4 update version 2020-11-05 23:18:43 -05:00
Sean Macfarlane
6646226cb7 Merge pull request #72 from Telecominfraproject/hotfix/WIFI-1043
hotfix/WIFI-1043: Usage info on dashboard shows total sum of traffic
2020-11-05 16:16:28 -05:00
chris-cosentino
120ae073fb hotfix/WIFI-1043: Usage info on dashboard shows total sum of traffic 2020-11-05 15:05:59 -05:00
chris-cosentino
834b7b28a7 hotfix/WIFI-1043: Usage info on dashboard shows total sum of traffic 2020-11-05 14:01:27 -05:00
chris-cosentino
d9a970350b hotfix/WIFI-1043: Usage info on dashboard shows total sum of traffic 2020-11-05 13:53:19 -05:00
Sean Macfarlane
60c2c21997 fixed webpack less loader 2020-11-04 20:31:31 -05:00
Sean Macfarlane
26d74f6059 audit fixed 2020-11-04 20:23:48 -05:00
Sean Macfarlane
1682a2ca21 fixed webpack 2020-11-04 20:05:57 -05:00
Sean Macfarlane
1fa7080593 update version 2020-11-04 14:29:49 -05:00
Sean Macfarlane
ac405ae1c4 Merge pull request #71 from Telecominfraproject/feature/WIFI-1012
feature/WIFI-1012: Added client device status support
2020-11-02 15:55:47 -05:00
chris-cosentino
c1264c3ea0 WIFI-1012: Added client device status support 2020-11-02 15:06:39 -05:00
chris-cosentino
cfee505a5b feature/WIFI-1012: Added client device status support 2020-11-02 13:16:05 -05:00
chris-cosentino
ba49ca4e16 feature/WIFI-1012: Added client device status support 2020-10-30 16:43:48 -04:00
Toan Do
acf36fb42b deleted error 401 verification 2020-10-19 10:52:57 -04:00
Toan Do
273ca85fde prevents error message when Auth Token expires 2020-10-16 17:08:18 -04:00
Sean Macfarlane
c40a8ca157 update version 2020-10-14 15:13:16 -04:00
Sean Macfarlane
0dfb7a7901 Merge pull request #69 from Telecominfraproject/WIFI-846
WIFI 846: docker cron schedule
2020-10-13 10:27:35 -04:00
AkshayJagadish-ne
153394cad0 Updated condition for push job
Updated condition for push job to get executed even on nightly builds
2020-10-13 02:09:11 -04:00
AkshayJagadish-ne
1507320fae Added a commit.properties file to support running the docker locally 2020-10-13 02:05:16 -04:00
AkshayJagadish-ne
673002b685 Correction
moved copy statement to the production environment
2020-10-12 23:05:28 -04:00
Sean Macfarlane
c014ba5e40 Merge pull request #61 from Telecominfraproject/hotfix/WIFI-851
hotfix/WIFI-851: Fixed editing Model Target Version creating duplicates
2020-10-09 11:25:25 -04:00
Sean Macfarlane
b20caa666d update version 2020-10-09 10:27:09 -04:00
Sean Macfarlane
c75e5ea934 fixed OUI Upload 2020-10-08 18:12:35 -04:00
Sean Macfarlane
631482ab6f Merge pull request #66 from Telecominfraproject/WIFI-846
Wifi 846
2020-10-07 18:19:55 -04:00
Sean Macfarlane
2d42d59c54 Merge pull request #65 from Telecominfraproject/WIFI-845
WIFI-845: Support Kubernetes Deployment Versioning
2020-10-07 18:19:18 -04:00
Toan Do
229d50f1a8 Added parameter to handleUpdateTrack 2020-10-07 14:41:00 -04:00
AkshayJagadish-ne
f6078182ff Subtask WIFI-913
Added a step to copy the commit.properties file that would be created by the workflow into the container.
2020-10-07 13:40:07 -04:00
AkshayJagadish-ne
3f0c1c0e33 Subtask WIFI-913
cleared line spaces
2020-10-07 13:25:40 -04:00
AkshayJagadish-ne
6dbaddc021 Subtask WIFI-913 2020-10-07 13:24:21 -04:00
AkshayJagadish-ne
64096d040d Subtask WIFI-913
A property file with commit hash and version will be added to the container's directory during the build. This file would be used by QA
2020-10-07 13:20:14 -04:00
AkshayJagadish-ne
5a634b2e8a Subtask WIFI-922
Added nightly build to generate images with a timestamp. This is done so that the front-end and back-end components would have the same timestamp tag. The timestamp would then be used to test a deployment version for a specific day.
2020-10-07 13:02:49 -04:00
Sean Macfarlane
69972e0033 Merge pull request #62 from Telecominfraproject/hotfix/WIFI-774
hotfix/WIFI-774
2020-10-05 17:22:44 -04:00
Toan Do
743c4f3665 adjusted onComplete of searchOUI 2020-10-05 15:27:40 -04:00
Sean Macfarlane
d70df54986 Merge pull request #64 from Telecominfraproject/feature/WIFI-817
Feature/wifi 817: Switch to Inactive Bank, and Reboot AP
2020-10-02 17:51:03 -04:00
Sean Macfarlane
b40b29f73d new version 2020-10-02 17:49:01 -04:00
Sean Macfarlane
2206a9bf3f new version 2020-10-02 17:48:50 -04:00
Sean Macfarlane
450fe6280f added Inactive bank and Reboot AP 2020-10-02 17:14:42 -04:00
Toan Do
d0424480fe removed cache for searchOUI query 2020-10-02 13:20:09 -04:00
Toan Do
ea2b4f90b7 fixed searchOUI error notification 2020-10-02 11:49:59 -04:00
Toan Do
fbfd4895b1 updated condtion for updateTrackAssignment 2020-10-01 13:10:55 -04:00
Toan Do
eafc05b645 fixed updateTrackAssignment for edit btn 2020-09-30 17:54:48 -04:00
Sean Macfarlane
0009bd5ca6 Merge pull request #60 from Telecominfraproject/hotfix/WIFI-758
WIFI-758: Fixed data path for updateEquipmentFirmware
2020-09-15 13:43:20 -04:00
Sean Macfarlane
e38dd84f11 Merge pull request #59 from Telecominfraproject/feature/WIFI-613
Feature/wifi 613 Added Firmware Version to AP Table
2020-09-15 13:42:45 -04:00
Sean Macfarlane
e6a0dc9f12 added npm script for graphql server 2020-09-15 13:16:36 -04:00
Toan Do
327c4ea3d1 Fixed data path for updateEquipmentFirmware 2020-09-15 09:47:57 -04:00
Toan Do
01dbd0a887 changed FIRMWARE column title 2020-09-14 17:05:04 -04:00
Sean Macfarlane
5b46dbf657 Merge pull request #58 from Telecominfraproject/hotfix/WIFI-708
Hotfix/wifi 708: Added default values to the Access Points table
2020-09-14 17:04:09 -04:00
Toan Do
46c860f310 Added Firmware Version column to AP table 2020-09-14 14:47:43 -04:00
Toan Do
51d34055ba Modied FILTER_EQUIPMENT to include firmware 2020-09-14 14:47:01 -04:00
Toan Do
be3582514c removed padding 2020-09-11 16:52:59 -04:00
Toan Do
afc6ddc30e made default for AP table 2020-09-11 16:52:39 -04:00
Sean Macfarlane
4314239e1d fixed fetchPolicy for profiles 2020-09-11 15:32:21 -04:00
Toan Do
bac628ea67 added renderDefaultTableCell function 2020-09-11 13:56:48 -04:00
Sean Macfarlane
bac2f43eb0 made it easier to run repo locally 2020-09-08 13:21:59 -04:00
Sean Macfarlane
f7681e9bd3 update version 2020-09-02 19:47:54 -04:00
Sean Macfarlane
5d822bdd78 fixed bugs and pagination 2020-09-02 19:35:15 -04:00
Sean Macfarlane
cbfce876b3 Merge pull request #57 from Telecominfraproject/hotfix/Pagination
hotfix/Pagination: Pagination for profiles query
2020-09-02 11:22:50 -04:00
Sean Macfarlane
16d4933190 update version 2020-08-26 20:02:24 -04:00
Irtiza-h30
85f3386c23 pagination for profiles query 2020-08-26 18:33:04 -04:00
Sean Macfarlane
c929a1eff5 Merge pull request #53 from Telecominfraproject/hotfix/WIFI-644
hotfix/WIFI-644: Location restructure
2020-08-26 18:03:38 -04:00
Sean Macfarlane
401f22b10a Merge pull request #50 from Telecominfraproject/hotfix/WIFI-553
hotfix/WIFI-553: Confirm Modal
2020-08-26 18:00:17 -04:00
Sean Macfarlane
40f2ef31ce Merge branch 'master' into hotfix/WIFI-553 2020-08-26 17:54:19 -04:00
Sean Macfarlane
2813057c31 Merge branch 'master' into hotfix/WIFI-644 2020-08-26 17:09:59 -04:00
Sean Macfarlane
8d1339c412 added missing slash 2020-08-25 14:36:01 -04:00
Sean Macfarlane
54ca94cefa update version 2020-08-25 00:34:29 -04:00
Sean Macfarlane
d750a0e798 Merge branch 'master' of github.com:Telecominfraproject/wlan-cloud-ui 2020-08-24 23:54:43 -04:00
Sean Macfarlane
09f2e91f4c Merge pull request #54 from Telecominfraproject/feature/WIFI-661
Feature/WIFI-661: Upgrade Apollo Client
2020-08-24 23:54:30 -04:00
Sean Macfarlane
4f18a93375 changed apollo server to use express 2020-08-24 23:54:14 -04:00
Sean Macfarlane
5a41840f1d Merge pull request #55 from Telecominfraproject/hotfix/WIFI-679
hotfix/WIFI-679: Dashboard traffic has NaN values
2020-08-24 23:47:00 -04:00
Sean Macfarlane
f5f30f3784 Merge pull request #56 from Telecominfraproject/hotfix/WIFI-612
hotfix/WIFI-612: Fixed Firmware Query on AP Details
2020-08-24 23:41:55 -04:00
Sean Macfarlane
6edc98af47 increased profiles limit 2020-08-24 16:32:26 -04:00
Irtiza-h30
15df3caf6b fixed firwmare query 2020-08-24 14:01:04 -04:00
Hassan Azmi
94a26fef43 Use absolute value of bytes when determining exponent 2020-08-21 14:57:36 -04:00
Hassan Azmi
b44290a28a Add back cloud-ui-library to the package-lock 2020-08-21 13:30:57 -04:00
Hassan Azmi
823d7d0fef Merge branch 'master' into feature/WIFI-661
# Conflicts:
#	app/containers/Profiles/index.js
2020-08-21 13:07:04 -04:00
Hassan Azmi
d33caa8885 Upgraded to Apollo Client 3. 2020-08-21 12:43:56 -04:00
Irtiza-h30
c4d9f76c2e Merge branch 'master' into hotfix/WIFI-553 2020-08-21 12:30:11 -04:00
Sean Macfarlane
c416d87106 Merge pull request #51 from Telecominfraproject/hotfix/WIFI-592
hotfix/WIFI-592: Add Profile goes back and refreshes profiles
2020-08-21 11:19:47 -04:00
Sean Macfarlane
5023ed9d96 Merge pull request #52 from Telecominfraproject/hotfix/AddAP
hotfix/AddAP: filter_equipment query refetches after AP is added
2020-08-21 11:18:13 -04:00
Hassan Azmi
125e988f25 Perform add/edit/delete/create logic in this repo instead of library to prevent unnecessary passing of variables 2020-08-21 10:06:26 -04:00
Hassan Azmi
4069374d58 Workaround for root of tree to create COUNTRY locations 2020-08-20 16:24:13 -04:00
Irtiza-h30
ded926c98b filter_equipment query refetches after AP is added 2020-08-20 13:12:12 -04:00
Irtiza-h30
7b0becec58 merged with master 2020-08-20 10:24:00 -04:00
Irtiza-h30
9be76979ea fixed redirect 2020-08-19 20:50:01 -04:00
Irtiza-h30
cf9cc4d6ac undo 2020-08-19 20:35:20 -04:00
Irtiza-h30
0ef102e28e Merge branch 'hotfix/WIFI-553' of https://github.com/Telecominfraproject/wlan-cloud-ui into hotfix/WIFI-553 2020-08-19 20:33:44 -04:00
Irtiza-h30
41f27c76b1 undo 2020-08-19 20:33:36 -04:00
Irtiza-h30
124a84b75f undo 2020-08-19 20:33:15 -04:00
Hassan Azmi
1b5a09636f Only refetch when explicitly intended 2020-08-19 19:06:18 -04:00
Irtiza-h30
81cc493aa3 fixed redirect 2020-08-19 18:21:41 -04:00
Hassan Azmi
41a27ff9ef preliminary work 644 2020-08-19 18:09:04 -04:00
Sean Macfarlane
1c6f8dfdba Merge pull request #48 from Telecominfraproject/hotfix/WIFI-588
hotfix/WIFI-588: Error on login
2020-08-19 17:46:56 -04:00
Sean Macfarlane
5911395fac Merge branch 'master' into hotfix/WIFI-588 2020-08-19 17:45:53 -04:00
Hassan Azmi
941b952ff6 Route to profiles when adding profile is complete 2020-08-19 14:08:23 -04:00
Hassan Azmi
4065a9272c no message 2020-08-19 13:44:52 -04:00
Sean Macfarlane
333b37a139 Merge pull request #49 from Telecominfraproject/hotfix/WIFI-590
hotfix/WIFI-590: Reload profiles when one is deleted
2020-08-19 12:46:17 -04:00
Hassan Azmi
0939aacdbe Make resetting the store synchronous 2020-08-19 12:46:04 -04:00
Irtiza-h30
bb1da8f0c9 updated redirect 2020-08-19 12:33:48 -04:00
Sean Macfarlane
a11c7d651d update version 2020-08-19 12:09:31 -04:00
Sean Macfarlane
07f1f64537 Merge pull request #42 from Telecominfraproject/feature/TW-975
Feature/TW-975: Captive User List & Radius
2020-08-18 18:00:23 -04:00
Sean Macfarlane
8bde2ad4bc cleanup 2020-08-18 17:50:37 -04:00
Sean Macfarlane
ac848713ea Merge branch 'master' into feature/TW-975 2020-08-18 17:23:40 -04:00
Sean Macfarlane
4bebfe68f6 Merge pull request #47 from Telecominfraproject/hotfix/pagination
Hotfix/pagination
2020-08-18 17:23:06 -04:00
Sean Macfarlane
7bf25f4edb update version 2020-08-18 17:19:31 -04:00
Sean Macfarlane
0ff45e9d87 Merge branch 'master' into hotfix/pagination 2020-08-18 17:19:07 -04:00
Sean Macfarlane
f877b4c3c1 Merge branch 'master' into feature/TW-975 2020-08-18 17:15:28 -04:00
Sean Macfarlane
ecf2c2fa8c Merge branch 'master' of github.com:Telecominfraproject/wlan-cloud-ui 2020-08-18 16:52:42 -04:00
Sean Macfarlane
d5c094d749 update antd 2020-08-18 16:52:39 -04:00
Hassan Azmi
26dba66470 Refetch profiles when going back to router 2020-08-18 16:45:17 -04:00
Sean Macfarlane
5ae31d7198 Merge pull request #45 from Telecominfraproject/hotfix/WIFI-571
hotfix/WIFI-571: updated firmware query
2020-08-18 16:41:43 -04:00
Sean Macfarlane
2bd50d4560 update version 2020-08-18 16:20:10 -04:00
Sean Macfarlane
a8843d4be7 fixed pagination 2020-08-18 16:18:49 -04:00
Hassan Azmi
644cdd2c45 Refetch instead of reload table 2020-08-18 15:24:05 -04:00
Hassan Azmi
035a714fa6 Reload table on profile create 2020-08-18 14:35:06 -04:00
Hassan Azmi
2d7514fbde Do not reset store when user is authenticated. Instead clear cache. 2020-08-18 13:58:59 -04:00
Irtiza-h30
0c5f0842e9 split up errors/loading for profile and firmware 2020-08-18 11:00:59 -04:00
Sean Macfarlane
86087930da fixed profiles pagination 2020-08-18 00:40:45 -04:00
Irtiza-h30
e60ec0c713 added tab to access point details component route 2020-08-17 19:27:05 -04:00
Sean Macfarlane
fd4f90173b Update README.md 2020-08-17 11:56:34 -04:00
Sean Macfarlane
a4d4dce73a Update README.md 2020-08-17 11:54:59 -04:00
Sean Macfarlane
7b8f45d9f2 Update README.md 2020-08-17 11:44:48 -04:00
Irtiza-h30
3affd7b6a6 removed useEffect and used skip (works) 2020-08-15 10:27:27 -04:00
Irtiza-h30
5854c1a0a0 updated query 2020-08-14 23:43:50 -04:00
Sean Macfarlane
a2352e2d01 Merge branch 'master' into feature/TW-975 2020-08-14 14:20:29 -04:00
Irtiza-h30
2514d9e77c updated firmware query 2020-08-13 16:38:16 -04:00
Irtiza-h30
5a49a0301e get radius profile query 2020-08-05 12:02:08 -04:00
70 changed files with 4543 additions and 25049 deletions

View File

@@ -1,9 +1,6 @@
{
"extends": ["airbnb", "prettier", "prettier/react"],
"plugins": ["prettier"],
"env": {
"jest": true
},
"rules": {
"react/jsx-filename-extension": [
1,

View File

@@ -13,6 +13,10 @@ on:
# Run tests for any PRs.
pull_request:
schedule:
# runs nightly build at 5AM
- cron: '00 09 * * *'
env:
IMAGE_NAME: wlan-cloud-ui
DOCKER_REPO: tip-tip-wlan-cloud-docker-repo.jfrog.io
@@ -39,11 +43,28 @@ jobs:
needs: test
runs-on: ubuntu-latest
if: github.event_name == 'push'
if: github.event_name == 'push' || github.event_name == 'schedule'
steps:
- uses: actions/checkout@v2
- name: Adding property file with component version and commit hash
run: |
# Strip git ref prefix from version
VERSION=$(echo "${{ github.ref }}" | sed -e 's,.*/\(.*\),\1,')
# Strip "v" prefix from tag name
[[ "${{ github.ref }}" == "refs/tags/"* ]] && VERSION=$(echo $VERSION | sed -e 's/^v//')
# Use Docker `latest` tag convention
[ "$VERSION" == "master" ] && VERSION=latest
TIMESTAMP=$(date +'%Y-%m-%d')
echo date=$TIMESTAMP > app/commit.properties
echo commitId=$GITHUB_SHA >> app/commit.properties
echo projectVersion=$VERSION>> app/commit.properties
- name: Build image
run: docker build . -f Dockerfile -t image --build-arg NPM_TOKEN=${{secrets.NPM_REPO_AUTH_TOKEN}}
@@ -56,6 +77,7 @@ jobs:
- name: Push image
run: |
IMAGE_ID=$DOCKER_REPO/$IMAGE_NAME
TIMESTAMP=$(date +'%Y-%m-%d')
# Change all uppercase to lowercase
IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
@@ -71,6 +93,10 @@ jobs:
echo IMAGE_ID=$IMAGE_ID
echo VERSION=$VERSION
echo TIMESTAMP=$TIMESTAMP
docker tag image $IMAGE_ID:$VERSION
docker push $IMAGE_ID:$VERSION
docker tag image $IMAGE_ID:$VERSION-$TIMESTAMP
docker push $IMAGE_ID:$VERSION-$TIMESTAMP

View File

@@ -13,6 +13,7 @@ ENV PATH /app/node_modules/.bin:$PATH
# where available (npm@5+)
COPY package*.json ./
#RUN npm install
# If you are building your code for production
RUN (echo "@tip-wlan:registry=https://tip.jfrog.io/artifactory/api/npm/tip-wlan-cloud-npm-repo/" && echo "//tip.jfrog.io/artifactory/api/npm/tip-wlan-cloud-npm-repo/:_authToken=$NPM_TOKEN") > .npmrc
@@ -28,7 +29,8 @@ RUN apk add --no-cache jq
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx/nginx.conf /etc/nginx/conf.d/default.conf
COPY docker_entrypoint.sh generate_config_js.sh /
COPY app/commit.properties /
RUN chmod +x docker_entrypoint.sh generate_config_js.sh
EXPOSE 80
ENTRYPOINT ["/docker_entrypoint.sh"]
ENTRYPOINT ["/docker_entrypoint.sh"]

View File

@@ -2,12 +2,30 @@
## Set up environment:
Delete from package.json (undo this delete after all steps)
`"@tip-wlan/wlan-cloud-ui-library": X.X.X,`
Install Dependencies
Install Dependencies:
`npm install`
You will get an error installing the package [wlan-cloud-ui-library](https://github.com/Telecominfraproject/wlan-cloud-ui-library) because it is in a private npm registry.
You can either install the package with the commands below or clone the repo [wlan-cloud-ui-library](https://github.com/Telecominfraproject/wlan-cloud-ui-library) and skip to the section Set up Full Development.
Run
```
npm login --registry=https://tip.jfrog.io/artifactory/api/npm/tip-wlan-cloud-npm-repo/
```
And enter the supplied credentials. Ask @sean-macfarlane for credentials if you don't have.
Install package:
```
npm i --registry=https://tip.jfrog.io/artifactory/api/npm/tip-wlan-cloud-npm-repo/ @tip-wlan/wlan-cloud-ui-library
```
### Set up Full Development
_Skip this section if you are not using a local [wlan-cloud-ui-library](https://github.com/Telecominfraproject/wlan-cloud-ui-library)_
Clone [wlan-cloud-ui-library](https://github.com/Telecominfraproject/wlan-cloud-ui-library) in parent folder
```
@@ -28,15 +46,25 @@ If `npm link` fails due to Permissions run with `sudo`
sudo npm link ../wlan-cloud-ui-library
```
To run Full Development you must clone [wlan-cloud-graphql-gw](https://github.com/Telecominfraproject/wlan-cloud-graphql-gw), follow it's README, and run it. Or you use the live production build by setting the environment variable `API` to the GraphQL domain.
## Run:
### Development
### Bare Development
This is if you only want to run this repo locally, and want to use the live production builds of [wlan-cloud-ui-library](https://github.com/Telecominfraproject/wlan-cloud-ui-library) and [wlan-cloud-graphql-gw](https://github.com/Telecominfraproject/wlan-cloud-graphql-gw)
`npm run start:bare`
### Full Development
If you have cloned [wlan-cloud-ui-library](https://github.com/Telecominfraproject/wlan-cloud-ui-library) and [wlan-cloud-graphql-gw](https://github.com/Telecominfraproject/wlan-cloud-graphql-gw)
`npm start`
### Tests
`npm run test`
`npm test`
### Production

4
app/commit.properties Normal file
View File

@@ -0,0 +1,4 @@
#This file will be used when running the docker locally
date=${date}
commitId=${commit.id}
projectVersion=${project.version}

View File

@@ -1 +0,0 @@
window.REACT_APP_API = undefined;

View File

@@ -1,126 +1,182 @@
import React, { useContext } from 'react';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { Alert, notification } from 'antd';
import { useMutation, gql } from '@apollo/client';
import { notification } from 'antd';
import { Accounts as AccountsPage } from '@tip-wlan/wlan-cloud-ui-library';
import { Accounts as AccountsPage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { GET_ALL_USERS } from 'graphql/queries';
import { CREATE_USER, UPDATE_USER, DELETE_USER } from 'graphql/mutations';
import UserContext from 'contexts/UserContext';
import { withQuery } from 'containers/QueryWrapper';
const Accounts = () => {
const { customerId } = useContext(UserContext);
const { data, loading, error, refetch, fetchMore } = useQuery(GET_ALL_USERS, {
variables: { customerId },
});
const [createUser] = useMutation(CREATE_USER);
const [updateUser] = useMutation(UPDATE_USER);
const [deleteUser] = useMutation(DELETE_USER);
const handleLoadMore = () => {
if (!data.getAllUsers.context.lastPage) {
fetchMore({
variables: { cursor: data.getAllUsers.context.cursor },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.getAllUsers;
const newItems = fetchMoreResult.getAllUsers.items;
return {
getAllUsers: {
context: fetchMoreResult.getAllUsers.context,
items: [...previousEntry.items, ...newItems],
__typename: previousEntry.__typename,
},
};
},
});
const GET_ALL_USERS = gql`
query GetAllUsers($customerId: ID!, $context: JSONObject) {
getAllUsers(customerId: $customerId, context: $context) {
items {
id
email: username
role
lastModifiedTimestamp
customerId
}
context
}
};
const handleCreateUser = (email, password, role) => {
createUser({
variables: {
username: email,
password,
role,
customerId,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Account successfully created.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Account could not be created.',
})
);
};
const handleEditUser = (id, email, password, role, lastModifiedTimestamp) => {
updateUser({
variables: {
id,
username: email,
password,
role,
customerId,
lastModifiedTimestamp,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Account successfully updated.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Account could not be updated.',
})
);
};
const handleDeleteUser = id => {
deleteUser({ variables: { id } })
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Account successfully deleted.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Account could not be deleted.',
})
);
};
if (loading) {
return <Loading />;
}
`;
if (error) {
return <Alert message="Error" description="Failed to load Users." type="error" showIcon />;
const CREATE_USER = gql`
mutation CreateUser($username: String!, $password: String!, $role: String!, $customerId: ID!) {
createUser(username: $username, password: $password, role: $role, customerId: $customerId) {
username
role
customerId
}
}
`;
const UPDATE_USER = gql`
mutation UpdateUser(
$id: ID!
$username: String!
$password: String!
$role: String!
$customerId: ID!
$lastModifiedTimestamp: String
) {
updateUser(
id: $id
username: $username
password: $password
role: $role
customerId: $customerId
lastModifiedTimestamp: $lastModifiedTimestamp
) {
id
username
role
customerId
lastModifiedTimestamp
}
}
`;
const DELETE_USER = gql`
mutation DeleteUser($id: ID!) {
deleteUser(id: $id) {
id
}
}
`;
const Accounts = withQuery(
({ data, fetchMore, refetch }) => {
const { customerId } = useContext(UserContext);
const [createUser] = useMutation(CREATE_USER);
const [updateUser] = useMutation(UPDATE_USER);
const [deleteUser] = useMutation(DELETE_USER);
const handleLoadMore = () => {
if (!data.getAllUsers.context.lastPage) {
fetchMore({
variables: { context: data.getAllUsers.context },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.getAllUsers;
const newItems = fetchMoreResult.getAllUsers.items;
return {
getAllUsers: {
context: fetchMoreResult.getAllUsers.context,
items: [...previousEntry.items, ...newItems],
__typename: previousEntry.__typename,
},
};
},
});
}
};
const handleCreateUser = (email, password, role) => {
createUser({
variables: {
username: email,
password,
role,
customerId,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Account successfully created.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Account could not be created.',
})
);
};
const handleEditUser = (id, email, password, role, lastModifiedTimestamp) => {
updateUser({
variables: {
id,
username: email,
password,
role,
customerId,
lastModifiedTimestamp,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Account successfully updated.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Account could not be updated.',
})
);
};
const handleDeleteUser = id => {
deleteUser({ variables: { id } })
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Account successfully deleted.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Account could not be deleted.',
})
);
};
return (
<AccountsPage
data={data.getAllUsers.items}
onLoadMore={handleLoadMore}
onCreateUser={handleCreateUser}
onEditUser={handleEditUser}
onDeleteUser={handleDeleteUser}
isLastPage={data.getAllUsers.context.lastPage}
/>
);
},
GET_ALL_USERS,
() => {
const { customerId } = useContext(UserContext);
return { customerId };
}
);
return (
<AccountsPage
data={data.getAllUsers.items}
onLoadMore={handleLoadMore}
onCreateUser={handleCreateUser}
onEditUser={handleEditUser}
onDeleteUser={handleDeleteUser}
isLastPage={data.getAllUsers.context.lastPage}
/>
);
};
export default Accounts;

View File

@@ -1,222 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { fireEvent, render, waitFor } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { accountsMutationMock, accountsQueryMock } from './mock';
import Accounts from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<Accounts />', () => {
afterEach(jest.resetModules);
it('should render with data', async () => {
const { getByText } = render(
<MockedProvider mocks={[accountsQueryMock.success]} addTypename={false}>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
});
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider mocks={[accountsQueryMock.error]} addTypename={false}>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load Users.')).toBeVisible());
});
it('deleting account should be successful with valid query', async () => {
const { getByText, getByRole, getAllByRole } = render(
<MockedProvider
mocks={[
accountsQueryMock.success,
accountsMutationMock.deleteAccountSuccess,
accountsQueryMock.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
fireEvent.click(getAllByRole('button', { name: /delete/i })[0]);
expect(getByRole('button', { name: 'Delete' }));
fireEvent.click(getByRole('button', { name: 'Delete' }));
await waitFor(() => expect(getByText('Account successfully deleted.')).toBeVisible());
});
it('deleting account should not be successful with invalid query', async () => {
const { getByText, getByRole, getAllByRole } = render(
<MockedProvider
mocks={[accountsQueryMock.success, accountsMutationMock.deleteAccountError]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
fireEvent.click(getAllByRole('button', { name: /delete/i })[0]);
expect(getByRole('button', { name: 'Delete' }));
fireEvent.click(getByRole('button', { name: 'Delete' }));
await waitFor(() => expect(getByText('Account could not be deleted.')).toBeVisible());
});
it('editing user should not be successful when query is invalid', async () => {
const { getByText, getByLabelText, getByRole, getAllByRole } = render(
<MockedProvider
mocks={[accountsQueryMock.success, accountsMutationMock.editUserError]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
fireEvent.click(getAllByRole('button', { name: /edit/i })[0]);
expect(getByText('Edit Account')).toBeVisible();
fireEvent.change(getByLabelText('E-mail'), { target: { value: 'test@test.com' } });
fireEvent.change(getByLabelText('Password'), { target: { value: 'password' } });
fireEvent.change(getByLabelText('Confirm Password'), { target: { value: 'password' } });
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Account could not be updated.')).toBeVisible());
});
it('adding user should be successful when query is valid', async () => {
const { getByText, getByLabelText, getAllByRole, getByRole } = render(
<MockedProvider
mocks={[
accountsQueryMock.success,
accountsQueryMock.success,
accountsQueryMock.success,
accountsMutationMock.addUserSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
fireEvent.click(getAllByRole('button', { name: /addaccount/i })[0]);
expect(getByText('Add Account', { selector: 'div' })).toBeVisible();
fireEvent.change(getByLabelText('E-mail'), { target: { value: 'test@test.com' } });
fireEvent.change(getByLabelText('Password'), { target: { value: 'password' } });
fireEvent.change(getByLabelText('Confirm Password'), { target: { value: 'password' } });
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Account successfully created.')).toBeVisible());
});
it('adding user should not be successful when query is invalid', async () => {
const { getByText, getByLabelText, getByRole } = render(
<MockedProvider
mocks={[accountsQueryMock.success, accountsMutationMock.addUserError]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
fireEvent.click(getByRole('button', { name: /addaccount/i }));
expect(getByText('Add Account', { selector: 'div' })).toBeVisible();
fireEvent.change(getByLabelText('E-mail'), { target: { value: 'test@test.com' } });
fireEvent.change(getByLabelText('Password'), { target: { value: 'password' } });
fireEvent.change(getByLabelText('Confirm Password'), { target: { value: 'password' } });
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Account could not be created.')).toBeVisible());
});
it('fetchmore shoudl be called when onLoadMore button is clicked', async () => {
const { getByRole, getByText } = render(
<MockedProvider
mocks={[accountsQueryMock.success, accountsQueryMock.fetchMore, accountsQueryMock.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Load More' }));
await waitFor(() => expect(getByText('user-18')).toBeVisible());
});
it('editing user should be successful when query is valid', async () => {
const { getByText, getByLabelText, getByRole, getAllByRole } = render(
<MockedProvider
mocks={[
accountsQueryMock.success,
accountsQueryMock.success,
accountsMutationMock.editUserSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Accounts />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('user-0')).toBeVisible());
fireEvent.click(getAllByRole('button', { name: /edit/i })[0]);
await waitFor(() => expect(getByText('Edit Account')).toBeVisible());
fireEvent.change(getByLabelText('E-mail'), { target: { value: 'test@test.com' } });
fireEvent.change(getByLabelText('Password'), { target: { value: 'password' } });
fireEvent.change(getByLabelText('Confirm Password'), { target: { value: 'password' } });
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('user-0')).toBeVisible());
await waitFor(() => expect(getByText('Edit Account')).not.toBeVisible());
await waitFor(() => expect(getByText('Account successfully updated.')).toBeVisible());
}, 5000);
});

View File

@@ -1,202 +0,0 @@
import { GET_ALL_USERS } from 'graphql/queries';
import { CREATE_USER, UPDATE_USER, DELETE_USER } from 'graphql/mutations';
export const accountsQueryMock = {
success: {
request: {
query: GET_ALL_USERS,
variables: { customerId: 2 },
},
result: {
data: {
getAllUsers: {
items: [
{
id: '1',
email: 'user-0',
role: 'CustomerIT',
lastModifiedTimestamp: '1596814602673',
customerId: '2',
__typename: 'User',
},
{
id: '2',
email: 'user-1',
role: 'CustomerIT',
lastModifiedTimestamp: '1596814602814',
customerId: '2',
__typename: 'User',
},
{
id: '3',
email: 'user-2',
role: 'CustomerIT',
lastModifiedTimestamp: '1596814602815',
customerId: '2',
__typename: 'User',
},
{
id: '4',
email: 'user-3',
role: 'CustomerIT',
lastModifiedTimestamp: '1596814602815',
customerId: '2',
__typename: 'User',
},
{
id: '5',
email: 'user-4',
role: 'CustomerIT',
lastModifiedTimestamp: '1596814602815',
customerId: '2',
__typename: 'User',
},
],
context: {
cursor: 'test',
lastPage: false,
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
fetchMore: {
request: {
query: GET_ALL_USERS,
variables: { customerId: 2, cursor: 'test' },
},
result: {
data: {
getAllUsers: {
items: [
{
id: '18',
email: 'user-18',
role: 'CustomerIT',
lastModifiedTimestamp: '1596814602673',
customerId: '2',
__typename: 'User',
},
],
context: {
cursor: 'test',
lastPage: true,
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_ALL_USERS,
variables: { customerId: 2 },
errorPolicy: 'all',
},
result: {
data: null,
errors: [{}],
loading: false,
networkStatus: 7,
stale: false,
},
},
};
export const accountsMutationMock = {
addUserSuccess: {
request: {
query: CREATE_USER,
variables: {
username: 'test@test.com',
password: 'password',
role: 'CustomerIT',
customerId: 2,
},
},
result: {
data: {
createUser: {
username: 'test@test.com',
role: 'CustomerIT',
customerId: '2',
},
},
},
},
addUserError: {
request: {
query: CREATE_USER,
variables: {},
},
result: {
data: null,
errors: [{}],
},
},
editUserSuccess: {
request: {
query: UPDATE_USER,
variables: {
id: '1',
username: 'test@test.com',
password: 'password',
role: 'CustomerIT',
customerId: 2,
lastModifiedTimestamp: '1596814602673',
},
},
result: {
data: {
updateUser: {
id: '1',
username: 'test@test.com',
role: 'CustomerIT',
customerId: '2',
lastModifiedTimestamp: '1597080851726',
__typename: 'User',
},
},
},
},
editUserError: {
request: {
query: UPDATE_USER,
variables: {},
},
result: {
data: null,
errors: [{}],
},
},
deleteAccountSuccess: {
request: {
query: DELETE_USER,
variables: { id: '1' },
},
result: {
data: {
deleteUser: {
id: '1',
__typename: 'User',
},
},
},
},
deleteAccountError: {
request: {
query: DELETE_USER,
variables: { id: '2' },
},
result: {
data: null,
errors: [{}],
loading: false,
},
},
};

View File

@@ -1,18 +1,44 @@
import React, { useContext } from 'react';
import { AddProfile as AddProfilePage } from '@tip-wlan/wlan-cloud-ui-library';
import { useMutation, useQuery } from '@apollo/react-hooks';
import { useMutation, useQuery, gql } from '@apollo/client';
import { notification } from 'antd';
import { useHistory } from 'react-router-dom';
import UserContext from 'contexts/UserContext';
import { GET_ALL_PROFILES } from 'graphql/queries';
import { CREATE_PROFILE } from 'graphql/mutations';
import { updateQueryGetAllProfiles } from 'graphql/functions';
const CREATE_PROFILE = gql`
mutation CreateProfile(
$profileType: String!
$customerId: ID!
$name: String!
$childProfileIds: [ID]
$details: JSONObject
) {
createProfile(
profileType: $profileType
customerId: $customerId
name: $name
childProfileIds: $childProfileIds
details: $details
) {
profileType
customerId
name
childProfileIds
details
}
}
`;
const AddProfile = () => {
const { customerId } = useContext(UserContext);
const { data: ssidProfiles } = useQuery(GET_ALL_PROFILES, {
const { data: ssidProfiles, fetchMore } = useQuery(GET_ALL_PROFILES(), {
variables: { customerId, type: 'ssid' },
});
const [createProfile] = useMutation(CREATE_PROFILE);
const history = useHistory();
const handleAddProfile = (profileType, name, details, childProfileIds = []) => {
createProfile({
@@ -29,6 +55,7 @@ const AddProfile = () => {
message: 'Success',
description: 'Profile successfully created.',
});
history.push('/profiles', { refetch: true });
})
.catch(() =>
notification.error({
@@ -38,12 +65,31 @@ const AddProfile = () => {
);
};
const handleFetchProfiles = e => {
if (ssidProfiles.getAllProfiles.context.lastPage) {
return false;
}
e.persist();
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
fetchMore({
variables: { context: { ...ssidProfiles.getAllProfiles.context } },
updateQuery: updateQueryGetAllProfiles,
});
}
return true;
};
return (
<AddProfilePage
onCreateProfile={handleAddProfile}
ssidProfiles={
(ssidProfiles && ssidProfiles.getAllProfiles && ssidProfiles.getAllProfiles.items) || []
}
onFetchMoreProfiles={handleFetchProfiles}
/>
);
};

View File

@@ -1,75 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { addProfileMutationMock, getAllProfilesQueryMock } from './mock';
import AddProfile from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
const DOWN_ARROW = { keyCode: 40 };
describe('<AddProfile />', () => {
afterEach(cleanup);
it('should create profile when provide correct Mutation', async () => {
const { getByText, getByLabelText, getByRole } = render(
<MockedProvider
mocks={[getAllProfilesQueryMock.success, addProfileMutationMock.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<AddProfile />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByRole('button', { name: 'Save' })).toBeVisible());
fireEvent.change(getByLabelText('Name'), { target: { value: 'test' } });
await waitFor(() => expect(getByLabelText('Name')).toHaveValue('test'));
fireEvent.keyDown(getByLabelText('Type'), DOWN_ARROW);
fireEvent.click(getByText('Access Point'));
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Profile successfully created.')).toBeVisible());
});
it('should show error when provide incorrect Mutation', async () => {
const { getByText, getByLabelText, getByRole } = render(
<MockedProvider mocks={[getAllProfilesQueryMock.success]} addTypename={false}>
<UserProvider {...mockProp}>
<AddProfile />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByRole('button', { name: 'Save' })).toBeVisible());
fireEvent.change(getByLabelText('Name'), { target: { value: 'test' } });
await waitFor(() => expect(getByLabelText('Name')).toHaveValue('test'));
fireEvent.keyDown(getByLabelText('Type'), DOWN_ARROW);
fireEvent.click(getByText('Access Point'));
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Profile could not be created.')).toBeVisible());
});
});

View File

@@ -1,146 +0,0 @@
import { GET_ALL_PROFILES } from 'graphql/queries';
import { CREATE_PROFILE } from 'graphql/mutations';
export const getAllProfilesQueryMock = {
success: {
request: {
query: GET_ALL_PROFILES,
variables: { customerId: 2, type: 'ssid' },
},
result: {
data: {
getAllProfiles: {
items: [
{
id: '1',
name: 'Radius-Profile',
profileType: 'radius',
details: {
model_type: 'RadiusProfile',
subnetConfiguration: null,
serviceRegionMap: {
Ottawa: {
model_type: 'RadiusServiceRegion',
serverMap: {
'Radius-Profile': [
{
model_type: 'RadiusServer',
ipAddress: '192.168.0.1',
secret: 'testing123',
authPort: 1812,
timeout: null,
},
],
},
regionName: 'Ottawa',
},
},
profileType: 'radius',
},
__typename: 'Profile',
},
],
context: {
cursor:
'bnVsbEBAQHsibW9kZWxfdHlwZSI6IkNvbnRleHRDaGlsZHJlbiIsImNoaWxkcmVuIjp7fX1AQEBudWxs',
lastPage: true,
__typename: 'PaginationContext',
},
__typename: 'ProfilePagination',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
errpr: [],
};
export const addProfileMutationMock = {
success: {
request: {
query: CREATE_PROFILE,
variables: {
profileType: 'equipment_ap',
customerId: 2,
name: 'test',
childProfileIds: [],
details: {
profileType: 'equipment_ap',
name: 'test',
vlanNative: true,
ntpServer: { auto: undefined },
ledControlEnabled: undefined,
rtlsSettings: { enabled: false },
syslogRelay: { enabled: false },
syntheticClientEnabled: false,
equipmentDiscovery: false,
childProfileIds: [],
model_type: 'ApNetworkConfiguration',
},
},
},
result: {
data: {
createProfile: {
profileType: 'equipment_ap',
customerId: '2',
name: 'test',
childProfileIds: [],
details: {
model_type: 'ApNetworkConfiguration',
networkConfigVersion: 'AP-1',
equipmentType: 'AP',
vlanNative: true,
vlan: 0,
ntpServer: {
model_type: 'AutoOrManualString',
auto: false,
value: null,
},
syslogRelay: {
model_type: 'SyslogRelay',
enabled: false,
srvHostIp: null,
srvHostPort: 514,
severity: 'NOTICE',
},
rtlsSettings: {
model_type: 'RtlsSettings',
enabled: false,
srvHostIp: null,
srvHostPort: 0,
},
syntheticClientEnabled: false,
ledControlEnabled: true,
equipmentDiscovery: false,
radioMap: {
is5GHz: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is2dot4GHz: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is5GHzU: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is5GHzL: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
},
profileType: 'equipment_ap',
},
__typename: 'Profile',
},
},
},
},
};

View File

@@ -1,70 +1,81 @@
import React, { useContext } from 'react';
import { useQuery } from '@apollo/react-hooks';
import { Alert, notification } from 'antd';
import { Alarms as AlarmsPage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { gql } from '@apollo/client';
import { notification } from 'antd';
import { Alarms as AlarmsPage } from '@tip-wlan/wlan-cloud-ui-library';
import { withQuery } from 'containers/QueryWrapper';
import UserContext from 'contexts/UserContext';
import { GET_ALL_ALARMS } from 'graphql/queries';
const Alarms = () => {
const { customerId } = useContext(UserContext);
const { loading, error, data, refetch, fetchMore } = useQuery(GET_ALL_ALARMS, {
variables: { customerId },
errorPolicy: 'all',
});
const handleOnReload = () => {
refetch()
.then(() => {
notification.success({
message: 'Success',
description: 'Alarms reloaded.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Alarms could not be reloaded.',
})
);
};
const handleLoadMore = () => {
if (!data.getAllAlarms.context.lastPage) {
fetchMore({
variables: { cursor: data.getAllAlarms.context.cursor },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.getAllAlarms;
const newItems = fetchMoreResult.getAllAlarms.items;
return {
getAllAlarms: {
context: fetchMoreResult.getAllAlarms.context,
items: [...previousEntry.items, ...newItems],
__typename: previousEntry.__typename,
},
};
},
});
const GET_ALL_ALARMS = gql`
query GetAllAlarms($customerId: ID!, $context: JSONObject) {
getAllAlarms(customerId: $customerId, context: $context) {
items {
severity
alarmCode
details
createdTimestamp
equipment {
id
name
}
}
context
}
};
if (loading) {
return <Loading />;
}
`;
if (error && !data?.getAllAlarms?.items) {
return <Alert message="Error" description="Failed to load alarms." type="error" showIcon />;
const Alarms = withQuery(
({ data, refetch, fetchMore }) => {
const handleOnReload = () => {
refetch()
.then(() => {
notification.success({
message: 'Success',
description: 'Alarms reloaded.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Alarms could not be reloaded.',
})
);
};
const handleLoadMore = () => {
if (!data.getAllAlarms.context.lastPage) {
fetchMore({
variables: { context: data.getAllAlarms.context },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.getAllAlarms;
const newItems = fetchMoreResult.getAllAlarms.items;
return {
getAllAlarms: {
context: fetchMoreResult.getAllAlarms.context,
items: [...previousEntry.items, ...newItems],
__typename: previousEntry.__typename,
},
};
},
});
}
};
return (
<AlarmsPage
data={data.getAllAlarms.items}
onReload={handleOnReload}
onLoadMore={handleLoadMore}
isLastPage={data.getAllAlarms.context.lastPage}
/>
);
},
GET_ALL_ALARMS,
() => {
const { customerId } = useContext(UserContext);
return { customerId, errorPolicy: 'all' };
}
return (
<AlarmsPage
data={data.getAllAlarms.items}
onReload={handleOnReload}
onLoadMore={handleLoadMore}
isLastPage={data.getAllAlarms.context.lastPage}
/>
);
};
);
export default Alarms;

View File

@@ -1,121 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import { BrowserRouter as Router } from 'react-router-dom';
import UserProvider from 'contexts/UserProvider';
import { alarmsQueryMock } from './mock';
import Alarms from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<Alarms />', () => {
afterEach(jest.resetModules);
it('should render with Data', async () => {
const { getAllByText } = render(
<MockedProvider mocks={[alarmsQueryMock.success]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<Alarms />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getAllByText('Available memory is too low')[0]).toBeVisible());
});
it('should show error when query return error', async () => {
const { getByText } = render(
<MockedProvider mocks={[alarmsQueryMock.error]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<Alarms />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load alarms.')).toBeVisible());
});
it('should work with the onLoadMore', async () => {
const { getAllByText, getByRole } = render(
<MockedProvider
mocks={[alarmsQueryMock.success, alarmsQueryMock.loadmore]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Alarms />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getAllByText('Available memory is too low')[0]).toBeVisible());
fireEvent.click(getByRole('button', { name: /load more/i }));
await waitFor(() => expect(getAllByText('Available memory is too low')[0]).toBeVisible());
});
it('should work with the onReload', async () => {
const { getAllByText, getByText, container } = render(
<MockedProvider
mocks={[alarmsQueryMock.success, alarmsQueryMock.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Alarms />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getAllByText('Available memory is too low')[0]).toBeVisible());
const reloadButton = container.querySelector(
'.ant-btn.index-module__Button___VGygY.ant-btn-icon-only'
);
fireEvent.click(reloadButton);
await waitFor(() => expect(getByText('Alarms reloaded.')).toBeVisible());
});
it('should show error when reload wuery return error', async () => {
const { getAllByText, getByText, container } = render(
<MockedProvider mocks={[alarmsQueryMock.success]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<Alarms />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getAllByText('Available memory is too low')[0]).toBeVisible());
const reloadButton = container.querySelector(
'.ant-btn.index-module__Button___VGygY.ant-btn-icon-only'
);
fireEvent.click(reloadButton);
await waitFor(() => expect(getByText('Alarms reloaded.')).toBeVisible());
});
});

View File

@@ -1,191 +0,0 @@
import { GET_ALL_ALARMS } from 'graphql/queries';
export const alarmsQueryMock = {
success: {
request: {
query: GET_ALL_ALARMS,
variables: { customerId: 2 },
errorPolicy: 'all',
},
result: {
data: {
getAllAlarms: {
items: [
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564234684',
equipment: {
id: '7',
name: 'AP 7',
},
},
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564234796',
equipment: {
id: '14',
name: 'AP 14',
},
},
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564234885',
equipment: {
id: '21',
name: 'AP 21',
},
},
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564234957',
equipment: {
id: '28',
name: 'AP 28',
},
},
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564235022',
equipment: {
id: '35',
name: 'AP 35',
},
},
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564235082',
equipment: {
id: '42',
name: 'AP 42',
},
},
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564235155',
equipment: {
id: '49',
name: 'AP 49',
},
},
],
context: {
cursor: 'test',
lastPage: false,
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
loadmore: {
request: {
query: GET_ALL_ALARMS,
variables: { customerId: 2, cursor: 'test' },
errorPolicy: 'all',
},
result: {
data: {
getAllAlarms: {
items: [
{
severity: 'error',
alarmCode: 'MemoryUtilization',
details: {
model_type: 'AlarmDetails',
message: 'Available memory is too low',
affectedEquipmentIds: null,
generatedBy: null,
contextAttrs: null,
},
createdTimestamp: '1596564234684',
equipment: {
id: '7',
name: 'AP 7',
},
},
],
context: {
cursor: 'test2',
lastPage: true,
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_ALL_ALARMS,
variables: { customerId: 2 },
errorPolicy: 'all',
},
result: {
data: null,
loading: false,
errors: [{}],
networkStatus: 7,
stale: false,
},
},
};

View File

@@ -1,10 +1,10 @@
import React, { useContext, useEffect, useMemo, useState, useRef } from 'react';
import { Alert } from 'antd';
import moment from 'moment';
import { useQuery } from '@apollo/react-hooks';
import { Dashboard as DashboardPage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { useQuery } from '@apollo/client';
import { Dashboard as DashboardPage } from '@tip-wlan/wlan-cloud-ui-library';
import UserContext from 'contexts/UserContext';
import { FILTER_SYSTEM_EVENTS, GET_ALL_STATUS } from 'graphql/queries';
import { withQuery } from 'containers/QueryWrapper';
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
@@ -13,7 +13,7 @@ function formatBytes(bytes, decimals = 2) {
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(k));
// eslint-disable-next-line no-restricted-properties
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i] || ''}`;
@@ -46,231 +46,242 @@ const lineChartConfig = [
},
];
const Dashboard = () => {
const initialGraphTime = useRef({
toTime: moment()
.valueOf()
.toString(),
fromTime: moment()
.subtract(24, 'hours')
.valueOf()
.toString(),
});
const { customerId } = useContext(UserContext);
const { loading, error, data } = useQuery(GET_ALL_STATUS, {
variables: { customerId, statusDataTypes: ['CUSTOMER_DASHBOARD'] },
});
const Dashboard = withQuery(
({ data }) => {
const { customerId } = useContext(UserContext);
const initialGraphTime = useRef({
toTime: moment()
.valueOf()
.toString(),
fromTime: moment()
.subtract(24, 'hours')
.valueOf()
.toString(),
});
const [lineChartData, setLineChartData] = useState({
inservicesAPs: {
key: 'Inservice APs',
value: [],
},
clientDevices: {
is2dot4GHz: {
key: USER_FRIENDLY_RADIOS.is2dot4GHz,
const [lineChartData, setLineChartData] = useState({
inservicesAPs: {
key: 'Inservice APs',
value: [],
},
is5GHz: {
key: USER_FRIENDLY_RADIOS.is5GHz,
value: [],
clientDevices: {
is2dot4GHz: {
key: USER_FRIENDLY_RADIOS.is2dot4GHz,
value: [],
},
is5GHz: {
key: USER_FRIENDLY_RADIOS.is5GHz,
value: [],
},
},
},
traffic: {
trafficBytesDownstream: {
key: 'Down Stream',
value: [],
traffic: {
trafficBytesDownstream: {
key: 'Down Stream',
value: [],
},
trafficBytesUpstream: {
key: 'Up Stream',
value: [],
},
},
trafficBytesUpstream: {
key: 'Up Stream',
value: [],
},
},
});
});
const { loading: metricsLoading, error: metricsError, data: metricsData, fetchMore } = useQuery(
FILTER_SYSTEM_EVENTS,
{
variables: {
customerId,
fromTime: initialGraphTime.current.fromTime,
toTime: initialGraphTime.current.toTime,
equipmentIds: [0],
dataTypes: ['StatusChangedEvent'],
limit: 3000, // TODO: make get all in GraphQL
},
}
);
const { loading: metricsLoading, error: metricsError, data: metricsData, fetchMore } = useQuery(
FILTER_SYSTEM_EVENTS,
{
variables: {
customerId,
fromTime: initialGraphTime.current.fromTime,
toTime: initialGraphTime.current.toTime,
equipmentIds: [0],
dataTypes: ['StatusChangedEvent'],
limit: 3000, // TODO: make get all in GraphQL
},
}
);
const formatLineChartData = (list = []) => {
if (list.length) {
setLineChartData(prev => {
const inservicesAPs = [];
const clientDevices2dot4GHz = [];
const clientDevices5GHz = [];
const trafficBytesDownstreamData = [];
const trafficBytesUpstreamData = [];
const formatLineChartData = (list = []) => {
if (list.length) {
setLineChartData(prev => {
const inservicesAPs = [];
const clientDevices2dot4GHz = [];
const clientDevices5GHz = [];
const trafficBytesDownstreamData = [];
const trafficBytesUpstreamData = [];
let totalDown = 0;
let totalUp = 0;
list.forEach(
({
eventTimestamp,
details: {
payload: {
details: {
equipmentInServiceCount,
associatedClientsCountPerRadio: radios,
trafficBytesDownstream,
trafficBytesUpstream,
list.forEach(
({
eventTimestamp,
details: {
payload: {
details: {
equipmentInServiceCount,
associatedClientsCountPerRadio: radios,
trafficBytesDownstream,
trafficBytesUpstream,
},
},
},
}) => {
inservicesAPs.push([eventTimestamp, equipmentInServiceCount]);
let total5GHz = 0;
total5GHz += (radios?.is5GHz || 0) + (radios?.is5GHzL || 0) + (radios?.is5GHzU || 0); // combine all 5GHz radios
clientDevices2dot4GHz.push([eventTimestamp, radios.is2dot4GHz || 0]);
clientDevices5GHz.push([eventTimestamp, total5GHz || 0]);
trafficBytesDownstreamData.push([eventTimestamp, trafficBytesDownstream || 0]);
trafficBytesUpstreamData.push([eventTimestamp, trafficBytesUpstream || 0]);
totalDown += trafficBytesDownstream || 0;
totalUp += trafficBytesUpstream || 0;
}
);
return {
inservicesAPs: {
...prev.inservicesAPs,
value: [...prev.inservicesAPs.value, ...inservicesAPs],
},
}) => {
inservicesAPs.push([eventTimestamp, equipmentInServiceCount]);
clientDevices: {
is2dot4GHz: {
...prev.clientDevices.is2dot4GHz,
value: [...prev.clientDevices.is2dot4GHz.value, ...clientDevices2dot4GHz],
},
is5GHz: {
...prev.clientDevices.is5GHz,
value: [...prev.clientDevices.is5GHz.value, ...clientDevices5GHz],
},
},
traffic: {
trafficBytesDownstream: {
...prev.traffic.trafficBytesDownstream,
value: [
...prev.traffic.trafficBytesDownstream.value,
...trafficBytesDownstreamData,
],
},
trafficBytesUpstream: {
...prev.traffic.trafficBytesUpstream,
value: [...prev.traffic.trafficBytesUpstream.value, ...trafficBytesUpstreamData],
},
},
totalDownstreamTraffic: totalDown,
totalUpstreamTraffic: totalUp,
};
});
}
};
let total5GHz = 0;
total5GHz += (radios?.is5GHz || 0) + (radios?.is5GHzL || 0) + (radios?.is5GHzU || 0); // combine all 5GHz radios
useEffect(() => {
const interval = setInterval(() => {
const toTime = moment()
.valueOf()
.toString();
const fromTime = moment()
.subtract(5, 'minutes')
.valueOf()
.toString();
fetchMore({
variables: {
fromTime,
toTime,
},
updateQuery: (_, { fetchMoreResult }) => {
formatLineChartData(fetchMoreResult?.filterSystemEvents?.items);
},
});
}, 300000);
clientDevices2dot4GHz.push([eventTimestamp, radios.is2dot4GHz || 0]);
clientDevices5GHz.push([eventTimestamp, total5GHz]);
return () => clearInterval(interval);
}, []);
trafficBytesDownstreamData.push([eventTimestamp, trafficBytesDownstream]);
trafficBytesUpstreamData.push([eventTimestamp, trafficBytesUpstream]);
useEffect(() => {
formatLineChartData(metricsData?.filterSystemEvents?.items);
}, [metricsData]);
const statsData = useMemo(() => {
const status = data?.getAllStatus?.items[0]?.detailsJSON || {};
const {
associatedClientsCountPerRadio,
totalProvisionedEquipment,
equipmentInServiceCount,
equipmentWithClientsCount,
} = status;
const clientRadios = {};
let totalAssociated = 0;
if (associatedClientsCountPerRadio) {
Object.keys(associatedClientsCountPerRadio).forEach(i => {
if (i.includes('5GHz')) {
if (!clientRadios['5GHz']) {
clientRadios['5GHz'] = 0;
}
clientRadios['5GHz'] += associatedClientsCountPerRadio[i];
} else {
const key = USER_FRIENDLY_RADIOS[i] || i;
clientRadios[key] = associatedClientsCountPerRadio[i];
}
);
totalAssociated += associatedClientsCountPerRadio[i];
});
}
return {
inservicesAPs: {
...prev.inservicesAPs,
value: [...prev.inservicesAPs.value, ...inservicesAPs],
return {
totalProvisionedEquipment,
equipmentInServiceCount,
equipmentWithClientsCount,
totalAssociated,
clientRadios,
};
}, [data]);
const pieChartsData = useMemo(() => {
const { clientCountPerOui, equipmentCountPerOui } =
data?.getAllStatus?.items[0]?.details || {};
return [
{ title: 'AP Vendors', ...equipmentCountPerOui },
{ title: 'Client Vendors', ...clientCountPerOui },
];
}, [data]);
return (
<DashboardPage
statsCardDetails={[
{
title: 'Access Point',
'Total Provisioned': statsData?.totalProvisionedEquipment,
'In Service': statsData?.equipmentInServiceCount,
'With Clients': statsData?.equipmentWithClientsCount,
},
clientDevices: {
is2dot4GHz: {
...prev.clientDevices.is2dot4GHz,
value: [...prev.clientDevices.is2dot4GHz.value, ...clientDevices2dot4GHz],
},
is5GHz: {
...prev.clientDevices.is5GHz,
value: [...prev.clientDevices.is5GHz.value, ...clientDevices5GHz],
},
{
title: 'Client Devices',
'Total Associated': statsData?.totalAssociated,
...statsData?.clientRadios,
},
traffic: {
trafficBytesDownstream: {
...prev.traffic.trafficBytesDownstream,
value: [...prev.traffic.trafficBytesDownstream.value, ...trafficBytesDownstreamData],
},
trafficBytesUpstream: {
...prev.traffic.trafficBytesUpstream,
value: [...prev.traffic.trafficBytesUpstream.value, ...trafficBytesUpstreamData],
},
{
title: 'Usage Information (24 hours)',
'Total Traffic (US)': formatBytes(lineChartData?.totalUpstreamTraffic),
'Total Traffic (DS)': formatBytes(lineChartData?.totalDownstreamTraffic),
},
};
});
}
};
useEffect(() => {
const interval = setInterval(() => {
const toTime = moment()
.valueOf()
.toString();
const fromTime = moment()
.subtract(5, 'minutes')
.valueOf()
.toString();
fetchMore({
variables: {
fromTime,
toTime,
},
updateQuery: (_, { fetchMoreResult }) => {
formatLineChartData(fetchMoreResult?.filterSystemEvents?.items);
},
});
}, 300000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
formatLineChartData(metricsData?.filterSystemEvents?.items);
}, [metricsData]);
const statsArr = useMemo(() => {
const status = data?.getAllStatus?.items[0]?.detailsJSON || {};
const {
associatedClientsCountPerRadio,
totalProvisionedEquipment,
equipmentInServiceCount,
equipmentWithClientsCount,
trafficBytesDownstream,
trafficBytesUpstream,
} = status;
const clientRadios = {};
let totalAssociated = 0;
if (associatedClientsCountPerRadio) {
Object.keys(associatedClientsCountPerRadio).forEach(i => {
if (i.includes('5GHz')) {
if (!clientRadios['5GHz']) {
clientRadios['5GHz'] = 0;
}
clientRadios['5GHz'] += associatedClientsCountPerRadio[i];
} else {
const key = USER_FRIENDLY_RADIOS[i] || i;
clientRadios[key] = associatedClientsCountPerRadio[i];
}
totalAssociated += associatedClientsCountPerRadio[i];
});
}
return [
{
title: 'Access Point',
'Total Provisioned': totalProvisionedEquipment,
'In Service': equipmentInServiceCount,
'With Clients': equipmentWithClientsCount,
},
{
title: 'Client Devices',
'Total Associated': totalAssociated,
...clientRadios,
},
{
title: 'Usage Information',
'Total Traffic (US)': formatBytes(trafficBytesUpstream),
'Total Traffic (DS)': formatBytes(trafficBytesDownstream),
},
];
}, [data]);
const pieChartsData = useMemo(() => {
const { clientCountPerOui, equipmentCountPerOui } = data?.getAllStatus?.items[0]?.details || {};
return [
{ title: 'AP Vendors', ...equipmentCountPerOui },
{ title: 'Client Vendors', ...clientCountPerOui },
];
}, [data]);
if (loading) {
return <Loading />;
]}
pieChartDetails={pieChartsData}
lineChartData={lineChartData}
lineChartConfig={lineChartConfig}
lineChartLoading={metricsLoading}
lineChartError={metricsError}
/>
);
},
GET_ALL_STATUS,
() => {
const { customerId } = useContext(UserContext);
return { customerId, statusDataTypes: ['CUSTOMER_DASHBOARD'] };
}
if (error) {
return <Alert message="Error" description="Failed to load Dashboard" type="error" showIcon />;
}
return (
<DashboardPage
statsCardDetails={statsArr}
pieChartDetails={pieChartsData}
lineChartData={lineChartData}
lineChartConfig={lineChartConfig}
lineChartLoading={metricsLoading}
lineChartError={metricsError}
/>
);
};
);
export default Dashboard;

View File

@@ -1,68 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { render, waitFor } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { dashboardQueryMock } from './mock';
import Dashboard from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
jest.mock('moment', () => () => ({
subtract: () => ({ valueOf: () => ({ toString: () => '1234' }) }),
valueOf: () => ({ toString: () => '1234' }),
}));
jest.useFakeTimers();
describe('<Dashboard />', () => {
afterEach(jest.resetModules);
it('should render with data', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
dashboardQueryMock.filterSystemEvents.success,
dashboardQueryMock.filterSystemEvents.success,
dashboardQueryMock.getAllStatus.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Dashboard />
</UserProvider>
</MockedProvider>
);
jest.advanceTimersByTime('300000');
await waitFor(() => expect(getByText('2.4GHz')).toBeVisible());
});
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider mocks={[dashboardQueryMock.filterSystemEvents.error]} addTypename={false}>
<UserProvider {...mockProp}>
<Dashboard />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load Dashboard')).toBeVisible());
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,53 +1,88 @@
import React, { useContext } from 'react';
import { useMutation, useQuery } from '@apollo/react-hooks';
import { notification, Alert } from 'antd';
import { EditAccount as EditAccountPage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { useMutation, gql } from '@apollo/client';
import { notification } from 'antd';
import { EditAccount as EditAccountPage } from '@tip-wlan/wlan-cloud-ui-library';
import { withQuery } from 'containers/QueryWrapper';
import UserContext from 'contexts/UserContext';
import { GET_USER } from 'graphql/queries';
import { UPDATE_USER } from 'graphql/mutations';
const EditAccount = () => {
const { id, email } = useContext(UserContext);
const { loading, error, data } = useQuery(GET_USER, { variables: { id } });
const [updateUser] = useMutation(UPDATE_USER);
const GET_USER = gql`
query GetUser($id: ID!) {
getUser(id: $id) {
id
username
role
customerId
lastModifiedTimestamp
}
}
`;
const handleSubmit = newPassword => {
const { role, customerId, lastModifiedTimestamp } = data.getUser;
const UPDATE_USER = gql`
mutation UpdateUser(
$id: ID!
$username: String!
$password: String!
$role: String!
$customerId: ID!
$lastModifiedTimestamp: String
) {
updateUser(
id: $id
username: $username
password: $password
role: $role
customerId: $customerId
lastModifiedTimestamp: $lastModifiedTimestamp
) {
id
username
role
customerId
lastModifiedTimestamp
}
}
`;
updateUser({
variables: {
id,
username: email,
password: newPassword,
role,
customerId,
lastModifiedTimestamp,
},
})
.then(() => {
notification.success({
message: 'Success',
description: 'Password successfully updated.',
});
const EditAccount = withQuery(
({ data }) => {
const { id, email } = useContext(UserContext);
const [updateUser] = useMutation(UPDATE_USER);
const handleSubmit = newPassword => {
const { role, customerId, lastModifiedTimestamp } = data.getUser;
updateUser({
variables: {
id,
username: email,
password: newPassword,
role,
customerId,
lastModifiedTimestamp,
},
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Password could not be updated.',
.then(() => {
notification.success({
message: 'Success',
description: 'Password successfully updated.',
});
})
);
};
.catch(() =>
notification.error({
message: 'Error',
description: 'Password could not be updated.',
})
);
};
if (loading) {
return <Loading />;
return <EditAccountPage onSubmit={handleSubmit} email={email} />;
},
GET_USER,
() => {
const { id } = useContext(UserContext);
return { id };
}
if (error) {
return <Alert message="Error" description="Failed to load User." type="error" showIcon />;
}
return <EditAccountPage onSubmit={handleSubmit} email={email} />;
};
);
export default EditAccount;

View File

@@ -1,86 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import UserProvider from 'contexts/UserProvider';
import { editAccountMutationMock, editAccountQueryMock } from './mock';
import EditAccount from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<EditAccount />', () => {
afterEach(jest.resetModules);
it('should render with Data and Edit Profile when valid Mutation', async () => {
const { getByText, getByTestId, getByLabelText } = render(
<MockedProvider
mocks={[editAccountQueryMock.success, editAccountMutationMock.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<EditAccount />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('New Password')).toBeVisible());
fireEvent.change(getByLabelText('New Password'), { target: { value: 'password' } });
await waitFor(() => expect(getByLabelText('New Password')).toHaveValue('password'));
fireEvent.change(getByLabelText('Confirm Password'), { target: { value: 'password' } });
fireEvent.submit(getByTestId('saveButton'));
await waitFor(() => expect(getByText('Password successfully updated.')).toBeVisible());
});
it('should show error when query return Error', async () => {
const { getByText } = render(
<MockedProvider mocks={[editAccountQueryMock.error]} addTypename={false}>
<UserProvider {...mockProp}>
<EditAccount />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load User.')).toBeVisible());
});
it('should show error when edit profile Mutation return error', async () => {
const { getByText, getByTestId, getByLabelText } = render(
<MockedProvider
mocks={[editAccountQueryMock.success, editAccountMutationMock.error]}
addTypename={false}
>
<UserProvider {...mockProp}>
<EditAccount />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('New Password')).toBeVisible());
fireEvent.change(getByLabelText('New Password'), { target: { value: 'password' } });
await waitFor(() => expect(getByLabelText('New Password')).toHaveValue('password'));
fireEvent.change(getByLabelText('Confirm Password'), { target: { value: 'password' } });
fireEvent.submit(getByTestId('saveButton'));
await waitFor(() => expect(getByText('Password could not be updated.')).toBeVisible());
});
});

View File

@@ -1,85 +0,0 @@
import { GET_USER } from 'graphql/queries';
import { UPDATE_USER } from 'graphql/mutations';
export const editAccountQueryMock = {
success: {
request: {
query: GET_USER,
variables: { id: 123 },
},
result: {
data: {
getUser: {
id: '123',
username: 'user-0',
role: 'CustomerIT',
customerId: '2',
lastModifiedTimestamp: '1597238767547',
__typename: 'User',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_USER,
variables: { id: 123 },
},
result: {
data: null,
errors: [{}],
loading: false,
networkStatus: 7,
stale: false,
},
},
};
export const editAccountMutationMock = {
success: {
request: {
query: UPDATE_USER,
variables: {
id: 123,
username: 'test@test.com',
password: 'password',
role: 'CustomerIT',
customerId: '2',
lastModifiedTimestamp: '1597238767547',
},
},
result: {
data: {
updateUser: {
id: 123,
username: 'user-0',
role: 'CustomerIT',
customerId: '2',
lastModifiedTimestamp: '1597238767547',
__typename: 'User',
},
},
},
},
error: {
request: {
query: UPDATE_USER,
variables: {
id: 123,
username: 'test@test.com',
password: 'password',
role: 'CustomerIT',
customerId: '2',
lastModifiedTimestamp: '1597238767547',
},
},
result: {
data: null,
errors: [{}],
},
},
};

View File

@@ -1,12 +1,21 @@
import React, { useContext } from 'react';
import { useMutation, useApolloClient } from '@apollo/react-hooks';
import { useMutation, useApolloClient, gql } from '@apollo/client';
import { useHistory } from 'react-router-dom';
import { notification } from 'antd';
import { Login as LoginPage } from '@tip-wlan/wlan-cloud-ui-library';
import UserContext from 'contexts/UserContext';
import { AUTHENTICATE_USER } from 'graphql/mutations';
const AUTHENTICATE_USER = gql`
mutation AuthenticateUser($email: String!, $password: String!) {
authenticateUser(email: $email, password: $password) {
access_token
refresh_token
expires_in
}
}
`;
const Login = () => {
const history = useHistory();
@@ -17,9 +26,10 @@ const Login = () => {
const handleLogin = (email, password) => {
authenticateUser({ variables: { email, password } })
.then(({ data }) => {
client.resetStore();
updateToken(data.authenticateUser);
history.push('/');
client.resetStore().then(() => {
updateToken(data.authenticateUser);
history.push('/');
});
})
.catch(() =>
notification.error({

View File

@@ -1,71 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, cleanup, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import UserProvider from 'contexts/UserProvider';
import { ThemeProvider } from '@tip-wlan/wlan-cloud-ui-library';
import { loginMutationMock } from './mock';
import Login from '..';
jest.mock('react-router-dom', () => ({
useHistory: () => ({ push: jest.fn() }),
}));
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<Login />', () => {
afterEach(() => cleanup);
it('login should be successful when mutation is valid', async () => {
const { getByLabelText, getByTestId } = render(
<ThemeProvider company="Test" logo="test.png" logoMobile="test.png">
<MockedProvider mocks={[loginMutationMock.loginSuccess]} addTypename={false}>
<UserProvider {...mockProp}>
<Login />
</UserProvider>
</MockedProvider>
</ThemeProvider>
);
fireEvent.change(getByLabelText('E-mail'), { target: { value: 'test@test.com' } });
fireEvent.change(getByLabelText('Password'), { target: { value: 'password' } });
fireEvent.submit(getByTestId('loginButton'));
await waitFor(() => expect(getByLabelText('E-mail')).toBeVisible());
});
it('login should not be successful when mutation is invalid', async () => {
const { getByLabelText, getByText, getByTestId } = render(
<ThemeProvider company="Test" logo="test.png" logoMobile="test.png">
<MockedProvider mocks={[loginMutationMock.loginError]} addTypename={false}>
<UserProvider {...mockProp}>
<Login />
</UserProvider>
</MockedProvider>
</ThemeProvider>
);
fireEvent.change(getByLabelText('E-mail'), { target: { value: 'test@test.com' } });
fireEvent.change(getByLabelText('Password'), { target: { value: 'password' } });
fireEvent.submit(getByTestId('loginButton'));
await waitFor(() => expect(getByText('Invalid e-mail or password.')).toBeVisible());
});
});

View File

@@ -1,32 +0,0 @@
import { AUTHENTICATE_USER } from 'graphql/mutations';
export const loginMutationMock = {
loginSuccess: {
request: {
query: AUTHENTICATE_USER,
variables: {
email: 'test@test.com',
password: 'password',
},
},
result: {
data: {
authenticateUser: {
access_token: '123',
refresh_token: '345',
expires_in: '1',
},
},
},
},
loginError: {
request: {
query: AUTHENTICATE_USER,
variables: {},
},
result: {
data: null,
errors: [{}],
},
},
};

View File

@@ -1,7 +1,7 @@
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { useLocation } from 'react-router-dom';
import { useApolloClient, useQuery } from '@apollo/react-hooks';
import { useApolloClient, useQuery } from '@apollo/client';
import { AppLayout as Layout } from '@tip-wlan/wlan-cloud-ui-library';
import { GET_ALARM_COUNT } from 'graphql/queries';

View File

@@ -1,37 +1,122 @@
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import gql from 'graphql-tag';
import { useParams } from 'react-router-dom';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { Alert, notification } from 'antd';
import { useQuery, useMutation, gql } from '@apollo/client';
import { notification } from 'antd';
import moment from 'moment';
import { AccessPointDetails as AccessPointDetailsPage } from '@tip-wlan/wlan-cloud-ui-library';
import { FILTER_SERVICE_METRICS, GET_ALL_FIRMWARE, GET_ALL_PROFILES } from 'graphql/queries';
import {
AccessPointDetails as AccessPointDetailsPage,
Loading,
} from '@tip-wlan/wlan-cloud-ui-library';
import { GET_EQUIPMENT, GET_ALL_FIRMWARE, FILTER_SERVICE_METRICS } from 'graphql/queries';
import { UPDATE_EQUIPMENT, UPDATE_EQUIPMENT_FIRMWARE } from 'graphql/mutations';
UPDATE_EQUIPMENT_FIRMWARE,
REQUEST_EQUIPMENT_SWITCH_BANK,
REQUEST_EQUIPMENT_REBOOT,
} from 'graphql/mutations';
import { updateQueryGetAllProfiles } from 'graphql/functions';
import UserContext from 'contexts/UserContext';
import { withQuery } from 'containers/QueryWrapper';
export const GET_ALL_PROFILES = gql`
query GetAllProfiles($customerId: ID!, $cursor: String, $type: String, $limit: Int) {
getAllProfiles(customerId: $customerId, cursor: $cursor, type: $type, limit: $limit) {
items {
const GET_EQUIPMENT = gql`
query GetEquipment($id: ID!) {
getEquipment(id: $id) {
id
equipmentType
inventoryId
customerId
profileId
locationId
name
latitude
longitude
serial
lastModifiedTimestamp
details
profile {
id
name
profileType
details
childProfiles {
id
name
details
}
}
context {
cursor
lastPage
status {
firmware {
detailsJSON
}
protocol {
detailsJSON
details {
reportedMacAddr
manufacturer
}
}
radioUtilization {
detailsJSON
}
clientDetails {
detailsJSON
details {
numClientsPerRadio
}
}
osPerformance {
detailsJSON
}
}
model
alarmsCount
alarms {
severity
alarmCode
details
createdTimestamp
}
}
}
`;
const UPDATE_EQUIPMENT = gql`
mutation UpdateEquipment(
$id: ID!
$equipmentType: String!
$inventoryId: String!
$customerId: ID!
$profileId: ID!
$locationId: ID!
$name: String!
$latitude: String
$longitude: String
$serial: String
$lastModifiedTimestamp: String
$details: JSONObject
) {
updateEquipment(
id: $id
equipmentType: $equipmentType
inventoryId: $inventoryId
customerId: $customerId
profileId: $profileId
locationId: $locationId
name: $name
latitude: $latitude
longitude: $longitude
serial: $serial
lastModifiedTimestamp: $lastModifiedTimestamp
details: $details
) {
id
equipmentType
inventoryId
customerId
profileId
locationId
name
latitude
longitude
serial
lastModifiedTimestamp
details
}
}
`;
@@ -39,168 +124,222 @@ export const GET_ALL_PROFILES = gql`
const toTime = moment();
const fromTime = moment().subtract(1, 'hour');
const AccessPointDetails = ({ locations }) => {
const { id } = useParams();
const { customerId } = useContext(UserContext);
const AccessPointDetails = withQuery(
({ data, refetch, locations }) => {
const { id } = useParams();
const { customerId } = useContext(UserContext);
const { loading, error, data, refetch } = useQuery(GET_EQUIPMENT, {
variables: { id },
});
const { data: dataProfiles, error: errorProfiles, loading: landingProfiles } = useQuery(
GET_ALL_PROFILES,
{
variables: { customerId, type: 'equipment_ap', limit: 100 },
}
);
const {
loading: metricsLoading,
error: metricsError,
data: metricsData,
refetch: metricsRefetch,
} = useQuery(FILTER_SERVICE_METRICS, {
variables: {
customerId,
fromTime: fromTime.valueOf().toString(),
toTime: toTime.valueOf().toString(),
equipmentIds: [id],
dataTypes: ['ApNode'],
limit: 100,
},
});
const { data: dataFirmware, error: errorFirmware, loading: loadingFirmware } = useQuery(
GET_ALL_FIRMWARE,
{
skip: !data?.getEquipment?.model,
variables: { modelId: data?.getEquipment?.model },
}
);
const [updateEquipment] = useMutation(UPDATE_EQUIPMENT);
const [updateEquipmentFirmware] = useMutation(UPDATE_EQUIPMENT_FIRMWARE);
const {
data: dataProfiles,
error: errorProfiles,
loading: loadingProfiles,
fetchMore,
} = useQuery(
GET_ALL_PROFILES(`
childProfiles {
id
name
details
}`),
{
variables: { customerId, type: 'equipment_ap' },
}
);
const { data: dataFirmware, error: errorFirmware, loading: landingFirmware } = useQuery(
GET_ALL_FIRMWARE
);
const refetchData = () => {
refetch();
metricsRefetch();
};
const handleUpdateEquipment = (
equipmentId,
equipmentType,
inventoryId,
custId,
profileId,
locationId,
name,
latitude,
longitude,
serial,
lastModifiedTimestamp,
details
) => {
updateEquipment({
const {
loading: metricsLoading,
error: metricsError,
data: metricsData,
refetch: metricsRefetch,
} = useQuery(FILTER_SERVICE_METRICS, {
variables: {
id: equipmentId,
equipmentType,
inventoryId,
customerId: custId,
profileId,
locationId,
name,
latitude,
longitude,
serial,
lastModifiedTimestamp,
details,
customerId,
fromTime: fromTime.valueOf().toString(),
toTime: toTime.valueOf().toString(),
equipmentIds: [id],
dataTypes: ['ApNode'],
limit: 100,
},
})
.then(() => {
notification.success({
message: 'Success',
description: 'Equipment settings successfully updated.',
});
});
const [updateEquipment] = useMutation(UPDATE_EQUIPMENT);
const [updateEquipmentFirmware] = useMutation(UPDATE_EQUIPMENT_FIRMWARE);
const [requestEquipmentSwitchBank] = useMutation(REQUEST_EQUIPMENT_SWITCH_BANK);
const [requestEquipmentReboot] = useMutation(REQUEST_EQUIPMENT_REBOOT);
const refetchData = () => {
refetch();
metricsRefetch();
};
const handleUpdateEquipment = (
equipmentId,
equipmentType,
inventoryId,
custId,
profileId,
locationId,
name,
latitude,
longitude,
serial,
lastModifiedTimestamp,
details
) => {
updateEquipment({
variables: {
id: equipmentId,
equipmentType,
inventoryId,
customerId: custId,
profileId,
locationId,
name,
latitude,
longitude,
serial,
lastModifiedTimestamp,
details,
},
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment settings could not be updated.',
.then(() => {
notification.success({
message: 'Success',
description: 'Equipment settings successfully updated.',
});
})
);
};
const handleUpdateEquipmentFirmware = (equipmentId, firmwareVersionId) =>
updateEquipmentFirmware({ variables: { equipmentId, firmwareVersionId } })
.then(firmwareResp => {
if (firmwareResp && firmwareResp.updateEquipmentFirmware.success === false) {
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment settings could not be updated.',
})
);
};
const handleUpdateEquipmentFirmware = (equipmentId, firmwareVersionId) =>
updateEquipmentFirmware({ variables: { equipmentId, firmwareVersionId } })
.then(firmwareResp => {
if (firmwareResp?.data?.updateEquipmentFirmware?.success === true) {
notification.success({
message: 'Success',
description: 'Equipment Firmware Upgrade in progress',
});
} else {
notification.error({
message: 'Error',
description: 'Equipment Firmware Upgrade could not be updated.',
});
}
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment Firmware Upgrade could not be updated.',
});
} else {
notification.success({
message: 'Success',
description: 'Equipment Firmware Upgrade in progress',
});
}
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment Firmware Upgrade could not be updated.',
})
);
const handleRequestEquipmentSwitchBank = equipmentId =>
requestEquipmentSwitchBank({ variables: { equipmentId } })
.then(firmwareResp => {
if (firmwareResp?.data?.requestEquipmentSwitchBank?.success === true) {
notification.success({
message: 'Success',
description: 'Equipment Firmware in progress',
});
} else {
notification.error({
message: 'Error',
description: 'Equipment Firmware could not be updated.',
});
}
})
);
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment Firmware could not be updated.',
})
);
if (loading || landingProfiles || landingFirmware) {
return <Loading />;
}
const handleRequestEquipmentReboot = equipmentId =>
requestEquipmentReboot({ variables: { equipmentId } })
.then(firmwareResp => {
if (firmwareResp?.data?.requestEquipmentReboot?.success === true) {
notification.success({
message: 'Success',
description: 'Equipment Firmware in progress',
});
} else {
notification.error({
message: 'Error',
description: 'Equipment Firmware could not be updated.',
});
}
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment Firmware could not be updated.',
})
);
const handleFetchProfiles = e => {
if (dataProfiles.getAllProfiles.context.lastPage) {
return false;
}
e.persist();
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
fetchMore({
variables: { context: { ...dataProfiles.getAllProfiles.context } },
updateQuery: updateQueryGetAllProfiles,
});
}
return true;
};
if (error) {
return (
<Alert
message="Error"
description="Failed to load Access Point data."
type="error"
showIcon
<AccessPointDetailsPage
handleRefresh={refetchData}
onUpdateEquipment={handleUpdateEquipment}
data={data?.getEquipment}
profiles={dataProfiles?.getAllProfiles?.items}
osData={{
loading: metricsLoading,
error: metricsError,
data: metricsData && metricsData.filterServiceMetrics.items,
}}
firmware={dataFirmware?.getAllFirmware}
locations={locations}
onUpdateEquipmentFirmware={handleUpdateEquipmentFirmware}
onRequestEquipmentSwitchBank={handleRequestEquipmentSwitchBank}
onRequestEquipmentReboot={handleRequestEquipmentReboot}
loadingProfiles={loadingProfiles}
errorProfiles={errorProfiles}
loadingFirmware={loadingFirmware}
errorFirmware={errorFirmware}
onFetchMoreProfiles={handleFetchProfiles}
isLastProfilesPage={dataProfiles?.getAllProfiles?.context?.lastPage}
/>
);
},
GET_EQUIPMENT,
() => {
const { id } = useParams();
return { id };
}
if (errorProfiles) {
return (
<Alert
message="Error"
description="Failed to load Access Point profiles."
type="error"
showIcon
/>
);
}
if (errorFirmware) {
return (
<Alert
message="Error"
description="Failed to load Access Point firmware."
type="error"
showIcon
/>
);
}
return (
<AccessPointDetailsPage
handleRefresh={refetchData}
onUpdateEquipment={handleUpdateEquipment}
data={data.getEquipment}
profiles={dataProfiles.getAllProfiles.items}
osData={{
loading: metricsLoading,
error: metricsError,
data: metricsData && metricsData.filterServiceMetrics.items,
}}
firmware={dataFirmware.getAllFirmware}
locations={locations}
onUpdateEquipmentFirmware={handleUpdateEquipmentFirmware}
/>
);
};
);
AccessPointDetails.propTypes = {
locations: PropTypes.instanceOf(Array).isRequired,

View File

@@ -1,106 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { render, waitFor } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { APDetailsQueryMock } from './mock';
import AccessPointDetails from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
jest.mock('moment', () => () => ({
subtract: () => ({ valueOf: () => ({ toString: () => '1234' }) }),
valueOf: () => ({ toString: () => '1234' }),
}));
jest.mock('react-router-dom', () => ({
useParams: () => ({
id: '1',
}),
useHistory: () => ({ push: jest.fn() }),
}));
jest.useFakeTimers();
describe('<AccessPointDetails />', () => {
afterEach(jest.resetModules);
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
APDetailsQueryMock.getEquipment.error,
APDetailsQueryMock.getAllProfiles.error,
APDetailsQueryMock.getAllFirmware.error,
APDetailsQueryMock.filterServiceMetrics.error,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<AccessPointDetails locations={[1, 2, 3]} />
</UserProvider>
</MockedProvider>
);
jest.advanceTimersByTime(1000);
await waitFor(() => expect(getByText('Failed to load Access Point data.')).toBeVisible());
});
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
APDetailsQueryMock.getEquipment.success,
APDetailsQueryMock.getAllProfiles.error,
APDetailsQueryMock.getAllFirmware.success,
APDetailsQueryMock.filterServiceMetrics.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<AccessPointDetails locations={[1, 2, 3]} />
</UserProvider>
</MockedProvider>
);
jest.advanceTimersByTime(1000);
await waitFor(() => expect(getByText('Failed to load Access Point profiles.')).toBeVisible());
});
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
APDetailsQueryMock.getEquipment.success,
APDetailsQueryMock.getAllProfiles.success,
APDetailsQueryMock.getAllFirmware.error,
APDetailsQueryMock.filterServiceMetrics.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<AccessPointDetails locations={[1, 2, 3]} />
</UserProvider>
</MockedProvider>
);
jest.advanceTimersByTime(1000);
await waitFor(() => expect(getByText('Failed to load Access Point firmware.')).toBeVisible());
});
});

View File

@@ -1,7 +1,7 @@
import React, { useEffect, useContext } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { useLazyQuery } from '@apollo/react-hooks';
import { useLazyQuery } from '@apollo/client';
import { notification } from 'antd';
import { floor, padStart } from 'lodash';
import { NetworkTableContainer } from '@tip-wlan/wlan-cloud-ui-library';
@@ -11,18 +11,21 @@ import { FILTER_EQUIPMENT } from 'graphql/queries';
import styles from './index.module.scss';
const renderTableCell = tabCell => {
if (Array.isArray(tabCell)) {
const renderTableCell = (text, _record, _index, defaultValue = 'N/A') => {
if (Array.isArray(text)) {
if (text.length < 1) {
return defaultValue;
}
return (
<div className={styles.tabColumn}>
{tabCell.map((i, key) => (
{text.map((i, key) => (
// eslint-disable-next-line react/no-array-index-key
<span key={key}>{i}</span>
))}
</div>
);
}
return tabCell;
return text !== null ? text : defaultValue;
};
const durationToString = duration =>
@@ -63,6 +66,11 @@ const accessPointsTableColumns = [
dataIndex: ['status', 'protocol', 'details', 'manufacturer'],
render: renderTableCell,
},
{
title: 'FIRMWARE',
dataIndex: ['status', 'firmware', 'detailsJSON', 'activeSwVersion'],
render: renderTableCell,
},
{
title: 'ASSET ID',
dataIndex: 'inventoryId',
@@ -96,7 +104,7 @@ const accessPointsTableColumns = [
{
title: 'DEVICES',
dataIndex: ['status', 'clientDetails', 'details', 'numClientsPerRadio'],
render: renderTableCell,
render: (text, record, index) => renderTableCell(text, record, index, 0),
},
];
@@ -128,7 +136,7 @@ const AccessPoints = ({ checkedLocations }) => {
const handleLoadMore = () => {
if (!equipData.filterEquipment.context.lastPage) {
fetchMore({
variables: { cursor: equipData.filterEquipment.context.cursor },
variables: { context: equipData.filterEquipment.context },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.filterEquipment;
const newItems = fetchMoreResult.filterEquipment.items;

View File

@@ -1,5 +1,4 @@
.tabColumn {
display: flex;
flex-direction: column;
padding: 0 30px;
}

View File

@@ -1,124 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { fireEvent, render, waitFor } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { BrowserRouter as Router } from 'react-router-dom';
import { AccessPointsQueryMock } from './mock';
import AccessPoints from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<AccessPoints />', () => {
afterEach(jest.resetModules);
it('should render with data', async () => {
const { getByText } = render(
<MockedProvider mocks={[AccessPointsQueryMock.filterEquipment.success]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<AccessPoints checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('AP 1')).toBeVisible());
});
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider mocks={[AccessPointsQueryMock.filterEquipment.error]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<AccessPoints checkedLocations={[1, 2, 3]} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load equipment.')).toBeVisible());
});
it('click on Load More should fetch more data', async () => {
const { getByRole, getByText } = render(
<MockedProvider
mocks={[
AccessPointsQueryMock.filterEquipment.success,
AccessPointsQueryMock.filterEquipment.loadmore,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<AccessPoints checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('AP 1')).toBeVisible());
fireEvent.click(getByRole('button', { name: /load more/i }));
await waitFor(() => expect(getByText('AP 1')).toBeVisible());
});
it('click on reload button should refetch data', async () => {
const { getByText, container } = render(
<MockedProvider
mocks={[
AccessPointsQueryMock.filterEquipment.success,
AccessPointsQueryMock.filterEquipment.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<AccessPoints checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('AP 1')).toBeVisible());
const reloadButton = container.querySelector(
'.ant-btn.index-module__Button___VGygY.ant-btn-icon-only'
);
fireEvent.click(reloadButton);
await waitFor(() => expect(getByText('Access points reloaded.')).toBeVisible());
});
it('click on reload button should not refetch data when query return error', async () => {
const { getByText, container } = render(
<MockedProvider mocks={[AccessPointsQueryMock.filterEquipment.success]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<AccessPoints checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('AP 1')).toBeVisible());
const reloadButton = container.querySelector(
'.ant-btn.index-module__Button___VGygY.ant-btn-icon-only'
);
fireEvent.click(reloadButton);
await waitFor(() => expect(getByText('Access points could not be reloaded.')).toBeVisible());
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,8 @@
import React, { useContext, useMemo } from 'react';
import PropTypes from 'prop-types';
import { Alert, notification } from 'antd';
import { useParams } from 'react-router-dom';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { useParams, Redirect } from 'react-router-dom';
import { useQuery, useMutation } from '@apollo/client';
import { BulkEditAccessPoints, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { FILTER_EQUIPMENT_BULK_EDIT_APS } from 'graphql/queries';
@@ -327,7 +327,7 @@ const BulkEditAPs = ({ locations, checkedLocations }) => {
const handleLoadMore = () => {
if (!equipData.filterEquipment.context.lastPage) {
fetchMore({
variables: { cursor: equipData.filterEquipment.context.cursor },
variables: { context: equipData.filterEquipment.context },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.filterEquipment;
const newItems = fetchMoreResult.filterEquipment.items;
@@ -348,6 +348,12 @@ const BulkEditAPs = ({ locations, checkedLocations }) => {
}
if (filterEquipmentError) {
if (
filterEquipmentError.message === '403: Forbidden' ||
filterEquipmentError.message === '401: Unauthorized'
) {
return <Redirect to="/login" />;
}
return (
<Alert message="Error" description="Failed to load equipments data." type="error" showIcon />
);

View File

@@ -1,152 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { render, waitFor } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { BulkEditAPsQueryMock } from './mock';
import BulkEditAPs from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
const locations = [
{
children: [
{
children: [
{
id: '4',
key: '4',
locationType: 'FLOOR',
name: 'Floor 1',
parentId: '3',
title: '',
value: '4',
__typename: 'Location',
},
{
id: '5',
key: '5',
locationType: 'FLOOR',
name: 'Floor 2',
parentId: '3',
title: '',
value: '5',
__typename: 'Location',
},
{
id: '6',
key: '6',
locationType: 'FLOOR',
name: 'Floor 3',
parentId: '3',
title: '',
value: '6',
__typename: 'Location',
},
],
id: '3',
key: '3',
locationType: 'BUILDING',
name: 'Building 1',
parentId: '2',
title: '',
value: '3',
__typename: 'Location',
},
{
id: '7',
key: '7',
locationType: 'BUILDING',
name: 'Building 2',
parentId: '2',
title: '',
value: '7',
__typename: 'Location',
},
],
id: '2',
key: '2',
locationType: 'SITE',
name: 'Menlo Park',
parentId: '0',
title: '',
value: '2',
__typename: 'Location',
},
{
id: '8',
key: '8',
locationType: 'SITE',
name: 'Ottawa',
parentId: '0',
title: 'test',
value: '8',
__typename: 'Location',
},
];
jest.mock('react-router-dom', () => ({
useParams: () => ({
id: '6',
}),
useHistory: () => ({ push: jest.fn() }),
}));
describe('<BulkEditAPs />', () => {
afterEach(jest.resetModules);
it('should render with data', async () => {
const { getByText } = render(
<MockedProvider
mocks={[BulkEditAPsQueryMock.filterEquipmentBulkEditAps.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<BulkEditAPs
locations={locations}
checkedLocations={['2', '3', '4', '5', '6', '7', '8']}
/>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('AP 1')).toBeVisible());
});
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider
mocks={[BulkEditAPsQueryMock.filterEquipmentBulkEditAps.error]}
addTypename={false}
>
<UserProvider {...mockProp}>
<BulkEditAPs
locations={locations}
checkedLocations={['2', '3', '4', '5', '6', '7', '8']}
/>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load equipments data.')).toBeVisible());
});
});

View File

@@ -1,81 +1,74 @@
import React, { useContext } from 'react';
import { useParams } from 'react-router-dom';
import { useQuery } from '@apollo/react-hooks';
import { useQuery } from '@apollo/client';
import moment from 'moment';
import { Alert, notification } from 'antd';
import {
Loading,
ClientDeviceDetails as ClientDevicesDetailsPage,
} from '@tip-wlan/wlan-cloud-ui-library';
import { notification } from 'antd';
import { ClientDeviceDetails as ClientDevicesDetailsPage } from '@tip-wlan/wlan-cloud-ui-library';
import UserContext from 'contexts/UserContext';
import { GET_CLIENT_SESSION, FILTER_SERVICE_METRICS } from 'graphql/queries';
import { withQuery } from 'containers/QueryWrapper';
const toTime = moment();
const fromTime = moment().subtract(4, 'hours');
const ClientDeviceDetails = () => {
const { id } = useParams();
const { customerId } = useContext(UserContext);
const { loading, error, data, refetch } = useQuery(GET_CLIENT_SESSION, {
variables: { customerId, macAddress: id },
errorPolicy: 'all',
});
const {
loading: metricsLoading,
error: metricsError,
data: metricsData,
refetch: metricsRefetch,
} = useQuery(FILTER_SERVICE_METRICS, {
variables: {
customerId,
fromTime: fromTime.valueOf().toString(),
toTime: toTime.valueOf().toString(),
clientMacs: [id],
dataTypes: ['Client'],
limit: 1000,
},
});
const ClientDeviceDetails = withQuery(
({ data, refetch }) => {
const { id } = useParams();
const { customerId } = useContext(UserContext);
const handleOnRefresh = () => {
metricsRefetch();
refetch()
.then(() => {
notification.success({
message: 'Success',
description: 'Successfully reloaded.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Could not be reloaded.',
const {
loading: metricsLoading,
error: metricsError,
data: metricsData,
refetch: metricsRefetch,
} = useQuery(FILTER_SERVICE_METRICS, {
variables: {
customerId,
fromTime: fromTime.valueOf().toString(),
toTime: toTime.valueOf().toString(),
clientMacs: [id],
dataTypes: ['Client'],
limit: 1000,
},
});
const handleOnRefresh = () => {
metricsRefetch();
refetch()
.then(() => {
notification.success({
message: 'Success',
description: 'Successfully reloaded.',
});
})
);
};
.catch(() =>
notification.error({
message: 'Error',
description: 'Could not be reloaded.',
})
);
};
if (loading) {
return <Loading />;
}
if (error && !data?.getClientSession) {
return (
<Alert message="Error" description="Failed to load Client Device." type="error" showIcon />
<ClientDevicesDetailsPage
data={data.getClientSession[0]}
onRefresh={handleOnRefresh}
metricsLoading={metricsLoading}
metricsError={metricsError}
metricsData={
metricsData && metricsData.filterServiceMetrics && metricsData.filterServiceMetrics.items
}
historyDate={{ toTime, fromTime }}
/>
);
},
GET_CLIENT_SESSION,
() => {
const { id } = useParams();
const { customerId } = useContext(UserContext);
return { customerId, macAddress: id, errorPolicy: 'all' };
}
return (
<ClientDevicesDetailsPage
data={data.getClientSession[0]}
onRefresh={handleOnRefresh}
metricsLoading={metricsLoading}
metricsError={metricsError}
metricsData={
metricsData && metricsData.filterServiceMetrics && metricsData.filterServiceMetrics.items
}
historyDate={{ toTime, fromTime }}
/>
);
};
);
export default ClientDeviceDetails;

View File

@@ -1,122 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { fireEvent, render, waitFor, cleanup } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { ClientDevicesDetailsQueryMock } from './mock';
import ClientDeviceDetails from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
jest.mock('moment', () => () => ({
subtract: () => ({ valueOf: () => ({ toString: () => '1234' }) }),
valueOf: () => ({ toString: () => '1234' }),
}));
jest.mock('react-router-dom', () => ({
useParams: () => ({
id: '74:9c:00:01:45:ae',
}),
useHistory: () => ({ push: jest.fn() }),
}));
jest.useFakeTimers();
describe('<ClientDeviceDetails />', () => {
afterEach(cleanup);
beforeEach(() => jest.useFakeTimers());
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider
mocks={[ClientDevicesDetailsQueryMock.getClientSession.error]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ClientDeviceDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load Client Device.')).toBeVisible());
});
it('should render with data', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
ClientDevicesDetailsQueryMock.getClientSession.success,
ClientDevicesDetailsQueryMock.filterServiceMetrics.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ClientDeviceDetails />
</UserProvider>
</MockedProvider>
);
// jest.advanceTimersByTime('1000');
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
});
it.only('click on reload button should refetch data', async () => {
const { getByText, container } = render(
<MockedProvider
mocks={[
ClientDevicesDetailsQueryMock.getClientSession.success,
ClientDevicesDetailsQueryMock.filterServiceMetrics.success,
ClientDevicesDetailsQueryMock.getClientSession.success,
ClientDevicesDetailsQueryMock.filterServiceMetrics.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ClientDeviceDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
// await waitFor(() => expect(getByText('hostName-128213363803566')).toBeVisible());
const reloadButton = container.querySelector(
'.ant-btn.index-module__Button___VGygY.ant-btn-icon-only'
);
fireEvent.click(reloadButton);
await waitFor(() => expect(getByText('Successfully reloaded.')).toBeVisible());
});
// it('error message should be visible with error true', async () => {
// const { getByText } = render(
// <MockedProvider
// mocks={[
// ClientDevicesDetailsQueryMock.getClientSession.success,
// ClientDevicesDetailsQueryMock.filterServiceMetrics.success,
// ClientDevicesDetailsQueryMock.filterServiceMetrics.success,
// ClientDevicesDetailsQueryMock.getClientSession.success,
// ]}
// addTypename={false}
// >
// <UserProvider {...mockProp}>
// <ClientDeviceDetails />
// </UserProvider>
// </MockedProvider>
// );
// jest.advanceTimersByTime(60000);
// });
});

View File

@@ -1,183 +0,0 @@
import { GET_CLIENT_SESSION, FILTER_SERVICE_METRICS } from 'graphql/queries';
export const ClientDevicesDetailsQueryMock = {
getClientSession: {
success: {
request: {
query: GET_CLIENT_SESSION,
variables: {
customerId: 2,
macAddress: '74:9c:00:01:45:ae',
},
},
result: {
data: {
getClientSession: [
{
id: '74:9c:00:01:45:ae',
macAddress: '74:9c:00:01:45:ae',
ipAddress: '192.168.10.171',
hostname: 'hostName-128213363803566',
ssid: 'Default-SSID-1597172801679',
radioType: 'is2dot4GHz',
signal: '-56',
manufacturer: null,
equipment: {
name: 'AP 40',
__typename: 'Equipment',
},
details: {
model_type: 'ClientSessionDetails',
sessionId: 1597172802575,
authTimestamp: null,
assocTimestamp: 1597172185365,
assocInternalSC: null,
ipTimestamp: null,
disconnectByApTimestamp: null,
disconnectByClientTimestamp: null,
timeoutTimestamp: null,
firstDataSentTimestamp: null,
firstDataRcvdTimestamp: null,
ipAddress: '192.168.10.171',
radiusUsername: null,
ssid: 'Default-SSID-1597172801679',
radioType: 'is2dot4GHz',
lastEventTimestamp: 0,
hostname: 'hostName-128213363803566',
apFingerprint: 'fp 74:9c:00:01:45:ae',
userAgentStr: null,
lastRxTimestamp: null,
lastTxTimestamp: null,
cpUsername: null,
dhcpDetails: {
model_type: 'ClientDhcpDetails',
dhcpServerIp: '192.168.0.1',
primaryDns: '8.8.8.8',
secondaryDns: '192.168.0.1',
subnetMask: '192.168.0.255',
gatewayIp: '192.168.0.1',
leaseStartTimestamp: 1597160501039,
leaseTimeInSeconds: 14400,
firstRequestTimestamp: null,
firstOfferTimestamp: null,
firstDiscoverTimestamp: null,
nakTimestamp: null,
fromInternal: false,
associationId: 1597172802575,
},
eapDetails: null,
metricDetails: {
model_type: 'ClientSessionMetricDetails',
rxBytes: 6048860,
txBytes: 6400949,
totalRxPackets: null,
totalTxPackets: null,
rxMbps: 91.4453,
txMbps: 65.76753,
rssi: -56,
snr: -51,
rxRateKbps: null,
txRateKbps: null,
lastMetricTimestamp: 0,
lastRxTimestamp: null,
lastTxTimestamp: null,
classification: null,
txDataFrames: null,
txDataFramesRetried: null,
rxDataFrames: null,
},
isReassociation: null,
disconnectByApReasonCode: null,
disconnectByClientReasonCode: null,
disconnectByApInternalReasonCode: null,
disconnectByClientInternalReasonCode: null,
portEnabledTimestamp: null,
is11RUsed: null,
is11KUsed: null,
is11VUsed: null,
securityType: 'PSK',
steerType: null,
previousValidSessionId: null,
lastFailureDetails: null,
firstFailureDetails: null,
associationStatus: null,
dynamicVlan: null,
assocRssi: null,
priorSessionId: null,
priorEquipmentId: null,
classificationName: null,
associationState: null,
eapSuccessTimestamp: null,
eapKey4Timestamp: null,
},
__typename: 'ClientSession',
},
],
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_CLIENT_SESSION,
variables: { customerId: 2 },
errorPolicy: 'all',
},
result: {
data: null,
errors: [{}],
loading: false,
networkStatus: 7,
stale: false,
},
},
},
filterServiceMetrics: {
success: {
request: {
query: FILTER_SERVICE_METRICS,
variables: {
customerId: 2,
fromTime: '1234',
toTime: '1234',
clientMacs: ['74:9c:00:01:45:ae'],
dataTypes: ['Client'],
limit: 1000,
},
},
result: {
data: {
filterServiceMetrics: {
items: [],
context: {
lastPage: true,
cursor:
'bnVsbEBAQHsibW9kZWxfdHlwZSI6IkNvbnRleHRDaGlsZHJlbiIsImNoaWxkcmVuIjp7fX1AQEBudWxs',
__typename: 'PaginationContext',
},
__typename: 'ServiceMetricPagination',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: FILTER_SERVICE_METRICS,
variables: { customerId: 2 },
errorPolicy: 'all',
},
result: {
data: null,
errors: [{}],
loading: false,
networkStatus: 7,
stale: false,
},
},
},
};

View File

@@ -1,6 +1,6 @@
import React, { useEffect, useContext } from 'react';
import PropTypes from 'prop-types';
import { useLazyQuery } from '@apollo/react-hooks';
import { useLazyQuery } from '@apollo/client';
import { notification } from 'antd';
import { NetworkTableContainer } from '@tip-wlan/wlan-cloud-ui-library';
@@ -24,7 +24,19 @@ const clientDevicesTableColumns = [
{ title: 'SSID', dataIndex: 'ssid' },
{ title: 'BAND', dataIndex: 'radioType' },
{ title: 'SIGNAL', dataIndex: 'signal' },
{ title: 'STATUS', dataIndex: 'status' },
{
title: 'STATUS',
dataIndex: ['details', 'associationState'],
render: text => {
if (text === 'Active_Data') {
return 'Connected';
}
if (text === 'Disconnected') {
return 'Disconnected';
}
return 'N/A';
},
},
];
const ClientDevices = ({ checkedLocations }) => {
@@ -39,7 +51,7 @@ const ClientDevices = ({ checkedLocations }) => {
const handleLoadMore = () => {
if (!data.filterClientSessions.context.lastPage) {
fetchMore({
variables: { cursor: data.filterClientSessions.context.cursor },
variables: { context: data.filterClientSessions.context },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.filterClientSessions;
const newItems = fetchMoreResult.filterClientSessions.items;
@@ -86,7 +98,7 @@ const ClientDevices = ({ checkedLocations }) => {
<NetworkTableContainer
activeTab="/network/client-devices"
tableColumns={clientDevicesTableColumns}
tableData={data && data.filterClientSessions && data.filterClientSessions.items}
tableData={data?.filterClientSessions?.items}
onLoadMore={handleLoadMore}
onRefresh={handleOnRefresh}
isLastPage={data && data.filterClientSessions && data.filterClientSessions.context.lastPage}

View File

@@ -1,138 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { MockedProvider } from '@apollo/react-testing';
import { fireEvent, render, waitFor } from '@testing-library/react';
import UserProvider from 'contexts/UserProvider';
import { BrowserRouter as Router } from 'react-router-dom';
import { ClientDevicesQueryMock } from './mock';
import ClientDevices from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<ClientDevices />', () => {
afterEach(jest.resetModules);
it('should render with data', async () => {
const { getByText } = render(
<MockedProvider
mocks={[ClientDevicesQueryMock.filterClientSessions.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<ClientDevices checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
await waitFor(() => expect(getByText('hostName-128213363803566')).toBeVisible());
});
it('error message should be visible with error true', async () => {
const { getByText } = render(
<MockedProvider
mocks={[ClientDevicesQueryMock.filterClientSessions.error]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<ClientDevices checkedLocations={[1, 2, 3]} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load client devices.')).toBeVisible());
});
it('click on Load More should fetch more data', async () => {
const { getByRole, getByText, getAllByText } = render(
<MockedProvider
mocks={[
ClientDevicesQueryMock.filterClientSessions.success,
ClientDevicesQueryMock.filterClientSessions.loadmore,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<ClientDevices checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
await waitFor(() => expect(getByText('hostName-128213363803566')).toBeVisible());
fireEvent.click(getByRole('button', { name: /load more/i }));
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
await waitFor(() => expect(getAllByText('hostName-128213363803566')[1]).toBeVisible());
});
it('click on reload button should refetch data', async () => {
const { getByText, container } = render(
<MockedProvider
mocks={[
ClientDevicesQueryMock.filterClientSessions.success,
ClientDevicesQueryMock.filterClientSessions.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<ClientDevices checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
await waitFor(() => expect(getByText('hostName-128213363803566')).toBeVisible());
const reloadButton = container.querySelector(
'.ant-btn.index-module__Button___VGygY.ant-btn-icon-only'
);
fireEvent.click(reloadButton);
await waitFor(() => expect(getByText('Client devices reloaded.')).toBeVisible());
});
it('click on reload button should not refetch data when query return error', async () => {
const { getByText, container } = render(
<MockedProvider
mocks={[ClientDevicesQueryMock.filterClientSessions.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<ClientDevices checkedLocations={['2', '3', '4', '5', '6', '7', '8']} />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
await waitFor(() => expect(getByText('hostName-128213363803566')).toBeVisible());
const reloadButton = container.querySelector(
'.ant-btn.index-module__Button___VGygY.ant-btn-icon-only'
);
fireEvent.click(reloadButton);
await waitFor(() => expect(getByText('Client devices could not be reloaded.')).toBeVisible());
});
});

View File

@@ -1,591 +0,0 @@
import { FILTER_CLIENT_SESSIONS } from 'graphql/queries';
export const ClientDevicesQueryMock = {
filterClientSessions: {
success: {
request: {
query: FILTER_CLIENT_SESSIONS,
variables: {
customerId: 2,
locationIds: ['2', '3', '4', '5', '6', '7', '8'],
equipmentType: 'AP',
},
},
result: {
data: {
filterClientSessions: {
items: [
{
id: '74:9c:00:01:45:ae',
macAddress: '74:9c:00:01:45:ae',
ipAddress: '192.168.10.171',
hostname: 'hostName-128213363803566',
ssid: 'Default-SSID-1597172801679',
radioType: 'is2dot4GHz',
signal: '-56',
manufacturer: null,
equipment: {
name: 'AP 40',
},
},
{
id: '74:9c:00:8a:70:8b',
macAddress: '74:9c:00:8a:70:8b',
ipAddress: '192.168.10.159',
hostname: 'hostName-128213372792971',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 2',
},
},
{
id: '74:9c:00:ae:78:0b',
macAddress: '74:9c:00:ae:78:0b',
ipAddress: '192.168.10.21',
hostname: 'hostName-128213375154187',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzL',
signal: '-56',
manufacturer: null,
equipment: {
name: 'AP 37',
},
},
{
id: '74:9c:00:b8:6e:6b',
macAddress: '74:9c:00:b8:6e:6b',
ipAddress: '192.168.10.145',
hostname: 'hostName-128213375807083',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-55',
manufacturer: null,
equipment: {
name: 'AP 9',
},
},
{
id: '74:9c:00:da:28:86',
macAddress: '74:9c:00:da:28:86',
ipAddress: '192.168.10.136',
hostname: 'hostName-128213378017414',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzL',
signal: '-54',
manufacturer: null,
equipment: {
name: 'AP 34',
},
},
{
id: '74:9c:01:20:7f:35',
macAddress: '74:9c:01:20:7f:35',
ipAddress: '192.168.10.132',
hostname: 'hostName-128213382627125',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzU',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 37',
},
},
{
id: '74:9c:01:4b:bd:77',
macAddress: '74:9c:01:4b:bd:77',
ipAddress: '192.168.10.114',
hostname: 'hostName-128213385461111',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 19',
},
},
{
id: '74:9c:01:77:97:6c',
macAddress: '74:9c:01:77:97:6c',
ipAddress: '192.168.10.35',
hostname: 'hostName-128213388334956',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-52',
manufacturer: null,
equipment: {
name: 'AP 26',
},
},
{
id: '74:9c:01:9c:29:be',
macAddress: '74:9c:01:9c:29:be',
ipAddress: '192.168.10.174',
hostname: 'hostName-128213390731710',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-44',
manufacturer: null,
equipment: {
name: 'AP 6',
},
},
{
id: '74:9c:01:bf:ce:af',
macAddress: '74:9c:01:bf:ce:af',
ipAddress: '192.168.10.36',
hostname: 'hostName-128213393067695',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-60',
manufacturer: null,
equipment: {
name: 'AP 31',
},
},
{
id: '74:9c:02:41:bf:2a',
macAddress: '74:9c:02:41:bf:2a',
ipAddress: '192.168.10.202',
hostname: 'hostName-128213401583402',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-42',
manufacturer: null,
equipment: {
name: 'AP 29',
},
},
{
id: '74:9c:02:86:89:6a',
macAddress: '74:9c:02:86:89:6a',
ipAddress: '192.168.10.77',
hostname: 'hostName-128213406091626',
ssid: 'Default-SSID-1597172801679',
radioType: 'is2dot4GHz',
signal: '-54',
manufacturer: null,
equipment: {
name: 'AP 38',
},
},
{
id: '74:9c:02:8f:14:91',
macAddress: '74:9c:02:8f:14:91',
ipAddress: '192.168.10.144',
hostname: 'hostName-128213406651537',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-60',
manufacturer: null,
equipment: {
name: 'AP 3',
},
},
{
id: '74:9c:02:9f:25:27',
macAddress: '74:9c:02:9f:25:27',
ipAddress: '192.168.10.125',
hostname: 'hostName-128213407704359',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-45',
manufacturer: null,
equipment: {
name: 'AP 3',
},
},
{
id: '74:9c:03:12:cd:00',
macAddress: '74:9c:03:12:cd:00',
ipAddress: '192.168.10.214',
hostname: 'hostName-128213415283968',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-46',
manufacturer: null,
equipment: {
name: 'AP 14',
},
},
{
id: '74:9c:03:47:bc:43',
macAddress: '74:9c:03:47:bc:43',
ipAddress: '192.168.10.187',
hostname: 'hostName-128213418753091',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-49',
manufacturer: null,
equipment: {
name: 'AP 3',
},
},
{
id: '74:9c:03:73:2d:d0',
macAddress: '74:9c:03:73:2d:d0',
ipAddress: '192.168.10.107',
hostname: 'hostName-128213421600208',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-49',
manufacturer: null,
equipment: {
name: 'AP 17',
},
},
{
id: '74:9c:04:1f:a0:26',
macAddress: '74:9c:04:1f:a0:26',
ipAddress: '192.168.10.48',
hostname: 'hostName-128213432901670',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-44',
manufacturer: null,
equipment: {
name: 'AP 10',
},
},
{
id: '74:9c:04:61:19:c8',
macAddress: '74:9c:04:61:19:c8',
ipAddress: '192.168.10.218',
hostname: 'hostName-128213437192648',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzL',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 48',
},
},
{
id: '74:9c:04:7e:5c:ae',
macAddress: '74:9c:04:7e:5c:ae',
ipAddress: '192.168.10.92',
hostname: 'hostName-128213439110318',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-43',
manufacturer: null,
equipment: {
name: 'AP 5',
},
},
],
context: {
lastPage: false,
cursor: 'test',
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
loadmore: {
request: {
query: FILTER_CLIENT_SESSIONS,
variables: {
customerId: 2,
locationIds: ['2', '3', '4', '5', '6', '7', '8'],
equipmentType: 'AP',
cursor: 'test',
},
},
result: {
data: {
filterClientSessions: {
items: [
{
id: '74:9c:00:01:45:ae',
macAddress: '74:9c:00:01:45:ae',
ipAddress: '192.168.10.171',
hostname: 'hostName-128213363803566',
ssid: 'Default-SSID-1597172801679',
radioType: 'is2dot4GHz',
signal: '-56',
manufacturer: null,
equipment: {
name: 'AP 40',
},
},
{
id: '74:9c:00:8a:70:8b',
macAddress: '74:9c:00:8a:70:8b',
ipAddress: '192.168.10.159',
hostname: 'hostName-128213372792971',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 2',
},
},
{
id: '74:9c:00:ae:78:0b',
macAddress: '74:9c:00:ae:78:0b',
ipAddress: '192.168.10.21',
hostname: 'hostName-128213375154187',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzL',
signal: '-56',
manufacturer: null,
equipment: {
name: 'AP 37',
},
},
{
id: '74:9c:00:b8:6e:6b',
macAddress: '74:9c:00:b8:6e:6b',
ipAddress: '192.168.10.145',
hostname: 'hostName-128213375807083',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-55',
manufacturer: null,
equipment: {
name: 'AP 9',
},
},
{
id: '74:9c:00:da:28:86',
macAddress: '74:9c:00:da:28:86',
ipAddress: '192.168.10.136',
hostname: 'hostName-128213378017414',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzL',
signal: '-54',
manufacturer: null,
equipment: {
name: 'AP 34',
},
},
{
id: '74:9c:01:20:7f:35',
macAddress: '74:9c:01:20:7f:35',
ipAddress: '192.168.10.132',
hostname: 'hostName-128213382627125',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzU',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 37',
},
},
{
id: '74:9c:01:4b:bd:77',
macAddress: '74:9c:01:4b:bd:77',
ipAddress: '192.168.10.114',
hostname: 'hostName-128213385461111',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 19',
},
},
{
id: '74:9c:01:77:97:6c',
macAddress: '74:9c:01:77:97:6c',
ipAddress: '192.168.10.35',
hostname: 'hostName-128213388334956',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-52',
manufacturer: null,
equipment: {
name: 'AP 26',
},
},
{
id: '74:9c:01:9c:29:be',
macAddress: '74:9c:01:9c:29:be',
ipAddress: '192.168.10.174',
hostname: 'hostName-128213390731710',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-44',
manufacturer: null,
equipment: {
name: 'AP 6',
},
},
{
id: '74:9c:01:bf:ce:af',
macAddress: '74:9c:01:bf:ce:af',
ipAddress: '192.168.10.36',
hostname: 'hostName-128213393067695',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-60',
manufacturer: null,
equipment: {
name: 'AP 31',
},
},
{
id: '74:9c:02:41:bf:2a',
macAddress: '74:9c:02:41:bf:2a',
ipAddress: '192.168.10.202',
hostname: 'hostName-128213401583402',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-42',
manufacturer: null,
equipment: {
name: 'AP 29',
},
},
{
id: '74:9c:02:86:89:6a',
macAddress: '74:9c:02:86:89:6a',
ipAddress: '192.168.10.77',
hostname: 'hostName-128213406091626',
ssid: 'Default-SSID-1597172801679',
radioType: 'is2dot4GHz',
signal: '-54',
manufacturer: null,
equipment: {
name: 'AP 38',
},
},
{
id: '74:9c:02:8f:14:91',
macAddress: '74:9c:02:8f:14:91',
ipAddress: '192.168.10.144',
hostname: 'hostName-128213406651537',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-60',
manufacturer: null,
equipment: {
name: 'AP 3',
},
},
{
id: '74:9c:02:9f:25:27',
macAddress: '74:9c:02:9f:25:27',
ipAddress: '192.168.10.125',
hostname: 'hostName-128213407704359',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-45',
manufacturer: null,
equipment: {
name: 'AP 3',
},
},
{
id: '74:9c:03:12:cd:00',
macAddress: '74:9c:03:12:cd:00',
ipAddress: '192.168.10.214',
hostname: 'hostName-128213415283968',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is2dot4GHz',
signal: '-46',
manufacturer: null,
equipment: {
name: 'AP 14',
},
},
{
id: '74:9c:03:47:bc:43',
macAddress: '74:9c:03:47:bc:43',
ipAddress: '192.168.10.187',
hostname: 'hostName-128213418753091',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-49',
manufacturer: null,
equipment: {
name: 'AP 3',
},
},
{
id: '74:9c:03:73:2d:d0',
macAddress: '74:9c:03:73:2d:d0',
ipAddress: '192.168.10.107',
hostname: 'hostName-128213421600208',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-49',
manufacturer: null,
equipment: {
name: 'AP 17',
},
},
{
id: '74:9c:04:1f:a0:26',
macAddress: '74:9c:04:1f:a0:26',
ipAddress: '192.168.10.48',
hostname: 'hostName-128213432901670',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzL',
signal: '-44',
manufacturer: null,
equipment: {
name: 'AP 10',
},
},
{
id: '74:9c:04:61:19:c8',
macAddress: '74:9c:04:61:19:c8',
ipAddress: '192.168.10.218',
hostname: 'hostName-128213437192648',
ssid: 'Default-SSID-1597172801679',
radioType: 'is5GHzL',
signal: '-53',
manufacturer: null,
equipment: {
name: 'AP 48',
},
},
{
id: '74:9c:04:7e:5c:ae',
macAddress: '74:9c:04:7e:5c:ae',
ipAddress: '192.168.10.92',
hostname: 'hostName-128213439110318',
ssid: 'TipWlan-cloud-3-radios',
radioType: 'is5GHzU',
signal: '-43',
manufacturer: null,
equipment: {
name: 'AP 5',
},
},
],
context: {
lastPage: false,
cursor: 'test',
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: FILTER_CLIENT_SESSIONS,
variables: { customerId: 2 },
errorPolicy: 'all',
},
result: {
data: null,
errors: [{}],
loading: false,
networkStatus: 7,
stale: false,
},
},
},
};

View File

@@ -1,273 +1,326 @@
import React, { useMemo, useContext, useState } from 'react';
import { Switch, Route, useRouteMatch, Redirect } from 'react-router-dom';
import { useQuery, useMutation, useLazyQuery } from '@apollo/react-hooks';
import { Alert, notification } from 'antd';
import { useQuery, useMutation, useLazyQuery } from '@apollo/client';
import { notification } from 'antd';
import _ from 'lodash';
import { Network as NetworkPage, PopoverMenu, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { Network as NetworkPage, PopoverMenu } from '@tip-wlan/wlan-cloud-ui-library';
import AccessPointDetails from 'containers/Network/containers/AccessPointDetails';
import AccessPoints from 'containers/Network/containers/AccessPoints';
import ClientDevices from 'containers/Network/containers/ClientDevices';
import ClientDeviceDetails from 'containers/Network/containers/ClientDeviceDetails';
import BulkEditAccessPoints from 'containers/Network/containers/BulkEditAccessPoints';
import { withQuery } from 'containers/QueryWrapper';
import UserContext from 'contexts/UserContext';
import { GET_ALL_LOCATIONS, GET_LOCATION, GET_ALL_PROFILES } from 'graphql/queries';
import {
GET_ALL_LOCATIONS,
GET_LOCATION,
GET_ALL_PROFILES,
FILTER_EQUIPMENT,
} from 'graphql/queries';
import {
CREATE_LOCATION,
UPDATE_LOCATION,
DELETE_LOCATION,
CREATE_EQUIPMENT,
} from 'graphql/mutations';
import { updateQueryGetAllProfiles } from 'graphql/functions';
const Network = () => {
const { path } = useRouteMatch();
const { customerId } = useContext(UserContext);
const { loading, error, refetch, data } = useQuery(GET_ALL_LOCATIONS, {
variables: { customerId },
});
const { loading: loadingProfile, error: errorProfile, data: apProfiles } = useQuery(
GET_ALL_PROFILES,
{
variables: { customerId, type: 'equipment_ap' },
}
);
const Network = withQuery(
({ data, refetch }) => {
const { path } = useRouteMatch();
const { customerId } = useContext(UserContext);
const [getLocation, { data: selectedLocation }] = useLazyQuery(GET_LOCATION);
const [createLocation] = useMutation(CREATE_LOCATION);
const [updateLocation] = useMutation(UPDATE_LOCATION);
const [deleteLocation] = useMutation(DELETE_LOCATION);
const [createEquipment] = useMutation(CREATE_EQUIPMENT);
const [checkedLocations, setCheckedLocations] = useState([]);
const [deleteModal, setDeleteModal] = useState(false);
const [editModal, setEditModal] = useState(false);
const [addModal, setAddModal] = useState(false);
const [apModal, setApModal] = useState(false);
const handleGetSingleLocation = id => {
getLocation({
variables: { id },
});
};
const formatLocationListForTree = (list = []) => {
const checkedTreeLocations = [];
list.forEach(ele => {
checkedTreeLocations.push(ele.id);
});
setCheckedLocations(checkedTreeLocations);
function unflatten(array, p, t) {
let tree = typeof t !== 'undefined' ? t : [];
const parent = typeof p !== 'undefined' ? p : { id: '0' };
let children = _.filter(array, child => child.parentId === parent.id);
children = children.map(c => ({
title: (
<PopoverMenu
locationId={c.id}
locationType={c.locationType}
setAddModal={setAddModal}
setEditModal={setEditModal}
setDeleteModal={setDeleteModal}
setApModal={setApModal}
>
{c.name}
</PopoverMenu>
),
value: `${c.id}`,
key: c.id,
...c,
}));
if (!_.isEmpty(children)) {
if (parent.id === '0') {
tree = children;
} else {
parent.children = children;
}
_.each(children, child => unflatten(array, child));
}
return tree;
}
return [
const { loading: loadingProfile, error: errorProfile, data: apProfiles, fetchMore } = useQuery(
GET_ALL_PROFILES(),
{
title: (
<PopoverMenu locationType="NETWORK" setAddModal={setAddModal}>
Network
</PopoverMenu>
),
id: '0',
value: '0',
key: '0',
children: unflatten(list),
},
];
};
variables: { customerId, type: 'equipment_ap' },
}
);
const handleAddLocation = (name, parentId, locationType) => {
setAddModal(false);
createLocation({
variables: {
locationType,
customerId,
parentId,
name,
},
})
.then(() => {
notification.success({
message: 'Success',
description: 'Location successfully added.',
});
refetch();
const [getLocation, { data: selectedLocation }] = useLazyQuery(GET_LOCATION);
const [createLocation] = useMutation(CREATE_LOCATION);
const [updateLocation] = useMutation(UPDATE_LOCATION);
const [deleteLocation] = useMutation(DELETE_LOCATION);
const [checkedLocations, setCheckedLocations] = useState([]);
const [deleteModal, setDeleteModal] = useState(false);
const [editModal, setEditModal] = useState(false);
const [addModal, setAddModal] = useState(false);
const [apModal, setApModal] = useState(false);
const [createEquipment] = useMutation(CREATE_EQUIPMENT, {
refetchQueries: [
{
query: FILTER_EQUIPMENT,
variables: { customerId, locationIds: checkedLocations, equipmentType: 'AP' },
},
],
});
const handleGetSingleLocation = id => {
getLocation({
variables: { id },
});
};
const formatLocationListForTree = (list = []) => {
const checkedTreeLocations = ['0'];
list.forEach(ele => {
checkedTreeLocations.push(ele.id);
});
setCheckedLocations(checkedTreeLocations);
function unflatten(array, p, t) {
let tree = typeof t !== 'undefined' ? t : [];
const parent = typeof p !== 'undefined' ? p : { id: '0' };
let children = _.filter(array, child => child.parentId === parent.id);
children = children.map(c => ({
title: (
<PopoverMenu
locationId={c.id}
locationType={c.locationType}
setAddModal={setAddModal}
setEditModal={setEditModal}
setDeleteModal={setDeleteModal}
setApModal={setApModal}
>
{c.name}
</PopoverMenu>
),
value: `${c.id}`,
key: c.id,
...c,
}));
if (!_.isEmpty(children)) {
if (parent.id === '0') {
tree = children;
} else {
parent.children = children;
}
_.each(children, child => unflatten(array, child));
}
return tree;
}
return [
{
title: (
<PopoverMenu locationId="0" locationType="NETWORK" setAddModal={setAddModal}>
Network
</PopoverMenu>
),
id: '0',
key: '0',
value: '0',
children: unflatten(list),
},
];
};
const handleAddLocation = ({ location }) => {
setAddModal(false);
let id;
let locationType;
// adding location from root makes selecetedLocation null so we check for that
if (selectedLocation && selectedLocation.getLocation) {
id = selectedLocation.getLocation.id;
locationType = 'SITE';
} else {
id = '0';
locationType = 'COUNTRY';
}
createLocation({
variables: {
locationType,
customerId,
parentId: id,
name: location,
},
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Location could not be added.',
.then(() => {
notification.success({
message: 'Success',
description: 'Location successfully added.',
});
refetch();
})
);
};
.catch(() =>
notification.error({
message: 'Error',
description: 'Location could not be added.',
})
);
};
const handleEditLocation = (id, parentId, name, locationType, lastModifiedTimestamp) => {
setEditModal(false);
updateLocation({
variables: {
customerId,
id,
parentId,
name,
locationType,
lastModifiedTimestamp,
},
})
.then(() => {
notification.success({
message: 'Success',
description: 'Location successfully edited.',
});
refetch();
const handleEditLocation = ({ name }) => {
setEditModal(false);
const { id, parentId, locationType, lastModifiedTimestamp } = selectedLocation.getLocation;
updateLocation({
variables: {
customerId,
id,
parentId,
name,
locationType,
lastModifiedTimestamp,
},
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Location could not be edited.',
.then(() => {
notification.success({
message: 'Success',
description: 'Location successfully edited.',
});
refetch();
})
);
};
.catch(() =>
notification.error({
message: 'Error',
description: 'Location could not be edited.',
})
);
};
const handleDeleteLocation = id => {
setDeleteModal(false);
deleteLocation({ variables: { id } })
.then(() => {
notification.success({
message: 'Success',
description: 'Location successfully deleted.',
const handleDeleteLocation = () => {
setDeleteModal(false);
const { id } = selectedLocation.getLocation;
deleteLocation({ variables: { id } })
.then(() => {
notification.success({
message: 'Success',
description: 'Location successfully deleted.',
});
refetch();
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Location could not be deleted.',
})
);
};
const handleCreateEquipment = ({ inventoryId, name, profileId }) => {
setApModal(false);
const { id: locationId } = selectedLocation.getLocation;
createEquipment({ variables: { customerId, inventoryId, locationId, name, profileId } })
.then(() => {
notification.success({
message: 'Success',
description: 'Equipment successfully created.',
});
refetch();
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment could not be created.',
})
);
};
const onSelect = (selectedKeys, info) => {
const { id } = info.node;
handleGetSingleLocation(id);
};
const onCheck = checkedKeys => {
setCheckedLocations(checkedKeys.checked);
};
const handleFetchProfiles = e => {
if (apProfiles.getAllProfiles.context.lastPage) {
return false;
}
e.persist();
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
fetchMore({
variables: { context: { ...apProfiles.getAllProfiles.context } },
updateQuery: updateQueryGetAllProfiles,
});
refetch();
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Location could not be deleted.',
})
);
};
}
const handleCreateEquipment = (inventoryId, locationId, name, profileId) => {
setApModal(false);
createEquipment({ variables: { customerId, inventoryId, locationId, name, profileId } })
.then(() => {
notification.success({
message: 'Success',
description: 'Equipment successfully created.',
});
refetch();
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Equipment could not be created.',
})
);
};
return true;
};
const onSelect = (selectedKeys, info) => {
const { id } = info.node;
handleGetSingleLocation(id);
};
const locationsTree = useMemo(() => formatLocationListForTree(data && data.getAllLocations), [
data,
]);
const onCheck = checkedKeys => {
setCheckedLocations(checkedKeys.checked);
};
return (
<NetworkPage
onSelect={onSelect}
onCheck={onCheck}
checkedLocations={checkedLocations}
locations={locationsTree}
selectedLocation={selectedLocation && selectedLocation.getLocation}
addModal={addModal}
editModal={editModal}
deleteModal={deleteModal}
apModal={apModal}
setAddModal={setAddModal}
setEditModal={setEditModal}
setDeleteModal={setDeleteModal}
setApModal={setApModal}
onAddLocation={handleAddLocation}
onEditLocation={handleEditLocation}
onDeleteLocation={handleDeleteLocation}
onCreateEquipment={handleCreateEquipment}
profiles={
(apProfiles && apProfiles.getAllProfiles && apProfiles.getAllProfiles.items) || []
}
loadingProfile={loadingProfile}
errorProfile={errorProfile}
onFetchMoreProfiles={handleFetchProfiles}
isLastProfilesPage={apProfiles?.getAllProfiles?.context?.lastPage}
>
<Switch>
<Route
exact
path={`${path}/access-points/bulk-edit/:id`}
render={props => (
<BulkEditAccessPoints
locations={locationsTree}
checkedLocations={checkedLocations}
{...props}
/>
)}
/>
<Route
exact
path={`${path}/access-points`}
render={props => <AccessPoints checkedLocations={checkedLocations} {...props} />}
/>
<Route
exact
path={`${path}/access-points/:id/:tab`}
render={props => <AccessPointDetails locations={locationsTree} {...props} />}
/>
const locationsTree = useMemo(
() => formatLocationListForTree(data && data.getAllLocations)[0].children,
[data]
);
if (loading) {
return <Loading />;
<Route
exact
path={`${path}/client-devices`}
render={props => <ClientDevices checkedLocations={checkedLocations} {...props} />}
/>
<Route exact path={`${path}/client-devices/:id`} component={ClientDeviceDetails} />
<Redirect from={`${path}/access-points/:id`} to={`${path}/access-points/:id/general`} />
<Redirect from={path} to={`${path}/access-points`} />
</Switch>
</NetworkPage>
);
},
GET_ALL_LOCATIONS,
() => {
const { customerId } = useContext(UserContext);
return { customerId };
}
if (error) {
return <Alert message="Error" description="Failed to load locations." type="error" showIcon />;
}
return (
<NetworkPage
onSelect={onSelect}
onCheck={onCheck}
checkedLocations={checkedLocations}
locations={locationsTree}
selectedLocation={selectedLocation && selectedLocation.getLocation}
addModal={addModal}
editModal={editModal}
deleteModal={deleteModal}
apModal={apModal}
setAddModal={setAddModal}
setEditModal={setEditModal}
setDeleteModal={setDeleteModal}
setApModal={setApModal}
onAddLocation={handleAddLocation}
onEditLocation={handleEditLocation}
onDeleteLocation={handleDeleteLocation}
onCreateEquipment={handleCreateEquipment}
profiles={(apProfiles && apProfiles.getAllProfiles && apProfiles.getAllProfiles.items) || []}
loadingProfile={loadingProfile}
errorProfile={errorProfile}
>
<Switch>
<Route
exact
path={`${path}/access-points/bulk-edit/:id`}
render={props => (
<BulkEditAccessPoints
locations={locationsTree}
checkedLocations={checkedLocations}
{...props}
/>
)}
/>
<Route
exact
path={`${path}/access-points`}
render={props => <AccessPoints checkedLocations={checkedLocations} {...props} />}
/>
<Route
exact
path={`${path}/access-points/:id`}
render={props => <AccessPointDetails locations={locationsTree} {...props} />}
/>
<Route
exact
path={`${path}/client-devices`}
render={props => <ClientDevices checkedLocations={checkedLocations} {...props} />}
/>
<Route exact path={`${path}/client-devices/:id`} component={ClientDeviceDetails} />
<Redirect from={path} to={`${path}/access-points`} />
</Switch>
</NetworkPage>
);
};
);
export default Network;

View File

@@ -1,118 +1,247 @@
import React, { useState, useContext } from 'react';
import { useParams, Redirect } from 'react-router-dom';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { Alert, notification } from 'antd';
import { ProfileDetails as ProfileDetailsPage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { useQuery, useMutation, gql } from '@apollo/client';
import { notification } from 'antd';
import { ProfileDetails as ProfileDetailsPage } from '@tip-wlan/wlan-cloud-ui-library';
import UserContext from 'contexts/UserContext';
import { GET_PROFILE, GET_ALL_PROFILES } from 'graphql/queries';
import { FILE_UPLOAD, UPDATE_PROFILE, DELETE_PROFILE } from 'graphql/mutations';
import { GET_ALL_PROFILES } from 'graphql/queries';
import { FILE_UPLOAD } from 'graphql/mutations';
import { updateQueryGetAllProfiles } from 'graphql/functions';
import { withQuery } from 'containers/QueryWrapper';
const ProfileDetails = () => {
const { customerId } = useContext(UserContext);
const { id } = useParams();
const [redirect, setRedirect] = useState(false);
const { loading, error, data } = useQuery(GET_PROFILE, {
variables: { id },
});
const { data: ssidProfiles } = useQuery(GET_ALL_PROFILES, {
variables: { customerId, type: 'ssid' },
});
const [updateProfile] = useMutation(UPDATE_PROFILE);
const [deleteProfile] = useMutation(DELETE_PROFILE);
const [fileUpload] = useMutation(FILE_UPLOAD);
const handleDeleteProfile = () => {
deleteProfile({ variables: { id } })
.then(() => {
notification.success({
message: 'Success',
description: 'Profile successfully deleted.',
});
setRedirect(true);
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Profile could not be deleted.',
})
);
};
const handleUpdateProfile = (
name,
details,
childProfileIds = data.getProfile.childProfileIds
) => {
updateProfile({
variables: {
...data.getProfile,
name,
childProfileIds,
details,
},
})
.then(() => {
notification.success({
message: 'Success',
description: 'Profile successfully updated.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Profile could not be updated.',
})
);
};
const handleFileUpload = (fileName, file) =>
fileUpload({ variables: { fileName, file } })
.then(() => {
notification.success({
message: 'Success',
description: 'File successfully uploaded.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'File could not be uploaded.',
})
);
if (loading) {
return <Loading />;
}
if (error) {
return (
<Alert message="Error" description="Failed to load profile data." type="error" showIcon />
);
}
if (redirect) {
return <Redirect to="/profiles" />;
}
return (
<ProfileDetailsPage
name={data.getProfile.name}
profileType={data.getProfile.profileType}
details={data.getProfile.details}
childProfileIds={data.getProfile.childProfileIds}
onDeleteProfile={handleDeleteProfile}
onUpdateProfile={handleUpdateProfile}
ssidProfiles={
(ssidProfiles && ssidProfiles.getAllProfiles && ssidProfiles.getAllProfiles.items) || []
const GET_PROFILE = gql`
query GetProfile($id: ID!) {
getProfile(id: $id) {
id
profileType
customerId
name
childProfiles {
id
name
profileType
details
}
fileUpload={handleFileUpload}
/>
);
};
childProfileIds
createdTimestamp
lastModifiedTimestamp
details
}
}
`;
const UPDATE_PROFILE = gql`
mutation UpdateProfile(
$id: ID!
$profileType: String!
$customerId: ID!
$name: String!
$childProfileIds: [ID]
$lastModifiedTimestamp: String
$details: JSONObject
) {
updateProfile(
id: $id
profileType: $profileType
customerId: $customerId
name: $name
childProfileIds: $childProfileIds
lastModifiedTimestamp: $lastModifiedTimestamp
details: $details
) {
id
profileType
customerId
name
childProfileIds
lastModifiedTimestamp
details
}
}
`;
const DELETE_PROFILE = gql`
mutation DeleteProfile($id: ID!) {
deleteProfile(id: $id) {
id
}
}
`;
const ProfileDetails = withQuery(
({ data }) => {
const { customerId } = useContext(UserContext);
const { id } = useParams();
const [redirect, setRedirect] = useState(false);
const { data: ssidProfiles, fetchMore } = useQuery(GET_ALL_PROFILES(), {
variables: { customerId, type: 'ssid' },
});
const { data: radiusProfiles, fetchMore: fetchMoreRadiusProfiles } = useQuery(
GET_ALL_PROFILES(),
{
variables: { customerId, type: 'radius' },
}
);
const { data: captiveProfiles, fetchMore: fetchMoreCaptiveProfiles } = useQuery(
GET_ALL_PROFILES(),
{
variables: { customerId, type: 'captive_portal' },
}
);
const [updateProfile] = useMutation(UPDATE_PROFILE);
const [deleteProfile] = useMutation(DELETE_PROFILE);
const [fileUpload] = useMutation(FILE_UPLOAD);
const handleDeleteProfile = () => {
deleteProfile({ variables: { id } })
.then(() => {
notification.success({
message: 'Success',
description: 'Profile successfully deleted.',
});
setRedirect(true);
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Profile could not be deleted.',
})
);
};
const handleUpdateProfile = (
name,
details,
childProfileIds = data.getProfile.childProfileIds
) => {
updateProfile({
variables: {
...data.getProfile,
name,
childProfileIds,
details,
},
})
.then(() => {
notification.success({
message: 'Success',
description: 'Profile successfully updated.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Profile could not be updated.',
})
);
};
const handleFileUpload = (fileName, file) =>
fileUpload({ variables: { fileName, file } })
.then(() => {
notification.success({
message: 'Success',
description: 'File successfully uploaded.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'File could not be uploaded.',
})
);
const handleFetchProfiles = e => {
if (ssidProfiles.getAllProfiles.context.lastPage) {
return false;
}
e.persist();
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
fetchMore({
variables: { context: { ...ssidProfiles.getAllProfiles.context } },
updateQuery: updateQueryGetAllProfiles,
});
}
return true;
};
const handleFetchRadiusProfiles = e => {
if (radiusProfiles.getAllProfiles.context.lastPage) {
return false;
}
e.persist();
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
fetchMoreRadiusProfiles({
variables: { context: { ...radiusProfiles.getAllProfiles.context } },
updateQuery: updateQueryGetAllProfiles,
});
}
return true;
};
const handleFetchCaptiveProfiles = e => {
if (captiveProfiles.getAllProfiles.context.lastPage) {
return false;
}
e.persist();
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
fetchMoreCaptiveProfiles({
variables: { context: { ...captiveProfiles.getAllProfiles.context } },
updateQuery: updateQueryGetAllProfiles,
});
}
return true;
};
if (redirect) {
return <Redirect to="/profiles" />;
}
return (
<ProfileDetailsPage
name={data.getProfile.name}
profileType={data.getProfile.profileType}
details={data.getProfile.details}
childProfileIds={data.getProfile.childProfileIds}
onDeleteProfile={handleDeleteProfile}
onUpdateProfile={handleUpdateProfile}
ssidProfiles={
(ssidProfiles && ssidProfiles.getAllProfiles && ssidProfiles.getAllProfiles.items) || []
}
radiusProfiles={radiusProfiles?.getAllProfiles?.items}
captiveProfiles={captiveProfiles?.getAllProfiles?.items}
fileUpload={handleFileUpload}
onFetchMoreProfiles={handleFetchProfiles}
onFetchMoreRadiusProfiles={handleFetchRadiusProfiles}
onFetchMoreCaptiveProfiles={handleFetchCaptiveProfiles}
/>
);
},
GET_PROFILE,
() => {
const { id } = useParams();
return { id, fetchPolicy: 'network-only' };
}
);
export default ProfileDetails;

View File

@@ -1,186 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import UserProvider from 'contexts/UserProvider';
import { getAllProfilesQueryMock } from '../../AddProfile/tests/mock';
import { profileDetailsMutationMock, profileDetailsQueryMock } from './mock';
import ProfileDetails from '..';
jest.mock('rc-upload/lib/uid.js', () => ({
__esModule: true,
default: () => '1234',
}));
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
jest.mock('react-router-dom', () => ({
useParams: () => ({
id: 123,
}),
useHistory: () => ({ push: jest.fn() }),
}));
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<ProfileDetails />', () => {
afterEach(jest.resetModules);
it('should render with Data', async () => {
const { getByLabelText } = render(
<MockedProvider
mocks={[profileDetailsQueryMock.success, getAllProfilesQueryMock.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ProfileDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByLabelText('Profile Name')).toHaveValue('Radius-Profile'));
});
it('should show error when query return error', async () => {
const { getByText } = render(
<MockedProvider mocks={[profileDetailsQueryMock.error]} addTypename={false}>
<UserProvider {...mockProp}>
<ProfileDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load profile data.')).toBeVisible());
});
it('should render with Data and update successfully', async () => {
const { getByLabelText, getByText, getByRole } = render(
<MockedProvider
mocks={[
profileDetailsQueryMock.success,
getAllProfilesQueryMock.success,
profileDetailsMutationMock.updateSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ProfileDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByLabelText('Profile Name')).toHaveValue('Radius-Profile'));
await waitFor(() => expect(getByText('0.0.0.0')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Profile successfully updated.')).toBeVisible());
});
it('should render with Data and show error when update mutation return error', async () => {
const { getByLabelText, getByText, getByRole } = render(
<MockedProvider
mocks={[
profileDetailsQueryMock.success,
getAllProfilesQueryMock.success,
profileDetailsMutationMock.updateError,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ProfileDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByLabelText('Profile Name')).toHaveValue('Radius-Profile'));
await waitFor(() => expect(getByText('0.0.0.0')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Profile could not be updated.')).toBeVisible());
});
it('should render with Data and upload image successfully', async () => {
global.URL.createObjectURL = jest.fn();
const { getByLabelText, getByTestId, getByText } = render(
<MockedProvider
mocks={[
profileDetailsQueryMock.successCaptivePortal,
getAllProfilesQueryMock.success,
profileDetailsMutationMock.uploadSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ProfileDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByLabelText('Profile Name')).toHaveValue('Captive-portal'));
fireEvent.change(getByTestId('logoFile'), {
target: {
files: [
{
lastModified: 1595008730671,
lastModifiedDate: undefined,
name: 'testImg.jpg',
size: 100,
type: 'image/jpg',
percent: 0,
originFileObj: { uid: 'rc-upload-1595008718690-73' },
},
],
},
});
expect(getByText(/testImg\.jpg/)).toBeInTheDocument();
await waitFor(() => expect(getByText('File successfully uploaded.')).toBeVisible());
});
it('should render with Data and show error when upload mutation return error', async () => {
global.URL.createObjectURL = jest.fn();
const { getByLabelText, getByTestId, getByText } = render(
<MockedProvider
mocks={[
profileDetailsQueryMock.successCaptivePortal,
getAllProfilesQueryMock.success,
profileDetailsMutationMock.uploadError,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<ProfileDetails />
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByLabelText('Profile Name')).toHaveValue('Captive-portal'));
fireEvent.change(getByTestId('logoFile'), {
target: {
files: [
{
lastModified: 1595008730671,
lastModifiedDate: undefined,
name: 'testImg.jpg',
size: 100,
type: 'image/jpg',
percent: 0,
originFileObj: { uid: 'rc-upload-1595008718690-73' },
},
],
},
});
expect(getByText(/testImg\.jpg/)).toBeInTheDocument();
await waitFor(() => expect(getByText('File could not be uploaded.')).toBeVisible());
});
});

View File

@@ -1,344 +0,0 @@
import { GET_PROFILE } from 'graphql/queries';
import { FILE_UPLOAD, UPDATE_PROFILE } from 'graphql/mutations';
export const profileDetailsQueryMock = {
success: {
request: {
query: GET_PROFILE,
variables: { id: 123 },
},
result: {
data: {
getProfile: {
id: '123',
profileType: 'radius',
customerId: '2',
name: 'Radius-Profile',
childProfiles: [],
childProfileIds: [],
createdTimestamp: '0',
lastModifiedTimestamp: '1597243756957',
details: {
model_type: 'RadiusProfile',
subnetConfiguration: {
test: {
model_type: 'RadiusSubnetConfiguration',
subnetAddress: '0.0.0.0',
subnetCidrPrefix: 0,
subnetName: 'test',
proxyConfig: {
model_type: 'RadiusProxyConfiguration',
floatingIpAddress: null,
floatingIfCidrPrefix: null,
floatingIfGwAddress: null,
floatingIfVlan: null,
sharedSecret: null,
},
probeInterval: null,
serviceRegionName: 'Ottawa',
},
},
serviceRegionMap: {
Ottawa: {
model_type: 'RadiusServiceRegion',
serverMap: {
'Radius-Profile': [
{
model_type: 'RadiusServer',
ipAddress: '192.168.0.1',
secret: 'testing123',
authPort: 1812,
timeout: null,
},
],
},
regionName: 'Ottawa',
},
},
profileType: 'radius',
},
__typename: 'Profile',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
successCaptivePortal: {
request: {
query: GET_PROFILE,
variables: { id: 123 },
},
result: {
data: {
getProfile: {
id: '123',
profileType: 'captive_portal',
customerId: '2',
name: 'Captive-portal',
childProfiles: [],
childProfileIds: [],
createdTimestamp: '1597238768150',
lastModifiedTimestamp: '1597238768150',
details: {
model_type: 'CaptivePortalConfiguration',
name: 'Captive-portal',
browserTitle: 'Access the network as Guest',
headerContent: 'Captive Portal',
userAcceptancePolicy: 'Use this network at your own risk. No warranty of any kind.',
successPageMarkdownText: 'Welcome to the network',
redirectURL: '',
externalCaptivePortalURL: null,
sessionTimeoutInMinutes: 60,
logoFile: null,
backgroundFile: null,
walledGardenWhitelist: [],
usernamePasswordFile: null,
authenticationType: 'guest',
radiusAuthMethod: 'CHAP',
maxUsersWithSameCredentials: 42,
externalPolicyFile: null,
backgroundPosition: 'left_top',
backgroundRepeat: 'no_repeat',
radiusServiceName: null,
expiryType: 'unlimited',
userList: [],
macWhiteList: [],
profileType: 'captive_portal',
},
__typename: 'Profile',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_PROFILE,
variables: { id: 123 },
},
result: {
data: null,
errors: [{}],
loading: false,
networkStatus: 7,
stale: false,
},
},
};
export const profileDetailsMutationMock = {
updateSuccess: {
request: {
query: UPDATE_PROFILE,
variables: {
id: '123',
profileType: 'radius',
customerId: '2',
name: 'Radius-Profile',
childProfiles: [],
childProfileIds: [],
createdTimestamp: '0',
lastModifiedTimestamp: '1597243756957',
details: {
model_type: 'RadiusProfile',
subnetConfiguration: {
test: {
model_type: 'RadiusSubnetConfiguration',
subnetAddress: '0.0.0.0',
subnetCidrPrefix: 0,
subnetName: 'test',
proxyConfig: {
model_type: 'RadiusProxyConfiguration',
floatingIpAddress: null,
floatingIfCidrPrefix: null,
floatingIfGwAddress: null,
floatingIfVlan: null,
sharedSecret: null,
},
probeInterval: null,
serviceRegionName: 'Ottawa',
},
},
serviceRegionMap: {
Ottawa: {
regionName: 'Ottawa',
serverMap: {
'Radius-Profile': [
{
model_type: 'RadiusServer',
ipAddress: '192.168.0.1',
secret: 'testing123',
authPort: 1812,
timeout: null,
},
],
},
},
},
profileType: 'radius',
name: 'Radius-Profile',
probeInterval: 0,
services: [
{
name: 'Radius-Profile',
ips: [
{
model_type: 'RadiusServer',
ipAddress: '192.168.0.1',
secret: 'testing123',
authPort: 1812,
timeout: null,
},
],
},
],
zones: [
{
name: 'Ottawa',
subnets: [
{
model_type: 'RadiusSubnetConfiguration',
subnetAddress: '0.0.0.0',
subnetCidrPrefix: 0,
subnetName: 'test',
proxyConfig: {
model_type: 'RadiusProxyConfiguration',
floatingIpAddress: null,
floatingIfCidrPrefix: null,
floatingIfGwAddress: null,
floatingIfVlan: null,
sharedSecret: null,
},
probeInterval: null,
serviceRegionName: 'Ottawa',
},
],
},
],
},
},
},
result: {
data: {
updateProfile: {
id: '123',
profileType: 'radius',
customerId: '2',
name: 'Radius-Profile',
childProfileIds: [],
lastModifiedTimestamp: '1597245742733',
details: {
model_type: 'RadiusProfile',
subnetConfiguration: {
test: {
model_type: 'RadiusSubnetConfiguration',
subnetAddress: '0.0.0.0',
subnetCidrPrefix: 0,
subnetName: 'test',
proxyConfig: {
model_type: 'RadiusProxyConfiguration',
floatingIpAddress: null,
floatingIfCidrPrefix: null,
floatingIfGwAddress: null,
floatingIfVlan: null,
sharedSecret: null,
},
probeInterval: null,
serviceRegionName: 'Ottawa',
},
},
serviceRegionMap: {
Ottawa: {
model_type: 'RadiusServiceRegion',
serverMap: {
'Radius-Profile': [
{
model_type: 'RadiusServer',
ipAddress: '192.168.0.1',
secret: 'testing123',
authPort: 1812,
timeout: null,
},
],
},
regionName: 'Ottawa',
},
},
profileType: 'radius',
},
__typename: 'Profile',
},
},
},
},
updateError: {
request: {
query: UPDATE_PROFILE,
variables: {
id: 123,
username: 'test@test.com',
password: 'password',
role: 'CustomerIT',
customerId: '2',
lastModifiedTimestamp: '1597238767547',
},
},
result: {
data: null,
errors: [{}],
},
},
uploadSuccess: {
request: {
query: FILE_UPLOAD,
variables: {
fileName: 'testImg.jpg',
file: {
uid: '1234',
lastModified: 1595008730671,
lastModifiedDate: undefined,
name: 'testImg.jpg',
size: 100,
type: 'image/jpg',
percent: 0,
originFileObj: { uid: 'rc-upload-1595008718690-73' },
},
},
},
result: {
data: {
fileUpload: {
fileName: 'talkblog@4x.png',
baseUrl: 'https://localhost:9091/',
__typename: 'File',
},
},
},
},
uploadError: {
request: {
query: FILE_UPLOAD,
variables: {
fileName: 'testImg.jpg',
file: {
uid: '1234',
lastModified: 1595008730671,
lastModifiedDate: undefined,
name: 'testImg.jpg',
size: 100,
type: 'image/jpg',
percent: 0,
originFileObj: { uid: 'rc-upload-1595008718690-73' },
},
},
},
result: {
data: null,
errors: [{}],
},
},
};

View File

@@ -1,107 +1,101 @@
import React, { useContext } from 'react';
import gql from 'graphql-tag';
import { useQuery, useMutation } from '@apollo/react-hooks';
import React, { useContext, useEffect } from 'react';
import { useMutation, gql } from '@apollo/client';
import { useLocation } from 'react-router-dom';
import { notification } from 'antd';
import { Profile as ProfilePage } from '@tip-wlan/wlan-cloud-ui-library';
import { Alert, notification } from 'antd';
import { Profile as ProfilePage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { GET_ALL_PROFILES } from 'graphql/queries';
import { updateQueryGetAllProfiles } from 'graphql/functions';
import UserContext from 'contexts/UserContext';
import { DELETE_PROFILE } from 'graphql/mutations';
import { withQuery } from 'containers/QueryWrapper';
export const GET_ALL_PROFILES = gql`
query GetAllProfiles($customerId: ID!, $cursor: String, $limit: Int) {
getAllProfiles(customerId: $customerId, cursor: $cursor, limit: $limit) {
items {
id
name
profileType
details
equipmentCount
}
context {
cursor
lastPage
}
const DELETE_PROFILE = gql`
mutation DeleteProfile($id: ID!) {
deleteProfile(id: $id) {
id
}
}
`;
const Profiles = () => {
const { customerId } = useContext(UserContext);
const { loading, error, data, refetch, fetchMore } = useQuery(GET_ALL_PROFILES, {
variables: { customerId, limit: 100 },
});
const [deleteProfile] = useMutation(DELETE_PROFILE);
const Profiles = withQuery(
({ data, fetchMore, refetch }) => {
const [deleteProfile] = useMutation(DELETE_PROFILE);
const { customerId } = useContext(UserContext);
const location = useLocation();
const reloadTable = () => {
refetch()
.then(() => {
notification.success({
message: 'Success',
description: 'Profiles reloaded.',
useEffect(() => {
if (location.state && location.state.refetch) {
refetch({
variables: { refresh: Date.now() },
});
}
}, []);
const reloadTable = () => {
refetch({
variables: { refresh: Date.now() },
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Profiles could not be reloaded.',
.then(() => {
notification.success({
message: 'Success',
description: 'Profiles reloaded.',
});
})
);
};
.catch(() =>
notification.error({
message: 'Error',
description: 'Profiles could not be reloaded.',
})
);
};
const handleLoadMore = () => {
if (!data.getAllProfiles.context.lastPage) {
fetchMore({
variables: { cursor: data.getAllProfiles.context.cursor },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.getAllProfiles;
const newItems = fetchMoreResult.getAllProfiles.items;
return {
getAllProfiles: {
context: fetchMoreResult.getAllProfiles.context,
items: [...previousEntry.items, ...newItems],
__typename: previousEntry.__typename,
},
};
},
});
}
};
const handleDeleteProfile = id => {
deleteProfile({ variables: { id } })
.then(() => {
notification.success({
message: 'Success',
description: 'Profile successfully deleted.',
const handleLoadMore = () => {
if (!data.getAllProfiles.context.lastPage) {
fetchMore({
variables: { context: { ...data.getAllProfiles.context } },
updateQuery: updateQueryGetAllProfiles,
});
}
};
const handleDeleteProfile = id => {
deleteProfile({
variables: { id },
refetchQueries: [
{
query: GET_ALL_PROFILES(`equipmentCount`),
variables: { customerId },
},
],
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Profile could not be deleted.',
.then(() => {
notification.success({
message: 'Success',
description: 'Profile successfully deleted.',
});
})
);
};
if (loading) {
return <Loading />;
.catch(() =>
notification.error({
message: 'Error',
description: 'Profile could not be deleted.',
})
);
};
return (
<ProfilePage
data={data.getAllProfiles.items}
onReload={reloadTable}
isLastPage={data?.getAllProfiles?.context?.lastPage}
onDeleteProfile={handleDeleteProfile}
onLoadMore={handleLoadMore}
/>
);
},
GET_ALL_PROFILES(`equipmentCount`),
() => {
const { customerId } = useContext(UserContext);
return { customerId, fetchPolicy: 'network-only' };
}
if (error) {
return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
}
return (
<ProfilePage
data={data.getAllProfiles.items}
onReload={reloadTable}
isLastPage={data.getAllProfiles.context.lastPage}
onDeleteProfile={handleDeleteProfile}
onLoadMore={handleLoadMore}
/>
);
};
);
export default Profiles;

View File

@@ -1,171 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import { BrowserRouter as Router } from 'react-router-dom';
import { screen } from '@testing-library/dom';
import UserProvider from 'contexts/UserProvider';
import { profilesMutationMock, profilesQueryMock } from './mock';
import Profiles from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<Profiles />', () => {
afterEach(jest.resetModules);
it('should render with Data', async () => {
const { getByText } = render(
<MockedProvider mocks={[profilesQueryMock.success]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<Profiles />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
});
it('should show error when query return error', async () => {
const { getByText } = render(
<MockedProvider mocks={[profilesQueryMock.error]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<Profiles />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load profiles.')).toBeVisible());
});
it('should render with Data and call onReload if reload button is clicked', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[profilesQueryMock.success, profilesQueryMock.success]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Profiles />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
fireEvent.click(getByRole('button', { name: /reload/i }));
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
});
it('should render with Data and show error if reload button is clicked', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[profilesQueryMock.success, profilesQueryMock.error]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Profiles />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
fireEvent.click(getByRole('button', { name: /reload/i }));
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
});
it('should render with Data and Load More Button Should show when isLastPage false', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[profilesQueryMock.success, profilesQueryMock.loadmore]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Profiles />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Load More' }));
await waitFor(() => expect(getByText('TipWlan-cloud-Enterprise')).toBeVisible());
});
it('should render with Data and Delete profile successfully', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
profilesQueryMock.success,
profilesQueryMock.loadmore,
profilesMutationMock.deleteSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Profiles />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Load More' }));
await waitFor(() => expect(getByText('TipWlan-cloud-Enterprise')).toBeVisible());
fireEvent.click(screen.getByTitle('delete'));
expect(getByRole('button', { name: 'Delete' }));
fireEvent.click(getByRole('button', { name: 'Delete' }));
await waitFor(() => expect(getByText('Profile successfully deleted.')).toBeVisible());
});
it('should render with Data and show error when Delete profile', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
profilesQueryMock.success,
profilesQueryMock.loadmore,
profilesMutationMock.deleteError,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Profiles />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Radius-Profile')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Load More' }));
await waitFor(() => expect(getByText('TipWlan-cloud-Enterprise')).toBeVisible());
fireEvent.click(screen.getByTitle('delete'));
expect(getByRole('button', { name: 'Delete' }));
fireEvent.click(getByRole('button', { name: 'Delete' }));
await waitFor(() => expect(getByText('Profile could not be deleted.')).toBeVisible());
});
});

View File

@@ -1,175 +0,0 @@
import { DELETE_PROFILE } from 'graphql/mutations';
import { GET_ALL_PROFILES } from '..';
export const profilesQueryMock = {
success: {
request: {
query: GET_ALL_PROFILES,
variables: { customerId: 2, limit: 100 },
},
result: {
data: {
getAllProfiles: {
items: [
{
id: '123',
name: 'Radius-Profile',
profileType: 'radius',
details: {
model_type: 'RadiusProfile',
subnetConfiguration: {
test: {
model_type: 'RadiusSubnetConfiguration',
subnetAddress: '0.0.0.0',
subnetCidrPrefix: 0,
subnetName: 'test',
proxyConfig: {
model_type: 'RadiusProxyConfiguration',
floatingIpAddress: null,
floatingIfCidrPrefix: null,
floatingIfGwAddress: null,
floatingIfVlan: null,
sharedSecret: null,
},
probeInterval: null,
serviceRegionName: 'Ottawa',
},
},
serviceRegionMap: {
Ottawa: {
model_type: 'RadiusServiceRegion',
serverMap: {
'Radius-Profile': [
{
model_type: 'RadiusServer',
ipAddress: '192.168.0.1',
secret: 'testing123',
authPort: 1812,
timeout: null,
},
],
},
regionName: 'Ottawa',
},
},
profileType: 'radius',
},
__typename: 'Profile',
},
],
context: {
cursor: 'test',
lastPage: false,
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
loadmore: {
request: {
query: GET_ALL_PROFILES,
variables: { customerId: 2, limit: 100, cursor: 'test' },
},
result: {
data: {
getAllProfiles: {
items: [
{
id: '2',
name: 'TipWlan-cloud-Enterprise',
profileType: 'ssid',
details: {
model_type: 'SsidConfiguration',
ssid: 'Default-SSID-1597238767760',
appliedRadios: ['is5GHzU', 'is2dot4GHz', 'is5GHzL'],
ssidAdminState: 'enabled',
secureMode: 'wpaEAP',
vlanId: 1,
keyStr: 'testing123',
broadcastSsid: 'enabled',
keyRefresh: 0,
noLocalSubnets: false,
radiusServiceName: 'Radius-Profile',
captivePortalId: null,
bandwidthLimitDown: 0,
bandwidthLimitUp: 0,
videoTrafficOnly: false,
radioBasedConfigs: {
is5GHz: {
model_type: 'RadioBasedSsidConfiguration',
enable80211r: null,
enable80211k: null,
enable80211v: null,
},
is2dot4GHz: {
model_type: 'RadioBasedSsidConfiguration',
enable80211r: null,
enable80211k: null,
enable80211v: null,
},
is5GHzU: {
model_type: 'RadioBasedSsidConfiguration',
enable80211r: null,
enable80211k: null,
enable80211v: null,
},
is5GHzL: {
model_type: 'RadioBasedSsidConfiguration',
enable80211r: null,
enable80211k: null,
enable80211v: null,
},
},
bonjourGatewayProfileId: null,
enable80211w: null,
wepConfig: null,
forwardMode: null,
profileType: 'ssid',
},
},
],
context: {
cursor: 'test2',
lastPage: true,
},
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_ALL_PROFILES,
variables: { customerId: 2 },
},
result: {
data: null,
errors: [{}],
},
},
};
export const profilesMutationMock = {
deleteSuccess: {
request: {
query: DELETE_PROFILE,
variables: { id: '2' },
},
result: { data: { deleteProfile: { id: '2', __typename: 'Profile' } } },
},
deleteError: {
request: {
query: DELETE_PROFILE,
variables: { id: '2' },
},
result: {
data: null,
errors: [{}],
},
},
};

View File

@@ -0,0 +1,25 @@
import React from 'react';
import { Alert } from 'antd';
import { Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { useQuery } from '@apollo/client';
import { Redirect } from 'react-router-dom';
export const withQuery = (Comp, query, getVariables) => props => {
const { loading, error, data, refetch, fetchMore } = useQuery(query, {
variables: getVariables(),
});
if (loading) {
return <Loading />;
}
if (error) {
if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
return <Redirect to="/login" />;
}
return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
}
return <Comp {...props} data={data} fetchMore={fetchMore} refetch={refetch} />;
};

View File

@@ -1,87 +1,82 @@
import React, { useContext } from 'react';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { Alert, notification } from 'antd';
import { AutoProvision as AutoProvisionPage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { useQuery, useMutation } from '@apollo/client';
import { notification } from 'antd';
import { AutoProvision as AutoProvisionPage } from '@tip-wlan/wlan-cloud-ui-library';
import UserContext from 'contexts/UserContext';
import { GET_CUSTOMER, GET_ALL_LOCATIONS, GET_ALL_PROFILES } from 'graphql/queries';
import { UPDATE_CUSTOMER } from 'graphql/mutations';
import { withQuery } from 'containers/QueryWrapper';
const AutoProvision = () => {
const { customerId } = useContext(UserContext);
const { data, loading, error, refetch } = useQuery(GET_CUSTOMER, {
variables: { id: customerId },
});
const [updateCustomer] = useMutation(UPDATE_CUSTOMER);
const AutoProvision = withQuery(
({ data, refetch }) => {
const { customerId } = useContext(UserContext);
const [updateCustomer] = useMutation(UPDATE_CUSTOMER);
const { data: dataLocation, loading: loadingLoaction, error: errorLocation } = useQuery(
GET_ALL_LOCATIONS,
{
variables: { customerId },
}
);
const { data: dataProfile, loading: loadingProfile, error: errorProfile } = useQuery(
GET_ALL_PROFILES,
{
variables: { customerId, type: 'equipment_ap' },
}
);
const handleUpdateCustomer = (
id,
email,
name,
details,
createdTimestamp,
lastModifiedTimestamp
) => {
updateCustomer({
variables: {
id,
email,
name,
details,
createdTimestamp,
lastModifiedTimestamp,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Settings successfully updated.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Settings could not be updated.',
})
);
};
if (loading) {
return <Loading />;
}
if (error) {
return (
<Alert message="Error" description="Failed to load Customer Data." type="error" showIcon />
const { data: dataLocation, loading: loadingLoaction, error: errorLocation } = useQuery(
GET_ALL_LOCATIONS,
{
variables: { customerId },
}
);
const { data: dataProfile, loading: loadingProfile, error: errorProfile } = useQuery(
GET_ALL_PROFILES(),
{
variables: { customerId, type: 'equipment_ap', limit: 100 },
}
);
}
return (
<AutoProvisionPage
data={data && data.getCustomer}
dataLocation={dataLocation && dataLocation.getAllLocations}
dataProfile={dataProfile && dataProfile.getAllProfiles.items}
loadingLoaction={loadingLoaction}
loadingProfile={loadingProfile}
errorLocation={errorLocation}
errorProfile={errorProfile}
onUpdateCustomer={handleUpdateCustomer}
/>
);
};
const handleUpdateCustomer = (
id,
email,
name,
details,
createdTimestamp,
lastModifiedTimestamp
) => {
updateCustomer({
variables: {
id,
email,
name,
details,
createdTimestamp,
lastModifiedTimestamp,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Settings successfully updated.',
});
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Settings could not be updated.',
})
);
};
return (
<AutoProvisionPage
data={data && data.getCustomer}
dataLocation={dataLocation && dataLocation.getAllLocations}
dataProfile={dataProfile && dataProfile.getAllProfiles.items}
loadingLoaction={loadingLoaction}
loadingProfile={loadingProfile}
errorLocation={errorLocation}
errorProfile={errorProfile}
onUpdateCustomer={handleUpdateCustomer}
/>
);
},
GET_CUSTOMER,
() => {
const { customerId } = useContext(UserContext);
return { id: customerId };
}
);
export default AutoProvision;

View File

@@ -1,124 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import { BrowserRouter as Router } from 'react-router-dom';
import UserProvider from 'contexts/UserProvider';
import { autoProvisionMutationMock, autoProvisionQueryMock } from './mock';
import AutoProvision from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<AutoProvision />', () => {
afterEach(jest.resetModules);
it('should render with Data', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
autoProvisionQueryMock.getAllProfilesSuccess,
autoProvisionQueryMock.getCustomerSuccess,
autoProvisionQueryMock.getAllLocationsSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<AutoProvision />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('EA8300')).toBeVisible());
});
it('should show error when customer query return error', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
autoProvisionQueryMock.getAllProfilesSuccess,
autoProvisionQueryMock.error,
autoProvisionQueryMock.getAllLocationsSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<AutoProvision />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load Customer Data.')).toBeVisible());
});
it('should render with Data and update successfully', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
autoProvisionQueryMock.getAllProfilesSuccess,
autoProvisionQueryMock.getCustomerSuccess,
autoProvisionQueryMock.getCustomerSuccess,
autoProvisionQueryMock.getAllLocationsSuccess,
autoProvisionMutationMock.success,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<AutoProvision />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('EA8300')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Settings successfully updated.')).toBeVisible());
await waitFor(() => expect(getByText('EA8300')).toBeVisible());
});
it('should render with Data and update show error when mutation return error', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
autoProvisionQueryMock.getAllProfilesSuccess,
autoProvisionQueryMock.getCustomerSuccess,
autoProvisionQueryMock.getCustomerSuccess,
autoProvisionQueryMock.getAllLocationsSuccess,
autoProvisionMutationMock.error,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<AutoProvision />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('EA8300')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() => expect(getByText('Settings could not be updated.')).toBeVisible());
});
});

View File

@@ -1,361 +0,0 @@
import { GET_ALL_LOCATIONS, GET_ALL_PROFILES, GET_CUSTOMER } from 'graphql/queries';
import { UPDATE_CUSTOMER } from 'graphql/mutations';
export const autoProvisionQueryMock = {
getAllProfilesSuccess: {
request: {
query: GET_ALL_PROFILES,
variables: { customerId: 2, type: 'equipment_ap' },
},
result: {
data: {
getAllProfiles: {
items: [
{
id: '6',
name: 'ApProfile-3-radios',
profileType: 'equipment_ap',
details: {
model_type: 'ApNetworkConfiguration',
networkConfigVersion: 'AP-1',
equipmentType: 'AP',
vlanNative: true,
vlan: 0,
ntpServer: {
model_type: 'AutoOrManualString',
auto: true,
value: 'pool.ntp.org',
},
syslogRelay: null,
rtlsSettings: null,
syntheticClientEnabled: true,
ledControlEnabled: true,
equipmentDiscovery: false,
radioMap: {
is2dot4GHz: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is5GHzU: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is5GHzL: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
},
profileType: 'equipment_ap',
},
__typename: 'Profile',
},
{
id: '7',
name: 'ApProfile-2-radios',
profileType: 'equipment_ap',
details: {
model_type: 'ApNetworkConfiguration',
networkConfigVersion: 'AP-1',
equipmentType: 'AP',
vlanNative: true,
vlan: 0,
ntpServer: {
model_type: 'AutoOrManualString',
auto: true,
value: 'pool.ntp.org',
},
syslogRelay: null,
rtlsSettings: null,
syntheticClientEnabled: true,
ledControlEnabled: true,
equipmentDiscovery: false,
radioMap: {
is5GHz: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is2dot4GHz: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
},
profileType: 'equipment_ap',
},
__typename: 'Profile',
},
{
id: '8',
name: 'EnterpriseApProfile',
profileType: 'equipment_ap',
details: {
model_type: 'ApNetworkConfiguration',
networkConfigVersion: 'AP-1',
equipmentType: 'AP',
vlanNative: true,
vlan: 0,
ntpServer: {
model_type: 'AutoOrManualString',
auto: true,
value: 'pool.ntp.org',
},
syslogRelay: null,
rtlsSettings: null,
syntheticClientEnabled: true,
ledControlEnabled: true,
equipmentDiscovery: false,
radioMap: {
is5GHz: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is2dot4GHz: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is5GHzU: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
is5GHzL: {
model_type: 'RadioProfileConfiguration',
bestApEnabled: true,
bestAPSteerType: 'both',
},
},
profileType: 'equipment_ap',
},
__typename: 'Profile',
},
],
context: {
cursor:
'bnVsbEBAQHsibW9kZWxfdHlwZSI6IkNvbnRleHRDaGlsZHJlbiIsImNoaWxkcmVuIjp7fX1AQEBudWxs',
lastPage: true,
__typename: 'PaginationContext',
},
__typename: 'ProfilePagination',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
getCustomerSuccess: {
request: {
query: GET_CUSTOMER,
variables: { id: 2 },
},
result: {
data: {
getCustomer: {
id: '2',
name: 'Test Customer',
email: 'test@example.com',
createdTimestamp: '1597329016138',
lastModifiedTimestamp: '1597329017058',
details: {
model_type: 'CustomerDetails',
autoProvisioning: {
model_type: 'EquipmentAutoProvisioningSettings',
enabled: true,
locationId: 8,
equipmentProfileIdPerModel: {
default: 6,
TIP_AP: 7,
ECW5410: 7,
ECW5211: 7,
AP2220: 7,
'EA8300-CA': 6,
EA8300: 6,
},
},
},
__typename: 'Customer',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
getAllLocationsSuccess: {
request: {
query: GET_ALL_LOCATIONS,
variables: { customerId: 2 },
},
result: {
data: {
getAllLocations: [
{
id: '2',
name: 'Menlo Park',
parentId: '0',
locationType: 'SITE',
__typename: 'Location',
},
{
id: '3',
name: 'Building 1',
parentId: '2',
locationType: 'BUILDING',
__typename: 'Location',
},
{
id: '4',
name: 'Floor 1',
parentId: '3',
locationType: 'FLOOR',
__typename: 'Location',
},
{
id: '5',
name: 'Floor 2',
parentId: '3',
locationType: 'FLOOR',
__typename: 'Location',
},
{
id: '6',
name: 'Floor 3',
parentId: '3',
locationType: 'FLOOR',
__typename: 'Location',
},
{
id: '7',
name: 'Building 2',
parentId: '2',
locationType: 'BUILDING',
__typename: 'Location',
},
{
id: '8',
name: 'Ottawa',
parentId: '0',
locationType: 'SITE',
__typename: 'Location',
},
],
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_CUSTOMER,
variables: { id: 2 },
},
result: {
data: null,
errors: [{}],
},
},
};
export const autoProvisionMutationMock = {
success: {
request: {
query: UPDATE_CUSTOMER,
variables: {
id: '2',
email: 'test@example.com',
name: 'Test Customer',
details: {
model_type: 'CustomerDetails',
autoProvisioning: {
model_type: 'EquipmentAutoProvisioningSettings',
enabled: true,
locationId: '8',
equipmentProfileIdPerModel: {
default: 6,
TIP_AP: 7,
ECW5410: 7,
ECW5211: 7,
AP2220: 7,
'EA8300-CA': 6,
EA8300: 6,
},
},
},
createdTimestamp: '1597329016138',
lastModifiedTimestamp: '1597329017058',
},
},
result: {
data: {
updateCustomer: {
id: '2',
email: 'test@example.com',
name: 'Test Customer',
details: {
model_type: 'CustomerDetails',
autoProvisioning: {
model_type: 'EquipmentAutoProvisioningSettings',
enabled: true,
locationId: 8,
equipmentProfileIdPerModel: {
default: 6,
TIP_AP: 7,
ECW5410: 7,
ECW5211: 7,
AP2220: 7,
'EA8300-CA': 6,
EA8300: 6,
},
},
},
createdTimestamp: '1597329016138',
lastModifiedTimestamp: '1597331154979',
__typename: 'Customer',
},
},
},
},
error: {
request: {
query: UPDATE_CUSTOMER,
variables: {
id: '2',
email: 'test@example.com',
name: 'Test Customer',
details: {
model_type: 'CustomerDetails',
autoProvisioning: {
model_type: 'EquipmentAutoProvisioningSettings',
enabled: true,
locationId: '8',
equipmentProfileIdPerModel: {
default: 6,
TIP_AP: 7,
ECW5410: 7,
ECW5211: 7,
AP2220: 7,
'EA8300-CA': 6,
EA8300: 6,
},
},
},
createdTimestamp: '1597329016138',
lastModifiedTimestamp: '1597329017058',
},
},
result: {
data: null,
errors: [{}],
},
},
};

View File

@@ -1,78 +1,76 @@
import React, { useContext } from 'react';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { Alert, notification } from 'antd';
import { BlockedList as BlockedListPage, Loading } from '@tip-wlan/wlan-cloud-ui-library';
import { useMutation } from '@apollo/client';
import { notification } from 'antd';
import { BlockedList as BlockedListPage } from '@tip-wlan/wlan-cloud-ui-library';
import { GET_BLOCKED_CLIENTS } from 'graphql/queries';
import { UPDATE_CLIENT, ADD_BLOCKED_CLIENT } from 'graphql/mutations';
import UserContext from 'contexts/UserContext';
import { withQuery } from 'containers/QueryWrapper';
const BlockedList = () => {
const { customerId } = useContext(UserContext);
const { data, error, loading, refetch } = useQuery(GET_BLOCKED_CLIENTS, {
variables: { customerId },
});
const [addClient] = useMutation(ADD_BLOCKED_CLIENT);
const [updateClient] = useMutation(UPDATE_CLIENT);
const BlockedList = withQuery(
({ refetch, data }) => {
const { customerId } = useContext(UserContext);
const [addClient] = useMutation(ADD_BLOCKED_CLIENT);
const [updateClient] = useMutation(UPDATE_CLIENT);
const handleAddClient = macAddress => {
addClient({
variables: {
customerId,
macAddress,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Client successfully added to Blocked List',
});
const handleAddClient = macAddress => {
addClient({
variables: {
customerId,
macAddress,
},
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Client could not be added to Blocked List',
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Client successfully added to Blocked List',
});
})
);
};
.catch(() =>
notification.error({
message: 'Error',
description: 'Client could not be added to Blocked List',
})
);
};
const handleUpdateClient = (macAddress, details) => {
updateClient({
variables: {
customerId,
macAddress,
details,
},
})
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Client successfully removed from Blocked List',
});
const handleUpdateClient = (macAddress, details) => {
updateClient({
variables: {
customerId,
macAddress,
details,
},
})
.catch(() =>
notification.error({
message: 'Error',
description: 'Client could not be removed from Blocked List',
.then(() => {
refetch();
notification.success({
message: 'Success',
description: 'Client successfully removed from Blocked List',
});
})
);
};
.catch(() =>
notification.error({
message: 'Error',
description: 'Client could not be removed from Blocked List',
})
);
};
if (loading) return <Loading />;
if (error)
return (
<Alert message="Error" description="Failed to load Client Data." type="error" showIcon />
<BlockedListPage
data={data && data.getBlockedClients}
onUpdateClient={handleUpdateClient}
onAddClient={handleAddClient}
/>
);
return (
<BlockedListPage
data={data && data.getBlockedClients}
onUpdateClient={handleUpdateClient}
onAddClient={handleAddClient}
/>
);
};
},
GET_BLOCKED_CLIENTS,
() => {
const { customerId } = useContext(UserContext);
return customerId;
}
);
export default BlockedList;

View File

@@ -1,167 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import { BrowserRouter as Router } from 'react-router-dom';
import UserProvider from 'contexts/UserProvider';
import { blockListMutationMock, blockListQueryMock } from './mock';
import BlockedList from '..';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<BlockedList />', () => {
afterEach(jest.resetModules);
it('should render with Data', async () => {
const { getByText } = render(
<MockedProvider mocks={[blockListQueryMock.success]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<BlockedList />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
});
it('should show error when Block query return error', async () => {
const { getByText } = render(
<MockedProvider mocks={[blockListQueryMock.error]} addTypename={false}>
<UserProvider {...mockProp}>
<Router>
<BlockedList />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('Failed to load Client Data.')).toBeVisible());
});
it('should render with Data and add Client successfully', async () => {
const { getByText, getByLabelText, getByRole } = render(
<MockedProvider
mocks={[
blockListQueryMock.success,
blockListQueryMock.success,
blockListMutationMock.addClientSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<BlockedList />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Add Client' }));
fireEvent.change(getByLabelText('MAC Address'), { target: { value: '74:8c:00:01:45:ae' } });
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() =>
expect(getByText('Client successfully added to Blocked List')).toBeVisible()
);
});
it('should render with Data and add Client return error when mutation not work', async () => {
const { getByText, getByLabelText, getByRole } = render(
<MockedProvider
mocks={[blockListQueryMock.success, blockListMutationMock.addClientError]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<BlockedList />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
fireEvent.click(getByRole('button', { name: 'Add Client' }));
fireEvent.change(getByLabelText('MAC Address'), { target: { value: '74:8c:00:01:45:ae' } });
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() =>
expect(getByText('Client could not be added to Blocked List')).toBeVisible()
);
});
it('should render with Data and update Client successfully', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
blockListQueryMock.success,
blockListQueryMock.success,
blockListMutationMock.updateClientSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<BlockedList />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
fireEvent.click(
getByRole('button', {
name: `delete-mac-74:9c:00:01:45:ae`,
})
);
fireEvent.click(getByRole('button', { name: 'Remove' }));
await waitFor(() =>
expect(getByText('Client successfully removed from Blocked List')).toBeVisible()
);
});
it('should render with Data and update Client return error when mutation not work', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
blockListQueryMock.success,
blockListQueryMock.success,
blockListMutationMock.updateClientError,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<BlockedList />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('74:9c:00:01:45:ae')).toBeVisible());
fireEvent.click(
getByRole('button', {
name: `delete-mac-74:9c:00:01:45:ae`,
})
);
fireEvent.click(getByRole('button', { name: 'Remove' }));
await waitFor(() =>
expect(getByText('Client could not be removed from Blocked List')).toBeVisible()
);
});
});

View File

@@ -1,189 +0,0 @@
import { ADD_BLOCKED_CLIENT, UPDATE_CLIENT } from 'graphql/mutations';
import { GET_BLOCKED_CLIENTS } from 'graphql/queries';
export const blockListQueryMock = {
success: {
request: {
query: GET_BLOCKED_CLIENTS,
variables: { customerId: 2 },
},
result: {
data: {
getBlockedClients: [
{
customerId: '2',
macAddress: '74:9c:00:01:45:ae',
createdTimestamp: '1597172802575',
lastModifiedTimestamp: '1597333913133',
details: {
model_type: 'ClientInfoDetails',
alias: 'alias 128213363803566',
clientType: 0,
apFingerprint: 'fp 74:9c:00:01:45:ae',
userName: 'user-128213363803566',
hostName: 'hostName-128213363803566',
lastUsedCpUsername: null,
lastUserAgent: null,
doNotSteer: false,
blocklistDetails: {
model_type: 'BlocklistDetails',
enabled: true,
startTime: null,
endTime: null,
},
},
__typename: 'Client',
},
],
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_BLOCKED_CLIENTS,
variables: { customerId: 2 },
},
result: {
data: null,
errors: [{}],
},
},
};
export const blockListMutationMock = {
addClientSuccess: {
request: {
query: ADD_BLOCKED_CLIENT,
variables: {
customerId: 2,
macAddress: '74:8c:00:01:45:ae',
},
},
result: {
data: {
addBlockedClient: {
customerId: '2',
macAddress: '74:8c:00:01:45:ae',
details: {
model_type: 'ClientInfoDetails',
alias: null,
clientType: 0,
apFingerprint: null,
userName: null,
hostName: null,
lastUsedCpUsername: null,
lastUserAgent: null,
doNotSteer: false,
blocklistDetails: {
model_type: 'BlocklistDetails',
enabled: true,
startTime: null,
endTime: null,
},
},
lastModifiedTimestamp: '1597334825157',
createdTimestamp: '1597334825157',
__typename: 'Client',
},
},
},
},
addClientError: {
request: {
query: ADD_BLOCKED_CLIENT,
},
result: {
data: null,
errors: [{}],
},
},
updateClientSuccess: {
request: {
query: UPDATE_CLIENT,
variables: {
customerId: 2,
macAddress: '74:9c:00:01:45:ae',
details: {
model_type: 'ClientInfoDetails',
alias: 'alias 128213363803566',
clientType: 0,
apFingerprint: 'fp 74:9c:00:01:45:ae',
userName: 'user-128213363803566',
hostName: 'hostName-128213363803566',
lastUsedCpUsername: null,
lastUserAgent: null,
doNotSteer: false,
blocklistDetails: {
model_type: 'BlocklistDetails',
enabled: false,
startTime: null,
endTime: null,
},
},
},
},
result: {
data: {
updateClient: {
customerId: '2',
macAddress: 'mac-74:9c:00:01:45:ae',
createdTimestamp: '0',
lastModifiedTimestamp: '1597336036972',
details: {
model_type: 'ClientInfoDetails',
alias: 'alias 128213363803566',
clientType: 0,
apFingerprint: 'fp 74:9c:00:01:45:ae',
userName: 'user-128213363803566',
hostName: 'hostName-128213363803566',
lastUsedCpUsername: null,
lastUserAgent: null,
doNotSteer: false,
blocklistDetails: {
model_type: 'BlocklistDetails',
enabled: false,
startTime: null,
endTime: null,
},
},
__typename: 'Client',
},
},
},
},
updateClientError: {
request: {
query: UPDATE_CLIENT,
variables: {
customerId: 2,
macAddress: '74:9c:00:01:45:ae',
details: {
model_type: 'ClientInfoDetails',
alias: 'alias 128213363803566',
clientType: 0,
apFingerprint: 'fp 74:9c:00:01:45:ae',
userName: 'user-128213363803566',
hostName: 'hostName-128213363803566',
lastUsedCpUsername: null,
lastUserAgent: null,
doNotSteer: false,
blocklistDetails: {
model_type: 'BlocklistDetails',
enabled: false,
startTime: null,
endTime: null,
},
},
},
},
result: {
data: null,
errors: [{}],
},
},
};

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { useQuery, useMutation, useLazyQuery } from '@apollo/react-hooks';
import { useQuery, useMutation, useLazyQuery } from '@apollo/client';
import { notification } from 'antd';
import {
GET_ALL_FIRMWARE,
@@ -83,8 +83,18 @@ const Firmware = () => {
firmwareVersionRecordId,
modelId,
createdTimestamp,
lastModifiedTimestamp
lastModifiedTimestamp,
prevFirmwareVersionRecordId
) => {
if (prevFirmwareVersionRecordId !== firmwareVersionRecordId) {
deleteTrackAssignment({
variables: {
firmwareTrackId: firmwareTrackData.getFirmwareTrack.recordId,
firmwareVersionId: prevFirmwareVersionRecordId,
},
});
}
updateTrackAssignment({
variables: {
trackRecordId: firmwareTrackData.getFirmwareTrack.recordId,

View File

@@ -1,119 +0,0 @@
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/react-testing';
import { BrowserRouter as Router } from 'react-router-dom';
import UserProvider from 'contexts/UserProvider';
import { firmwareMutationMock, firmwareQueryMock } from './mock';
import Firmware from '..';
const {
getAllFirmwareModelsSuccess,
getAllFirmwareSuccess,
getFirmwareTrackAssignmentSuccess,
getFirmwareTrackSuccess,
} = firmwareQueryMock;
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
const mockProp = {
id: 123,
email: 'test@test.com',
role: 'admin',
customerId: 2,
updateUser: jest.fn(),
updateToken: jest.fn(),
};
describe('<Firmware />', () => {
afterEach(jest.resetModules);
it('should render with Data', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
getAllFirmwareModelsSuccess,
getAllFirmwareSuccess,
getFirmwareTrackAssignmentSuccess,
getFirmwareTrackSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Firmware />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('ap2220-2020-06-25-ce03472')).toBeVisible());
});
it('should render with Data and Edit Model Target successfully', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
getAllFirmwareModelsSuccess,
getAllFirmwareSuccess,
getFirmwareTrackAssignmentSuccess,
getFirmwareTrackAssignmentSuccess,
getFirmwareTrackSuccess,
firmwareMutationMock.updateTrackAssignmentSuccess,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Firmware />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('ap2220-2020-06-25-ce03472')).toBeVisible());
fireEvent.click(getByRole('button', { name: `edit-track-ap2220` }));
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() =>
expect(getByText('Model Target Version successfully updated.')).toBeVisible()
);
});
it('should render with Data and Edit Model Target show error when mutation not work ', async () => {
const { getByText, getByRole } = render(
<MockedProvider
mocks={[
getAllFirmwareModelsSuccess,
getAllFirmwareSuccess,
getFirmwareTrackAssignmentSuccess,
getFirmwareTrackAssignmentSuccess,
getFirmwareTrackSuccess,
firmwareMutationMock.updateTrackAssignmentError,
]}
addTypename={false}
>
<UserProvider {...mockProp}>
<Router>
<Firmware />
</Router>
</UserProvider>
</MockedProvider>
);
await waitFor(() => expect(getByText('ap2220-2020-06-25-ce03472')).toBeVisible());
fireEvent.click(getByRole('button', { name: `edit-track-ap2220` }));
fireEvent.click(getByRole('button', { name: 'Save' }));
await waitFor(() =>
expect(getByText('Model Target Version could not be updated.')).toBeVisible()
);
});
});

View File

@@ -1,223 +0,0 @@
import { UPDATE_TRACK_ASSIGNMENT } from 'graphql/mutations';
import {
GET_ALL_FIRMWARE,
GET_ALL_FIRMWARE_MODELS,
GET_FIRMWARE_TRACK,
GET_TRACK_ASSIGNMENTS,
} from 'graphql/queries';
export const firmwareQueryMock = {
getAllFirmwareSuccess: {
request: {
query: GET_ALL_FIRMWARE,
},
result: {
data: {
getAllFirmware: [
{
id: '1',
modelId: 'ap2220',
versionName: 'ap2220-2020-06-25-ce03472',
description: '',
filename:
'https://tip-read:tip-read@tip.jfrog.io/artifactory/tip-wlan-ap-firmware/ap2220/ap2220-2020-06-25-ce03472.tar.gz',
commit: 'ce03472',
releaseDate: '1597329017106',
validationCode: 'c69370aa5b6622d91a0fba3a5441f31c',
createdTimestamp: '1597329017115',
lastModifiedTimestamp: '1597329017115',
__typename: 'Firmware',
},
{
id: '2',
modelId: 'ea8300',
versionName: 'ea8300-2020-06-25-ce03472',
description: '',
filename:
'https://tip-read:tip-read@tip-read:tip-read@tip.jfrog.io/artifactory/tip-wlan-ap-firmware/ea8300/ea8300-2020-06-25-ce03472.tar.gz',
commit: 'ce03472',
releaseDate: '1597329017115',
validationCode: 'b209deb9847bdf40a31e45edf2e5a8d7',
createdTimestamp: '1597329017115',
lastModifiedTimestamp: '1597329017115',
__typename: 'Firmware',
},
{
id: '3',
modelId: 'ea8300-ca',
versionName: 'ea8300-2020-06-25-ce03472',
description: '',
filename:
'https://tip-read:tip-read@tip.jfrog.io/artifactory/tip-wlan-ap-firmware/ea8300/ea8300-2020-06-25-ce03472.tar.gz',
commit: 'ce03472',
releaseDate: '1597329017115',
validationCode: 'b209deb9847bdf40a31e45edf2e5a8d7',
createdTimestamp: '1597329017115',
lastModifiedTimestamp: '1597329017115',
__typename: 'Firmware',
},
{
id: '4',
modelId: 'ecw5211',
versionName: 'ecw5211-2020-06-26-4ff7208',
description: '',
filename:
'https://tip-read:tip-read@tip.jfrog.io/artifactory/tip-wlan-ap-firmware/ecw5211/ecw5211-2020-06-26-4ff7208.tar.gz',
commit: '4ff7208',
releaseDate: '1597329017115',
validationCode: '133072b0e8a440063109604375938fba',
createdTimestamp: '1597329017115',
lastModifiedTimestamp: '1597329017115',
__typename: 'Firmware',
},
{
id: '5',
modelId: 'ecw5410',
versionName: 'ecw5410-2020-06-25-ce03472',
description: '',
filename:
'https://tip-read:tip-read@tip.jfrog.io/artifactory/tip-wlan-ap-firmware/ecw5410/ecw5410-2020-06-25-ce03472.tar.gz',
commit: 'ce03472',
releaseDate: '1597329017115',
validationCode: '2940ca34eeab85be18f3a4b79f4da6d9',
createdTimestamp: '1597329017115',
lastModifiedTimestamp: '1597329017115',
__typename: 'Firmware',
},
],
},
loading: false,
networkStatus: 7,
stale: false,
},
},
getAllFirmwareModelsSuccess: {
request: {
query: GET_ALL_FIRMWARE_MODELS,
},
result: {
data: {
getAllFirmwareModelId: ['ea8300-ca', 'ap2220', 'ecw5211', 'ea8300', 'ecw5410'],
},
loading: false,
networkStatus: 7,
stale: false,
},
},
getFirmwareTrackAssignmentSuccess: {
request: {
query: GET_TRACK_ASSIGNMENTS,
},
result: {
data: {
getAllFirmwareTrackAssignment: [
{
modelId: 'ap2220',
firmwareVersionRecordId: '1',
trackRecordId: '1',
lastModifiedTimestamp: '1597342689340',
__typename: 'FirmwareTrackAssignment',
},
{
modelId: 'ea8300',
firmwareVersionRecordId: '2',
trackRecordId: '1',
lastModifiedTimestamp: '1597172802693',
__typename: 'FirmwareTrackAssignment',
},
{
modelId: 'ea8300-ca',
firmwareVersionRecordId: '3',
trackRecordId: '1',
lastModifiedTimestamp: '1597172802693',
__typename: 'FirmwareTrackAssignment',
},
{
modelId: 'ecw5211',
firmwareVersionRecordId: '4',
trackRecordId: '1',
lastModifiedTimestamp: '1597172802693',
__typename: 'FirmwareTrackAssignment',
},
],
},
loading: false,
networkStatus: 7,
stale: false,
},
},
getFirmwareTrackSuccess: {
request: {
query: GET_FIRMWARE_TRACK,
variables: { firmwareTrackName: 'DEFAULT' },
},
result: {
data: {
getFirmwareTrack: {
recordId: '1',
trackName: 'DEFAULT',
createdTimestamp: '1597329017117',
lastModifiedTimestamp: '1597329017117',
__typename: 'FirmwareTrack',
},
},
loading: false,
networkStatus: 7,
stale: false,
},
},
error: {
request: {
query: GET_FIRMWARE_TRACK,
variables: { customerId: 2 },
},
result: {
data: null,
errors: [{}],
},
},
};
export const firmwareMutationMock = {
updateTrackAssignmentSuccess: {
request: {
query: UPDATE_TRACK_ASSIGNMENT,
variables: {
trackRecordId: '1',
firmwareVersionRecordId: '1',
modelId: 'ap2220',
lastModifiedTimestamp: '1597342689340',
},
},
result: {
data: {
updateFirmwareTrackAssignment: {
trackRecordId: '1',
firmwareVersionRecordId: '1',
modelId: 'ap2220',
createdTimestamp: '0',
lastModifiedTimestamp: '1597342689340',
__typename: 'FirmwareTrackAssignment',
},
},
},
},
updateTrackAssignmentError: {
request: {
query: UPDATE_TRACK_ASSIGNMENT,
variables: {
trackRecordId: '1',
firmwareVersionRecordId: '1',
modelId: 'ap2220',
lastModifiedTimestamp: '1597342689340',
},
},
result: {
data: null,
errors: [{}],
},
},
};

View File

@@ -1,9 +1,11 @@
import React from 'react';
import gql from 'graphql-tag';
import { useMutation, useLazyQuery } from '@apollo/react-hooks';
import React, { useState } from 'react';
import { useQuery, useMutation, useLazyQuery, gql } from '@apollo/client';
import { notification } from 'antd';
import { Manufacturer as ManufacturerPage } from '@tip-wlan/wlan-cloud-ui-library';
import { OUI_UPLOAD } from 'graphql/mutations';
import { AUTH_TOKEN } from 'constants/index';
import { GET_API_URL } from 'graphql/queries';
import { getItem } from 'utils/localStorage';
const GET_OUI = gql`
query GetOui($oui: String!) {
@@ -28,7 +30,12 @@ const UPDATE_OUI = gql`
}
}
`;
const System = () => {
const token = getItem(AUTH_TOKEN);
const [loadingFileUpload, setLoadingFileUpload] = useState(false);
const { data: apiUrl } = useQuery(GET_API_URL);
const [updateOUI] = useMutation(UPDATE_OUI);
const [searchOUI, { data }] = useLazyQuery(GET_OUI, {
onError: () => {
@@ -37,8 +44,16 @@ const System = () => {
description: 'No matching manufacturer found for OUI',
});
},
onCompleted: () => {
if (!data?.getOui?.oui) {
notification.error({
message: 'Error',
description: 'No matching manufacturer found for OUI',
});
}
},
fetchPolicy: 'no-cache',
});
const [fileUpload] = useMutation(OUI_UPLOAD);
const handleUpdateOUI = (oui, manufacturerAlias, manufacturerName) => {
updateOUI({
@@ -66,33 +81,54 @@ const System = () => {
searchOUI({ variables: { oui } });
};
const handleFileUpload = (fileName, file) =>
fileUpload({ variables: { fileName, file } })
.then(resp => {
if (resp?.ouiUpload?.success) {
notification.success({
message: 'Success',
description: 'File successfully uploaded.',
});
} else {
const handleFileUpload = (fileName, file) => {
if (apiUrl?.getApiUrl) {
setLoadingFileUpload(true);
fetch(`${apiUrl?.getApiUrl}portal/manufacturer/oui/upload?fileName=${fileName}`, {
method: 'POST',
headers: {
Authorization: token ? `Bearer ${token.access_token}` : '',
'Content-Type': 'application/octet-stream',
},
body: file,
})
.then(response => response.json())
.then(resp => {
if (resp?.success) {
notification.success({
message: 'Success',
description: 'File successfully uploaded.',
});
} else {
notification.error({
message: 'Error',
description: 'File could not be uploaded.',
});
}
})
.catch(() => {
notification.error({
message: 'Error',
description: 'File could not be uploaded.',
});
}
})
.catch(() =>
notification.error({
message: 'Error',
description: 'File could not be uploaded.',
})
);
.finally(() => setLoadingFileUpload(false));
} else {
notification.error({
message: 'Error',
description: 'File could not be uploaded.',
});
}
};
return (
<ManufacturerPage
onSearchOUI={handleSearchOUI}
onUpdateOUI={handleUpdateOUI}
returnedOUI={data && data.getOui}
fileUpload={handleFileUpload}
loadingFileUpload={loadingFileUpload}
/>
);
};

12
app/graphql/functions.js Normal file
View File

@@ -0,0 +1,12 @@
export const updateQueryGetAllProfiles = (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.getAllProfiles;
const newItems = fetchMoreResult.getAllProfiles.items;
return {
getAllProfiles: {
context: { ...fetchMoreResult.getAllProfiles.context },
items: [...previousEntry.items, ...newItems],
__typename: previousEntry.__typename,
},
};
};

View File

@@ -1,4 +1,4 @@
import gql from 'graphql-tag';
import { gql } from '@apollo/client';
export const REFRESH_TOKEN = gql`
mutation UpdateToken($refreshToken: String!) {
@@ -10,167 +10,6 @@ export const REFRESH_TOKEN = gql`
}
`;
export const AUTHENTICATE_USER = gql`
mutation AuthenticateUser($email: String!, $password: String!) {
authenticateUser(email: $email, password: $password) {
access_token
refresh_token
expires_in
}
}
`;
export const UPDATE_PROFILE = gql`
mutation UpdateProfile(
$id: ID!
$profileType: String!
$customerId: ID!
$name: String!
$childProfileIds: [ID]
$lastModifiedTimestamp: String
$details: JSONObject
) {
updateProfile(
id: $id
profileType: $profileType
customerId: $customerId
name: $name
childProfileIds: $childProfileIds
lastModifiedTimestamp: $lastModifiedTimestamp
details: $details
) {
id
profileType
customerId
name
childProfileIds
lastModifiedTimestamp
details
}
}
`;
export const UPDATE_USER = gql`
mutation UpdateUser(
$id: ID!
$username: String!
$password: String!
$role: String!
$customerId: ID!
$lastModifiedTimestamp: String
) {
updateUser(
id: $id
username: $username
password: $password
role: $role
customerId: $customerId
lastModifiedTimestamp: $lastModifiedTimestamp
) {
id
username
role
customerId
lastModifiedTimestamp
}
}
`;
export const UPDATE_EQUIPMENT = gql`
mutation UpdateEquipment(
$id: ID!
$equipmentType: String!
$inventoryId: String!
$customerId: ID!
$profileId: ID!
$locationId: ID!
$name: String!
$latitude: String
$longitude: String
$serial: String
$lastModifiedTimestamp: String
$details: JSONObject
) {
updateEquipment(
id: $id
equipmentType: $equipmentType
inventoryId: $inventoryId
customerId: $customerId
profileId: $profileId
locationId: $locationId
name: $name
latitude: $latitude
longitude: $longitude
serial: $serial
lastModifiedTimestamp: $lastModifiedTimestamp
details: $details
) {
id
equipmentType
inventoryId
customerId
profileId
locationId
name
latitude
longitude
serial
lastModifiedTimestamp
details
}
}
`;
export const DELETE_PROFILE = gql`
mutation DeleteProfile($id: ID!) {
deleteProfile(id: $id) {
id
}
}
`;
export const CREATE_PROFILE = gql`
mutation CreateProfile(
$profileType: String!
$customerId: ID!
$name: String!
$childProfileIds: [ID]
$details: JSONObject
) {
createProfile(
profileType: $profileType
customerId: $customerId
name: $name
childProfileIds: $childProfileIds
details: $details
) {
profileType
customerId
name
childProfileIds
details
}
}
`;
export const CREATE_USER = gql`
mutation CreateUser($username: String!, $password: String!, $role: String!, $customerId: ID!) {
createUser(username: $username, password: $password, role: $role, customerId: $customerId) {
username
role
customerId
}
}
`;
export const DELETE_USER = gql`
mutation DeleteUser($id: ID!) {
deleteUser(id: $id) {
id
}
}
`;
export const CREATE_LOCATION = gql`
mutation CreateLocation(
$locationType: String!
@@ -260,6 +99,22 @@ export const UPDATE_EQUIPMENT_FIRMWARE = gql`
}
`;
export const REQUEST_EQUIPMENT_SWITCH_BANK = gql`
mutation RequestEquipmentSwitchBank($equipmentId: ID) {
requestEquipmentSwitchBank(equipmentId: $equipmentId) {
success
}
}
`;
export const REQUEST_EQUIPMENT_REBOOT = gql`
mutation RequestEquipmentReboot($equipmentId: ID) {
requestEquipmentReboot(equipmentId: $equipmentId) {
success
}
}
`;
export const UPDATE_TRACK_ASSIGNMENT = gql`
mutation UpdateFirmwareTrackAssignment(
$trackRecordId: ID!

View File

@@ -1,168 +1,8 @@
import gql from 'graphql-tag';
import { gql } from '@apollo/client';
export const GET_PROFILE = gql`
query GetProfile($id: ID!) {
getProfile(id: $id) {
id
profileType
customerId
name
childProfiles {
id
name
profileType
details
}
childProfileIds
createdTimestamp
lastModifiedTimestamp
details
}
}
`;
export const GET_USER = gql`
query GetUser($id: ID!) {
getUser(id: $id) {
id
username
role
customerId
lastModifiedTimestamp
}
}
`;
export const GET_EQUIPMENT = gql`
query GetEquipment($id: ID!) {
getEquipment(id: $id) {
id
equipmentType
inventoryId
customerId
profileId
locationId
name
latitude
longitude
serial
lastModifiedTimestamp
details
profile {
id
name
childProfiles {
id
name
details
}
}
status {
firmware {
detailsJSON
}
protocol {
detailsJSON
details {
reportedMacAddr
manufacturer
}
}
radioUtilization {
detailsJSON
}
clientDetails {
detailsJSON
details {
numClientsPerRadio
}
}
osPerformance {
detailsJSON
}
}
model
alarmsCount
alarms {
severity
alarmCode
details
createdTimestamp
}
}
}
`;
export const GET_ALL_FIRMWARE = gql`
query GetAllFirmware($modelId: String) {
getAllFirmware(modelId: $modelId) {
id
modelId
versionName
description
filename
commit
releaseDate
validationCode
createdTimestamp
lastModifiedTimestamp
}
}
`;
export const GET_ALL_PROFILES = gql`
query GetAllProfiles($customerId: ID!, $cursor: String, $type: String) {
getAllProfiles(customerId: $customerId, cursor: $cursor, type: $type) {
items {
id
name
profileType
details
}
context {
cursor
lastPage
}
}
}
`;
export const GET_ALL_ALARMS = gql`
query GetAllAlarms($customerId: ID!, $cursor: String) {
getAllAlarms(customerId: $customerId, cursor: $cursor) {
items {
severity
alarmCode
details
createdTimestamp
equipment {
id
name
}
}
context {
cursor
lastPage
}
}
}
`;
export const GET_ALL_USERS = gql`
query GetAllUsers($customerId: ID!, $cursor: String) {
getAllUsers(customerId: $customerId, cursor: $cursor) {
items {
id
email: username
role
lastModifiedTimestamp
customerId
}
context {
cursor
lastPage
}
}
export const GET_API_URL = gql`
query GetApiUrl {
getApiUrl
}
`;
@@ -182,13 +22,13 @@ export const FILTER_EQUIPMENT = gql`
$locationIds: [ID]
$customerId: ID!
$equipmentType: String
$cursor: String
$context: JSONObject
) {
filterEquipment(
customerId: $customerId
locationIds: $locationIds
equipmentType: $equipmentType
cursor: $cursor
context: $context
) {
items {
name
@@ -227,12 +67,12 @@ export const FILTER_EQUIPMENT = gql`
numClientsPerRadio
}
}
firmware {
detailsJSON
}
}
}
context {
lastPage
cursor
}
context
}
}
`;
@@ -242,13 +82,13 @@ export const FILTER_EQUIPMENT_BULK_EDIT_APS = gql`
$locationIds: [ID]
$customerId: ID!
$equipmentType: String
$cursor: String
$context: JSONObject
) {
filterEquipment(
customerId: $customerId
locationIds: $locationIds
equipmentType: $equipmentType
cursor: $cursor
context: $context
) {
items {
name
@@ -257,10 +97,7 @@ export const FILTER_EQUIPMENT_BULK_EDIT_APS = gql`
channel
details
}
context {
lastPage
cursor
}
context
}
}
`;
@@ -278,8 +115,8 @@ export const GET_LOCATION = gql`
`;
export const FILTER_CLIENT_SESSIONS = gql`
query FilterClientSessions($customerId: ID!, $locationIds: [ID], $cursor: String) {
filterClientSessions(customerId: $customerId, locationIds: $locationIds, cursor: $cursor) {
query FilterClientSessions($customerId: ID!, $locationIds: [ID], $context: JSONObject) {
filterClientSessions(customerId: $customerId, locationIds: $locationIds, context: $context) {
items {
id
macAddress
@@ -289,14 +126,12 @@ export const FILTER_CLIENT_SESSIONS = gql`
radioType
signal
manufacturer
details
equipment {
name
}
}
context {
lastPage
cursor
}
context
}
}
`;
@@ -323,7 +158,7 @@ export const GET_CLIENT_SESSION = gql`
export const FILTER_SERVICE_METRICS = gql`
query FilterServiceMetrics(
$customerId: ID!
$cursor: String
$context: JSONObject
$fromTime: String!
$toTime: String!
$clientMacs: [String]
@@ -333,7 +168,7 @@ export const FILTER_SERVICE_METRICS = gql`
) {
filterServiceMetrics(
customerId: $customerId
cursor: $cursor
context: $context
fromTime: $fromTime
toTime: $toTime
clientMacs: $clientMacs
@@ -349,10 +184,34 @@ export const FILTER_SERVICE_METRICS = gql`
txBytes
detailsJSON
}
context {
lastPage
cursor
context
}
}
`;
export const GET_ALL_PROFILES = (fields = '') => gql`
query GetAllProfiles(
$customerId: ID!
$cursor: String
$limit: Int
$type: String
$context: JSONObject
) {
getAllProfiles(
customerId: $customerId
cursor: $cursor
limit: $limit
type: $type
context: $context
) {
items {
id
name
profileType
details
${fields}
}
context
}
}
`;
@@ -368,10 +227,7 @@ export const GET_ALL_STATUS = gql`
clientCountPerOui
}
}
context {
lastPage
cursor
}
context
}
}
`;
@@ -393,6 +249,23 @@ export const GET_FIRMWARE_TRACK = gql`
}
`;
export const GET_ALL_FIRMWARE = gql`
query GetAllFirmware($modelId: String) {
getAllFirmware(modelId: $modelId) {
id
modelId
versionName
description
filename
commit
releaseDate
validationCode
createdTimestamp
lastModifiedTimestamp
}
}
`;
export const GET_TRACK_ASSIGNMENTS = gql`
query GetAllFirmwareTrackAssignment {
getAllFirmwareTrackAssignment {
@@ -430,7 +303,7 @@ export const FILTER_SYSTEM_EVENTS = gql`
$toTime: String!
$equipmentIds: [ID]
$dataTypes: [String]
$cursor: String
$context: JSONObject
$limit: Int
) {
filterSystemEvents(
@@ -439,14 +312,11 @@ export const FILTER_SYSTEM_EVENTS = gql`
toTime: $toTime
dataTypes: $dataTypes
equipmentIds: $equipmentIds
cursor: $cursor
context: $context
limit: $limit
) {
items
context {
lastPage
cursor
}
context
}
}
`;

View File

@@ -1,12 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { Router } from 'react-router-dom';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { onError } from 'apollo-link-error';
import { ApolloClient, ApolloProvider, ApolloLink, Observable } from '@apollo/client';
import { InMemoryCache } from '@apollo/client/cache';
import { onError } from '@apollo/client/link/error';
import { createUploadLink } from 'apollo-upload-client';
import { ApolloLink, Observable } from 'apollo-link';
import { ApolloProvider } from '@apollo/react-hooks';
import 'styles/antd.less';
import 'styles/index.scss';
@@ -17,14 +15,13 @@ import { REFRESH_TOKEN } from 'graphql/mutations';
import { getItem, setItem, removeItem } from 'utils/localStorage';
import history from 'utils/history';
const API_URI =
process.env.NODE_ENV === 'development' ? 'http://localhost:4000/' : window.REACT_APP_API;
const API_URI = process.env.NODE_ENV === 'production' ? window.REACT_APP_API : process.env.API;
const MOUNT_NODE = document.getElementById('root');
const cache = new InMemoryCache();
const uploadLink = createUploadLink({
uri: API_URI,
uri: `${API_URI}/graphql`,
});
const request = async operation => {

6326
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "wlan-cloud-ui",
"version": "0.2.9",
"version": "0.5.3",
"author": "ConnectUs",
"description": "React Portal",
"engines": {
@@ -10,6 +10,8 @@
"scripts": {
"test": "jest --passWithNoTests --coverage",
"start": "cross-env NODE_ENV=development webpack-dev-server",
"start:bare": "cross-env API=https://wlan-graphql.zone3.lab.connectus.ai NODE_ENV=bare webpack-dev-server",
"start:dev": "cross-env API=https://wlan-graphql.qa.lab.wlan.tip.build NODE_ENV=development webpack-dev-server",
"build": "webpack --mode=production",
"format": "prettier --write \"app/**/*.js\"",
"eslint-fix": "eslint --fix \"app/**/*.js\"",
@@ -18,20 +20,13 @@
"license": "MIT",
"dependencies": {
"@ant-design/icons": "^4.2.1",
"@apollo/react-hoc": "^3.1.4",
"@apollo/react-hooks": "^3.1.3",
"@tip-wlan/wlan-cloud-ui-library": "^0.2.9",
"antd": "^4.3.1",
"apollo-cache-inmemory": "^1.6.6",
"apollo-client": "^2.6.10",
"apollo-link": "^1.2.14",
"apollo-link-error": "^1.1.13",
"apollo-link-http": "^1.5.17",
"@apollo/client": "^3.1.3",
"@tip-wlan/wlan-cloud-ui-library": "^0.3.16",
"antd": "^4.5.2",
"apollo-upload-client": "^13.0.0",
"clean-webpack-plugin": "^3.0.0",
"graphql": "^14.6.0",
"graphql-tag": "^2.10.3",
"highcharts": "^8.1.1",
"highcharts": "^8.1.0",
"highcharts-react-official": "^3.0.0",
"history": "^4.10.1",
"html-webpack-plugin": "^3.2.0",
@@ -49,13 +44,10 @@
"terser-webpack-plugin": "^2.3.5"
},
"devDependencies": {
"@apollo/react-testing": "3.0.0",
"@babel/core": "^7.8.7",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/preset-env": "^7.8.7",
"@babel/preset-react": "^7.8.3",
"@testing-library/dom": "^7.22.1",
"@testing-library/jest-dom": "^5.11.2",
"@testing-library/react": "^10.0.3",
"babel-core": "^6.26.3",
"babel-eslint": "^10.1.0",

View File

@@ -4,6 +4,7 @@ const common = require('./webpack/webpack.common');
const envs = {
development: 'dev',
production: 'prod',
bare: 'bare',
};
/* eslint-disable global-require,import/no-dynamic-require */
const env = envs[process.env.NODE_ENV || 'production'];

73
webpack/webpack.bare.js Normal file
View File

@@ -0,0 +1,73 @@
const path = require('path');
const commonPaths = require('./paths');
module.exports = {
mode: 'development',
output: {
path: commonPaths.outputPath,
publicPath: '/',
filename: '[name].js',
chunkFilename: '[name].js',
},
devtool: 'inline-source-map',
devServer: {
port: 3000,
historyApiFallback: true,
contentBase: commonPaths.outputPath,
},
module: {
rules: [
{
test: /\.(css|scss)$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
modules: {
localIdentName: '[name]__[local]___[hash:base64:5]',
},
sourceMap: true,
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
{
test: /\.less$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'less-loader', // compiles Less to CSS
options: {
lessOptions: {
javascriptEnabled: true,
},
},
},
],
},
],
},
resolve: {
modules: ['node_modules', 'app'],
alias: {
app: path.resolve(__dirname, '../', 'app'),
react: path.resolve(__dirname, '../', 'node_modules', 'react'),
'react-router-dom': path.resolve('./node_modules/react-router-dom'),
},
},
};

View File

@@ -22,23 +22,6 @@ module.exports = {
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'],
},
{
test: /\.less$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'less-loader',
options: {
javascriptEnabled: true,
},
},
],
},
],
},
plugins: [
@@ -47,7 +30,7 @@ module.exports = {
favicon: './app/images/favicon.ico',
}),
new webpack.DefinePlugin({
'process.env.GRAPHQL_URL': JSON.stringify(process.env.GRAPHQL_URL),
'process.env.API': JSON.stringify(process.env.API || 'http://localhost:4000'),
}),
],
};

View File

@@ -34,6 +34,26 @@ module.exports = {
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
{
test: /\.less$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'less-loader', // compiles Less to CSS
options: {
javascriptEnabled: true,
},
},
],
},

View File

@@ -14,6 +14,7 @@ module.exports = {
chunkFilename: `${commonPaths.jsFolder}/[name].[chunkhash].js`,
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
// Use multi-process parallel running to improve the build speed
@@ -67,6 +68,21 @@ module.exports = {
'sass-loader',
],
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
{
loader: 'less-loader', // compiles Less to CSS
options: {
javascriptEnabled: true,
},
},
],
},
],
},
resolve: {