├── .circleci ├── config.yml └── load-nvm.sh ├── .dockerignore ├── .env ├── .env.test ├── .gitignore ├── Dockerfile ├── LICENSE.md ├── README.md ├── _wait-for-services.sh ├── babel.config.js ├── build-and-test-all.sh ├── docker-compose.yml ├── ensure-variables-and-paths.sh ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── run-tests.sh ├── server ├── .dockerignore ├── .env ├── .gitignore ├── Dockerfile ├── LICENSE ├── Procfile ├── README.md ├── babel.config.js ├── package-lock.json ├── package.json └── src │ ├── api │ ├── address.js │ ├── cache.js │ ├── cart.js │ ├── index.js │ ├── payment.js │ ├── paymentIntentResponse.js │ └── restaurant.js │ ├── config.js │ ├── db.js │ ├── index.js │ ├── lib │ └── util.js │ ├── middleware │ └── index.js │ └── models │ ├── address.js │ └── menu.js ├── src ├── __mocks__ │ ├── fileMock.js │ └── styleMock.js ├── app │ ├── index.css │ ├── rootNode.js │ └── store.js ├── features │ ├── actions │ │ ├── api.js │ │ ├── api.test.js │ │ └── navigation.js │ ├── address │ │ ├── addressAPI.test.js │ │ ├── addressSlice.js │ │ └── addressSlice.test.js │ ├── card │ │ └── cardSlice.js │ ├── cart │ │ └── cartSlice.js │ ├── index.js │ ├── restaurants │ │ ├── restaurantsSlice.js │ │ └── restaurantsSlice.test.js │ └── ui │ │ └── loadingSlice.js ├── index.js ├── jest.config.js ├── serviceWorker.js ├── setupTests.js ├── shared │ ├── diagnostics │ │ └── index.js │ ├── e2e │ │ ├── e2e.test.js │ │ ├── helpers.js │ │ └── index.js │ ├── email │ │ ├── email.test.js │ │ └── index.js │ ├── env │ │ ├── env.test.js │ │ ├── envGetter.js │ │ └── index.js │ ├── forms │ │ ├── submissionHandling.js │ │ └── submissionHandling.test.js │ └── promises │ │ ├── index.js │ │ └── promises.test.js ├── testability │ ├── index.js │ └── selectors.js ├── ui │ ├── components │ │ ├── SelectedAddressRow.js │ │ └── SelectedRestaurantRow.js │ ├── elements │ │ ├── Loading.js │ │ ├── Snippet │ │ │ ├── Snippet.test.js │ │ │ ├── index.js │ │ │ └── snippet.scss │ │ ├── conditions.js │ │ ├── errorBoundary.js │ │ ├── errorBoundary.test.js │ │ ├── formElements.js │ │ ├── icons.js │ │ ├── icons.module.scss │ │ ├── paginatedTable.js │ │ ├── reactBootstrapTableCustomization.scss │ │ └── textElements.js │ └── pages │ │ ├── AppLayout │ │ ├── AppLayout.test.js │ │ ├── RootRoutes.js │ │ ├── appLayout.css │ │ └── index.js │ │ ├── AppRoutes │ │ ├── index.js │ │ └── routePaths.js │ │ ├── CheckoutPage │ │ ├── cardElement.js │ │ ├── checkoutForm.js │ │ ├── checkoutForm.scss │ │ ├── index.js │ │ ├── orderInfo.js │ │ └── paymentModal.js │ │ ├── LandingPage │ │ ├── index.js │ │ ├── landingPageForm.js │ │ └── landingPageForm.test.js │ │ ├── LoginPage │ │ └── index.js │ │ ├── RestaurantListPage │ │ └── index.js │ │ ├── RestaurantPage │ │ ├── hooks.js │ │ ├── index.js │ │ ├── menuItems.js │ │ └── yourTrayItems.js │ │ └── ThankYouPage │ │ └── index.js └── window.setup.js ├── start-http-server.sh ├── test-docker-image.sh ├── tests-ui ├── browserSetup.js ├── comprehensive.spec.js ├── ensure_env.js ├── envLoader.js ├── helpers │ └── index.js ├── jest.config.js ├── jest.dev.config.json ├── jest.setup.js ├── navigation.js ├── pages │ ├── checkout.js │ ├── landing.js │ ├── navigation.js │ ├── pageComponents.js │ ├── restaurantMenu.js │ ├── restaurantsList.js │ ├── thankYou.js │ └── utilities.js ├── puppeteerExtensions.js ├── reporters │ ├── .gitignore │ ├── defaultNotifier.js │ ├── defaultReporter.js │ └── utilities.js ├── selectors.js ├── testInfoProvider.js └── testWrapper.js └── wait-for-services.sh /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | machine: true 5 | working_directory: ~/ftgo-consumer-web-ui 6 | steps: 7 | - checkout 8 | - run: 9 | name: Install Node v12.22.1 10 | command: | 11 | . ./.circleci/load-nvm.sh 12 | nvm install v12.22.1 13 | nvm alias default v12.22.1 14 | - run: 15 | name: Install dependencies 16 | command: | 17 | sudo apt-get update 18 | sudo apt-get install -y libgbm-dev 19 | - run: 20 | command: | 21 | . ./.circleci/load-nvm.sh 22 | export CI_ARTIFACTS_PATH=~/ftgo-consumer-web-ui/ci-artifacts 23 | export JEST_JUNIT_OUTPUT_DIR_PARENT=~/ftgo-consumer-web-ui/reports 24 | ./build-and-test-all.sh 25 | - run: 26 | command: | 27 | export FTGO_BACKEND_API_URL=http://localhost:8080 28 | ./test-docker-image.sh 29 | - run: 30 | command: | 31 | . ./.circleci/load-nvm.sh 32 | export TEST_UI_URL=http://localhost:5000 33 | npm run test-ui 34 | - store_test_results: 35 | path: ~/ftgo-consumer-web-ui/reports 36 | - store_artifacts: 37 | path: ~/ftgo-consumer-web-ui/ci-artifacts 38 | -------------------------------------------------------------------------------- /.circleci/load-nvm.sh: -------------------------------------------------------------------------------- 1 | export NVM_DIR="/opt/circleci/.nvm" 2 | [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" 3 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .circleci 2 | build 3 | ci-artifacts 4 | node_modules 5 | reports 6 | server 7 | -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | GENERATE_SOURCEMAP=false 2 | XREACT_APP_BACKEND_API_URL= 3 | REACT_APP_STRIPE_PK_KEY= 4 | -------------------------------------------------------------------------------- /.env.test: -------------------------------------------------------------------------------- 1 | TEST_UI_DIMENSIONS=1200x800 2 | FTGO_TEST_EMAIL_ADDRESS=dart.andrew.revinsky@gmail.com 3 | FTGO_ENV= 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # IDE 4 | /.idea/ 5 | 6 | # dependencies 7 | node_modules 8 | 9 | # testing 10 | /reports/ 11 | /build/ 12 | coverage/ 13 | /junit.xml 14 | 15 | # production 16 | ./build 17 | 18 | # misc 19 | .DS_Store 20 | .env.local 21 | .env.development.local 22 | .env.test.local 23 | .env.production.local 24 | 25 | npm-debug.log* 26 | yarn-debug.log* 27 | yarn-error.log* 28 | 29 | #research memos 30 | /memo.md 31 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12.22.1-alpine 2 | #FROM ftgo-consumer-web-ui_server:latest 3 | RUN npx envinfo > ./envinfo.log 4 | RUN cat ./envinfo.log 5 | 6 | COPY package.json . 7 | COPY package-lock.json . 8 | RUN npm config set unsafe-perm true && npm install -g serve 9 | ENV NODE_OPTIONS --max_old_space_size=819 10 | ENV PUPPETEER_SKIP_DOWNLOAD true 11 | RUN npm ci 12 | ADD src ./src 13 | ADD public ./public 14 | 15 | ARG REACT_APP_BACKEND_API_URL 16 | RUN echo "REACT_APP_BACKEND_API_URL: $REACT_APP_BACKEND_API_URL" 17 | 18 | RUN npm run build:slim 19 | CMD npm run serve 20 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 Eventuate, Inc. All rights reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FTGO Consumer Web UI 2 | 3 | ## Installation 4 | 5 | ### `npm install` 6 | 7 | Installs all dependencies 8 | 9 | ## Application Scripts 10 | 11 | ### `npm test` 12 | 13 | Launches a test runner in a non-interactive single-threaded mode.
14 | Use `JEST_JUNIT_OUTPUT_DIR` environment var in order to set up a directory for test-runner output consumable by CI. 15 | 16 | ### `npm run build` 17 | 18 | Builds the app for production to the `build` folder.
19 | It correctly bundles React in production mode and optimizes the build for the best performance. 20 | 21 | The build is minified, and the filenames include the hashes.
22 | The build folder is ready to be deployed. If run by a Circle CI, the contents of the folder are packed and the resulting archive is stored under the **Artifacts** tab. You can download and unpack it. 23 | 24 | You may serve the contents of this folder with a static server: 25 | 26 | ```shell 27 | npm install -g serve # if 'serve' is not installed 28 | serve -s build # assuming the folder is called "build" 29 | ``` 30 | 31 | or even with a single command: 32 | 33 | ```shell 34 | npx serve -s build 35 | ``` 36 | 37 | When the `serve` command is run, the following output will inform you of how to view the web application: 38 | 39 | ``` 40 | 41 | ┌──────────────────────────────────────────────────┐ 42 | │ │ 43 | │ Serving! │ 44 | │ │ 45 | │ - Local: http://localhost:5000 │ 46 | │ - On Your Network: http://192.168.0.23:5000 │ 47 | │ │ 48 | │ Copied local address to clipboard! │ 49 | │ │ 50 | └──────────────────────────────────────────────────┘ 51 | 52 | ``` 53 | 54 | ## Using Docker 55 | 56 | For a number of reasons if you need the app running in Docker, run the shell script: 57 | 58 | ### `FTGO_BACKEND_API_URL= ./start-http-server.sh` 59 | 60 | (Presently it simply runs `docker-compose up -d --build`). 61 | 62 | ## Temporary Usage Conventions 63 | 64 | While the backend server is only an express-based fake one, several important bits of backend logic are emulated over the input parameters. 65 | 66 | ### Landing page 67 | 68 | Specify time ending in... 69 | 70 | #### odd numbers 71 | 72 | ... to receive form validation error 73 | 74 | #### ending in `0` 75 | 76 | ... to receive a list of 0 restaurants 77 | 78 | #### ending in `8` 79 | 80 | ... to receive a full list of available restaurants 81 | 82 | 83 | ### Pick restaurants page 84 | 85 | There is a specific restaurant in the full list titled... 86 | 87 | #### `'All-Ooma - All items'` 88 | 89 | ... to receive a full menu (of all available items) 90 | 91 | #### `'Imitates a restaurant with zero menu items'` 92 | 93 | ... to receive 0 items in the menu 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /_wait-for-services.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | path=$1 4 | shift 5 | ports=$* 6 | 7 | echo $path 8 | echo $ports 9 | 10 | host=${DOCKER_HOST_IP:-localhost} 11 | 12 | done=false 13 | counter=0 14 | 15 | while [[ "$done" = false ]]; do 16 | for port in $ports; do 17 | url=http://${host}:${port}$path 18 | curl --fail $url >& /dev/null 19 | if [[ "$?" -eq "0" ]]; then 20 | done=true 21 | else 22 | done=false 23 | break 24 | fi 25 | done 26 | if [[ "$done" = true ]]; then 27 | echo connected 28 | break; 29 | fi 30 | if [[ "$counter" -gt 12 ]]; then 31 | echo "Error. Timed out service: $url. Check list: $ports" 32 | exit 1 33 | else 34 | counter=$((counter+1)) 35 | echo "$counter" 36 | echo -n . 37 | sleep 5 38 | fi 39 | done 40 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | // babel.config.js 2 | console.log('babel.config.js'); 3 | 4 | module.exports = { 5 | presets: [ 6 | [ '@babel/preset-env', 7 | { 8 | targets: { 9 | node: 'current', 10 | }, 11 | }, 12 | ], 13 | // https://github.com/testing-library/react-testing-library/issues/810 14 | ['@babel/preset-react', { 15 | "runtime": "automatic" 16 | }] 17 | ], 18 | plugins: [ 19 | '@babel/plugin-proposal-export-namespace-from', 20 | '@babel/plugin-proposal-class-properties', 21 | // '@babel/plugin-syntax-jsx' 22 | ], 23 | "env": { 24 | "test": { 25 | "plugins": ["@babel/plugin-transform-modules-commonjs"] 26 | }, 27 | "development": { 28 | "plugins": ["@babel/plugin-transform-modules-commonjs"] 29 | } 30 | }, 31 | }; 32 | -------------------------------------------------------------------------------- /build-and-test-all.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | echo "00. Environment diagnostics" 5 | 6 | npx envinfo 7 | 8 | 9 | echo "" 10 | echo "" 11 | echo "10. Ensuring required env variables and directories" 12 | 13 | source ./ensure-variables-and-paths.sh 14 | 15 | 16 | echo "" 17 | echo "" 18 | echo "20. Installing dependencies" 19 | 20 | echo "running npm install in $(pwd)" 21 | rm -rf node_modules 22 | npm ci # --loglevel verbose 23 | 24 | 25 | echo "" 26 | echo "" 27 | echo "30. Running tests" 28 | 29 | npm run test 30 | 31 | 32 | echo "" 33 | echo "" 34 | echo "40. Building the site" 35 | 36 | npm run build 37 | 38 | 39 | echo "" 40 | echo "" 41 | echo "50. Archiving and copying the resulted built files" 42 | 43 | tar -czvf "$CI_ARTIFACTS_PATH/build_$(date '+%Y%m%d_%H%M').tar.gz" build 44 | tar -czvf "$CI_ARTIFACTS_PATH/coverage_$(date '+%Y%m%d_%H%M').tar.gz" "$JEST_COVERAGE_OUTPUT_DIR" 45 | 46 | cp ./junit.xml "$JEST_JUNIT_OUTPUT_DIR/junit_$(date '+%Y%m%d_%H%M').xml" 2>/dev/null || : 47 | 48 | echo "Copy NPM logs" 49 | [ -d "$HOME/.npm/_logs" ] && cp -R ~/.npm/_logs/* "$CI_ARTIFACTS_PATH/npm-logs" 2>/dev/null || : 50 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | backend: 4 | build: 5 | context: server/ 6 | ports: 7 | - "8080:8080" 8 | frontend: 9 | build: 10 | context: . 11 | dockerfile: Dockerfile 12 | args: 13 | REACT_APP_BACKEND_API_URL: http://${FTGO_BACKEND_HOST:-localhost}:8080 14 | ports: 15 | - "5000:5000" 16 | -------------------------------------------------------------------------------- /ensure-variables-and-paths.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | if [[ -z "$JEST_JUNIT_OUTPUT_DIR_PARENT" ]]; then 5 | export JEST_JUNIT_OUTPUT_DIR_PARENT=$(pwd)/reports 6 | fi 7 | 8 | echo "JEST_JUNIT_OUTPUT_DIR_PARENT=$JEST_JUNIT_OUTPUT_DIR_PARENT" 9 | 10 | rm -rf "$JEST_JUNIT_OUTPUT_DIR_PARENT" 11 | mkdir -p "$JEST_JUNIT_OUTPUT_DIR_PARENT" 12 | 13 | if [[ -z "$JEST_JUNIT_OUTPUT_DIR" ]]; then 14 | export JEST_JUNIT_OUTPUT_DIR=$JEST_JUNIT_OUTPUT_DIR_PARENT/junit 15 | mkdir -p "$JEST_JUNIT_OUTPUT_DIR" 16 | fi 17 | 18 | if [[ -z "$JEST_COVERAGE_OUTPUT_DIR" ]]; then 19 | export JEST_COVERAGE_OUTPUT_DIR=$JEST_JUNIT_OUTPUT_DIR_PARENT/coverage 20 | mkdir -p "$JEST_COVERAGE_OUTPUT_DIR" 21 | fi 22 | 23 | echo "JEST_JUNIT_OUTPUT_DIR=$JEST_JUNIT_OUTPUT_DIR" 24 | echo "JEST_COVERAGE_OUTPUT_DIR=$JEST_COVERAGE_OUTPUT_DIR" 25 | 26 | if [[ -z "$CI_ARTIFACTS_PATH" ]]; then 27 | export CI_ARTIFACTS_PATH=$(pwd)/ci-artifacts 28 | mkdir -p "$CI_ARTIFACTS_PATH" 29 | fi 30 | 31 | echo "CI_ARTIFACTS_PATH=$CI_ARTIFACTS_PATH" 32 | 33 | mkdir -p "$CI_ARTIFACTS_PATH/npm-logs" 34 | 35 | 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ftgo-consumer-web-ui", 3 | "version": "0.1.0", 4 | "private": true, 5 | "devDependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.5.0", 8 | "@testing-library/user-event": "^7.2.1", 9 | "faker": "^5.5.3", 10 | "jest-environment-jsdom-sixteen": "^1.0.3", 11 | "jest-extended": "^0.11.5", 12 | "jest-fetch-mock": "^3.0.3", 13 | "jest-junit": "^12.0.0", 14 | "node-sass": "^5.0.0", 15 | "puppeteer": "^9.1.1" 16 | }, 17 | "dependencies": { 18 | "@reduxjs/toolkit": "^1.5.1", 19 | "bootstrap": "^4.6.0", 20 | "classnames": "^2.3.1", 21 | "connected-react-router": "^6.9.1", 22 | "history": "^4.10.1", 23 | "lodash-es": "^4.17.21", 24 | "react": "^17.0.2", 25 | "react-bootstrap-table-next": "^4.0.3", 26 | "react-bootstrap-table2-paginator": "^2.1.2", 27 | "react-dom": "^17.0.2", 28 | "react-hook-form": "^7.2.1", 29 | "react-icons": "^4.2.0", 30 | "react-redux": "^7.2.3", 31 | "react-router": "^5.2.0", 32 | "react-router-dom": "^5.2.0", 33 | "react-scripts": "4.0.3", 34 | "react-syntax-highlighter": "^15.4.3", 35 | "react-use": "^17.2.3", 36 | "reactstrap": "^8.9.0", 37 | "styled-components": "^5.2.3" 38 | }, 39 | "peerDependencies": { 40 | "serve": "^11.3.2" 41 | }, 42 | "scripts": { 43 | "start": "react-scripts start", 44 | "build": "react-scripts build", 45 | "build:slim": "GENERATE_SOURCEMAP=false react-scripts build --expose-gc", 46 | "test": "$(npm bin)/jest --env=jest-environment-jsdom-sixteen --config=./src/jest.config.js --watchAll=false --bail --runInBand --reporters=default --reporters=jest-junit --collectCoverage=true --coverageDirectory=$JEST_COVERAGE_OUTPUT_DIR --unhandled-rejections=strict --verbose", 47 | "test:dev": "source ./ensure-variables-and-paths.sh && $(npm bin)/jest --env=jest-environment-jsdom-sixteen --config=./src/jest.config.js --watchAll=true --reporters=default --reporters=jest-junit --unhandled-rejections=strict --verbose", 48 | "test-ui": "$(npm bin)/jest --config tests-ui/jest.config.js --runInBand --reporters=default --unhandled-rejections=strict --verbose", 49 | "test-ui:debug": "npx react-app-rewired --inspect-brk test --env=jsdom --config tests-ui/jest.config.js --runInBand", 50 | "serve": "serve -s build -C -l 5000 --debug", 51 | "eject": "#react-scripts eject" 52 | }, 53 | "proxy": "http://localhost:8080", 54 | "eslintConfig": { 55 | "extends": "react-app" 56 | }, 57 | "browserslist": { 58 | "production": [ 59 | ">0.2%", 60 | "not dead", 61 | "not op_mini all" 62 | ], 63 | "development": [ 64 | "last 1 chrome version", 65 | "last 1 firefox version", 66 | "last 1 safari version" 67 | ] 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microservices-patterns/ftgo-consumer-web-ui/e2f3c3b8eea20a97472e6f7744f15cb262bf1222/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | FTGO Web Application 15 | 16 | 17 | 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microservices-patterns/ftgo-consumer-web-ui/e2f3c3b8eea20a97472e6f7744f15cb262bf1222/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microservices-patterns/ftgo-consumer-web-ui/e2f3c3b8eea20a97472e6f7744f15cb262bf1222/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "FTGO App", 3 | "name": "FTGO Web Application", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /run-tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | source ./ensure-variables-and-paths.sh 5 | 6 | npm run test 7 | 8 | -------------------------------------------------------------------------------- /server/.dockerignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | -------------------------------------------------------------------------------- /server/.env: -------------------------------------------------------------------------------- 1 | STRIPE_SK_KEY= 2 | -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | /dist 2 | /logs 3 | /npm-debug.log 4 | /node_modules 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /server/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12.22.1-alpine 2 | 3 | RUN echo "Building the backend server:" 4 | RUN npx envinfo > ./envinfo.log 5 | RUN cat ./envinfo.log 6 | 7 | # Install app dependencies 8 | COPY babel.config.js . 9 | COPY package.json . 10 | COPY package-lock.json . 11 | RUN npm ci 12 | 13 | # Copy app source 14 | #COPY . /www 15 | ADD src ./src 16 | ENV PORT=8080 17 | EXPOSE 8080 18 | RUN npm run build 19 | CMD npx envinfo && npm run start 20 | -------------------------------------------------------------------------------- /server/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Jason Miller 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /server/Procfile: -------------------------------------------------------------------------------- 1 | web: npm start 2 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- 1 | Express & ES6 REST API Boilerplate 2 | ================================== 3 | 4 | This is a straightforward boilerplate for building REST APIs with ES6 and Express. 5 | 6 | - ES6 support via [babel](https://babeljs.io) 7 | - REST resources as middleware via [resource-router-middleware](https://github.com/developit/resource-router-middleware) 8 | - CORS support via [cors](https://github.com/troygoode/node-cors) 9 | - Body Parsing via [body-parser](https://github.com/expressjs/body-parser) 10 | 11 | > Tip: If you are using [Mongoose](https://github.com/Automattic/mongoose), you can automatically expose your Models as REST resources using [restful-mongoose](https://git.io/restful-mongoose). 12 | 13 | 14 | 15 | Getting Started 16 | --------------- 17 | 18 | ```sh 19 | # clone it 20 | git clone git@github.com:developit/express-es6-rest-api.git 21 | cd express-es6-rest-api 22 | 23 | # Make it your own 24 | rm -rf .git && git init && npm init 25 | 26 | # Install dependencies 27 | npm install 28 | 29 | # Start development live-reload server 30 | PORT=8080 npm run dev 31 | 32 | # Start production server: 33 | PORT=8080 npm start 34 | ``` 35 | Docker Support 36 | ------ 37 | ```sh 38 | cd express-es6-rest-api 39 | 40 | # Build your docker 41 | docker build -t es6/api-service . 42 | # ^ ^ ^ 43 | # tag tag name Dockerfile location 44 | 45 | # run your docker 46 | docker run -p 8080:8080 es6/api-service 47 | # ^ ^ 48 | # bind the port container tag 49 | # to your host 50 | # machine port 51 | 52 | ``` 53 | 54 | License 55 | ------- 56 | 57 | MIT 58 | -------------------------------------------------------------------------------- /server/babel.config.js: -------------------------------------------------------------------------------- 1 | // babel.config.js 2 | console.log('babel.config.js'); 3 | 4 | module.exports = 5 | //export default 6 | { 7 | presets: [ 8 | [ '@babel/preset-env', 9 | { 10 | 'useBuiltIns': 'entry', // 'usage', // alternative mode: "entry" 11 | 'debug': true, 12 | 'corejs': '3.15', 13 | 'targets': { 14 | 'node': '12.22.1' 15 | }, 16 | 'shippedProposals': true, 17 | 'modules': 'auto', 18 | }, 19 | ], 20 | 21 | ], 22 | // plugins: [ 23 | // // https://babeljs.io/docs/en/babel-plugin-transform-runtime#docsNav 24 | // [ 25 | // '@babel/plugin-transform-runtime', 26 | // { 27 | // 'regenerator': true, 28 | // } 29 | // ], 30 | //// '@babel/plugin-transform-modules-commonjs', 31 | // '@babel/plugin-proposal-export-namespace-from', 32 | // '@babel/plugin-proposal-class-properties', 33 | // // '@babel/plugin-syntax-jsx' 34 | // ] 35 | }; 36 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-es6-rest-api", 3 | "version": "0.3.0", 4 | "description": "Starter project for an ES6 RESTful Express API", 5 | "main": "dist/index.js", 6 | "module": "src/index.js", 7 | "scripts": { 8 | "dev": "PORT=8080 nodemon -w src --exec \"babel-node src\"", 9 | "build": "$(npm bin)/babel src --out-dir dist", 10 | "xstart": "PORT=8080 node --experimental-specifier-resolution=node dist/index.js", 11 | "start": "PORT=8080 node dist", 12 | "prestart": "npm run -s build", 13 | "test": "eslint src" 14 | }, 15 | "repository": "developit/express-es6-rest-api", 16 | "author": "Jason Miller ", 17 | "license": "MIT", 18 | "dependencies": { 19 | "@babel/runtime": "^7.14.6", 20 | "body-parser": "^1.19.0", 21 | "compression": "^1.7.4", 22 | "core-js": "^3.15.2", 23 | "cors": "^2.8.5", 24 | "dotenv": "^10.0.0", 25 | "express": "^4.17.1", 26 | "morgan": "^1.10.0", 27 | "node-cache": "^5.1.2", 28 | "regenerator-runtime": "^0.13.7", 29 | "resource-router-middleware": "^0.7.0" 30 | }, 31 | "devDependencies": { 32 | "@babel/cli": "^7.14.3", 33 | "@babel/core": "^7.14.3", 34 | "@babel/node": "^7.14.2", 35 | "@babel/preset-env": "^7.14.2", 36 | "nodemon": "^2.0.7" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /server/src/api/address.js: -------------------------------------------------------------------------------- 1 | import resource from 'resource-router-middleware'; 2 | import restaurants from '../models/address'; 3 | import { cache } from './cache'; 4 | 5 | const addressResource = ({ config, db }) => resource({ 6 | 7 | /** Property name to store preloaded entity on `request`. */ 8 | id: 'facet', 9 | 10 | /** GET / - List all entities */ 11 | index({ params }, res) { 12 | res.json(restaurants); 13 | }, 14 | 15 | /** POST / - Create a new entity */ 16 | create(req, res) { 17 | 18 | const { body } = req; 19 | const { address, time } = body; 20 | if (!address || !time) { 21 | return res.status(400).json({ 22 | message: `Missing field`, 23 | code: 400, 24 | errors: { 25 | ...(!time ? { time: 'Required' } : {}), 26 | ...(!address ? { address: 'Required' } : {}), 27 | ...(!origin ? { origin: 'Required' } : {}), 28 | } 29 | }); 30 | } 31 | 32 | if (/[02468]$/.test(time)) { 33 | const result = [ 34 | ...(/0$/.test(time) ? [] : (/[68]$/.test(time) ? restaurants : restaurants.slice(0, 2))) 35 | ]; 36 | 37 | cache.del('cart'); 38 | body.restaurants = result; 39 | res.json(body); 40 | return; 41 | } 42 | 43 | res.status(500).json({ 44 | message: 'Form submission error', 45 | code: 500, 46 | errors: { 47 | time: 'Wrong time', 48 | address: 'Return to sender, address unknown' 49 | } 50 | }); 51 | 52 | }, 53 | 54 | /** GET /:id - Return a given entity */ 55 | read({ facet }, res) { 56 | res.sendStatus(501); 57 | }, 58 | 59 | /** PUT /:id - Update a given entity */ 60 | update({ facet, body }, res) { 61 | res.sendStatus(501); 62 | }, 63 | 64 | /** DELETE /:id - Delete a given entity */ 65 | delete({ facet }, res) { 66 | res.sendStatus(501); 67 | } 68 | }); 69 | 70 | export default addressResource; 71 | -------------------------------------------------------------------------------- /server/src/api/cache.js: -------------------------------------------------------------------------------- 1 | // TODO: The real server must absolutely NOT have this file or its logic 2 | 3 | import NodeCache from 'node-cache'; 4 | 5 | export const cache = new NodeCache(); 6 | -------------------------------------------------------------------------------- /server/src/api/cart.js: -------------------------------------------------------------------------------- 1 | import resource from 'resource-router-middleware'; 2 | import { cache } from './cache'; 3 | import menu from '../models/menu'; 4 | 5 | const initialCart = {}; 6 | 7 | const TAX_AMOUNT = 0.06; 8 | const DELIVERY_FEE = 0.0; 9 | 10 | const facetName = 'cart'; 11 | 12 | function createNewCart() { 13 | return Object.assign({}, initialCart, { 14 | items: [], 15 | orderId: `FTGO_${ Math.random().toString().replace(/(\d{4,4})/, '_$1_').split('_')[1] }` 16 | }); 17 | } 18 | 19 | const cartResource = ({ config, db }) => resource({ 20 | /** Property name to store preloaded entity on `request`. */ 21 | id: facetName, 22 | 23 | index({ params }, res) { 24 | 25 | // this is probably the point where a new order needs to be created 26 | cache.set('cart', createNewCart()); 27 | 28 | const inMemoCart = cache.get('cart'); 29 | 30 | res.json(updateCartWithStats(inMemoCart)); 31 | }, 32 | 33 | 34 | /** PUT /:id - Update a given entity */ 35 | update({ body, ...req }, res) { 36 | 37 | const { restaurantId, itemId, quantity } = body; 38 | 39 | if (!cache.has('cart')) { 40 | cache.set('cart', createNewCart()); 41 | } 42 | 43 | const inMemoCart = cache.get('cart'); 44 | const foundItem = inMemoCart.items.find(item => item.id === itemId); 45 | const nextInMemoCart = foundItem ? { 46 | ...inMemoCart, 47 | items: [ 48 | ...inMemoCart.items.filter(item => item.id === itemId), //.map((i, iIdx) => (iIdx === idx) ? { ...i, count: quantity } : i) 49 | { 50 | ...foundItem, 51 | count: quantity 52 | } 53 | ] 54 | } : { 55 | ...inMemoCart, 56 | items: [ 57 | ...inMemoCart.items, 58 | { 59 | id: itemId, 60 | count: quantity, 61 | restaurantId: restaurantId, 62 | } 63 | ] 64 | } 65 | 66 | if (nextInMemoCart.items.every(({ count }) => count === 0)) { 67 | nextInMemoCart.items = []; 68 | } 69 | 70 | cache.set('cart', updateCartWithStats(nextInMemoCart)); 71 | console.log(JSON.stringify(updateCartWithStats(nextInMemoCart), null, 2)); 72 | return new Promise(rs => setTimeout(() => { 73 | const result = updateCartWithStats(nextInMemoCart) 74 | res.json(result); 75 | rs(); 76 | }, 2000)); 77 | 78 | }, 79 | }); 80 | 81 | export default cartResource; 82 | 83 | export function updateCartWithStats(cart) { 84 | 85 | const itemsMap = new Map(cart.items.map(item => ([ item.id, item ]))); 86 | const menuMap = new Map(menu.map(item => ([ item.id, item ]))); 87 | const source = cart.items.map(i => Object.assign({}, menuMap.get(i.id), itemsMap.get(i.id))); 88 | console.log('source', source); 89 | 90 | const subTotal = source.reduce((sum, { price, count }) => (sum + Number(price) * Number(count)), 0); 91 | 92 | console.log('subTotal:', subTotal); 93 | 94 | const tax = TAX_AMOUNT * subTotal; 95 | const delivery = Number(DELIVERY_FEE); 96 | const total = subTotal + tax + delivery; 97 | 98 | return { 99 | ...cart, 100 | subTotal, 101 | tax, 102 | taxAmount: TAX_AMOUNT, 103 | delivery, 104 | total 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /server/src/api/index.js: -------------------------------------------------------------------------------- 1 | //import { version } from '../../package.json'; 2 | import { Router } from 'express'; 3 | import addresses from './address'; 4 | import restaurants from './restaurant'; 5 | import cart from './cart'; 6 | import { postPaymentConfirmHandler, postPaymentIntentHandler } from './payment'; 7 | 8 | const defaultExport = ({ config, db }) => { 9 | let api = Router(); 10 | 11 | // mount the facets resource 12 | api.use('/cart/address', addresses({ config, db })); 13 | api.use('/cart', cart({ config, db })); 14 | api.use('/restaurants', restaurants({ config, db })); 15 | 16 | api.post('/payment/intent', postPaymentIntentHandler); 17 | api.post('/payment/confirm', postPaymentConfirmHandler); 18 | 19 | 20 | // perhaps expose some API metadata at the root 21 | api.get('/', (req, res) => { 22 | res.json({ version: '1.0.0' }); 23 | }); 24 | 25 | return api; 26 | }; 27 | 28 | export default defaultExport; 29 | -------------------------------------------------------------------------------- /server/src/api/payment.js: -------------------------------------------------------------------------------- 1 | import { paymentIntentFakeStripeResponse } from './paymentIntentResponse'; 2 | import { cache } from './cache'; 3 | import { updateCartWithStats } from './cart'; 4 | 5 | // left this here intentionally 6 | // ```js 7 | //import stripeDefault from 'stripe'; 8 | //const stripe = stripeDefault(process.env.STRIPE_SK_KEY); 9 | // ``` 10 | 11 | const aGeneralCCCardNumberPattern = /^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/; 12 | 13 | const paymentIntent = paymentIntentFakeStripeResponse; 14 | 15 | export const postPaymentIntentHandler = (req, res) => { 16 | const { items } = req.body; 17 | 18 | // Create a PaymentIntent with the order amount and currency 19 | // ```js 20 | // await stripe.paymentIntents.create({ 21 | // amount: calculateOrderAmount(items), 22 | // currency: "usd" 23 | // }); 24 | // ``` 25 | 26 | console.log('[paymentIntent]', paymentIntent); 27 | 28 | res.send({ 29 | clientSecret: paymentIntent.client_secret, 30 | amount: calculateOrderAmount(items) 31 | }); 32 | 33 | }; 34 | 35 | export const postPaymentConfirmHandler = (req, res) => { 36 | 37 | const [ err, clientSecret, card ] = safelyDestructure(req.body, 38 | ({ 39 | clientSecret, 40 | paymentMethod: { 41 | card 42 | } 43 | }) => ([ clientSecret, card ])); 44 | 45 | if (err) { 46 | console.log(err); 47 | return res.status(400).json({ error: { message: 'invalid parameters in the request' } }); 48 | } 49 | 50 | console.log('[stripe-ish.confirmCardPayment]', clientSecret, card); 51 | 52 | if (clientSecret !== paymentIntent.client_secret) { 53 | console.log('payment intent client secret mismatch'); 54 | return res.status(400).json({ error: { message: 'payment intent client secret mismatch' } }); 55 | } 56 | 57 | if (!aGeneralCCCardNumberPattern.test(card?.card_number ?? '')) { 58 | return res.status(400).json({ error: { message: 'Invalid card number' }, errors: { card_number: 'Invalid' } }); 59 | } 60 | 61 | if (!card?.exp_year || !card?.exp_month) { 62 | return res.json({ 63 | error: { message: 'Expiration (MM/YY) is required' }, errors: { 64 | ...(!card?.exp_year ? { exp_year: 'Required' } : {}), 65 | ...(!card?.exp_month ? { exp_month: 'Required' } : {}) 66 | } 67 | }).status(400); 68 | } 69 | 70 | if ((Number(card?.exp_year ?? '00') < (new Date().getFullYear() % 100)) || ( 71 | (Number(card?.exp_year ?? '00') === (new Date().getFullYear() % 100)) && 72 | (Number(card?.exp_month ?? '00') < (new Date().getMonth() % 12 + 1)) 73 | )) { 74 | return res.json({ 75 | error: { message: 'Card is expired.' }, 76 | errors: { exp_month: 'Invalid', exp_year: 'Invalid' } 77 | }).status(400); 78 | } 79 | 80 | if (!card?.cvv) { 81 | return res.json({ error: { message: 'CVV is required' }, errors: { cvv: 'Required' } }).status(400); 82 | } 83 | 84 | 85 | // 4242 4242 4242 4242 - Payment succeeds 86 | // 4000 0025 0000 3155 - Payment requires authentication 87 | // 4000 0000 0000 9995 - Payment is declined 88 | 89 | if (/^4242\s*4242\s*4242\s*4242$/.test(card?.card_number ?? '')) { 90 | return respondWithSuccessfulPayment(res); 91 | } else if (/^4000\s*0025\s*0000\s*3155$/.test(card?.card_number ?? '')) { 92 | const isOdd = (new Date().getTime() % 2) === 0; 93 | return setTimeout(() => { 94 | if (isOdd) { 95 | return res.json({ 96 | error: { message: 'Payment requires authentication. The odds now are for simulating an error. Try again for successful payment.' }, 97 | errors: { card_number: 'Bank requested authentication.' } 98 | }).status(400); 99 | } else { 100 | return respondWithSuccessfulPayment(res); 101 | } 102 | }, 3500); 103 | } else if (/^4000\s*0000\s*0000\s*9995$/.test(card?.card_number ?? '')) { 104 | return setTimeout(() => { 105 | return res.status(400).json({ error: { message: 'Payment is declined' } }); 106 | }, 2000); 107 | } else { 108 | return respondWithSuccessfulPayment(res); 109 | } 110 | 111 | }; 112 | 113 | function respondWithSuccessfulPayment(res) { 114 | cache.del('cart'); 115 | 116 | return setTimeout(() => { 117 | return res.status(200).json({ success: true }); 118 | }, 1000); 119 | } 120 | 121 | 122 | function safelyDestructure(source, destructor) { 123 | try { 124 | return [ null, ...destructor(source) ]; 125 | } catch (err) { 126 | return [ err ]; 127 | } 128 | } 129 | 130 | 131 | const calculateOrderAmount = items => { 132 | const cart = updateCartWithStats({ items }); 133 | const { total } = cart; 134 | // Replace this constant with a calculation of the order's amount 135 | // Calculate the order total on the server to prevent 136 | // people from directly manipulating the amount on the client 137 | console.log(`[calculateOrderAmount]`, JSON.stringify(cart, null, 2)); 138 | return total; 139 | }; 140 | -------------------------------------------------------------------------------- /server/src/api/paymentIntentResponse.js: -------------------------------------------------------------------------------- 1 | export const paymentIntentFakeStripeResponse = { 2 | id: 'pi_1JAlngAJaaowfuNtCEWgaJdp', 3 | object: 'payment_intent', 4 | amount: 1400, 5 | amount_capturable: 0, 6 | amount_received: 0, 7 | application: null, 8 | application_fee_amount: null, 9 | canceled_at: null, 10 | cancellation_reason: null, 11 | capture_method: 'automatic', 12 | charges: { 13 | object: 'list', 14 | data: [], 15 | has_more: false, 16 | total_count: 0, 17 | url: '/v1/charges?payment_intent=pi_1JAlngAJaaowfuNtCEWgaJdp' 18 | }, 19 | client_secret: 'pi_1JAlngAJaaowfuNtCEWgaJdp_secret_vmFuE8wC5Tx0YLao0KWyswt1d', 20 | confirmation_method: 'automatic', 21 | created: 1625706792, 22 | currency: 'usd', 23 | customer: null, 24 | description: null, 25 | invoice: null, 26 | last_payment_error: null, 27 | livemode: false, 28 | metadata: {}, 29 | next_action: null, 30 | on_behalf_of: null, 31 | payment_method: null, 32 | payment_method_options: { 33 | card: { 34 | installments: null, 35 | network: null, 36 | request_three_d_secure: 'automatic' 37 | } 38 | }, 39 | payment_method_types: [ 'card' ], 40 | receipt_email: null, 41 | review: null, 42 | setup_future_usage: null, 43 | shipping: null, 44 | source: null, 45 | statement_descriptor: null, 46 | statement_descriptor_suffix: null, 47 | status: 'requires_payment_method', 48 | transfer_data: null, 49 | transfer_group: null 50 | }; 51 | -------------------------------------------------------------------------------- /server/src/api/restaurant.js: -------------------------------------------------------------------------------- 1 | import resource from 'resource-router-middleware'; 2 | import restaurants from '../models/address'; 3 | import menu from '../models/menu'; 4 | 5 | const facetName = 'restaurant'; 6 | 7 | const restaurantsMenuResource = ({ config, db }) => resource({ 8 | 9 | /** Property name to store preloaded entity on `request`. */ 10 | id: facetName, 11 | 12 | /** GET / - List all entities */ 13 | index({ params }, res) { 14 | res.sendStatus(501); 15 | }, 16 | 17 | /** POST / - Create a new entity */ 18 | create(req, res) { 19 | res.sendStatus(501); 20 | }, 21 | 22 | /** GET /:id - Return a given entity */ 23 | read(req, res) { 24 | const { [ facetName] : id } = req.params; 25 | if (String(id) === '0') { 26 | 27 | res.status(500).json({ 28 | message: '/api/restaurants/0 - test API rejection', 29 | code: 500 30 | }); 31 | 32 | return; 33 | } 34 | 35 | const result = restaurants.find(r => String(r.id) === String(id)); 36 | if (!result) { 37 | return res.status(404).json({ message: 'Not found', code: 404 }); 38 | } 39 | const effectiveMenu = /0$/.test(id) ? 40 | [] : 41 | (/[89]$/.test(id) ? 42 | menu : 43 | menu.filter(m => /[1357]$/.test(m.id) === /[1357]$/.test(id))); 44 | res.json(Object.assign(result, { menu: effectiveMenu })); 45 | }, 46 | 47 | /** PUT /:id - Update a given entity */ 48 | update({ facet, body }, res) { 49 | res.sendStatus(501); 50 | }, 51 | 52 | /** DELETE /:id - Delete a given entity */ 53 | delete({ facet }, res) { 54 | res.sendStatus(501); 55 | } 56 | }); 57 | 58 | export default restaurantsMenuResource; 59 | -------------------------------------------------------------------------------- /server/src/config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | "port": 8080, 3 | "bodyLimit": "100kb", 4 | "corsHeaders": ["Link"] 5 | } 6 | -------------------------------------------------------------------------------- /server/src/db.js: -------------------------------------------------------------------------------- 1 | export default callback => { 2 | // connect to a database if needed, then pass it to `callback`: 3 | const db = () => { debugger; }; 4 | callback(db); 5 | } 6 | -------------------------------------------------------------------------------- /server/src/index.js: -------------------------------------------------------------------------------- 1 | import http from 'http'; 2 | import express from 'express'; 3 | import cors from 'cors'; 4 | import morgan from 'morgan'; 5 | import bodyParser from 'body-parser'; 6 | import initializeDb from './db'; 7 | import middleware from './middleware'; 8 | import api from './api'; 9 | import config from './config.js'; 10 | 11 | let app = express(); 12 | app.server = http.createServer(app); 13 | 14 | // logger 15 | //app.use(morgan('combined')); 16 | 17 | // 3rd party middleware 18 | app.use(cors({ 19 | // exposedHeaders: config.corsHeaders, 20 | origin: '*' 21 | })); 22 | 23 | app.use(bodyParser.json({ 24 | limit: config.bodyLimit 25 | })); 26 | 27 | // connect to db 28 | initializeDb(db => { 29 | 30 | // internal middleware 31 | app.use(middleware({ config, db })); 32 | 33 | // api router 34 | app.use('/api', api({ config, db })); 35 | 36 | app.server.listen(process.env.PORT || config.port, () => { 37 | console.log(`Started on port ${ app.server.address().port }`); 38 | }); 39 | }); 40 | 41 | export default app; 42 | -------------------------------------------------------------------------------- /server/src/lib/util.js: -------------------------------------------------------------------------------- 1 | 2 | /** Creates a callback that proxies node callback style arguments to an Express Response object. 3 | * @param {express.Response} res Express HTTP Response 4 | * @param {number} [status=200] Status code to send on success 5 | * 6 | * @example 7 | * list(req, res) { 8 | * collection.find({}, toRes(res)); 9 | * } 10 | */ 11 | export function toRes(res, status=200) { 12 | return (err, thing) => { 13 | if (err) return res.status(500).send(err); 14 | 15 | if (thing && typeof thing.toObject==='function') { 16 | thing = thing.toObject(); 17 | } 18 | res.status(status).json(thing); 19 | }; 20 | } 21 | -------------------------------------------------------------------------------- /server/src/middleware/index.js: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | 3 | export default ({ config, db }) => { 4 | let routes = Router(); 5 | 6 | // add middleware here 7 | 8 | return routes; 9 | } 10 | -------------------------------------------------------------------------------- /server/src/models/address.js: -------------------------------------------------------------------------------- 1 | // our example model is just an Array 2 | const restaurants = [ 3 | // { 4 | // 'id': '0', 5 | // 'name': 'Imitates a server-side error', 6 | // }, 7 | { 8 | 'id': '10', 9 | 'name': 'Imitates a restaurant with zero menu items', 10 | }, 11 | { 12 | 'id': '121721', 13 | 'name': 'Nandos Banani', 14 | 'address': 'Road-11, Banani, Dhaka', 15 | street1: '', 16 | street2: '', 17 | locality: 'city', 18 | region: 'state', 19 | postcode: '', 20 | country: '', 21 | "cuisine": "Indian", 22 | 'delivery-fee': 75.00, 23 | avgDeliveryTime: 60 24 | }, { 25 | 'id': '6317637', 26 | 'name': 'Le Petit Souffle', 27 | "cuisine": "Indian", 28 | 'address': 'Third Floor, Century City Mall, Kalayaan Avenue, Poblacion, Makati City', 29 | 'delivery-fee': 75.00, 30 | avgDeliveryTime: 60 31 | }, 32 | { 33 | 'id': '6304287', 34 | 'name': 'Izakaya Kikufuji', 35 | 'address': 'Little Tokyo, 2277 Chino Roces Avenue, Legaspi Village, Makati City', 36 | "cuisine": "Fast Food", 37 | 'delivery-fee': 75.00, 38 | avgDeliveryTime: 60 39 | }, { 40 | 'id': '6300002', 41 | 'name': 'Heat - Edsa Shangri-La', 42 | 'address': 'Edsa Shangri-La, 1 Garden Way, Ortigas, Mandaluyong City', 43 | "cuisine": "Fast Food", 44 | 'delivery-fee': 75.00, 45 | avgDeliveryTime: 60 46 | }, { 47 | 'id': '6318506', 48 | 'name': 'Ooma', 49 | 'address': 'Third Floor, Mega Fashion Hall, SM Megamall, Ortigas, Mandaluyong City', 50 | "cuisine": "Fast Food", 51 | 'delivery-fee': 75.00, 52 | avgDeliveryTime: 60 53 | }, { 54 | 'id': '63185068', 55 | 'name': 'All-Ooma - All items', 56 | 'address': 'Fourth Floor, Mega Fashion Hall, SM Megamall, Ortigas, Mandaluyong City', 57 | "cuisine": "Oriental", 58 | 'delivery-fee': 80.00, 59 | avgDeliveryTime: 55 60 | }, 61 | ]; 62 | export default restaurants; 63 | -------------------------------------------------------------------------------- /server/src/models/menu.js: -------------------------------------------------------------------------------- 1 | // source: https://codebeautify.org/jsonviewer/cb51497a 2 | 3 | const menu = [ 4 | { 5 | "id": "224471", 6 | "name": "3 Chicken Wings", 7 | "position": 1, 8 | "price": "250.00", 9 | "consumable": "1:1", 10 | "category_name": "Appeteasers", 11 | "discount": { 12 | "type": "", 13 | "amount": "0.00" 14 | }, 15 | "tags": [] 16 | }, 17 | { 18 | "id": "224474", 19 | "name": "Chicken Livers and Portuguese Roll", 20 | "position": 1, 21 | "price": "250.00", 22 | "consumable": "1:1", 23 | "category_name": "Appeteasers", 24 | "discount": { 25 | "type": "", 26 | "amount": "0.00" 27 | }, 28 | "tags": [] 29 | }, 30 | { 31 | "id": "224477", 32 | "name": "Spicy Mixed Olives (V)", 33 | "position": 1, 34 | "price": "215.00", 35 | "consumable": "1:1", 36 | "category_name": "Appeteasers", 37 | "discount": { 38 | "type": "", 39 | "amount": "0.00" 40 | }, 41 | "tags": [] 42 | }, 43 | { 44 | "id": "224480", 45 | "name": "Hummus with PERI-PERI Drizzle (V)", 46 | "position": 1, 47 | "price": "215.00", 48 | "consumable": "1:1", 49 | "category_name": "Appeteasers", 50 | "discount": { 51 | "type": "", 52 | "amount": "0.00" 53 | }, 54 | "tags": [] 55 | }, 56 | { 57 | "id": "224483", 58 | "name": "Red Pepper Dip (V)", 59 | "position": 1, 60 | "price": "205.00", 61 | "consumable": "1:1", 62 | "category_name": "Appeteasers", 63 | "discount": { 64 | "type": "", 65 | "amount": "0.00" 66 | }, 67 | "tags": [] 68 | }, 69 | { 70 | "id": "224486", 71 | "name": "Appeteaser Platter", 72 | "position": 1, 73 | "price": "615.00", 74 | "consumable": "1:1", 75 | "category_name": "Appeteasers", 76 | "discount": { 77 | "type": "", 78 | "amount": "0.00" 79 | }, 80 | "tags": [] 81 | }, 82 | { 83 | "id": "224489", 84 | "name": "All Together Now (V)", 85 | "position": 1, 86 | "price": "520.00", 87 | "consumable": "1:1", 88 | "category_name": "Appeteasers", 89 | "discount": { 90 | "type": "", 91 | "amount": "0.00" 92 | }, 93 | "tags": [] 94 | }, 95 | { 96 | "id": "224522", 97 | "name": "Regular", 98 | "position": 1, 99 | "price": "190.00", 100 | "consumable": "1:1", 101 | "category_name": "Fino sides", 102 | "discount": { 103 | "type": "", 104 | "amount": "0.00" 105 | }, 106 | "tags": [] 107 | }, 108 | { 109 | "id": "224525", 110 | "name": "Large", 111 | "position": 2, 112 | "price": "330.00", 113 | "consumable": "1:1", 114 | "category_name": "Fino sides", 115 | "discount": { 116 | "type": "", 117 | "amount": "0.00" 118 | }, 119 | "tags": [] 120 | }, 121 | { 122 | "id": "224528", 123 | "name": "Regular", 124 | "position": 1, 125 | "price": "190.00", 126 | "consumable": "1:1", 127 | "category_name": "Fino sides", 128 | "discount": { 129 | "type": "", 130 | "amount": "0.00" 131 | }, 132 | "tags": [] 133 | }, 134 | { 135 | "id": "224531", 136 | "name": "Large", 137 | "position": 2, 138 | "price": "330.00", 139 | "consumable": "1:1", 140 | "category_name": "Fino sides", 141 | "discount": { 142 | "type": "", 143 | "amount": "0.00" 144 | }, 145 | "tags": [] 146 | }, 147 | { 148 | "id": "224543", 149 | "name": "On its own", 150 | "position": 1, 151 | "price": "385.00", 152 | "consumable": "1:1", 153 | "category_name": "Peri-peri chicken", 154 | "discount": { 155 | "type": "", 156 | "amount": "0.00" 157 | }, 158 | "tags": [] 159 | }, 160 | { 161 | "id": "224546", 162 | "name": "With 1 Regular Side", 163 | "position": 2, 164 | "price": "485.00", 165 | "consumable": "1:1", 166 | "category_name": "Peri-peri chicken", 167 | "discount": { 168 | "type": "", 169 | "amount": "0.00" 170 | }, 171 | "tags": [] 172 | }, 173 | { 174 | "id": "224549", 175 | "name": "With 2 Regular Sides", 176 | "position": 3, 177 | "price": "575.00", 178 | "consumable": "1:1", 179 | "category_name": "Peri-peri chicken", 180 | "discount": { 181 | "type": "", 182 | "amount": "0.00" 183 | }, 184 | "tags": [] 185 | }, 186 | { 187 | "id": "224552", 188 | "name": "On its own", 189 | "position": 1, 190 | "price": "685.00", 191 | "consumable": "1:1", 192 | "category_name": "Peri-peri chicken", 193 | "discount": { 194 | "type": "", 195 | "amount": "0.00" 196 | }, 197 | "tags": [] 198 | }, 199 | { 200 | "id": "224555", 201 | "name": "With 1 Regular Side", 202 | "position": 2, 203 | "price": "785.00", 204 | "consumable": "1:1", 205 | "category_name": "Peri-peri chicken", 206 | "discount": { 207 | "type": "", 208 | "amount": "0.00" 209 | }, 210 | "tags": [] 211 | }, 212 | { 213 | "id": "224558", 214 | "name": "With 2 Regular Sides", 215 | "position": 3, 216 | "price": "875.00", 217 | "consumable": "1:1", 218 | "category_name": "Peri-peri chicken", 219 | "discount": { 220 | "type": "", 221 | "amount": "0.00" 222 | }, 223 | "tags": [] 224 | } 225 | ]; 226 | 227 | export default menu; 228 | -------------------------------------------------------------------------------- /src/__mocks__/fileMock.js: -------------------------------------------------------------------------------- 1 | module.exports = 'test-file-stub'; 2 | -------------------------------------------------------------------------------- /src/__mocks__/styleMock.js: -------------------------------------------------------------------------------- 1 | module.exports = {}; 2 | -------------------------------------------------------------------------------- /src/app/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/app/rootNode.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Provider } from 'react-redux'; 3 | import { ConnectedRouter } from 'connected-react-router'; 4 | import { history, store } from './store'; 5 | import { AppLayout } from '../ui/pages/AppLayout'; 6 | import './index.css'; 7 | 8 | const rootAppNode = 9 | 10 | 11 | 12 | 13 | 14 | ; 15 | 16 | export default rootAppNode; 17 | -------------------------------------------------------------------------------- /src/app/store.js: -------------------------------------------------------------------------------- 1 | import { configureStore } from '@reduxjs/toolkit'; 2 | import { createBrowserHistory as createHistory, createMemoryHistory as createMemHistory } from 'history'; 3 | import { makeConnectedReducer } from '../features'; 4 | import { routerMiddleware } from 'connected-react-router' 5 | //const baseURL = ensureEnvVariable('REACT_APP_API_URL'); 6 | 7 | export const history = process.env.NODE_ENV === 'test' ? 8 | createMemHistory() : 9 | createHistory({ 10 | // getUserConfirmation: getConfirmation 11 | }); 12 | 13 | const connectedReducer = makeConnectedReducer(history); 14 | 15 | export const store = configureStore({ 16 | reducer: connectedReducer, 17 | devTools: true, 18 | middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(routerMiddleware(history)) 19 | }); 20 | -------------------------------------------------------------------------------- /src/features/actions/api.js: -------------------------------------------------------------------------------- 1 | import { safelyExecuteAsync } from '../../shared/promises'; 2 | import { ensureEnvVariable } from '../../shared/env'; 3 | 4 | const API_URL = ensureEnvVariable('REACT_APP_BACKEND_API_URL', window.location.origin); 5 | 6 | const urlResolver = obtainFQDNUrl(API_URL, window.location); 7 | 8 | const apiRoutes = prepareRoutesForFetch({ 9 | postAddressObtainRestaurants: [ 10 | `POST /cart/address`, 11 | (address, time) => ({ address, time }) 12 | ], 13 | getRestaurantById: restaurantId => `/restaurants/${ restaurantId }`, 14 | getCart: `GET /cart`, 15 | putUpdateCartWithItem: [ 16 | `PUT /cart/0`, 17 | (restaurantId, itemId, quantity) => ({ restaurantId, itemId, quantity }) 18 | ], 19 | postCreatePaymentIntent: [ 20 | `POST /payment/intent`, 21 | (items) => ({ items }) 22 | ], 23 | postConfirmPayment: [ 24 | `POST /payment/confirm`, 25 | (clientSecret, card) => ({ clientSecret, paymentMethod: { card } }) 26 | ] 27 | }, urlResolver); 28 | 29 | export const { 30 | postAddressObtainRestaurants, getRestaurantById, putUpdateCartWithItem, 31 | getCart, postCreatePaymentIntent, postConfirmPayment 32 | } = apiRoutes; 33 | 34 | function prepareRoutesForFetch(routes, urlResolver) { 35 | return Object.fromEntries(Array.from(Object.entries(routes), ([ k, v ]) => { 36 | const [ resource, init ] = Array.isArray(v) ? v : [ v ]; 37 | return [ k, async (...args) => { 38 | const [ method, url ] = parseResource(resource, args, urlResolver); 39 | const [ fetchErr, response ] = await safelyExecuteAsync(fetch(typeof url === 'function' ? url(...args) : url, { 40 | method, 41 | ...(init ? { body: JSON.stringify(init(...args)) } : {}), 42 | mode: 'cors', // no-cors, *cors, same-origin 43 | headers: { 44 | 'Content-Type': 'application/json' 45 | }, 46 | })); 47 | 48 | if (fetchErr || !response.ok) { 49 | throw fetchErr || await response.json(); 50 | } 51 | 52 | return response.json(); 53 | } 54 | ]; 55 | })); 56 | } 57 | 58 | function parseResource(input, args, urlResolver) { 59 | const parts = (((typeof input === 'function') ? input(...args) : input).split(/\s+/)); 60 | return (parts.length === 1) ? [ 'GET', urlResolver(parts[ 0 ]) ] : [ parts[ 0 ].toUpperCase(), urlResolver(parts[ 1 ]) ]; 61 | } 62 | 63 | function obtainFQDNUrl(baseUrl, location) { 64 | const resolvedLocation = resolveBaseUrl(baseUrl, location); 65 | resolvedLocation.pathname = 'api'; 66 | const resolvedAPILocation = resolvedLocation.toString(); 67 | 68 | return pathPart => 69 | [ 70 | resolvedAPILocation, 71 | pathPart 72 | ].join('/').replace(`${ resolvedAPILocation }//`, `${ resolvedAPILocation }/`); 73 | } 74 | 75 | function resolveBaseUrl(baseUrl, location) { 76 | try { 77 | const result = new window.URL(baseUrl); 78 | if (result.origin == null) { 79 | return new URL(`${ location.protocol }${ baseUrl }`); 80 | } 81 | return result; 82 | } catch (ex) { 83 | return new URL(`${ location.protocol }${ baseUrl }`); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/features/actions/api.test.js: -------------------------------------------------------------------------------- 1 | import { getRestaurantById, postAddressObtainRestaurants } from './api'; 2 | 3 | describe(`src/features/actions/api.test.js`, () => { 4 | 5 | afterEach(() => { 6 | global.fetch.resetMocks(); 7 | }); 8 | 9 | describe(`postAddressObtainRestaurants()`, () => { 10 | beforeEach(() => { 11 | global.fetch.mockResponseOnce(JSON.stringify({ 12 | time: '10:10', 13 | origin: 12355, 14 | address: 'address', 15 | restaurants: [] 16 | })); 17 | }); 18 | test(`postAddressObtainRestaurants`, () => { 19 | expect(postAddressObtainRestaurants({ 20 | time: '10:10', origin: 12355, address: 'address' 21 | })).resolves.toBeTruthy(); 22 | }); 23 | }); 24 | describe(`getRestaurantById()`, () => { 25 | beforeEach(() => { 26 | global.fetch.mockResponseOnce(JSON.stringify({ id: '1234', menu: [] })); 27 | }); 28 | test(`getRestaurantById`, () => { 29 | expect(getRestaurantById({ 30 | time: '10:10', origin: 12355, address: 'address' 31 | })).resolves.toBeTruthy(); 32 | }); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /src/features/actions/navigation.js: -------------------------------------------------------------------------------- 1 | import { push } from 'connected-react-router'; 2 | import { routePaths } from '../../ui/pages/AppRoutes/routePaths'; 3 | 4 | export const navigateToEditDeliveryAddress = () => push(routePaths.landing); 5 | export const navigateToPickRestaurants = () => push(routePaths.restaurants); 6 | export const navigateToEditMenu = (restaurantId) => push(routePaths.restaurant.replace(':placeId', restaurantId)); 7 | export const navigateToCheckout = () => push(routePaths.checkout); 8 | export const navigateToThankYou = () => push(routePaths.thankyou); 9 | -------------------------------------------------------------------------------- /src/features/address/addressAPI.test.js: -------------------------------------------------------------------------------- 1 | 2 | describe(`src/features/address/addressAPI.test.js`, () => { 3 | 4 | const fetchRestaurants = () => {}; 5 | describe.skip(`fetchRestaurants(address, time, now) - silly implementation (no network call)`, () => { 6 | 7 | afterAll(() => { 8 | jest.clearAllMocks(); 9 | }); 10 | 11 | const successfulResponse = { 12 | data: expect.objectContaining({ 13 | address: expect.any(String), 14 | time: expect.any(String), 15 | origin: expect.any(Number), 16 | restaurants: expect.any(Array) 17 | }) 18 | }; 19 | 20 | const failingResponse = { 21 | message: expect.any(String), 22 | code: expect.any(Number), 23 | errors: expect.any(Object) 24 | }; 25 | 26 | test(`returns a promise`, () => { 27 | 28 | expect(fetchRestaurants('address', '10:20')).toBeInstanceOf(Promise); 29 | }); 30 | 31 | test(`successful response`, () => { 32 | // time ending even number - resolves to successful answer 33 | expect(fetchRestaurants('address', '10:20')).resolves.toEqual(successfulResponse); 34 | }); 35 | 36 | test(`response with an error`, () => { 37 | // time ending odd number - resolves to server-side error + validation errors 38 | expect(fetchRestaurants('address', '10:21')).rejects.toEqual(failingResponse); 39 | }); 40 | 41 | }); 42 | 43 | }); 44 | -------------------------------------------------------------------------------- /src/features/address/addressSlice.js: -------------------------------------------------------------------------------- 1 | import { createAsyncThunk, createEntityAdapter, createSlice } from '@reduxjs/toolkit'; 2 | import { safelyExecuteAsync } from '../../shared/promises'; 3 | import { navigateToPickRestaurants } from '../actions/navigation'; 4 | import { getRestaurantById, postAddressObtainRestaurants } from '../actions/api'; 5 | 6 | 7 | const restaurantsAdapter = createEntityAdapter({ 8 | selectId: ({ id }) => id, 9 | sortComparer: ({ id: a }, { id: b }) => a.localeCompare(b) 10 | }); 11 | 12 | const { selectById: selectRestaurantById, selectAll: selectAllRestaurants } = restaurantsAdapter.getSelectors(); 13 | 14 | const initialState = { 15 | address: null, 16 | time: null, 17 | origin: null, 18 | status: 'idle', 19 | value: null, 20 | error: null, 21 | restaurants: restaurantsAdapter.getInitialState() 22 | }; 23 | 24 | 25 | const ns = 'address'; 26 | 27 | export const retrieveRestaurantsForAddress = createAsyncThunk( 28 | 'address/postAddressObtainRestaurants', 29 | /** 30 | * 31 | * @param { { address: string, time: string, now: number }} data 32 | * @param rejectWithValue 33 | * @param dispatch 34 | * @return {Promise|*>} 35 | */ 36 | async (data, { rejectWithValue, dispatch }) => { 37 | const { address, time, now = (new Date() - 0) } = data; 38 | const [ err, payload ] = await safelyExecuteAsync(postAddressObtainRestaurants(address, time, now)); 39 | if (err) { 40 | return rejectWithValue(err); 41 | } 42 | 43 | dispatch(keepAddressAndTime({ address, time, now })); 44 | dispatch(navigateToPickRestaurants()); 45 | 46 | return payload; 47 | } 48 | ); 49 | 50 | 51 | export const retrieveRestaurantByIdAsyncThunk = createAsyncThunk( 52 | 'restaurant/fetchById', 53 | async (data, { dispatch }) => { 54 | debugger; 55 | if (!data) { 56 | return; 57 | } 58 | const { restaurantId } = data; 59 | if (!restaurantId) { 60 | return; 61 | } 62 | return getRestaurantById(restaurantId); 63 | } 64 | ); 65 | 66 | 67 | export const addressSlice = createSlice({ 68 | name: ns, 69 | initialState, 70 | reducers: { 71 | resetAddressAndTime(state) { 72 | state.address = null; 73 | state.time = null; 74 | state.origin = null; 75 | }, 76 | keepAddressAndTime(state, action) { 77 | state.address = action.payload.address; 78 | state.time = action.payload.time; 79 | state.origin = action.payload.now; 80 | } 81 | }, 82 | extraReducers: (builder) => builder 83 | .addCase(retrieveRestaurantsForAddress.pending, state => { 84 | state.status = 'loading'; 85 | }) 86 | .addCase(retrieveRestaurantsForAddress.fulfilled, (state, { payload }) => { 87 | state.status = 'idle'; 88 | restaurantsAdapter.setAll(state.restaurants, payload.restaurants); 89 | }) 90 | .addCase(retrieveRestaurantsForAddress.rejected, (state, action) => { 91 | state.status = 'error'; 92 | state.error = action.error; 93 | }).addCase( 94 | retrieveRestaurantByIdAsyncThunk.pending, state => { 95 | state.status = 'loading'; 96 | } 97 | ).addCase( 98 | retrieveRestaurantByIdAsyncThunk.fulfilled, (state, { payload }) => { 99 | state.status = 'idle'; 100 | if (!payload) { 101 | return; 102 | } 103 | restaurantsAdapter.addOne(state.restaurants, payload); 104 | } 105 | ).addCase( 106 | retrieveRestaurantByIdAsyncThunk.rejected, (state, action) => { 107 | state.status = 'error'; 108 | state.error = action.error; 109 | } 110 | ) 111 | }); 112 | 113 | export const { keepAddressAndTime, /*keepRestaurants, */resetAddressAndTime } = addressSlice.actions; 114 | 115 | export const accessAddressStatus = () => ({ [ ns ]: state }) => state.status; 116 | export const accessDeliveryAddress = () => ({ [ ns ]: state }) => state.address; 117 | export const accessDeliveryTime = () => ({ [ ns ]: state }) => state.time; 118 | export const accessDeliveryTimeBlock = () => ({ [ ns ]: state }) => (state.time && state.origin) ? ({ 119 | time: state.time, 120 | origin: state.origin 121 | }) : null; 122 | export const accessRestaurantsList = () => ({ [ ns ]: state }) => selectAllRestaurants(state.restaurants); 123 | export const accessRestaurantInfo = (id) => ({ [ ns ]: state }) => selectRestaurantById(state.restaurants, id); 124 | 125 | 126 | const namedReducer = { 127 | [ ns ]: addressSlice.reducer 128 | }; 129 | 130 | 131 | export default namedReducer; 132 | -------------------------------------------------------------------------------- /src/features/address/addressSlice.test.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line no-redeclare 2 | /* global describe, expect, test */ 3 | 4 | import addressReducer, { keepAddressAndTime, resetAddressAndTime, retrieveRestaurantsForAddress } from './addressSlice'; 5 | 6 | 7 | describe(`src/features/address/addressSlice.js`, () => { 8 | 9 | const fetchRestaurantsMocked = jest.fn() 10 | 11 | afterAll(() => { 12 | }); 13 | 14 | describe.skip(`addressReducer + keepAddressAndTime, resetAddressAndTime actions`, () => { 15 | 16 | const initialState = { 17 | address: null, 18 | time: null, 19 | origin: null, 20 | status: 'idle', 21 | value: null, 22 | error: null, 23 | restaurantsArr: null, 24 | restaurants: expect.objectContaining({ 25 | ids: expect.anything(), 26 | entities: expect.anything() 27 | }) 28 | }; 29 | 30 | test(`should handle initial state`, () => { 31 | expect(addressReducer(undefined, { type: 'unknown' })).toEqual(initialState); 32 | }); 33 | 34 | const payload = { address: 'address', time: '10:00', now: (new Date() - 0) }; 35 | 36 | test(`preserves address and time`, () => { 37 | const actual = addressReducer(initialState, keepAddressAndTime(payload)); 38 | expect(actual.address).toEqual(payload.address); 39 | expect(actual.time).toEqual(payload.time); 40 | expect(actual.origin).toEqual(payload.now); 41 | }); 42 | 43 | test(`restores initial state for address and time`, () => { 44 | const nextState = addressReducer(initialState, keepAddressAndTime(payload)); 45 | const actual = addressReducer(nextState, resetAddressAndTime()); 46 | 47 | expect(actual.address).toEqual(initialState.address); 48 | expect(actual.time).toEqual(initialState.time); 49 | expect(actual.origin).toEqual(initialState.origin); 50 | }); 51 | 52 | 53 | }); 54 | 55 | describe.skip(`retrieveRestaurantsForAddress()`, () => { 56 | 57 | const dispatch = jest.fn(); 58 | const getState = jest.fn(); 59 | const useDispatch = jest.fn(fn => fn(dispatch, getState)); 60 | 61 | beforeAll(() => { 62 | jest.useFakeTimers(); 63 | }); 64 | afterAll(() => { 65 | jest.useRealTimers(); 66 | }); 67 | afterEach(() => { 68 | jest.clearAllMocks(); 69 | jest.clearAllTimers(); 70 | }); 71 | 72 | test(`Calls real fetch/xhr function to retrieve data - receives data`, async () => { 73 | 74 | fetchRestaurantsMocked.mockImplementation(() => {}); 75 | 76 | const result = useDispatch(retrieveRestaurantsForAddress({})); 77 | 78 | expect(dispatch).toHaveBeenCalled(); 79 | expect(dispatch).toHaveBeenCalledTimes(1); 80 | expect(fetchRestaurantsMocked).toHaveBeenCalled(); 81 | expect(result).toBeInstanceOf(Promise); 82 | jest.advanceTimersToNextTimer(); 83 | try { 84 | await result; 85 | } catch {} 86 | expect(result).resolves.toEqual(expect.any(Object)); 87 | expect(dispatch).toHaveBeenCalledTimes(5); 88 | 89 | expect(dispatch.mock.calls).toEqual( 90 | Array.from({ length: 5 }, () =>([ expect.any(Object) ]))); 91 | 92 | const dispatchedTypes = dispatch.mock.calls.map(([ arg ]) => arg.type); 93 | expect(dispatchedTypes).toEqual(expect.arrayContaining([ 94 | expect.stringMatching('pending'), 95 | expect.stringMatching('keepAddressAndTime'), 96 | expect.stringMatching('keepRestaurants'), 97 | expect.stringMatching('router'), 98 | expect.stringMatching('fulfilled'), 99 | ])) 100 | 101 | }); 102 | 103 | test(`Calls real fetch/xhr function to retrieve data - handles errors`, async () => { 104 | 105 | fetchRestaurantsMocked.mockImplementation(() => Promise.reject({})); 106 | 107 | const result = useDispatch(retrieveRestaurantsForAddress({ time: '10:11' })); 108 | expect(dispatch).toHaveBeenCalled(); 109 | expect(dispatch).toHaveBeenCalledTimes(1); 110 | expect(fetchRestaurantsMocked).toHaveBeenCalled(); 111 | expect(result).toBeInstanceOf(Promise); 112 | jest.advanceTimersToNextTimer(); 113 | try { 114 | await result; 115 | } catch {} 116 | expect(result).resolves.toEqual(expect.any(Object)); 117 | expect(dispatch).toHaveBeenCalledTimes(2); 118 | 119 | 120 | }); 121 | 122 | 123 | }); 124 | }); 125 | -------------------------------------------------------------------------------- /src/features/card/cardSlice.js: -------------------------------------------------------------------------------- 1 | import { createSlice } from '@reduxjs/toolkit'; 2 | 3 | const ns= 'card'; 4 | const initialState = { 5 | value: {}, 6 | errors: {} 7 | }; 8 | 9 | export const accessCardValue = () => ({ [ns]: state }) => state.value; 10 | export const accessCardErrors = () => ({ [ns]: state }) => state.errors; 11 | 12 | export const cardSlice = createSlice({ 13 | name: ns, 14 | initialState, 15 | reducers: { 16 | updateCardValue: (state, { payload }) => { 17 | if (!payload) { 18 | return; 19 | } 20 | state.value = payload?.card; 21 | }, 22 | resetCard: (state) => { 23 | state.value = {}; 24 | state.errors = {}; 25 | } 26 | } 27 | }); 28 | 29 | 30 | export const { updateCardValue, resetCard } = cardSlice.actions; 31 | 32 | const namedReducer = { 33 | [ ns ]: cardSlice.reducer 34 | }; 35 | 36 | export default namedReducer; 37 | -------------------------------------------------------------------------------- /src/features/cart/cartSlice.js: -------------------------------------------------------------------------------- 1 | import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; 2 | import { getCart, postConfirmPayment, postCreatePaymentIntent, putUpdateCartWithItem } from '../actions/api'; 3 | 4 | const ns = 'cart'; 5 | 6 | export const obtainCartAsyncThunk = createAsyncThunk( 7 | 'cart/createNew', 8 | async (data, { rejectWithValue, dispatch }) => { 9 | void data; 10 | return getCart(); 11 | }); 12 | 13 | export const updateCartWithItemAsyncThunk = createAsyncThunk( 14 | 'cart/updateCartWithItem', 15 | async (data, { rejectWithValue, dispatch }) => { 16 | const { restaurantId, itemId, qty, item } = data; 17 | void item; 18 | if (!restaurantId || !itemId) { 19 | return; 20 | } 21 | return putUpdateCartWithItem(restaurantId, itemId, qty); 22 | }); 23 | 24 | export const postCreatePaymentIntentAsyncThunk = createAsyncThunk( 25 | 'payment/createPaymentIntent', 26 | async (data, { dispatch }) => { 27 | const { items } = data; 28 | return postCreatePaymentIntent(items); 29 | } 30 | ); 31 | 32 | export const postConfirmPaymentAsyncThunk = createAsyncThunk( 33 | 'payment/confirm', 34 | async (data, { rejectWithValue }) => { 35 | try { 36 | const { clientSecret, card } = data; 37 | return await postConfirmPayment(clientSecret, card); 38 | } catch (ex) { 39 | return rejectWithValue(ex); 40 | } 41 | } 42 | ); 43 | 44 | const initialState = { 45 | id: '123', 46 | orderId: '', 47 | cartInfo: { 48 | total: 0, 49 | subTotal: 0, 50 | delivery: 0, 51 | tax: 0, 52 | taxAmount: 0 53 | }, 54 | verboseCartInfo: { 55 | total: '$0.00', 56 | subTotal: '$0.00', 57 | delivery: '$0.00', 58 | tax: '$0.00', 59 | taxAmount: '0' 60 | }, 61 | status: null, 62 | items: [], 63 | paymentSuccessful: null 64 | }; 65 | 66 | export const accessCart = (propName) => ({ [ ns ]: state }) => propName ? (state?.[ propName ]) : state; 67 | export const accessCartItems = () => ({ [ ns ]: state }) => state?.items ?? []; 68 | export const accessCartStatus = () => ({ [ ns ]: state }) => state?.status; 69 | export const accessCartInfo = () => ({ [ ns ]: state }) => state?.cartInfo ?? {}; 70 | export const accessVerboseCartInfo = () => ({ [ ns ]: state }) => state?.verboseCartInfo ?? {}; 71 | export const accessPaymentSuccessful = () => ({ [ ns ]: state }) => state?.paymentSuccessful; 72 | 73 | export const cartSlice = createSlice({ 74 | name: ns, 75 | initialState, 76 | reducers: { 77 | resetCart: () => Object.assign({}, initialState, { items: [] }), 78 | paymentSuccessful: (state) => { 79 | debugger; 80 | state.paymentSuccessful = true; 81 | }, 82 | resetPaymentSuccessful: (state) => Object.assign({}, initialState, { items: [] }) 83 | }, 84 | extraReducers: builder => builder 85 | .addCase(obtainCartAsyncThunk.pending, (state, { payload }) => { 86 | state.status = 'pending'; 87 | }) 88 | .addCase(obtainCartAsyncThunk.fulfilled, 89 | (state, { payload, ...rest }) => { 90 | return Object.assign({}, state, payload, { status: 'ready' }); 91 | }) 92 | .addCase(obtainCartAsyncThunk.rejected, (state, { payload, ...rest }) => { 93 | state.status = 'error'; 94 | state.items = []; 95 | }) 96 | .addCase(updateCartWithItemAsyncThunk.pending, (state, { payload, meta }) => { 97 | const { itemId, item, restaurantId, qty } = meta.arg; 98 | const idx = state.items.findIndex(i => i.id === itemId); 99 | if (idx >= 0) { 100 | state.items = [ 101 | ...state.items.slice(0, idx), 102 | Object.assign({}, state.items[ idx ], { 103 | count: qty, 104 | oldCount: state.items[ idx ].count 105 | }), 106 | ...state.items.slice(idx + 1) 107 | ]; // state.items.splice(idx, 1); 108 | } else { 109 | state.items = [ 110 | ...state.items, 111 | Object.assign({}, item, { 112 | id: itemId, 113 | meta: { restaurantId }, 114 | count: qty, 115 | oldCount: 0 116 | }) 117 | ]; 118 | } 119 | 120 | }) 121 | .addCase(updateCartWithItemAsyncThunk.fulfilled, (state, { payload, meta }) => { 122 | 123 | if (!payload) { 124 | return state; 125 | } 126 | 127 | const { items, total, subTotal, delivery, tax, taxAmount, orderId } = payload; 128 | const cartInfo = { total, subTotal, delivery, tax, taxAmount }; 129 | const stateItemsMap = new Map(state.items.map(i => ([ i.id, i ]))); 130 | const arrivedItemsMap = new Map(items.map(i => ([ i.id, i ]))); 131 | const uniqueIds = [ ...new Set([ ...stateItemsMap.keys(), ...arrivedItemsMap.keys() ]) ]; 132 | state.items = uniqueIds.map((id) => Object.assign({}, 133 | stateItemsMap.get(id) || {}, 134 | arrivedItemsMap.get(id) || {}, 135 | { 'oldCount': undefined })); 136 | state.cartInfo = cartInfo; 137 | state.verboseCartInfo = verboseCurrencyProps(cartInfo); 138 | state.orderId = orderId; 139 | 140 | // [ 141 | // ...state.items.slice(0, idx), 142 | // ...(oldItem.count ? [ Object.assign({}, state.items[ idx ], { 143 | // oldCount: undefined 144 | // }) ] : []), 145 | // ...state.items.slice(idx + 1) 146 | // ]; 147 | 148 | }) 149 | .addCase(updateCartWithItemAsyncThunk.rejected, (state, { payload, meta, error }) => { 150 | const { itemId } = meta.arg; 151 | const idx = state.items.findIndex(item => item.id === itemId); 152 | if (idx < 0) { 153 | return; 154 | } 155 | 156 | state.items = [ 157 | ...state.items.slice(0, idx), 158 | ...((state.items[ idx ].oldCount === 0) ? [] : [ 159 | Object.assign({}, state.items[ idx ], { 160 | oldCount: undefined, 161 | count: state.items[ idx ].oldCount 162 | }) 163 | ]), 164 | ...state.items.slice(idx + 1) 165 | ]; 166 | 167 | }) 168 | 169 | .addCase(postCreatePaymentIntentAsyncThunk.pending, (state, { payload, meta }) => state) 170 | .addCase(postCreatePaymentIntentAsyncThunk.fulfilled, (state, { payload, meta }) => { 171 | // TODO: get amount sum from the response and set it here 172 | return state; 173 | }) 174 | .addCase(postCreatePaymentIntentAsyncThunk.rejected, (state, { payload, meta }) => state) 175 | .addCase(postConfirmPaymentAsyncThunk.pending, (state, { payload, meta }) => state) 176 | .addCase(postConfirmPaymentAsyncThunk.fulfilled, (state, { payload, meta }) => state) 177 | .addCase(postConfirmPaymentAsyncThunk.rejected, (state, { payload, meta }) => state) 178 | }); 179 | 180 | export const { resetCart, paymentSuccessful, resetPaymentSuccessful } = cartSlice.actions; 181 | 182 | const namedReducer = { 183 | [ ns ]: cartSlice.reducer 184 | }; 185 | 186 | export default namedReducer; 187 | 188 | function verboseCurrencyProps(src) { 189 | return Object.fromEntries(Array.from(Object.entries(src), ([ k, v ]) => ([ k, verboseCurrency(v) ]))); 190 | } 191 | 192 | function verboseCurrency(input) { 193 | if (!input) { 194 | return '$0.00'; 195 | } 196 | return (`$${ Number(input).toFixed(2) }`).replace('$.', '$0.'); 197 | } 198 | -------------------------------------------------------------------------------- /src/features/index.js: -------------------------------------------------------------------------------- 1 | import { connectRouter } from 'connected-react-router'; 2 | import address from './address/addressSlice'; 3 | import restaurants from './restaurants/restaurantsSlice'; 4 | import cart from './cart/cartSlice'; 5 | import card from './card/cardSlice'; 6 | import loading from './ui/loadingSlice'; 7 | 8 | export const unconnectedReducer = { 9 | ...address, 10 | ...restaurants, 11 | ...cart, 12 | ...card, 13 | ...loading 14 | }; 15 | 16 | export const makeConnectedReducer = history => ({ 17 | ...unconnectedReducer, 18 | ...(history ? { router: connectRouter(history) } : {}) 19 | }); 20 | -------------------------------------------------------------------------------- /src/features/restaurants/restaurantsSlice.js: -------------------------------------------------------------------------------- 1 | import { createEntityAdapter, createSlice } from '@reduxjs/toolkit'; 2 | import { retrieveRestaurantByIdAsyncThunk } from '../address/addressSlice'; 3 | 4 | const ns = 'restaurants'; 5 | 6 | const menuAdapter = createEntityAdapter({ 7 | selectId: ({ id }) => id, 8 | sortComparer: ({ id: a }, { id: b }) => a.localeCompare(b) 9 | }); 10 | const { selectAll } = menuAdapter.getSelectors(); 11 | 12 | const initialState = { 13 | selectedRestaurant: null, 14 | menuState: {}, 15 | menus: {} 16 | }; 17 | 18 | 19 | export const restaurantsSlice = createSlice({ 20 | name: ns, 21 | initialState, 22 | reducers: { 23 | resetSelectedRestaurant(state) { 24 | state.selectedRestaurant = null; 25 | }, 26 | keepSelectedRestaurant(state, { payload }) { 27 | state.selectedRestaurantId = payload?.id; 28 | } 29 | }, 30 | extraReducers: builder => builder.addCase( 31 | retrieveRestaurantByIdAsyncThunk.pending, (state, { payload, meta }) => { 32 | if (!meta) { 33 | return; 34 | } 35 | const { restaurantId } = meta.arg; 36 | state.menuState[ restaurantId ] = 'loading'; 37 | state.menus[ restaurantId ] = menuAdapter.getInitialState(); 38 | } 39 | ).addCase( 40 | retrieveRestaurantByIdAsyncThunk.fulfilled, (state, { payload, meta }) => { 41 | if (!payload) { 42 | return; 43 | } 44 | const { restaurantId } = meta.arg ?? {}; 45 | if (!restaurantId) { 46 | return; 47 | } 48 | state.menuState[ restaurantId ] = 'ready'; 49 | menuAdapter.setAll(state.menus[ restaurantId ], payload.menu); 50 | } 51 | ).addCase( 52 | retrieveRestaurantByIdAsyncThunk.rejected, (state, { payload, meta }) => { 53 | if (!meta) { 54 | return; 55 | } 56 | const { restaurantId } = meta.arg ?? {}; 57 | if (!restaurantId) { 58 | return; 59 | } 60 | state.menuState[ restaurantId ] = undefined; 61 | } 62 | ) 63 | }); 64 | 65 | export const { resetSelectedRestaurant, keepSelectedRestaurant } = restaurantsSlice.actions; 66 | 67 | export const accessSelectedRestaurantId = () => ({ [ ns ]: state }) => state.selectedRestaurantId; 68 | export const accessRestaurantMenuState = (restaurantId) => ({ [ ns ]: state }) => state.menuState[ restaurantId ]; 69 | export const accessMenuForRestaurant = (restaurantId, fallback) => ({ [ ns ]: state }) => (state.menus[ restaurantId ] ? 70 | selectAll(state.menus[ restaurantId ]) : 71 | undefined) || fallback; 72 | 73 | const namedReducer = { 74 | [ ns ]: restaurantsSlice.reducer 75 | }; 76 | 77 | 78 | export default namedReducer; 79 | -------------------------------------------------------------------------------- /src/features/restaurants/restaurantsSlice.test.js: -------------------------------------------------------------------------------- 1 | describe(`src/features/restaurants/restaurantsSlice.test.js`, function () { 2 | describe(`reducer`, function () { 3 | test(`pass`, () => {}); 4 | }); 5 | }); 6 | -------------------------------------------------------------------------------- /src/features/ui/loadingSlice.js: -------------------------------------------------------------------------------- 1 | const { createReducer } = require('@reduxjs/toolkit'); 2 | 3 | 4 | function isPendingAction(action) { 5 | return action.type.endsWith('/pending'); 6 | } 7 | 8 | function isFulfilledAction(action) { 9 | return action.type.endsWith('/fulfilled') || action.type.endsWith('/rejected'); 10 | } 11 | 12 | const initialState = { 13 | isLoading: false, 14 | pendingRequests: 0, 15 | requests: {} // Object.create(null) 16 | }; 17 | 18 | const ns = 'loading'; 19 | 20 | const loadingReducer = createReducer(initialState, builder => { 21 | builder 22 | .addMatcher(isPendingAction, (state, action) => { 23 | state.pendingRequests++; 24 | state.isLoading = true; 25 | state.requests[ action.meta.requestId ] = 'pending'; 26 | }) 27 | .addMatcher(isFulfilledAction, (state, action) => { 28 | state.pendingRequests--; 29 | state.isLoading = !!state.pendingRequests; 30 | state.requests[ action.meta.requestId ] = action.type.endsWith('/rejected') ? 'rejected' : 'resolved'; 31 | if (action.type.endsWith('/rejected')) { 32 | console.log('/rejected', action.payload, action.meta) 33 | } 34 | }); 35 | }); 36 | 37 | const namedReducer = { 38 | [ ns ]: loadingReducer 39 | }; 40 | 41 | export const accessIsLoading = () => ({ [ns]: state }) => state.isLoading; 42 | 43 | 44 | export default namedReducer; 45 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import ReactDOM from 'react-dom'; 2 | import * as serviceWorker from './serviceWorker'; 3 | import rootAppNode from './app/rootNode'; 4 | 5 | 6 | ReactDOM.render(rootAppNode, 7 | document.getElementById('root') 8 | ); 9 | 10 | // If you want your app to work offline and load faster, you can change 11 | // unregister() to register() below. Note this comes with some pitfalls. 12 | // Learn more about service workers: https://bit.ly/CRA-PWA 13 | serviceWorker.unregister(); 14 | -------------------------------------------------------------------------------- /src/jest.config.js: -------------------------------------------------------------------------------- 1 | console.log('Jest Config Loaded: maa-client/src/jest.config.js'); 2 | console.log('JEST_JUNIT_OUTPUT_DIR=', process.env.JEST_JUNIT_OUTPUT_DIR); 3 | 4 | module.exports = { 5 | setupFilesAfterEnv: [ 6 | './setupTests.js', 7 | '/window.setup.js' 8 | ], 9 | moduleNameMapper:{ 10 | "\\.(css|less|sass|scss)$": "/__mocks__/styleMock.js", 11 | "\\.(gif|ttf|eot|svg)$": "/__mocks__/fileMock.js" 12 | }, 13 | transformIgnorePatterns: [ 14 | 'node_modules/(?!(react-syntax-highlighter/dist/esm)|(reactstrap/es)|(@babel/runtime/helpers/esm))', 15 | ] 16 | }; 17 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then((registration) => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch((error) => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' }, 105 | }) 106 | .then((response) => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then((registration) => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready.then((registration) => { 134 | registration.unregister(); 135 | }); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 1 | import '@testing-library/jest-dom/extend-expect'; 2 | import fetchMock from "jest-fetch-mock"; 3 | 4 | console.log('src/setupTests.js') 5 | fetchMock.enableMocks(); 6 | -------------------------------------------------------------------------------- /src/shared/diagnostics/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @returns {{error:Function, debug:Function}} 4 | */ 5 | 6 | //export const getLogger = () => { 7 | // return [ 'log', 'warn', 'info', 'debug', 'error' ].reduce((obj, lvl) => 8 | // Object.assign(obj, { [ lvl ]: (...args) => 9 | // console[ lvl ](...args) }), {}); 10 | //}; 11 | 12 | const logger = console; 13 | 14 | export const logged = (...args) => { 15 | const [ fn, str, ...restArgs ] = args; 16 | if (fn instanceof Function) { 17 | return (...args) => { 18 | const [ arg0, ...rest ] = args; 19 | if (arg0 instanceof Error) { 20 | str ? logger.error(str, ...args) : logger.error(...args); 21 | } else { 22 | const arg00 = (typeof arg0 === 'object') ? JSON.stringify(arg0) : arg0; 23 | str ? logger.debug(str, arg00, ...rest) : logger.debug(arg00, ...rest); 24 | } 25 | return fn(...args); 26 | }; 27 | } 28 | const arg0 = fn; 29 | if (arg0 instanceof Error) { 30 | (typeof str === 'string') ? logger.error(str, arg0, ...restArgs) : logger.error(arg0, str, ...restArgs); 31 | } else { 32 | const arg00 = (typeof arg0 === 'object') ? JSON.stringify(arg0, getCircularRefsResolver()) : arg0; 33 | (typeof str === 'string') ? logger.debug(str, arg00, ...restArgs) : logger.debug(arg00, str, ...restArgs); 34 | } 35 | return arg0; 36 | }; 37 | 38 | function getCircularRefsResolver() { 39 | const cache = new Set(); 40 | 41 | return (key, value) => { 42 | if (typeof value === 'object' && value !== null) { 43 | // Duplicate reference found, discard key 44 | if (cache.has(value)) return; 45 | 46 | // Store value in our collection 47 | cache.add(value); 48 | } 49 | return value; 50 | }; 51 | } 52 | 53 | 54 | /** 55 | * 56 | * @param arg 57 | * @return {(function(...[*]): (*|undefined))|*} 58 | */ 59 | export function debugged(arg) { 60 | if (typeof arg === 'function') { 61 | return (...args) => { 62 | try { 63 | const result = arg(...args); 64 | 65 | // result of the function execution (success) 66 | console.log(...args); 67 | console.log(result); 68 | debugger; 69 | 70 | return result; 71 | } catch (ex) { 72 | 73 | // result of the function execution (failure) 74 | console.log(...args); 75 | console.error(ex); 76 | debugger; 77 | 78 | throw ex; 79 | } 80 | }; 81 | } 82 | 83 | // inspected non-callable argument 84 | console.log(arg); 85 | debugger; 86 | 87 | return arg; 88 | } 89 | -------------------------------------------------------------------------------- /src/shared/e2e/helpers.js: -------------------------------------------------------------------------------- 1 | export const FOR_TESTS = 'test'; 2 | export const FOR_RENDER = 'render'; 3 | export const FOR_TEST_SVG = 'testSvg'; 4 | export const FOR_RENDER_SVG = 'renderSvg'; 5 | 6 | /** 7 | * 8 | * @param arr {Array} 9 | * @return Array 10 | */ 11 | export function pickHeadUntilNullish(arr) { 12 | return arr.reduce((memo, arg, idx) => 13 | ((idx === memo.length) ? 14 | ((arg == null) ? memo : memo.concat([ arg ])) : 15 | memo), []); 16 | } 17 | 18 | /** 19 | * 20 | * @param {...string} args 21 | * @return {function(string): T} 22 | */ 23 | export function prepareTestId(...args) { 24 | return fn => fn(produceTestIdAttrValue(args)); 25 | } 26 | 27 | /** 28 | * 29 | * @param {...string} args 30 | * @return {function(function(string):P): function(...string): P} 31 | */ 32 | export function prepareTestIdOpen(...args) { 33 | return fn => (...args2) => { 34 | return fn(produceTestIdAttrValue([ ...args, ...args2 ])); 35 | }; 36 | } 37 | 38 | /** 39 | * 40 | * @param {Array} args 41 | * @return {string|''} 42 | */ 43 | function produceTestIdAttrValue(args) { 44 | const selector = pickHeadUntilNullish(args).map(String).join('|'); 45 | return selector ? selector + '|' : selector; 46 | } 47 | 48 | /** 49 | * 50 | * @param sel {string} 51 | * @return {{'data-testid'}} 52 | */ 53 | export function e2eAttr(sel) { 54 | return ({ 'data-testid': sel }); 55 | } 56 | 57 | /** 58 | * 59 | * @param sel {string} 60 | * @return {string} 61 | */ 62 | export function e2eSelector(sel) { 63 | if (sel) { 64 | return `[data-testid^="${ sel }"]`; 65 | } 66 | return '[data-testid=""]'; 67 | } 68 | 69 | const implMap = { 70 | [ FOR_TESTS ]: e2eSelector, 71 | [ FOR_RENDER ]: e2eAttr, 72 | [ FOR_TEST_SVG ]: null, 73 | [ FOR_RENDER_SVG ]: null 74 | }; 75 | 76 | /** 77 | * 78 | * @param {function(function(...string): function(arg:string): T, ?function(...string):function(function(string):P): function(...string): P):} cb 79 | * @return {function('test'|'render'): Object|T|P} 80 | */ 81 | export const defineTestIdDictionary = 82 | cb => 83 | testOrRuntime => { 84 | const cbResult = cb(prepareTestId, prepareTestIdOpen); 85 | const impl = implMap[ testOrRuntime ] || (K => K); 86 | return (typeof cbResult === 'function') ? cbResult(impl) : applyForEachPair(cbResult, impl); 87 | }; 88 | 89 | 90 | export const cssSel = val => { 91 | return new CssSel(val, null, ''); 92 | }; 93 | 94 | export class CssSel { 95 | /** 96 | * 97 | * @param val 98 | * @param {CssSel} [parent] 99 | * @param {''|' '|'>'|','|' ~ '} [rel=''] 100 | * @param {array} [marks] 101 | */ 102 | constructor(val, parent = null, rel = '', marks) { 103 | this._args = [ val, parent, rel, marks ]; 104 | this._marks = marks || (parent ? parent._marks : []) || []; 105 | } 106 | 107 | store() { 108 | return new CssSel('', this, '', [ ...this._marks, this ]); 109 | } 110 | 111 | get(idx) { 112 | return this._marks[ idx ]; 113 | } 114 | 115 | /** 116 | * add a selector part for a descendant 117 | * @param val 118 | * @return {CssSel} 119 | */ 120 | desc(val) { 121 | return new CssSel(val, this, ' '); 122 | } 123 | 124 | /** 125 | * add a selector part for an immediate child 126 | * @param val 127 | * @return {CssSel} 128 | */ 129 | child(val) { 130 | return new CssSel(val, this, '>'); 131 | } 132 | 133 | /** 134 | * add a modifier for a current selector 135 | * @param val 136 | * @return {CssSel} 137 | */ 138 | mod(val) { 139 | return new CssSel(val, this, ''); 140 | } 141 | 142 | not(sel) { 143 | return new CssSel('', this, '').mod(`:not(${ sel })`) 144 | } 145 | 146 | /** 147 | * 148 | * @param { string } attrName 149 | * @param { string|number } [attrValue] 150 | * @param { string } [attrCf] 151 | * @return {CssSel} 152 | */ 153 | attr(attrName, attrValue, attrCf) { 154 | if (attrValue == null) { 155 | return new CssSel(`[${ attrName }]`, this, ''); 156 | } 157 | if (attrCf == null) { 158 | return new CssSel(`[${ attrName }="${ String(attrValue).replace('"', '\\"') }"]`, this, ''); 159 | } 160 | return new CssSel(`[${ attrName }${ attrCf }="${ String(attrValue).replace('"', '\\"') }"]`, this, ''); 161 | } 162 | 163 | or(val) { 164 | return new CssSel(val, this, ','); 165 | }; 166 | 167 | second() { 168 | return new CssSel(getValue(this), this, ' ~ '); 169 | } 170 | 171 | third() { 172 | const next = this.second(); 173 | return new CssSel(getValue(this), next, ' ~ '); 174 | } 175 | 176 | toString() { 177 | return getValue(this); 178 | } 179 | 180 | valueOf() { 181 | return getValue(this); 182 | } 183 | } 184 | 185 | function getValue(node) { 186 | if (!node.effectiveVal) { 187 | const [ val, parent, rel ] = node._args; 188 | node.effectiveVal = String(parent || '') + rel + val; 189 | } 190 | return node.effectiveVal; 191 | } 192 | 193 | /** 194 | * 195 | * @param obj { Object} 196 | * @param fn { function(*): T} 197 | * @return {Object} 198 | */ 199 | export function applyForEachPair(obj, fn) { 200 | return Object.fromEntries( 201 | Array.from(Object.entries(obj || {}), 202 | ([ k, v ]) => [ k, typeof v === 'function' ? v(fn) : v ])); 203 | } 204 | 205 | -------------------------------------------------------------------------------- /src/shared/e2e/index.js: -------------------------------------------------------------------------------- 1 | import { cssSel, defineTestIdDictionary, FOR_RENDER, FOR_RENDER_SVG, FOR_TEST_SVG, FOR_TESTS } from './helpers'; 2 | 3 | const defaultExport = Object.assign(defineTestIdDictionary, { 4 | FOR_RENDER, 5 | FOR_TESTS, 6 | FOR_TEST_SVG, 7 | FOR_RENDER_SVG, 8 | cssSel 9 | }); 10 | export default defaultExport; 11 | export { FOR_RENDER, FOR_TESTS, FOR_TEST_SVG, FOR_RENDER_SVG, defineTestIdDictionary, cssSel }; 12 | -------------------------------------------------------------------------------- /src/shared/email/email.test.js: -------------------------------------------------------------------------------- 1 | import { destructureEmail, DEFAULT_LABEL_PREFIX, getRandomizedEmailTemplate, DEFAULT_RANDOM_PLACEHOLDER, getRandomEmail } from './index'; 2 | 3 | describe('A set of utilities to dissect email addresses', () => { 4 | 5 | describe('destructureEmail()', () => { 6 | 7 | [ 8 | [ 'a@a.com', [ 'a', DEFAULT_LABEL_PREFIX, 'a.com' ]], 9 | [ 'a+b@a.com', [ 'a', 'b', 'a.com' ]], 10 | ].filter(Boolean).forEach(([ input, [ expUserName, expLabel, expDomain ]]) => it(`can destructure '${ input }'`, () => { 11 | const { userName, label, domain } = destructureEmail(input); 12 | expect(userName).toEqual(expUserName); 13 | expect(label).toEqual(expLabel); 14 | expect(domain).toEqual(expDomain); 15 | })); 16 | 17 | it('throws for multilabel emails', () => { 18 | expect(() => destructureEmail('a++b@c.com')).toThrow(); 19 | expect(() => destructureEmail('a+a+b@c.com')).toThrow(); 20 | }); 21 | 22 | }); 23 | 24 | describe('getRandomizedEmailTemplate()', () => { 25 | [ 26 | [ 'a@a.com', undefined, `a+${ DEFAULT_LABEL_PREFIX }${ DEFAULT_RANDOM_PLACEHOLDER }@a.com` ], 27 | [ 'a@a.com', '', `a+${ DEFAULT_LABEL_PREFIX }@a.com` ], 28 | [ 'a+a@a.com', undefined, `a+a${ DEFAULT_RANDOM_PLACEHOLDER }@a.com` ], 29 | [ 'a+a@a.com', '_b_', `a+a_b_@a.com` ], 30 | ].filter(Boolean).forEach(([ input, randomPlaceholder, expectedResult ]) => it(`can provide template for random email for '${ input }'`, () => { 31 | const result = getRandomizedEmailTemplate(input, randomPlaceholder); 32 | expect(result).toEqual(expectedResult); 33 | })); 34 | }); 35 | 36 | describe('getRandomEmail()', () => { 37 | [ 38 | [ 'a@a.com', undefined, `a+${ DEFAULT_LABEL_PREFIX }@a.com` ], 39 | [ 'a@a.com', () => 'random', `a+${ DEFAULT_LABEL_PREFIX }random@a.com` ], 40 | [ 'a+a@a.com', undefined, `a+a@a.com` ], 41 | [ 'a+a@a.com', () => 'random', `a+arandom@a.com` ], 42 | ].filter(Boolean).forEach(([ input, randomPartGetter, expectedResult ]) => it(`can create unique emails by supplying random part generator, tested on '${ input }'`, () => { 43 | const result = getRandomEmail(input, randomPartGetter); 44 | expect(result).toEqual(expectedResult); 45 | })); 46 | }); 47 | 48 | }); 49 | -------------------------------------------------------------------------------- /src/shared/email/index.js: -------------------------------------------------------------------------------- 1 | export const DEFAULT_LABEL_PREFIX = 'maa-test-'; 2 | export const DEFAULT_RANDOM_PLACEHOLDER = '[RANDOM]'; 3 | 4 | export function destructureEmail(emailAddress, fn = K => K) { 5 | const [ userName, domain ] = emailAddress.split('@'); 6 | const [ realUserName, label, ...byproduct ] = userName.split(/\+/); 7 | if (byproduct.length) { 8 | throw new Error(`The email address has more than one label.`); 9 | } 10 | return fn({ userName: realUserName, label: label || DEFAULT_LABEL_PREFIX, domain }); 11 | } 12 | 13 | export function getRandomizedEmailTemplate (emailAddress, randomPlaceholder = DEFAULT_RANDOM_PLACEHOLDER) { 14 | return destructureEmail(emailAddress, ({ userName, label, domain }) => `${ userName }+${ label }${ randomPlaceholder }@${ domain }`); 15 | } 16 | 17 | export function getRandomEmail(emailAddress, randomPartGetter = () => '') { 18 | return getRandomizedEmailTemplate(emailAddress, randomPartGetter()); 19 | } -------------------------------------------------------------------------------- /src/shared/env/env.test.js: -------------------------------------------------------------------------------- 1 | import { getEnvVar } from './envGetter'; 2 | import { ensureEnvVariable, ensureEnvVariables } from './index'; 3 | 4 | jest.mock('./envGetter'); 5 | 6 | const ref = { 7 | current: null 8 | }; 9 | 10 | getEnvVar.mockImplementation((...args) => ref.current && ref.current(...args)) 11 | 12 | describe('A set of utilities to check presence of env variables', () => { 13 | 14 | beforeAll(() => { 15 | ref.current = key => ({ 16 | 'DEFINED': 'true', 17 | 'DEFINED2': '2' 18 | })[ key ]; 19 | }); 20 | 21 | describe('ensureEnvVariable()', () => { 22 | 23 | test('Checks the existence of an env variable and returns its value', () => { 24 | expect(ensureEnvVariable('DEFINED')).toEqual('true'); 25 | expect(ensureEnvVariable('DEFINED2')).toEqual('2'); 26 | }); 27 | 28 | test('Throws if a variable is not defined', () => { 29 | expect(() => ensureEnvVariable('UN-DEFINED')).toThrow(); 30 | }); 31 | 32 | test('Returns the supplied default value (even falsey) if a variable is not defined', () => { 33 | expect(ensureEnvVariable('UN-DEFINED-2', 2)).toEqual(2); 34 | expect(ensureEnvVariable('UN-DEFINED-0', 0)).toEqual(0); 35 | expect(ensureEnvVariable('UN-DEFINED-false', false)).toEqual(false); 36 | expect(ensureEnvVariable('UN-DEFINED-empty', '')).toEqual(''); 37 | }); 38 | 39 | }); 40 | 41 | describe('ensureEnvVariables()', () => { 42 | 43 | test('Can check several env variables at once, returning an array of their values', () => { 44 | expect(ensureEnvVariables([ 'DEFINED', 'DEFINED2' ])).toEqual([ 'true', '2' ]); 45 | }); 46 | 47 | test('Throws if any of the requested variables are not defined, error message contains missing variable names', () => { 48 | expect(() => ensureEnvVariables([ 'UN-DEFINED', 'UN-DEFINED2', 'DEFINED' ])).toThrow(/(UN-DEFINED.+UN-DEFINED2)|(UN-DEFINED2.+UN-DEFINED)/); 49 | }); 50 | 51 | test('Returns the supplied default value for the corresponding index', () => { 52 | expect(ensureEnvVariables( 53 | [ 'DEFINED', 'UN-DEFINED-2', 'UN-DEFINED-0', 'UN-DEFINED-false', 'UN-DEFINED-empty' 54 | ], 55 | [ undefined, 2, 0, false, '' ] 56 | )).toEqual([ 'true', 2, 0, false, '' ]); 57 | }); 58 | 59 | }); 60 | 61 | }); 62 | -------------------------------------------------------------------------------- /src/shared/env/envGetter.js: -------------------------------------------------------------------------------- 1 | 2 | export const getEnvVar = envVar => process.env[ envVar ]; 3 | -------------------------------------------------------------------------------- /src/shared/env/index.js: -------------------------------------------------------------------------------- 1 | import { getEnvVar } from './envGetter'; 2 | 3 | /** 4 | * @description this will be replaced by ensureEnvVariablesWithParameterStore() 5 | * @param envVars 6 | * @param fallbackValues 7 | * @returns {String[]} 8 | */ 9 | export function ensureEnvVariables(envVars, fallbackValues) { 10 | const hitsAndMisses = Array.from(envVars).map((envVar, idx) => ({ 11 | env: envVar, 12 | val: getEnvVar(envVar), 13 | fallback: fallbackValues && fallbackValues[ idx ] 14 | })); 15 | 16 | const misses = hitsAndMisses.filter(({ val, fallback }) => !val && (typeof fallback === 'undefined')).map(({ env }) => env); 17 | 18 | if (misses.length) { 19 | throw new Error(`Set up these environment variables: ${ misses.join(', ') }`); 20 | } 21 | 22 | return hitsAndMisses.map(({ val, fallback }) => (val || fallback)); 23 | } 24 | 25 | 26 | export function ensureEnvVariable(envVar, fallback) { 27 | const [ result ] = ensureEnvVariables([ envVar ], [ fallback ]); 28 | return result; 29 | } 30 | -------------------------------------------------------------------------------- /src/shared/forms/submissionHandling.js: -------------------------------------------------------------------------------- 1 | export function processFormSubmissionError(effectiveError, setError, clearErrors) { 2 | if (!effectiveError) { 3 | clearErrors && clearErrors(); 4 | return; 5 | } 6 | if (effectiveError.errors) { 7 | ((Array.isArray(effectiveError.errors) && effectiveError.errors.every(Array.isArray)) ? 8 | effectiveError.errors : 9 | Array.from(Object.entries(effectiveError.errors))).forEach(([ key, value ]) => 10 | setError(key, { type: 'server', message: value ?? 'Server-side error we cannot explain' })); 11 | } else { 12 | setError('form', { type: 'server', message: effectiveError.message ?? 'Server error' }); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/shared/forms/submissionHandling.test.js: -------------------------------------------------------------------------------- 1 | import { processFormSubmissionError } from './submissionHandling'; 2 | 3 | describe(`src/shared/forms/submissionHandling.js`, () => { 4 | 5 | describe(`processFormSubmissionError(effectiveError, setError, clearErrors)`, () => { 6 | 7 | const setError = jest.fn(); 8 | const clearErrors = jest.fn(); 9 | 10 | afterEach(() => { 11 | jest.clearAllMocks(); 12 | }); 13 | 14 | test(`falsy effectiveError makes clearErrors called`, () => { 15 | processFormSubmissionError(undefined, setError, clearErrors); 16 | expect(clearErrors).toHaveBeenCalled(); 17 | expect(setError).not.toHaveBeenCalled(); 18 | }); 19 | 20 | test(`truthy error with a message - supplied message form error`, () => { 21 | processFormSubmissionError({ message: 'Single error message' }, setError, clearErrors); 22 | expect(clearErrors).not.toHaveBeenCalled(); 23 | expect(setError).toHaveBeenCalled(); 24 | expect(setError).toHaveBeenCalledTimes(1); 25 | }); 26 | 27 | test(`truthy error with no message - default form error`, () => { 28 | processFormSubmissionError({ _no_message_prop: true }, setError, clearErrors); 29 | expect(clearErrors).not.toHaveBeenCalled(); 30 | expect(setError).toHaveBeenCalled(); 31 | expect(setError).toHaveBeenCalledTimes(1); 32 | }); 33 | 34 | test(`truthy error with messages for several props - by-fields errors`, () => { 35 | processFormSubmissionError({ 36 | errors: { 37 | foo: 'error1', bar: 'error2' 38 | } 39 | }, setError, clearErrors); 40 | expect(clearErrors).not.toHaveBeenCalled(); 41 | expect(setError).toHaveBeenCalled(); 42 | expect(setError).toHaveBeenCalledTimes(2); 43 | expect(setError).toHaveBeenNthCalledWith(1, 'foo',{ message: 'error1', type: 'server'}); 44 | expect(setError).toHaveBeenNthCalledWith(2, 'bar', { message: 'error2', type: 'server'}); 45 | }); 46 | 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /src/shared/promises/index.js: -------------------------------------------------------------------------------- 1 | export function forTimeout(ms, result) { 2 | return result ? 3 | ((typeof result === 'function') ? 4 | new Promise((rs, rj) => setTimeout(() => result(rs, rj), ms)) : 5 | new Promise(rs => setTimeout(() => rs(result), ms))) : 6 | new Promise(rs => setTimeout(rs, ms)); 7 | } 8 | 9 | const MSEC_IN_SEC = 1000; 10 | const MSEC_IN_MIN = MSEC_IN_SEC * 60; 11 | Object.assign(forTimeout, { 12 | SEC: MSEC_IN_SEC, 13 | MIN: MSEC_IN_MIN 14 | }); 15 | 16 | /** 17 | * 18 | * @param promise 19 | * @returns {Promise<*[]|*[]>} 20 | */ 21 | export async function safelyExecuteAsync(promise) { 22 | try { 23 | return [ null, await promise ]; 24 | } catch (ex) { 25 | return [ ex ]; 26 | } 27 | } 28 | 29 | /** 30 | * 31 | * @param asyncFn 32 | * @returns {(function(...[*]): Promise<[null, *]|[*]|undefined>)|*} 33 | */ 34 | export function makeSafelyRunAsyncFn(asyncFn) { 35 | return async (...args) => { 36 | try { 37 | return [ null, await asyncFn(...args) ]; 38 | } catch (ex) { 39 | return [ ex ]; 40 | } 41 | } 42 | } 43 | 44 | export function safelyExecuteSync(fn) { 45 | return (...args) => { 46 | try { 47 | return [ null, fn(...args) ]; 48 | } catch (ex) { 49 | return [ ex ]; 50 | } 51 | }; 52 | 53 | } 54 | 55 | export function stubAsync(promise) { 56 | promise.then(() => void 0, () => void 0); 57 | return promise; 58 | } 59 | 60 | /** 61 | * Prevents another async call if the previous is not fulfilled 62 | * @param asyncFn 63 | * @return {function(...[*]): null} 64 | */ 65 | export function blockedAsync(asyncFn) { 66 | const ctx = { current: null }; 67 | let count = 0; 68 | 69 | function cleanup() { 70 | ctx.current = null; 71 | } 72 | 73 | return (...args) => { 74 | if (!ctx.current) { 75 | ctx.current = asyncFn(...args); 76 | ctx.current.then(cleanup, cleanup); 77 | } else { 78 | console.log('blockedAsync blocked', count++); 79 | } 80 | return ctx.current; 81 | }; 82 | } 83 | 84 | export function ExposedPromise() { 85 | const ctx = this; 86 | return Object.assign(new Promise((resolve, reject) => { 87 | Object.assign(ctx, { resolve, reject }); 88 | }), ctx); 89 | } 90 | -------------------------------------------------------------------------------- /src/testability/index.js: -------------------------------------------------------------------------------- 1 | import { FOR_RENDER, FOR_TESTS } from '../shared/e2e'; 2 | import { selectors } from './selectors'; 3 | 4 | export const e2eAssist = selectors(FOR_RENDER); 5 | export const SEL = selectors(FOR_TESTS); 6 | -------------------------------------------------------------------------------- /src/testability/selectors.js: -------------------------------------------------------------------------------- 1 | import { defineTestIdDictionary } from '../shared/e2e'; 2 | 3 | /** 4 | * 5 | * @type {(function(("test"|"render")): Object)|T|P} 6 | */ 7 | export const selectors = defineTestIdDictionary((testId, testIdRest) => ({ 8 | PAGE_LANDING: testId('page', 'landing'), 9 | 10 | FORM_PICK_ADDRESS_TIME: testId('form', 'pick delivery time and address'), 11 | FORM_FIELD_ADDRESS: testId('field', 'text input', 'address'), 12 | FORM_FIELD_TIME: testId('field', 'time input', 'time'), 13 | FORM_FEEDBACK_ADDRESS: testId('feedback', 'error feedback', 'address'), 14 | FORM_FEEDBACK_TIME: testId('feedback', 'error feedback', 'time'), 15 | BTN_SUBMIT_FORM_PICK_ADDRESS_TIME: testId('button', 'submit', 'landing page form'), 16 | ICON_SPIN: testId('icon', 'spinning'), 17 | 18 | PAGE_RESTAURANTS_LIST: testId('page', 'restaurants list'), 19 | TEXT_RESTAURANTS_LIST_SIZE: testId('text', 'restaurants list size'), 20 | 21 | TBL_RESTAURANTS_LIST: testId('table', 'restaurants list'), 22 | CTL_SIZE_PER_PAGE_FOR_TABLE: testId('table nav', 'pagination control', 'size per page'), 23 | CTL_PAGINATION_FOR_TABLE: testId('table nav', 'pagination control', 'pagination buttons'), 24 | 25 | PAGE_RESTAURANT_MENU: testId('page', 'restaurant menu'), 26 | TBL_RESTAURANT_MENU: testId('table', 'restaurant menu'), 27 | TBL_YOUR_TRAY: testId('table', 'your tray'), 28 | 29 | BTN_TO_CHECKOUT: testId('button', 'navigation', 'to checkout'), 30 | BTN_ADD_TO_CART: testId('button', 'add to cart'), 31 | BTN_ADD_TO_CART_FRESH: testId('button', 'add to cart', 'no such item in cart'), 32 | BTN_ADD_TO_CART_ADDED: testId('button', 'add to cart', 'already in cart'), 33 | 34 | INFO_MENU_IS_EMPTY: testId('text', 'menu table is empty'), 35 | INFO_TRAY_IS_EMPTY: testId('text', 'tray table is empty'), 36 | INFO_CART_VALUE: testId('text', 'cart subtotal'), 37 | INFO_CART_VALUE_OF: testIdRest('text', 'cart subtotal'), 38 | 39 | PAGE_CHECKOUT: testId('page', 'checkout'), 40 | PAGE_THANKYOU: testId('page', 'thank you'), 41 | 42 | MODAL_PAYMENT: testId('modal', 'payment'), 43 | BTN_MODAL_PAYMENT_DISMISS_FN: testIdRest('button', 'dismiss payment modal'), 44 | BTN_MODAL_PAYMENT_DISMISS_GENERAL: testId('button', 'dismiss payment modal'), 45 | BTN_MODAL_PAYMENT_DISMISS: testId('button', 'dismiss payment modal', 'dismiss'), 46 | BTN_MODAL_PAYMENT_CANCEL: testId('button', 'dismiss payment modal', 'cancel'), 47 | 48 | FORM_PAYMENT: testId('form', 'payment'), 49 | BTN_FORM_PAYMENT_SUBMIT: testId('button', 'submit payment form'), 50 | TEXT_FORM_PAYMENT_ERRORS: testId('text', 'payment form errors'), 51 | TEXT_FORM_PAYMENT_SUCCESS: testId('text', 'payment form success'), 52 | 53 | FLD_FORM_PAYMENT_FN: testIdRest('field', 'payment form'), 54 | FLD_FORM_PAYMENT_CARD_NUMBER: testId('field', 'payment form', 'card_number'), 55 | FLD_FORM_PAYMENT_EXP_MONTH: testId('field', 'payment form', 'exp_month'), 56 | FLD_FORM_PAYMENT_EXP_YEAR: testId('field', 'payment form', 'exp_year'), 57 | FLD_FORM_PAYMENT_CVV: testId('field', 'payment form', 'cvv'), 58 | FLD_FORM_PAYMENT_ZIP: testId('field', 'payment form', 'zip'), 59 | 60 | BTN_INVOKE_PAYMENT_MODAL: testId('button', 'invoke payment modal'), 61 | BTN_CHECKOUT_MODIFY_CART: testId('button', 'modify cart', 'checkout page'), 62 | BTN_CHECKOUT_REMOVE_ITEM: testId('button', 'remove item', 'checkout page'), 63 | BTN_CHECKOUT_REMOVE_ITEM_FN: testIdRest('button', 'remove item', 'checkout page'), 64 | 65 | CARD_CHECKOUT_ITEM: testId('card', 'item', 'checkout page'), 66 | CARD_CHECKOUT_ITEM_FN: testIdRest('card', 'item', 'checkout page'), 67 | 68 | TEXT_ORDER_ID_FN: testIdRest('text', 'orderId'), 69 | TEXT_ORDER_ID: testId('text', 'orderId') 70 | 71 | })); 72 | -------------------------------------------------------------------------------- /src/ui/components/SelectedAddressRow.js: -------------------------------------------------------------------------------- 1 | import { useDispatch, useSelector } from 'react-redux'; 2 | import { accessDeliveryAddress, accessDeliveryTime, resetAddressAndTime } from '../../features/address/addressSlice'; 3 | import { useCallback, useEffect } from 'react'; 4 | import { navigateToEditDeliveryAddress } from '../../features/actions/navigation'; 5 | import { Col, Container } from 'reactstrap'; 6 | import { RoundedButton } from '../elements/formElements'; 7 | import { Span } from '../elements/textElements'; 8 | import { IconGeo, IconEdit } from '../elements/icons'; 9 | 10 | export const SelectedAddressRow = () => { 11 | 12 | const dispatch = useDispatch(); 13 | const deliveryAddress = useSelector(accessDeliveryAddress()); 14 | const deliveryTime = useSelector(accessDeliveryTime()); 15 | 16 | useEffect(() => { 17 | if (deliveryAddress && deliveryTime) { 18 | return; 19 | } 20 | dispatch(resetAddressAndTime()); 21 | dispatch(navigateToEditDeliveryAddress()); 22 | }, [ deliveryAddress, deliveryTime, dispatch ]); 23 | 24 | const handleEditAddress = useCallback(() => { 25 | dispatch(navigateToEditDeliveryAddress()); 26 | }, [ dispatch ]); 27 | 28 | 29 | return (
30 | 31 | 32 | 33 |
{ deliveryAddress }
34 | 35 | 36 |
37 | 38 |
39 | 40 | 41 |
42 |
); 43 | }; 44 | -------------------------------------------------------------------------------- /src/ui/components/SelectedRestaurantRow.js: -------------------------------------------------------------------------------- 1 | import { useDispatch, useSelector } from 'react-redux'; 2 | import { accessSelectedRestaurantId } from '../../features/restaurants/restaurantsSlice'; 3 | import { Col, Container } from 'reactstrap'; 4 | import { RoundedButton } from '../elements/formElements'; 5 | import { Span } from '../elements/textElements'; 6 | import { IconEdit, IconGeo, IconClock } from '../elements/icons'; 7 | import { useCallback } from 'react'; 8 | import { navigateToPickRestaurants } from '../../features/actions/navigation'; 9 | import { accessRestaurantInfo } from '../../features/address/addressSlice'; 10 | 11 | export function SelectedRestaurantRow() { 12 | 13 | const dispatch = useDispatch(); 14 | const selectedRestaurantId = useSelector(accessSelectedRestaurantId()); 15 | const selectedRestaurant = useSelector(accessRestaurantInfo(selectedRestaurantId)); 16 | const handleChangeRestaurant = useCallback(() => { 17 | dispatch(navigateToPickRestaurants()); 18 | }, [ dispatch ]); 19 | 20 | return (
21 | 22 | 23 | 24 |
{ selectedRestaurant?.address ?? 'No Address' }
25 | 26 | 27 |
{ selectedRestaurant?.name ?? 'No Restaurant' }
28 | 29 | 30 |
{ selectedRestaurant?.avgDeliveryTime }
31 | 32 | 33 |
34 |
); 35 | } 36 | -------------------------------------------------------------------------------- /src/ui/elements/Loading.js: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | import React from 'react'; 3 | import cx from 'classnames'; 4 | import { IconRefresh } from './icons'; 5 | 6 | export const Loading = styled.div` 7 | min-height: 80vh; 8 | text-align: center; 9 | vertical-align: center; 10 | display: flex; 11 | flex-direction: column; 12 | justify-content: center; 13 | align-content: center; 14 | border-radius: 2rem; 15 | font-size: 1.5rem; 16 | `; 17 | 18 | export const LoadingSpinner = ({ inline }) => 19 |
20 | 21 |
; 22 | -------------------------------------------------------------------------------- /src/ui/elements/Snippet/Snippet.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import '@testing-library/jest-dom/extend-expect'; 3 | import { cleanup, fireEvent, render, waitForDomChange } from '@testing-library/react'; 4 | import { Provider } from 'react-redux'; 5 | import { history, store } from '../../../app/store'; 6 | import { ConnectedRouter } from 'connected-react-router'; 7 | import { Snippet } from './index'; 8 | 9 | // from: https://github.com/popperjs/popper-core/issues/478 10 | // How to use Popper.js in Jest / JSDOM? 11 | jest.mock( 12 | 'popper.js', 13 | () => 14 | class Popper { 15 | static placements = [ 16 | 'auto', 'auto-end', 'auto-start', 17 | 'bottom', 'bottom-end', 'bottom-start', 18 | 'left', 'left-end', 'left-start', 19 | 'right', 'right-end', 'right-start', 20 | 'top', 'top-end', 'top-start' 21 | ]; 22 | 23 | constructor() { 24 | return { 25 | destroy: () => {}, 26 | scheduleUpdate: () => {} 27 | }; 28 | } 29 | } 30 | ); 31 | 32 | describe(`src/ui/elements/Snippet/index.js`, () => { 33 | describe(`Snippet component`, () => { 34 | 35 | afterEach(cleanup); 36 | 37 | test('renders a Snippet component', async () => { 38 | const { getByText, getAllByText } = render( 39 | 40 | 41 | 42 | 43 | 44 | ); 45 | 46 | expect(getByText(/lollapalooza/i)).toBeInTheDocument(); 47 | expect(getAllByText(/Copy/i)[ 0 ]).toBeInTheDocument(); 48 | 49 | getAllByText(/Copy/i)[ 0 ].focus(); 50 | fireEvent.click(getAllByText(/Copy/i)[ 0 ]); 51 | await waitForDomChange(); 52 | 53 | expect(getByText(/Successfully copied/i)).toBeInTheDocument(); 54 | 55 | }); 56 | 57 | 58 | }); 59 | 60 | }); 61 | -------------------------------------------------------------------------------- /src/ui/elements/Snippet/index.js: -------------------------------------------------------------------------------- 1 | import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; 2 | import { useCopyToClipboard } from 'react-use'; 3 | import { UncontrolledTooltip } from 'reactstrap'; 4 | import { If } from '../conditions'; 5 | import { Light as SyntaxHighlighter } from 'react-syntax-highlighter'; 6 | import js from 'react-syntax-highlighter/dist/esm/languages/hljs/javascript'; 7 | import bash from 'react-syntax-highlighter/dist/esm/languages/hljs/bash'; 8 | import docco from 'react-syntax-highlighter/dist/esm/styles/hljs/docco'; 9 | import './snippet.scss'; 10 | 11 | SyntaxHighlighter.registerLanguage('javascript', js); 12 | SyntaxHighlighter.registerLanguage('bash', bash); 13 | 14 | 15 | const COPIED_MESSAGE_LIFE = 5000; 16 | 17 | export const Snippet = ({ messageToCopy, lang, style = docco }) => { 18 | 19 | const initialized = useRef(true); 20 | 21 | const [ copiedTs, setCopiedTs ] = useState(0); 22 | const [ copyState, copyToClipboard ] = useCopyToClipboard(); 23 | 24 | const copyBtnHandler = useCallback(() => { 25 | copyToClipboard(messageToCopy); 26 | }, [ copyToClipboard, messageToCopy ]); 27 | 28 | useEffect(() => { 29 | if (copyState.error || !copyState.value) { 30 | return; 31 | } 32 | setCopiedTs(new Date() - 0); 33 | setTimeout(() => { 34 | if (!initialized.current) { 35 | return; 36 | } 37 | setCopiedTs(0); 38 | }, COPIED_MESSAGE_LIFE); 39 | }, [ copyState, copyState.error ]); 40 | 41 | useEffect(() => { 42 | // unloading 43 | return () => { 44 | initialized.current = false; 45 | }; 46 | }, []); 47 | 48 | const elapsedSinceCopied = new Date() - copiedTs; 49 | 50 | const buttonId = useMemo(() => `id_${ Math.random().toString().substring(2) }`, []); 51 | 52 | return (<> 53 |
54 | 57 | COPIED_MESSAGE_LIFE }>Copy 59 | to clipboardSuccessfully 60 | copied! 61 |
62 | 63 | 64 | { messageToCopy } 65 | 66 | ); 67 | }; 68 | -------------------------------------------------------------------------------- /src/ui/elements/Snippet/snippet.scss: -------------------------------------------------------------------------------- 1 | @import "~bootstrap/scss/functions"; 2 | @import "~bootstrap/scss/variables"; 3 | @import "~bootstrap/scss/mixins"; 4 | 5 | .highlight { 6 | padding: 1rem !important; 7 | padding-top: 2rem !important; 8 | margin-top: 1rem; 9 | margin-bottom: 1rem; 10 | background-color: $gray-100; 11 | -ms-overflow-style: -ms-autohiding-scrollbar; 12 | font-size: .89rem !important; 13 | 14 | @include media-breakpoint-up(sm) { 15 | padding: 1.5rem !important; 16 | padding-top: 2rem !important; 17 | } 18 | } 19 | 20 | .bd-content .highlight { 21 | margin-right: (-$grid-gutter-width / 2); 22 | margin-left: (-$grid-gutter-width / 2); 23 | 24 | @include media-breakpoint-up(sm) { 25 | margin-right: 0; 26 | margin-left: 0; 27 | } 28 | } 29 | 30 | .highlight { 31 | 32 | pre { 33 | padding: 0; 34 | margin-top: .65rem; 35 | margin-bottom: .65rem; 36 | background-color: transparent; 37 | border: 0; 38 | } 39 | pre code { 40 | @include font-size(inherit); 41 | color: $gray-900; // Effectively the base text color 42 | } 43 | } 44 | 45 | .bd-clipboard { 46 | position: relative; 47 | display: none; 48 | float: right; 49 | 50 | + .highlight { 51 | margin-top: 0; 52 | } 53 | 54 | @include media-breakpoint-up(md) { 55 | display: block; 56 | } 57 | } 58 | 59 | .btn-clipboard { 60 | position: absolute; 61 | top: .65rem; 62 | right: .65rem; 63 | z-index: 10; 64 | display: block; 65 | padding: .25rem .5rem; 66 | @include font-size(65%); 67 | color: $primary; 68 | background-color: $white; 69 | border: 1px solid; 70 | @include border-radius(); 71 | 72 | &:hover { 73 | color: $white; 74 | background-color: $primary; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/ui/elements/conditions.js: -------------------------------------------------------------------------------- 1 | //import React from 'react'; 2 | export const If = ({ condition, children, elseIf }) => condition ? (<>{ children }) : (elseIf || null); 3 | //export const ElseIf = ({ condition, children }) => condition ? null : (<>{ children }); 4 | -------------------------------------------------------------------------------- /src/ui/elements/errorBoundary.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Snippet } from './Snippet'; 4 | import { Container } from 'reactstrap'; 5 | 6 | export class ErrorBoundary extends React.Component { 7 | constructor(props) { 8 | super(props); 9 | this.state = { hasError: false }; 10 | this.handleDismissError = this.handleDismissError.bind(this); 11 | this.handleInvokeAssistance = this.handleInvokeAssistance.bind(this); 12 | } 13 | 14 | static getDerivedStateFromError(error) { 15 | return { hasError: true, error }; 16 | } 17 | 18 | componentDidCatch(error, info) { 19 | this.setState({ error, info }); 20 | } 21 | 22 | handleDismissError() { 23 | this.setState({ hasError: false, error: null, info: null }); 24 | // if (this.props.dispatch) { 25 | //// this.props.dispatch(navigateToAppsList()); 26 | // } 27 | } 28 | 29 | handleInvokeAssistance() { 30 | // if (this.props.dispatch) { 31 | //// this.props.dispatch(together(modalInvoked, gaModalInvoked)('assist')); 32 | // } 33 | } 34 | 35 | render() { 36 | if (!this.state.hasError) { 37 | return this.props.children; 38 | } 39 | 40 | const errorText = String(this.state.error); 41 | 42 | return 43 |

Something went wrong

44 |

Please try to reload the page. If the problem persists please seek support
45 | using the copy-pasted information below to describe what went wrong
and by clicking the button 47 |

48 | 49 |

Error:

50 |

51 | 52 |

53 | 54 |

55 | 56 |

57 | 58 |
; 59 | } 60 | } 61 | 62 | export default connect()(ErrorBoundary); 63 | -------------------------------------------------------------------------------- /src/ui/elements/errorBoundary.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import '@testing-library/jest-dom/extend-expect'; 3 | import { cleanup, render, wait } from '@testing-library/react'; 4 | import { Provider } from 'react-redux'; 5 | import { history, store } from '../../app/store'; 6 | import { ConnectedRouter } from 'connected-react-router'; 7 | import { ErrorBoundary } from './errorBoundary'; 8 | 9 | describe(`src/ui/elements/errorBoundary.js`, () => { 10 | describe(`ErrorBoundary component`, () => { 11 | 12 | afterEach(cleanup); 13 | 14 | test('renders ErrorBoundary component', async () => { 15 | const ThrowingComponent = () => { 16 | return {}; 17 | }; 18 | 19 | const { getByText } = render( 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | ); 28 | 29 | await wait(); 30 | 31 | expect(getByText(/Something went wrong/i)).toBeInTheDocument(); 32 | }); 33 | 34 | 35 | }); 36 | 37 | }); 38 | -------------------------------------------------------------------------------- /src/ui/elements/formElements.js: -------------------------------------------------------------------------------- 1 | import ReactDOMServer from 'react-dom/server'; 2 | import React from 'react'; 3 | import styled from 'styled-components'; 4 | import { Button, Input } from 'reactstrap'; 5 | 6 | export const RoundedButton = styled(Button)` 7 | border-radius: 1rem; 8 | `; 9 | const RoundedInput = styled(Input)` 10 | border-radius: 1rem; 11 | `; 12 | const RoundedInputWithIcon = styled(RoundedInput)` 13 | padding-left: calc(1.5em + 0.75rem); 14 | background-repeat: no-repeat; 15 | background-position: left calc(0.375em + 0.1875rem) center; 16 | background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem); 17 | `; 18 | 19 | export function InputWithIcon({ icon, ...props }) { 20 | const iconMarkup = ReactDOMServer.renderToStaticMarkup(icon); 21 | 22 | if (!iconMarkup) { 23 | return ; 24 | } 25 | return ; 31 | } 32 | -------------------------------------------------------------------------------- /src/ui/elements/icons.js: -------------------------------------------------------------------------------- 1 | import { FaSync as FaRefresh } from 'react-icons/fa'; 2 | import { FaHamburger, FaMapMarkerAlt, FaClock, FaSearch, FaEdit, FaPlus, FaMinus, FaCartPlus, FaTrashAlt } from 'react-icons/fa'; 3 | import { FaChevronRight } from 'react-icons/fa' 4 | import React from 'react'; 5 | import theme from './icons.module.scss' 6 | import { e2eAssist } from '../../testability'; 7 | 8 | export const IconRefresh = () => ; 9 | export const IconLogo = FaHamburger; 10 | export const IconGeo = FaMapMarkerAlt; 11 | export const IconClock = FaClock; 12 | export const IconSearch = FaSearch; 13 | export const IconEdit = FaEdit; 14 | export const IconPlus = FaPlus; 15 | export const IconTrash = FaTrashAlt; 16 | export const IconCartPlus = FaCartPlus; 17 | export const IconMinus = FaMinus; 18 | export const IconChevronRight = FaChevronRight; 19 | -------------------------------------------------------------------------------- /src/ui/elements/icons.module.scss: -------------------------------------------------------------------------------- 1 | .icon-spin { 2 | animation: icon-spin 2s infinite linear; 3 | } 4 | 5 | 6 | @keyframes icon-spin { 7 | 0% { 8 | transform: rotate(0deg); 9 | } 10 | 100% { 11 | transform: rotate(359deg); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/ui/elements/paginatedTable.js: -------------------------------------------------------------------------------- 1 | import BootstrapTable from 'react-bootstrap-table-next'; 2 | import paginationFactory, { 3 | PaginationListStandalone, 4 | PaginationProvider, 5 | SizePerPageDropdownStandalone 6 | } from 'react-bootstrap-table2-paginator'; 7 | import './reactBootstrapTableCustomization.scss'; 8 | import React from 'react'; 9 | import { e2eAssist } from '../../testability'; 10 | 11 | export const PaginatedTable = ({ 12 | data, 13 | columns, 14 | keyField, 15 | noPagination, 16 | paginationOnTop, 17 | paginationFactoryOptions, 18 | 'data-testid': dataTestIdAttr, 19 | ...tableProps 20 | }) => 21 | noPagination ? 22 |
: 28 | { 32 | ({ 33 | paginationProps, 34 | paginationTableProps // : { pagination: { options, ...restPagination } } 35 | }) => ( 36 |
37 |
45 |
46 |
47 |
48 |
51 | 52 |
55 |
56 |
57 |
58 | ) 59 | }
; 60 | -------------------------------------------------------------------------------- /src/ui/elements/reactBootstrapTableCustomization.scss: -------------------------------------------------------------------------------- 1 | .selection-cell-header, .selection-cell { 2 | display: none; 3 | } 4 | -------------------------------------------------------------------------------- /src/ui/elements/textElements.js: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const Span = styled.span` 4 | ${ props => props.vaMiddle ? `vertical-align: middle;` : '' } 5 | ${ props => props.centerEditIcon ? `transform: translate(2px, -2px); display: inline-block;` : '' } 6 | `; 7 | 8 | export const LargeTextDiv = styled.div` 9 | font-size: 4rem; 10 | font-weight: 800; 11 | color: rgba(0, 0, 0, .75); 12 | `; 13 | 14 | export const LessLargeTextDiv = styled.div` 15 | font-size: ${ props => props.size || 3 }rem; 16 | font-weight: 800; 17 | color: rgba(0, 0, 0, .8); 18 | `; 19 | -------------------------------------------------------------------------------- /src/ui/pages/AppLayout/AppLayout.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import '@testing-library/jest-dom/extend-expect'; 3 | import { render, wait, cleanup } from '@testing-library/react'; 4 | import { Provider } from 'react-redux'; 5 | import { history, store } from '../../../app/store'; 6 | import AppLayout from '../AppLayout'; 7 | import { ConnectedRouter } from 'connected-react-router'; 8 | 9 | describe(`src/ui/pages/AppLayout/AppLayout.test.js`, () => { 10 | 11 | afterEach(cleanup); 12 | 13 | test('renders ftgo application', async () => { 14 | const { getByText } = render( 15 | 16 | 17 | 18 | 19 | 20 | ); 21 | 22 | await wait(); 23 | 24 | expect(getByText(/FTGO Application/i)).toBeInTheDocument(); 25 | }); 26 | 27 | 28 | }); 29 | -------------------------------------------------------------------------------- /src/ui/pages/AppLayout/RootRoutes.js: -------------------------------------------------------------------------------- 1 | import { useState } from 'react'; 2 | import { getAppsRoutes } from '../AppRoutes'; 3 | 4 | export const RootRoutes = () => { 5 | const isAuthed = useState(true); 6 | if (!isAuthed) { 7 | return null; 8 | } 9 | return getAppsRoutes(); 10 | }; 11 | -------------------------------------------------------------------------------- /src/ui/pages/AppLayout/appLayout.css: -------------------------------------------------------------------------------- 1 | .navbar-shadow { 2 | box-shadow: 0 0.25rem 0.5rem rgb(0 0 0 / 18%); 3 | } 4 | -------------------------------------------------------------------------------- /src/ui/pages/AppLayout/index.js: -------------------------------------------------------------------------------- 1 | import { Container, Nav, Navbar, NavbarBrand, NavItem, NavLink } from 'reactstrap'; 2 | import styled from 'styled-components'; 3 | import { ErrorBoundary } from '../../elements/errorBoundary'; 4 | import { RootRoutes } from './RootRoutes'; 5 | import 'bootstrap/scss/bootstrap.scss'; 6 | import { IconLogo } from '../../elements/icons'; 7 | import './appLayout.css'; 8 | import { NavLink as RoutingLink } from 'react-router-dom'; 9 | import { routePaths } from '../AppRoutes/routePaths'; 10 | import { accessIsLoading } from '../../../features/ui/loadingSlice'; 11 | import { useSelector } from 'react-redux'; 12 | import { LoadingSpinner } from '../../elements/Loading'; 13 | import { Span } from '../../elements/textElements'; 14 | 15 | 16 | const CustomizedNavbarBrand = styled(NavbarBrand)` 17 | white-space: inherit; 18 | color: var(--black); 19 | font-size: 2rem; 20 | font-weight: 600; 21 | `; 22 | 23 | export const AppLayout = () => { 24 | 25 | const isLoading = useSelector(accessIsLoading()); 26 | 27 | return
28 |
29 |
{ 30 | isLoading && 31 |
32 |
33 | }
34 | 35 | 36 |
37 | 38 | FTGO 39 |
40 | 54 |
UserButton
(Logged in)
55 |
56 | 57 |
58 |
59 | 60 |
61 | 62 | 63 | 64 | 65 | 66 |
; 67 | }; 68 | 69 | export default AppLayout; 70 | -------------------------------------------------------------------------------- /src/ui/pages/AppRoutes/index.js: -------------------------------------------------------------------------------- 1 | import React, { lazy, Suspense } from 'react'; 2 | import { Loading, LoadingSpinner } from '../../elements/Loading'; 3 | import { Redirect, Route, Switch, useLocation } from 'react-router-dom'; 4 | import { routePaths } from './routePaths'; 5 | 6 | 7 | const LandingPage = lazy(() => import(/* webpackChunkName: "landing" */ '../LandingPage')); 8 | const LoginPage = lazy(() => import(/* webpackChunkName: "login" */ '../LoginPage')); 9 | const RestaurantListPage = lazy(() => import(/* webpackChunkName: "places" */ '../RestaurantListPage')); 10 | const RestaurantPage = lazy(() => import(/* webpackChunkName: "place" */ '../RestaurantPage')); 11 | const CheckoutPage = lazy(() => import(/* webpackChunkName: "checkout" */ '../CheckoutPage')); 12 | const ThankYouPage = lazy(() => import(/* webpackChunkName: "thankyou" */ '../ThankYouPage')); 13 | 14 | const repackWithComponentRender = ([ path, Component ]) => [ path, ({ 15 | path, 16 | render: props => 17 | }) ]; 18 | 19 | const routesMap = new Map([ 20 | [ routePaths.landing, LandingPage ], 21 | [ routePaths.restaurants, RestaurantListPage ], 22 | [ routePaths.restaurant, RestaurantPage ], 23 | [ routePaths.checkout, CheckoutPage ], 24 | [ routePaths.thankyou, ThankYouPage ], 25 | [ routePaths.login, LoginPage ] 26 | ].map(repackWithComponentRender)); 27 | 28 | const routes = [ 29 | routePaths.landing, 30 | routePaths.login, 31 | routePaths.restaurant, 32 | routePaths.restaurants, 33 | routePaths.checkout, 34 | routePaths.thankyou, 35 | ].filter(Boolean) 36 | .map(item => typeof item === 'string' ? 37 | : 38 | item); 39 | 40 | 41 | function Routes() { 42 | return 43 | 44 | { routes } 45 | 46 | 47 | 48 | 49 | ; 50 | } 51 | 52 | export function getAppsRoutes() { 53 | return }>; 54 | } 55 | 56 | function NoMatch() { 57 | let location = useLocation(); 58 | 59 | return ( 60 |
61 |

62 | No match for { location.pathname } 63 |

64 |
65 | ); 66 | } 67 | -------------------------------------------------------------------------------- /src/ui/pages/AppRoutes/routePaths.js: -------------------------------------------------------------------------------- 1 | export const routePaths = { 2 | landing: '/start', 3 | restaurants: '/place', 4 | restaurant: '/place/:placeId', 5 | checkout: '/checkout', 6 | thankyou: '/thankyou', 7 | login: '/login' 8 | }; 9 | -------------------------------------------------------------------------------- /src/ui/pages/CheckoutPage/cardElement.js: -------------------------------------------------------------------------------- 1 | import { Input, InputGroup, InputGroupText } from 'reactstrap'; 2 | import React, { useCallback, useEffect, useMemo, useState } from 'react'; 3 | import curry from 'lodash-es/curry'; 4 | import { accessCardValue, resetCard, updateCardValue } from '../../../features/card/cardSlice'; 5 | import { useDispatch, useSelector } from 'react-redux'; 6 | import { postConfirmPaymentAsyncThunk } from '../../../features/cart/cartSlice'; 7 | import { e2eAssist } from '../../../testability'; 8 | 9 | export const useElements = () => { 10 | const cardValue = useSelector(accessCardValue()); 11 | const getCardValue = useCallback(() => cardValue, [ cardValue ]); 12 | return useMemo(() => ({ 13 | getCardValue 14 | }), [ getCardValue ]); 15 | }; 16 | 17 | export const useStripe = () => { 18 | const dispatch = useDispatch(); 19 | 20 | return useMemo(() => ({ 21 | async confirmCardPayment(clientSecret, data) { 22 | const { 23 | payment_method: { 24 | card //: elements.getElement(CardElement) 25 | } 26 | } = data; 27 | 28 | console.log('[stripe.confirmCardPayment]', clientSecret, card); 29 | 30 | const response = await dispatch(postConfirmPaymentAsyncThunk({ clientSecret, card })); 31 | const { error, payload } = response; 32 | console.log(error, payload); 33 | return payload; 34 | } 35 | }), [ dispatch ]); 36 | }; 37 | 38 | export const CardElement = ({ errors, onChange, options = {} }) => { 39 | 40 | const [ ccNumber, setCCNumber ] = useState(''); 41 | const [ expMonth, setExpMonth ] = useState(''); 42 | const [ expYear, setExpYear ] = useState(''); 43 | const [ cvv, setCvv ] = useState(''); 44 | const [ zip, setZip ] = useState(''); 45 | 46 | const { style } = options; 47 | const baseStyle = style?.base ?? {}; 48 | const invalidStyle = style?.invalid ?? {}; 49 | 50 | const onChangeHandler = useMemo(() => curry((setter, evt) => { 51 | setter(evt.target.value); 52 | }), []); 53 | 54 | const dispatch = useDispatch(); 55 | 56 | useEffect(() => { 57 | dispatch(resetCard()); 58 | }, [ dispatch ]); 59 | 60 | const isEmpty = useMemo(() => [ ccNumber, cvv, expMonth, expYear, zip ].every(val => !val), 61 | [ ccNumber, cvv, expMonth, expYear, zip ]); 62 | 63 | useEffect(() => { 64 | 65 | const card = { 66 | card_number: ccNumber, 67 | exp_month: expMonth, 68 | exp_year: expYear, 69 | cvv, 70 | zip 71 | }; 72 | onChange && onChange({ 73 | empty: isEmpty, 74 | error: null, 75 | card 76 | }); 77 | dispatch(updateCardValue({ card, isEmpty })); 78 | }, [ ccNumber, cvv, dispatch, expMonth, expYear, isEmpty, onChange, zip ]); 79 | 80 | return <> 81 | 86 | 87 | 92 | / 93 | 98 | 99 | 100 | 105 | 110 | 111 |
112 | Try using these values for the card: 113 |
114 |         4242 4242 4242 4242 - Payment succeeds
115 |         
116 | 4000 0025 0000 3155 - Payment requires authentication 117 |
118 | 119 | 4000 0000 0000 9995 - Payment is declined 120 |
121 |
122 | 123 | ; 124 | }; 125 | 126 | -------------------------------------------------------------------------------- /src/ui/pages/CheckoutPage/checkoutForm.js: -------------------------------------------------------------------------------- 1 | import React, { useCallback, useEffect, useState } from 'react'; 2 | import { CardElement, useElements, useStripe } from './cardElement'; 3 | import { useDispatch, useSelector } from 'react-redux'; 4 | import { 5 | accessCartItems, accessVerboseCartInfo, 6 | paymentSuccessful, 7 | postCreatePaymentIntentAsyncThunk 8 | } from '../../../features/cart/cartSlice'; 9 | import { LoadingSpinner } from '../../elements/Loading'; 10 | import './checkoutForm.scss'; 11 | import { safelyExecuteSync } from '../../../shared/promises'; 12 | import { e2eAssist } from '../../../testability'; 13 | 14 | 15 | export function CheckoutForm() { 16 | 17 | const [ succeeded, setSucceeded ] = useState(false); 18 | const [ error, setError ] = useState(null); 19 | const [ errors, setErrors ] = useState(null); 20 | const [ processing, setProcessing ] = useState(''); 21 | const [ disabled, setDisabled ] = useState(true); 22 | const [ clientSecret, setClientSecret ] = useState(''); 23 | 24 | const stripe = useStripe(); 25 | const elements = useElements(); 26 | const cartItems = useSelector(accessCartItems()); 27 | const verboseCartInfo = useSelector(accessVerboseCartInfo()); 28 | 29 | const dispatch = useDispatch(); 30 | const handleCreatePaymentIntent = useCallback(async (items) => { 31 | // POST api/payment/intent: 32 | const { payload } = await dispatch(postCreatePaymentIntentAsyncThunk({ items })); 33 | setClientSecret(payload?.clientSecret ?? ''); 34 | }, [ dispatch ]); 35 | 36 | useEffect(() => { 37 | // Create PaymentIntent as soon as the page loads 38 | void handleCreatePaymentIntent(cartItems); 39 | setSucceeded(false); 40 | }, [ cartItems, handleCreatePaymentIntent ]); 41 | 42 | const cardStyle = { 43 | style: { 44 | base: { 45 | color: '#32325d', 46 | fontFamily: 'Arial, sans-serif', 47 | fontSmoothing: 'antialiased', 48 | fontSize: '16px', 49 | '::placeholder': { 50 | color: '#32325d' 51 | } 52 | }, 53 | invalid: { 54 | color: '#fa755a', 55 | iconColor: '#fa755a' 56 | } 57 | } 58 | }; 59 | 60 | const handleChange = useCallback(async (event) => { 61 | // Listen for changes in the CardElement 62 | // and display any errors as the customer types their card details 63 | setDisabled(event.empty); 64 | setError(event.error ? event.error.message : ''); 65 | }, []); 66 | 67 | const handleSubmit = useCallback(async ev => { 68 | 69 | ev.preventDefault(); 70 | setProcessing(true); 71 | 72 | const [ err, card ] = safelyExecuteSync(() => elements.getCardValue())(); 73 | if (err) { 74 | console.log(err); 75 | debugger; 76 | throw err; 77 | } 78 | 79 | const payload = await stripe.confirmCardPayment(clientSecret, { 80 | payment_method: { 81 | card //: elements.getElement(CardElement) 82 | } 83 | }); 84 | 85 | console.log(payload); 86 | debugger; 87 | 88 | if (payload.error) { 89 | setError(`${ payload.error.message }`); 90 | payload.errors ? setErrors(payload.errors) : setErrors(null); 91 | setProcessing(false); 92 | } else { 93 | setError(null); 94 | setErrors(null); 95 | setProcessing(false); 96 | setSucceeded(true); 97 | dispatch(paymentSuccessful()); 98 | } 99 | }, [ clientSecret, dispatch, elements, stripe ]); 100 | 101 | if (!clientSecret) { 102 | return null; 103 | } 104 | 105 | return ( 106 |
107 | 108 | 121 | {/* Show any error that happens when processing the payment */ } 122 | { error && ( 123 |
124 | Payment failed: { error } 125 |
126 | ) } 127 | {/* Show a success message upon completion */ } 128 |

129 | Payment succeeded! 130 |

131 | 132 | ); 133 | } 134 | -------------------------------------------------------------------------------- /src/ui/pages/CheckoutPage/checkoutForm.scss: -------------------------------------------------------------------------------- 1 | 2 | #card-error { 3 | color: rgb(105, 115, 134); 4 | font-size: 16px; 5 | line-height: 20px; 6 | margin-top: 12px; 7 | text-align: center; 8 | } 9 | #card-element { 10 | border-radius: 4px 4px 0 0; 11 | padding: 12px; 12 | border: 1px solid rgba(50, 50, 93, 0.1); 13 | max-height: 44px; 14 | width: 100%; 15 | background: white; 16 | box-sizing: border-box; 17 | } 18 | #payment-request-button { 19 | margin-bottom: 32px; 20 | } 21 | 22 | .result-message { 23 | line-height: 22px; 24 | font-size: 16px; 25 | } 26 | .result-message a { 27 | color: rgb(89, 111, 214); 28 | font-weight: 600; 29 | text-decoration: none; 30 | } 31 | 32 | 33 | /* Buttons and links */ 34 | button#submit { 35 | background: #5469d4; 36 | font-family: Arial, sans-serif; 37 | color: #ffffff; 38 | border-radius: 4px; 39 | border: 0; 40 | padding: 12px 16px; 41 | font-size: 16px; 42 | font-weight: 600; 43 | cursor: pointer; 44 | display: block; 45 | transition: all 0.2s ease; 46 | box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07); 47 | width: 100%; 48 | } 49 | button#submit:hover { 50 | filter: contrast(115%); 51 | } 52 | button#submit:disabled { 53 | opacity: 0.5; 54 | cursor: default; 55 | } 56 | -------------------------------------------------------------------------------- /src/ui/pages/CheckoutPage/index.js: -------------------------------------------------------------------------------- 1 | import React, { useCallback, useEffect, useState } from 'react'; 2 | import { useDispatch, useSelector } from 'react-redux'; 3 | import { 4 | accessCart, 5 | accessCartItems, 6 | accessCartStatus, 7 | accessPaymentSuccessful, 8 | accessVerboseCartInfo 9 | } from '../../../features/cart/cartSlice'; 10 | import { 11 | navigateToEditDeliveryAddress, 12 | navigateToEditMenu, 13 | navigateToPickRestaurants, 14 | navigateToThankYou 15 | } from '../../../features/actions/navigation'; 16 | import { Button, Col, Container, Row } from 'reactstrap'; 17 | import { accessSelectedRestaurantId } from '../../../features/restaurants/restaurantsSlice'; 18 | import { e2eAssist } from '../../../testability'; 19 | import { SelectedAddressRow } from '../../components/SelectedAddressRow'; 20 | import { SelectedRestaurantRow } from '../../components/SelectedRestaurantRow'; 21 | import { YourTrayItems } from '../RestaurantPage/yourTrayItems'; 22 | import { OrderInfo } from './orderInfo'; 23 | import { PaymentModal } from './paymentModal'; 24 | import { accessIsLoading } from '../../../features/ui/loadingSlice'; 25 | 26 | 27 | const CheckoutPage = () => { 28 | const dispatch = useDispatch(); 29 | const cartStatus = useSelector(accessCartStatus()); 30 | const cartItems = useSelector(accessCartItems()); 31 | const cartId = useSelector(accessCart('id')); 32 | const selectedRestaurantId = useSelector(accessSelectedRestaurantId()); 33 | const verboseCartInfo = useSelector(accessVerboseCartInfo()); 34 | const recentPaymentSuccess = useSelector(accessPaymentSuccessful()); 35 | const isLoading = useSelector(accessIsLoading()); 36 | 37 | useEffect(() => { 38 | if (!selectedRestaurantId) { 39 | return; 40 | } 41 | if (cartItems.length) { 42 | return; 43 | } 44 | dispatch(navigateToEditMenu(selectedRestaurantId)); 45 | }, [ cartItems.length, dispatch, selectedRestaurantId ]); 46 | 47 | useEffect(() => { 48 | if (!selectedRestaurantId) { 49 | dispatch(navigateToEditDeliveryAddress()); 50 | } 51 | }, [ dispatch, selectedRestaurantId ]); 52 | 53 | const handleChangeTray = useCallback(() => { 54 | dispatch(navigateToEditMenu(selectedRestaurantId)); 55 | }, [ dispatch, selectedRestaurantId ]); 56 | 57 | const [ showPaymentModal, setShowPaymentModal ] = useState(false); 58 | 59 | const toggle = useCallback(() => { 60 | setShowPaymentModal(!showPaymentModal); 61 | if (recentPaymentSuccess !== true) { 62 | debugger; 63 | return; 64 | } 65 | dispatch(navigateToThankYou()); 66 | }, [ dispatch, recentPaymentSuccess, showPaymentModal ]); 67 | 68 | const handleRequestPayment = useCallback(() => { 69 | setShowPaymentModal(true); 70 | }, []); 71 | 72 | 73 | useEffect(() => { 74 | if (!showPaymentModal) { 75 | return; 76 | } 77 | // fetch("/create-payment-intent", { 78 | // method: "POST", 79 | // headers: { 80 | // "Content-Type": "application/json" 81 | // }, 82 | // body: JSON.stringify(purchase) 83 | //}) 84 | }, [ showPaymentModal ]); 85 | 86 | useEffect(() => { 87 | if (cartId || (cartStatus !== 'ready')) { 88 | return null; 89 | } 90 | if (selectedRestaurantId) { 91 | //dispatch(navigateToEditMenu(selectedRestaurantId)); 92 | void dispatch; 93 | void navigateToEditMenu; 94 | void selectedRestaurantId; 95 | } else { 96 | //dispatch(navigateToPickRestaurants()); 97 | void navigateToPickRestaurants; 98 | } 99 | }, [ cartId, cartStatus, dispatch, selectedRestaurantId ]); 100 | 101 | if (!cartId || (cartStatus !== 'ready')) { 102 | debugger; 103 | return null; 104 | } 105 | 106 | return
107 | 108 | 109 | 110 | 111 | 112 |

Your Order

113 | 114 |
115 | 116 | 117 |

Items:

118 | 119 | 120 | 121 | 122 |
123 | 124 | 125 | 126 | 127 | 128 |

Summary:

129 | 130 | 131 | 132 | 133 |
134 | 135 | 137 | 138 | 139 |
140 | 141 |
; 142 | }; 143 | 144 | export default CheckoutPage; 145 | -------------------------------------------------------------------------------- /src/ui/pages/CheckoutPage/orderInfo.js: -------------------------------------------------------------------------------- 1 | import { useSelector } from 'react-redux'; 2 | import { accessCart, accessCartInfo, accessCartStatus, accessVerboseCartInfo } from '../../../features/cart/cartSlice'; 3 | 4 | export const OrderInfo = () => { 5 | 6 | const orderId = useSelector(accessCart('orderId')); 7 | const cartStatus = useSelector(accessCartStatus()); 8 | const verboseCartInfo = useSelector(accessVerboseCartInfo()); 9 | const cartInfo = useSelector(accessCartInfo()); 10 | console.log('[cartInfo]', cartInfo); 11 | 12 | void orderId; 13 | void cartStatus; 14 | 15 | const { total, subTotal, tax, delivery } = verboseCartInfo; 16 | const { taxAmount } = cartInfo; 17 | 18 | return <> 19 |
20 |
Subtotal:
21 |
{ subTotal }
22 |
23 |
24 |
Delivery Fee:
25 |
{ delivery }
26 |
27 |
28 |
Fees & Estimated Tax ({ (100 * taxAmount).toFixed(2) }%):
29 |
{ tax }
30 |
31 |
32 |
Total:
33 |
{ total }
34 |
35 | ; 36 | }; 37 | -------------------------------------------------------------------------------- /src/ui/pages/CheckoutPage/paymentModal.js: -------------------------------------------------------------------------------- 1 | import { Button, Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap'; 2 | import React from 'react'; 3 | import { CheckoutForm } from './checkoutForm'; 4 | import { e2eAssist } from '../../../testability'; 5 | 6 | //import { Elements } from '@stripe/react-stripe-js'; 7 | //import { loadStripe } from '@stripe/stripe-js'; 8 | //const stripePromise = loadStripe(ensureEnvVariable('REACT_APP_STRIPE_PK_KEY')); 9 | 10 | export const PaymentModal = ({ show, toggle, showDismiss }) => { 11 | // return 12 | return 13 | Payment Details: 14 | 15 | 16 | 17 | 18 | 20 | 21 | ; 22 | // ; 23 | }; 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/ui/pages/LandingPage/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { LandingPageForm } from './landingPageForm'; 3 | import { Container } from 'reactstrap'; 4 | import { LargeTextDiv, LessLargeTextDiv } from '../../elements/textElements'; 5 | import { e2eAssist } from '../../../testability'; 6 | 7 | 8 | const LandingPage = () => { 9 | 10 | return 11 |
12 | FTGO Application 13 | Pick delivery address and time: 14 |
15 |
16 | 17 |
18 |
; 19 | }; 20 | 21 | export default LandingPage; 22 | 23 | -------------------------------------------------------------------------------- /src/ui/pages/LandingPage/landingPageForm.js: -------------------------------------------------------------------------------- 1 | import { useForm } from 'react-hook-form'; 2 | import React, { useCallback } from 'react'; 3 | import { Col, Form, FormFeedback, FormGroup } from 'reactstrap'; 4 | import { InputWithIcon, RoundedButton } from '../../elements/formElements'; 5 | import { IconClock, IconGeo, IconRefresh, IconSearch } from '../../elements/icons'; 6 | import { useDispatch, useSelector } from 'react-redux'; 7 | import { 8 | accessDeliveryAddress, 9 | accessDeliveryTime, 10 | retrieveRestaurantsForAddress 11 | } from '../../../features/address/addressSlice'; 12 | import { If } from '../../elements/conditions'; 13 | import { processFormSubmissionError } from '../../../shared/forms/submissionHandling'; 14 | import { e2eAssist } from '../../../testability'; 15 | 16 | export const LandingPageForm = () => { 17 | 18 | const deliveryAddress = useSelector(accessDeliveryAddress()); 19 | const deliveryTime = useSelector(accessDeliveryTime()); 20 | 21 | const { register, handleSubmit, setError, clearErrors, formState: { isSubmitting, errors } } = useForm({ 22 | // a bug. In the presence of the below resolver, it is possible to resubmit after errors 23 | // however, the required fields validation is not taking place 24 | // TODO: resolve this dualistic condition 25 | resolver: (values, ctx, options) => { 26 | return ({ 27 | values, errors: {} 28 | }); 29 | }, 30 | defaultValues: { 31 | address: deliveryAddress, 32 | time: deliveryTime 33 | } 34 | }); 35 | 36 | const dispatch = useDispatch(); 37 | const onSubmit = useCallback(async data => { 38 | 39 | const payload = await dispatch(retrieveRestaurantsForAddress({ ...data })); 40 | 41 | payload.error && processFormSubmissionError((payload.meta.rejectedWithValue ? 42 | payload.payload : 43 | payload.error), setError, clearErrors); 44 | 45 | }, [ setError, dispatch, clearErrors ]); 46 | 47 | return
48 | 49 | 50 | . ( 51 | ) } invalid={ !!(errors.address) } disabled={ isSubmitting } bsSize="lg" placeholder="Enter Address" icon={ 54 | 55 | } /> 56 | { errors.address && 57 | { errors.address.message || 'Invalid address' } } 58 | 59 | 60 | 61 | ( 62 | ) } invalid={ !!(errors.time) } disabled={ isSubmitting } bsSize="lg" placeholder="Enter Time" icon={ 63 | } /> 64 | { errors.time && 65 | { errors.time.message || 'Invalid time' } } 66 | 67 | 68 | { errors.form && 69 | { errors.form.message || `Invalid data we couldn't understand` } } 70 | 71 | 72 | 73 | 74 | Search now 75 | 76 | 77 | 78 | 79 |
; 80 | }; 81 | -------------------------------------------------------------------------------- /src/ui/pages/LandingPage/landingPageForm.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import '@testing-library/jest-dom/extend-expect'; 3 | import { cleanup, render, wait } from '@testing-library/react'; 4 | import { Provider } from 'react-redux'; 5 | import { history, store } from '../../../app/store'; 6 | import { ConnectedRouter } from 'connected-react-router'; 7 | import { LandingPageForm } from './landingPageForm'; 8 | 9 | describe(`src/ui/pages/LandingPage/landingPageForm.js`, () => { 10 | 11 | describe(`LandingPageForm component`, () => { 12 | 13 | 14 | afterEach(cleanup); 15 | 16 | test('renders landing page form', async () => { 17 | const { getByText } = render( 18 | 19 | 20 | 21 | 22 | 23 | ); 24 | 25 | await wait(); 26 | 27 | expect(getByText(/Search now/i)).toBeInTheDocument(); 28 | }); 29 | 30 | 31 | }); 32 | 33 | }); 34 | -------------------------------------------------------------------------------- /src/ui/pages/LoginPage/index.js: -------------------------------------------------------------------------------- 1 | const LoginPage = () => { 2 | return <>LoginPage; 3 | } 4 | 5 | export default LoginPage; 6 | -------------------------------------------------------------------------------- /src/ui/pages/RestaurantListPage/index.js: -------------------------------------------------------------------------------- 1 | import { 2 | accessDeliveryAddress, 3 | accessDeliveryTime, 4 | accessRestaurantsList, 5 | retrieveRestaurantsForAddress 6 | } from '../../../features/address/addressSlice'; 7 | import { useDispatch, useSelector } from 'react-redux'; 8 | import React, { useCallback, useEffect, useMemo } from 'react'; 9 | import { navigateToEditMenu } from '../../../features/actions/navigation'; 10 | import { Col, Container } from 'reactstrap'; 11 | import { LessLargeTextDiv } from '../../elements/textElements'; 12 | import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css'; 13 | import { keepSelectedRestaurant } from '../../../features/restaurants/restaurantsSlice'; 14 | import { SelectedAddressRow } from '../../components/SelectedAddressRow'; 15 | import { PaginatedTable } from '../../elements/paginatedTable'; 16 | import { resetCart } from '../../../features/cart/cartSlice'; 17 | import { e2eAssist } from '../../../testability'; 18 | 19 | export const RestaurantListPage = () => { 20 | 21 | const dispatch = useDispatch(); 22 | const deliveryAddress = useSelector(accessDeliveryAddress()); 23 | const deliveryTime = useSelector(accessDeliveryTime()); 24 | const restaurants = useSelector(accessRestaurantsList()); 25 | 26 | useEffect(() => { 27 | if (restaurants) { 28 | return; 29 | } 30 | if (!deliveryAddress || !deliveryTime) { 31 | return; 32 | } 33 | dispatch(retrieveRestaurantsForAddress({ address: deliveryAddress, time: deliveryTime })); 34 | }, [ deliveryAddress, deliveryTime, dispatch, restaurants ]); 35 | 36 | 37 | const columns = [ { 38 | dataField: 'id', 39 | text: 'Ref ID', 40 | sort: true 41 | }, { 42 | dataField: 'name', 43 | text: 'Restaurant', 44 | sort: true 45 | }, { 46 | dataField: 'cuisine', 47 | text: 'Cuisine', 48 | sort: true 49 | }, { 50 | dataField: 'address', 51 | text: 'Address', 52 | sort: true 53 | } ]; 54 | 55 | const defaultSorted = [ { 56 | dataField: 'name', 57 | order: 'desc' 58 | } ]; 59 | 60 | const handleRowSelect = useCallback((entry) => { 61 | dispatch(keepSelectedRestaurant(entry)); 62 | dispatch(resetCart()); 63 | entry?.id && dispatch(navigateToEditMenu(entry.id)); 64 | }, [ dispatch ]); 65 | 66 | const selectRow = useMemo(() => ({ 67 | mode: 'radio', 68 | clickToSelect: true, 69 | selectionHeaderRenderer: () => null, 70 | selectionRenderer: ({ mode, ...rest }) => null, 71 | style: { backgroundColor: '#c8e6c980' }, 72 | onSelect: handleRowSelect 73 | }), [ handleRowSelect ]); 74 | 75 | return
76 | 77 | 78 | 79 | Restaurants: 80 | Listing: { String(restaurants?.length ?? 0) } 81 | 82 | 83 | No restaurants } 89 | columns={ columns } 90 | defaultSorted={ defaultSorted } 91 | selectRow={ selectRow } 92 | bordered={ false } 93 | paginationOnTop 94 | { ...e2eAssist.TBL_RESTAURANTS_LIST } 95 | paginationFactoryOptions={ { 96 | custom: true, 97 | sizePerPage: 5, 98 | sizePerPageList: [ 5, 10, 25, 30, 50 ], 99 | hidePageListOnlyOnePage: true 100 | } } 101 | /> 102 | 103 | 104 | 105 |
; 106 | }; 107 | 108 | export default RestaurantListPage; 109 | 110 | -------------------------------------------------------------------------------- /src/ui/pages/RestaurantPage/hooks.js: -------------------------------------------------------------------------------- 1 | import { debugged } from '../../../shared/diagnostics'; 2 | import { useDispatch } from 'react-redux'; 3 | import { useMemo } from 'react'; 4 | import curry from 'lodash-es/curry'; 5 | import { updateCartWithItemAsyncThunk } from '../../../features/cart/cartSlice'; 6 | 7 | /** 8 | * 9 | * @param orderId 10 | * @param cartItemsMap 11 | * @param selectedRestaurantId 12 | * @return {*|(function(*, *): function(*): (function(...[*]): (*|undefined))|*)} 13 | */ 14 | export function useUpdateCartHandler(orderId, cartItemsMap, selectedRestaurantId) { 15 | const dummyHandler = (a, b) => (c) => debugged([ a, b, c ]); 16 | 17 | const dispatch = useDispatch(); 18 | return useMemo(() => orderId ? curry((itemId, menuItem, cartItem, diff, _) => { 19 | const item = cartItem || { count: 0, name: menuItem?.name, price: menuItem?.price }; 20 | const restaurantId = selectedRestaurantId ?? (item.meta?.restaurantId ?? null); 21 | if (typeof item.oldCount !== 'undefined') { 22 | return; 23 | } 24 | dispatch(updateCartWithItemAsyncThunk({ 25 | restaurantId, 26 | itemId, 27 | qty: Math.max(0, item.count + diff), 28 | item 29 | })); 30 | }) : dummyHandler, [ orderId, selectedRestaurantId, dispatch ]); 31 | } 32 | 33 | export function createMap(arr, idGetter) { 34 | return new Map(arr.map(i => ([ idGetter(i), i ]))); 35 | } 36 | -------------------------------------------------------------------------------- /src/ui/pages/RestaurantPage/index.js: -------------------------------------------------------------------------------- 1 | import { SelectedAddressRow } from '../../components/SelectedAddressRow'; 2 | import { Button, Col, Container } from 'reactstrap'; 3 | import { SelectedRestaurantRow } from '../../components/SelectedRestaurantRow'; 4 | import { useDispatch, useSelector } from 'react-redux'; 5 | import { accessSelectedRestaurantId, resetSelectedRestaurant } from '../../../features/restaurants/restaurantsSlice'; 6 | import React, { useCallback, useEffect } from 'react'; 7 | import { navigateToCheckout, navigateToEditDeliveryAddress } from '../../../features/actions/navigation'; 8 | import { YourTrayItems } from './yourTrayItems'; 9 | import { MenuItems } from './menuItems'; 10 | import { IconChevronRight } from '../../elements/icons'; 11 | import { accessCartInfo, accessCartItems, accessVerboseCartInfo } from '../../../features/cart/cartSlice'; 12 | import { e2eAssist } from '../../../testability'; 13 | import { accessIsLoading } from '../../../features/ui/loadingSlice'; 14 | 15 | 16 | export const RestaurantPage = ({ match }) => { 17 | 18 | const { placeId: urlRestaurantId } = match.params; 19 | 20 | const dispatch = useDispatch(); 21 | const selectedRestaurantId = useSelector(accessSelectedRestaurantId()); 22 | const cartItems = useSelector(accessCartItems()); 23 | const isLoading = useSelector(accessIsLoading()); 24 | const cartInfo = useSelector(accessCartInfo()); 25 | const verboseCartInfo = useSelector(accessVerboseCartInfo()); 26 | 27 | const handleToCheckout = useCallback(() => { 28 | dispatch(navigateToCheckout()); 29 | }, [ dispatch ]); 30 | 31 | useEffect(() => { 32 | if (selectedRestaurantId && urlRestaurantId && (selectedRestaurantId === urlRestaurantId)) { 33 | return; 34 | } 35 | dispatch(resetSelectedRestaurant()); 36 | dispatch(navigateToEditDeliveryAddress()); 37 | }, [ dispatch, selectedRestaurantId, urlRestaurantId ]); 38 | 39 | return
40 | 41 | 42 | 43 | 44 |

Menu Items:

45 | 46 | 47 | 48 |

Your Tray:
{ verboseCartInfo.subTotal ?? '' }
49 |

50 | 51 |
52 | 53 |
54 | 55 |
56 |
; 57 | }; 58 | 59 | export default RestaurantPage; 60 | -------------------------------------------------------------------------------- /src/ui/pages/RestaurantPage/menuItems.js: -------------------------------------------------------------------------------- 1 | import { useDispatch, useSelector } from 'react-redux'; 2 | import { accessMenuForRestaurant, accessRestaurantMenuState } from '../../../features/restaurants/restaurantsSlice'; 3 | import { accessCart, accessCartItems, obtainCartAsyncThunk } from '../../../features/cart/cartSlice'; 4 | import React, { useCallback, useEffect, useMemo } from 'react'; 5 | import { retrieveRestaurantByIdAsyncThunk } from '../../../features/address/addressSlice'; 6 | import { createMap, useUpdateCartHandler } from './hooks'; 7 | import { Button } from 'reactstrap'; 8 | import { IconCartPlus, IconPlus } from '../../elements/icons'; 9 | import { PaginatedTable } from '../../elements/paginatedTable'; 10 | import { usePrevious } from 'react-use'; 11 | import { e2eAssist } from '../../../testability'; 12 | 13 | 14 | /** 15 | * @value { 16 | 'id': '224474', 17 | 'name': 'Chicken Livers and Portuguese Roll', 18 | 'position': 1, 19 | 'price': '250.00', 20 | 'consumable': '1:1', 21 | 'cuisine': 'Indian', 22 | 'category_name': 'Appeteasers', 23 | 'discount': { 24 | 'type': '', 25 | 'amount': '0.00' 26 | }, 27 | 'tags': [] 28 | } 29 | */ 30 | 31 | /** 32 | * 33 | * @param restaurantId 34 | * @return {JSX.Element} 35 | * @constructor 36 | */ 37 | export function MenuItems({ restaurantId }) { 38 | 39 | const dispatch = useDispatch(); 40 | const menuState = useSelector(accessRestaurantMenuState(restaurantId)); 41 | const emptyArr = useMemo(() => ([]), []); 42 | const menuList = useSelector(accessMenuForRestaurant(restaurantId, emptyArr)); 43 | const cartItems = useSelector(accessCartItems()); 44 | const cartItemsMap = useMemo(() => createMap(cartItems, i => i.id), [ cartItems ]); 45 | const dataSource = useMemo(() => menuList.map(item => cartItemsMap.has(item.id) ? 46 | Object.assign({ cart: cartItemsMap.get(item.id) }, item) : 47 | item), [ cartItemsMap, menuList ]); 48 | const orderId = useSelector(accessCart('orderId')); 49 | 50 | useEffect(() => { 51 | if (menuState) { 52 | return; 53 | } 54 | dispatch(retrieveRestaurantByIdAsyncThunk({ restaurantId })); 55 | }, [ dispatch, menuState, restaurantId ]); 56 | 57 | useEffect(() => { 58 | if (orderId) { 59 | return; 60 | } 61 | dispatch(obtainCartAsyncThunk()); 62 | }, [ orderId, dispatch ]); 63 | 64 | 65 | const handleAddToCart = useUpdateCartHandler(orderId, cartItemsMap, restaurantId); 66 | 67 | const actionColumnFormatter = useCallback((cellContent, row, rowId, orderId) => { 68 | if (row.cart) { 69 | const cartItem = row.cart; 70 | return ; 72 | } 73 | return ; 75 | }, [ handleAddToCart ]); 76 | 77 | const columns = useMemo(() => ([ 78 | { 79 | dataField: 'id', 80 | text: 'Ref ID', 81 | sort: true 82 | }, { 83 | dataField: 'name', 84 | text: 'Food Item', 85 | sort: true 86 | }, { 87 | dataField: 'category_name', 88 | text: 'Category', 89 | sort: true 90 | }, { 91 | dataField: 'price', 92 | text: 'Price', 93 | sort: true 94 | }, { 95 | dataField: 'actions', 96 | isDummyField: true, 97 | text: 'Add To Cart', 98 | formatter: actionColumnFormatter, 99 | formatExtraData: orderId, 100 | classes: 'text-right' 101 | } 102 | ]), [ actionColumnFormatter, orderId ]); 103 | 104 | const defaultSorted = [ { 105 | dataField: 'name', 106 | order: 'desc' 107 | } ]; 108 | 109 | const prevcartId = usePrevious(orderId); 110 | console.log(prevcartId, ' => ', orderId); 111 | 112 | if (menuState !== 'ready') { 113 | return <>Updating the menu...; 114 | } 115 | 116 | return Menu is temporarily empty } 122 | columns={ columns } 123 | defaultSorted={ defaultSorted } 124 | bordered={ false } 125 | paginationOnTop 126 | paginationFactoryOptions={ { 127 | custom: true, 128 | sizePerPage: 5, 129 | sizePerPageList: [ 5, 10, 25, 30, 50 ], 130 | hidePageListOnlyOnePage: true 131 | } } 132 | { ...e2eAssist.TBL_RESTAURANT_MENU } 133 | />; 134 | 135 | } 136 | -------------------------------------------------------------------------------- /src/ui/pages/RestaurantPage/yourTrayItems.js: -------------------------------------------------------------------------------- 1 | import { useSelector } from 'react-redux'; 2 | import { accessCart, accessCartItems, accessCartStatus } from '../../../features/cart/cartSlice'; 3 | import { createMap, useUpdateCartHandler } from './hooks'; 4 | import React, { useCallback, useMemo } from 'react'; 5 | import { Button, ButtonGroup, Card, CardBody, CardTitle } from 'reactstrap'; 6 | import { IconMinus, IconPlus, IconTrash } from '../../elements/icons'; 7 | import { PaginatedTable } from '../../elements/paginatedTable'; 8 | import { e2eAssist } from '../../../testability'; 9 | 10 | export function YourTrayItems({ checkout }) { 11 | 12 | const orderId = useSelector(accessCart('orderId')); 13 | const cartStatus = useSelector(accessCartStatus()); 14 | const cartItems = useSelector(accessCartItems()); 15 | const cartItemsMap = useMemo(() => createMap(cartItems || [], i => i.id), [ cartItems ]); 16 | const handleAddToCart = useUpdateCartHandler(orderId, cartItemsMap, undefined); 17 | 18 | const actionColumnFormatter = useCallback((cellContent, row, rowIdx, orderId) => { 19 | const disabled = !orderId || (typeof row.oldCount !== 'undefined'); 20 | return 21 | 22 | 23 | 24 | ; 25 | }, [ handleAddToCart ]); 26 | 27 | const columns = useMemo(() => ([ 28 | { 29 | dataField: 'name', 30 | text: 'Food Item', 31 | sort: !checkout 32 | }, 33 | { 34 | dataField: 'actions', 35 | isDummyField: true, 36 | text: 'Quantity', 37 | sort: true, 38 | sortFunc: (a, b, order, dataField, rowA, rowB) => { 39 | if (order === 'asc') { 40 | return rowA.count - rowB.count; 41 | } else { 42 | return -(rowA.count - rowB.count); 43 | } 44 | }, 45 | classes: 'text-right', 46 | formatter: actionColumnFormatter, 47 | formatExtraData: orderId 48 | } 49 | ]), [ actionColumnFormatter, orderId, checkout ]); 50 | 51 | const defaultSorted = [ { 52 | dataField: 'name', 53 | order: 'desc' 54 | } ]; 55 | 56 | if (!orderId || (cartStatus !== 'ready')) { 57 | return <>Updating the tray...; 58 | } 59 | 60 | if (checkout) { 61 | return cartItems.map((item, idx) => ( 62 | 63 | 64 | { item.name } 65 |
{ actionColumnFormatter(null, item, idx, orderId) }
66 |
67 | 68 |
69 |
70 | ${ Number(item.price).toFixed(2) } × { Number(item.count) } = ${ (Number(item.price) * Number(item.count)).toFixed(2) } 71 |
72 |
73 |
74 |
)); 75 | } 76 | 77 | return Add food to your tray } 83 | columns={ columns } 84 | defaultSorted={ defaultSorted } 85 | bordered={ false } 86 | paginationOnTop 87 | paginationFactoryOptions={ { 88 | custom: true, 89 | sizePerPage: 5, 90 | sizePerPageList: [ 5, 10, 25, 30, 50 ], 91 | hidePageListOnlyOnePage: true, 92 | } } 93 | { ...e2eAssist.TBL_YOUR_TRAY } 94 | />; 95 | } 96 | -------------------------------------------------------------------------------- /src/ui/pages/ThankYouPage/index.js: -------------------------------------------------------------------------------- 1 | import { Container } from 'reactstrap'; 2 | import { e2eAssist } from '../../../testability'; 3 | import React, { useEffect } from 'react'; 4 | import { useDispatch, useSelector } from 'react-redux'; 5 | import { accessCart, accessVerboseCartInfo } from '../../../features/cart/cartSlice'; 6 | import { navigateToEditDeliveryAddress } from '../../../features/actions/navigation'; 7 | 8 | export const ThankYouPage = () => { 9 | const verboseCartInfo = useSelector(accessVerboseCartInfo()); 10 | const orderId = useSelector(accessCart('orderId')); 11 | const dispatch = useDispatch(); 12 | 13 | useEffect(() => { 14 | if (!orderId) { 15 | dispatch(navigateToEditDeliveryAddress()); 16 | } 17 | }, [ dispatch, orderId ]); 18 | 19 | return
20 | 21 |

Thank You For Placing Your Order!

22 |
Your order
#{ orderId }
for the amount of
{ verboseCartInfo.total }
has been placed and is being processed. 23 |
24 |
25 |
; 26 | }; 27 | 28 | export default ThankYouPage; 29 | -------------------------------------------------------------------------------- /src/window.setup.js: -------------------------------------------------------------------------------- 1 | console.log('src/window.setup.js'); 2 | 3 | window.scrollTo = jest.fn(); 4 | window.prompt = jest.fn(); 5 | window.alert = jest.fn(); 6 | -------------------------------------------------------------------------------- /start-http-server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | docker-compose up -d --build 4 | sleep 10 5 | docker-compose logs 6 | docker-compose ps 7 | #docker-compose exec web /bin/bash 8 | -------------------------------------------------------------------------------- /test-docker-image.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | ./start-http-server.sh 4 | 5 | ./wait-for-services.sh 6 | -------------------------------------------------------------------------------- /tests-ui/browserSetup.js: -------------------------------------------------------------------------------- 1 | import puppeteer from 'puppeteer'; 2 | import { InflightRequests, safeJSONValue } from './puppeteerExtensions'; 3 | import { safelyExecuteAsync } from '../src/shared/promises'; 4 | import { initializeNavigationContext } from './navigation'; 5 | 6 | export function setUpBrowserAndPage(testLifecycleHooks, context, viewport, setPage) { 7 | 8 | const { beforeAll, afterAll } = testLifecycleHooks; 9 | if (!beforeAll || !afterAll) { 10 | throw new Error('Essential test lifecycle hooks are not specified ("beforeAll", "afterAll")'); 11 | } 12 | 13 | const { width, height } = viewport; 14 | 15 | let browser = null; 16 | let page = null; 17 | 18 | beforeAll(async () => { 19 | 20 | let launchErr; 21 | ([ launchErr, browser ] = await safelyExecuteAsync(puppeteer.launch({ 22 | // devtools: true, 23 | timeout: 0, 24 | headless: false, 25 | ignoreHTTPSErrors: true, 26 | slowMo: 2, 27 | args: [ 28 | `--window-size=${ width },${ height }`, 29 | // FTGO_ENV: dev - local machine 30 | process.env.FTGO_ENV === 'dev' ? '' : '--no-sandbox', 31 | '--disable-dev-shm-usage', 32 | '--disable-setuid-sandbox', 33 | '--disable-features=site-per-process', 34 | '--disable-accelerated-2d-canvas', 35 | '--disable-gpu', 36 | // '--disable-web-security', 37 | // '--user-data-dir=~/.' 38 | ] 39 | }))); 40 | if (launchErr || !browser) { 41 | throw new Error(`[ftgo-consumer-web-ui/tests-ui/browserSetup]: Puppeteer failed to produce a new instance of a browser when 'puppeteer.launch(..)'. Error: ${ launchErr?.message }`); 42 | } 43 | 44 | console.log(`Using Puppeteer Chromium version:`, await browser.version()); 45 | 46 | // browser.on('disconnected', () => { 47 | // try { 48 | // console.log('Browser disconnected.'); 49 | // } catch (_) {} 50 | // }); 51 | 52 | browser.on('targetdestroyed', (e) => { 53 | try { 54 | console.log('Browser target destroyed event. Event:', e, ' Stack trace:', (new Error()).stack); 55 | } catch (_) {} 56 | }); 57 | 58 | let pageErr; 59 | ([ pageErr, page ] = await safelyExecuteAsync(browser.newPage())); 60 | if (pageErr) { 61 | throw new Error(`[ftgo-consumer-web-ui/tests-ui/browserSetup]: Puppeteer failed to create a new page when 'browser.newPage()'. Error: ${ pageErr?.message }`); 62 | } 63 | 64 | Object.assign(context, { page }); 65 | 66 | await page.setRequestInterception(true); 67 | page.on('request', request => request.continue()); 68 | const requestsTracker = new InflightRequests(page); 69 | 70 | initializeNavigationContext({ requestsTracker }); 71 | 72 | Object.assign(context, { requestsTracker }); 73 | 74 | setPage && setPage(page); 75 | 76 | const consoleMsgs = []; 77 | Object.assign(context, { consoleMsgs }); 78 | 79 | page.on('console', async ({ _type, _text, _args }) => { 80 | context.consoleMsgs.push([ 81 | _type.padEnd(8), _text, ...(await Promise.all(_args.map(arg => safeJSONValue(arg)))).map(JSON.stringify) 82 | ]); 83 | }); 84 | 85 | await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'); 86 | await page.setViewport(viewport); // width, height 87 | 88 | }); 89 | 90 | afterAll(() => { 91 | if (context.requestsTracker) { 92 | context.requestsTracker.dispose(); 93 | } 94 | browser && browser.close(); 95 | }); 96 | 97 | return page; 98 | } 99 | -------------------------------------------------------------------------------- /tests-ui/comprehensive.spec.js: -------------------------------------------------------------------------------- 1 | import notifier from './reporters/defaultNotifier'; 2 | import { DEFAULT_TIMEOUT } from './jest.setup'; 3 | import { makeScreenshot, testWrap } from './testWrapper'; 4 | import { ensureLocalizedTimeString, obtainTestInfo } from './testInfoProvider'; 5 | import { ensureEnvVariable } from '../src/shared/env'; 6 | import { waitForTimeout } from './puppeteerExtensions'; 7 | import { setUpBrowserAndPage } from './browserSetup'; 8 | import { navigation } from './pages/navigation'; 9 | import { landingPage } from './pages/landing'; 10 | import { restaurantsListPage } from './pages/restaurantsList'; 11 | import { restaurantMenuPage } from './pages/restaurantMenu'; 12 | import { checkoutPage } from './pages/checkout'; 13 | import { summarizePageObject } from './pages/utilities'; 14 | import { thankYouPage } from './pages/thankYou'; 15 | 16 | void makeScreenshot; 17 | 18 | const ctx = { 19 | page: null, 20 | store: new Map(), 21 | testInfo: null 22 | }; 23 | 24 | const TIMEOUT = DEFAULT_TIMEOUT; 25 | const test$ = testWrap(global.test, ctx, TIMEOUT); 26 | const [ describe, xdescribe, test, xtest ] = ((d, xd) => ([ 27 | d, 28 | process.env.NODE_ENV === 'test' ? xd : d, 29 | test$, 30 | process.env.NODE_ENV === 'test' ? global.xtest : test$ 31 | ]))(global.describe, global.xdescribe); 32 | 33 | void xtest; 34 | void xdescribe; 35 | 36 | const [ width, height ] = ensureEnvVariable('TEST_UI_DIMENSIONS', '1200x800').split('x').map(Number); 37 | 38 | let page = setUpBrowserAndPage({ beforeAll, afterAll }, ctx, { width, height }, p => { 39 | ctx.page = page = p; 40 | // TODO: The default value can be changed by using the page.setDefaultNavigationTimeout(timeout) or 41 | // page.setDefaultTimeout(timeout) methods. NOTE page.setDefaultNavigationTimeout takes priority over 42 | // page.setDefaultTimeout 43 | }); 44 | 45 | const testInfo = ctx.testInfo = obtainTestInfo(); 46 | 47 | 48 | console.log('NODE_ENV: ', process.env.NODE_ENV, ensureEnvVariable('TEST_UI_URL'), testInfo.email, testInfo.password, `(${ testInfo.newPassword })`); 49 | 50 | 51 | // https://www.valentinog.com/blog/ui-testing-jest-puppetteer/ 52 | 53 | 54 | async function warnSpectator(page) { 55 | await notifier.notify('The interesting part starts in less than 5 seconds'); 56 | await page.waitForTimeout(5000); 57 | } 58 | 59 | void warnSpectator; 60 | 61 | describe('Interaction with the entire FTGO UI application:', () => { 62 | 63 | beforeAll(async () => { 64 | await ensureLocalizedTimeString(page, testInfo); 65 | }); 66 | 67 | afterAll(async () => { 68 | await waitForTimeout(page, 1000); 69 | }); 70 | 71 | afterAll(() => { 72 | summarizePageObject(true); 73 | }); 74 | 75 | describe('00. Ground-zero tests. Browser capabilities', () => { 76 | 77 | test(`Settings`, () => { 78 | 79 | console.log('NODE_ENV: ', process.env.NODE_ENV); 80 | console.log(ensureEnvVariable('TEST_UI_URL'), testInfo.email); 81 | console.log('[testInfo.goodAddress.time]', testInfo.goodAddress.time); 82 | 83 | }); 84 | 85 | test(`Navigation to Landing and a screenshot`, async () => { 86 | 87 | await navigation(page).visitTheSite(); 88 | await landingPage(page).expectVisitingSelf(); 89 | 90 | await makeScreenshot(page, { label: 'intro' }); 91 | 92 | }); 93 | }); 94 | 95 | describe(`[Landing Page] -> Restaurants List -> Menu Page`, () => { 96 | 97 | test(`Navigation to Landing`, async () => { 98 | await navigation(page).visitTheSite(); 99 | await landingPage(page).expectVisitingSelf(); 100 | }); 101 | 102 | test(`[landing page] Correct entry, submission, landing on Restaurants List`, async () => { 103 | 104 | await landingPage(page).fillOutTheAddressAndTimeForm(testInfo.goodAddress); 105 | await landingPage(page).submitTheAddressAndTimeFormSuccessfully(); 106 | await restaurantsListPage(page).expectVisitingSelf(); 107 | 108 | }); 109 | 110 | test(`[restaurants list page] Navigation, picking correct restaurant, landing of Menu page`, async () => { 111 | 112 | await restaurantsListPage(page).browseForRestaurantWithMenuItems(); 113 | await restaurantMenuPage(page).expectVisitingSelf(); 114 | 115 | }); 116 | 117 | test(`[restaurant menu page] Structure check, menu picking, going to checkout`, async () => { 118 | await restaurantMenuPage(page).checkStructure(); 119 | await restaurantMenuPage(page).putMenuItemIntoACart(); 120 | await restaurantMenuPage(page).proceedToCheckout(); 121 | 122 | await checkoutPage(page).expectVisitingSelf(); 123 | }); 124 | 125 | describe(`[checkout page]`, () => { 126 | 127 | test(`[required elements before payment]`, async () => { 128 | await checkoutPage(page, expect).expectCartNotEmptyAndReadyToPay(); 129 | }); 130 | 131 | test(`[payment modal interaction]`, async () => { 132 | await checkoutPage(page, expect).playWithThePaymentModal(); 133 | }); 134 | 135 | test(`[payment form interaction]`, async () => { 136 | await checkoutPage(page, expect).playWithThePaymentFormRequireds(); 137 | }); 138 | 139 | test(`[payment form] declined payment`, async () => { 140 | 141 | await checkoutPage(page, expect).attemptDeclinedCard(); 142 | 143 | }); 144 | 145 | test(`[payment form] accepted payment`, async () => { 146 | 147 | await checkoutPage(page, expect).attemptValidOkCard(); 148 | 149 | }); 150 | 151 | describe(`[thank you page]`, () => { 152 | 153 | test(`[thank you page] successful navigation`, async () => { 154 | 155 | await thankYouPage(page, expect).expectVisitingSelf(); 156 | 157 | }); 158 | 159 | test(`[thank you page] order ID is present`, async () => { 160 | 161 | await thankYouPage(page, expect).ensureOrderIdIsPresent(); 162 | 163 | }); 164 | }) 165 | 166 | }); 167 | 168 | }); 169 | 170 | }); 171 | -------------------------------------------------------------------------------- /tests-ui/ensure_env.js: -------------------------------------------------------------------------------- 1 | import 'react-scripts/config/env.js'; 2 | 3 | -------------------------------------------------------------------------------- /tests-ui/envLoader.js: -------------------------------------------------------------------------------- 1 | console.log('envLoader'); 2 | 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | 6 | const NODE_ENV = process.env.NODE_ENV; 7 | if (!NODE_ENV) { 8 | throw new Error( 9 | 'The NODE_ENV environment variable is required but was not specified.' 10 | ); 11 | } 12 | 13 | const SKIP_ENV_LOAD = process.env.SKIP_ENV_LOAD; 14 | if (SKIP_ENV_LOAD) { 15 | return; 16 | } 17 | 18 | const appDirectory = fs.realpathSync(process.cwd()); 19 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath); 20 | const dotenvPath = resolveApp('.env'); 21 | 22 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use 23 | const dotenvFiles = [ 24 | `${ dotenvPath }.${ NODE_ENV }.local`, 25 | `${ dotenvPath }.${ NODE_ENV }`, 26 | // Don't include `.env.local` for `test` environment 27 | // since normally you expect tests to produce the same 28 | // results for everyone 29 | NODE_ENV !== 'test' && `${ dotenvPath }.local`, 30 | dotenvPath, 31 | ].filter(Boolean); 32 | 33 | // Load environment variables from .env* files. Suppress warnings using silent 34 | // if this file is missing. dotenv will never modify any environment variables 35 | // that have already been set. Variable expansion is supported in .env files. 36 | // https://github.com/motdotla/dotenv 37 | // https://github.com/motdotla/dotenv-expand 38 | dotenvFiles.forEach(dotenvFile => { 39 | console.log('Attempting to load: ', dotenvFile); 40 | if (fs.existsSync(dotenvFile)) { 41 | console.log('Loading: ', dotenvFile); 42 | require('dotenv-expand')( 43 | require('dotenv').config({ 44 | path: dotenvFile, 45 | }) 46 | ); 47 | } 48 | }); 49 | 50 | // We support resolving modules according to `NODE_PATH`. 51 | // This lets you use absolute paths in imports inside large monorepos: 52 | // https://github.com/facebook/create-react-app/issues/253. 53 | // It works similar to `NODE_PATH` in Node itself: 54 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders 55 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. 56 | // Otherwise, we risk importing Node.js core modules into an app instead of webpack shims. 57 | // https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 58 | // We also resolve them to make sure all tools using them work consistently. 59 | process.env.NODE_PATH = (process.env.NODE_PATH || '') 60 | .split(path.delimiter) 61 | .filter(folder => folder && !path.isAbsolute(folder)) 62 | .map(folder => path.resolve(appDirectory, folder)) 63 | .join(path.delimiter); 64 | -------------------------------------------------------------------------------- /tests-ui/helpers/index.js: -------------------------------------------------------------------------------- 1 | //textField(page, SEL.FORM_FIELD_ADDRESS).enter(testData.address) 2 | 3 | //await waitClickAndType(page, SEL.FORM_FIELD_ADDRESS, testData.address); 4 | //await waitForTimeout(page, 10); 5 | import { 6 | readElementsText, 7 | waitClickAndType, 8 | waitForSelector, 9 | waitForSelectorAndClick, 10 | waitForSelectorNotPresent, 11 | waitForTimeout 12 | } from '../puppeteerExtensions'; 13 | import { cssSel } from '../../src/shared/e2e'; 14 | import { safelyExecuteAsync } from '../../src/shared/promises'; 15 | 16 | export const textField = (page, sel) => { 17 | return { 18 | enter(text, replace) { 19 | return waitClickAndType(page, sel, text, replace); 20 | }, 21 | ensurePresent() { 22 | return waitForSelector(page, sel); 23 | }, 24 | expectInvalid() { 25 | return waitForSelector(page, cssSel(sel).attr('data-testid', '|invalid|', '*')); 26 | }, 27 | expectNotInvalid() { 28 | return waitForSelector(page, cssSel(sel).not(cssSel('').attr('data-testid', '|invalid|', '*'))); 29 | } 30 | }; 31 | }; 32 | 33 | export const element = (page, sel) => { 34 | return { 35 | ensurePresent(options) { 36 | return waitForSelector(page, sel, options); 37 | }, 38 | expectAbsent() { 39 | return waitForSelectorNotPresent(page, sel); 40 | }, 41 | async click() { 42 | await waitForSelectorAndClick(page, sel); 43 | return waitForTimeout(page, 10); 44 | }, 45 | async expectDisabled(options) { 46 | return waitForSelector(page, cssSel(sel).mod('[disabled]'), options); 47 | }, 48 | expectNotDisabled() { 49 | return waitForSelector(page, cssSel(sel).mod(':not([disabled])')); 50 | }, 51 | async count() { 52 | console.log(`[Element.count]for selector: "${ String(sel) }"`); 53 | return (await page.$$(String(sel))).length; 54 | }, 55 | has(childSel) { 56 | return waitForSelector(page, cssSel(sel).desc(childSel)); 57 | }, 58 | safelyGetText() { 59 | return safelyExecuteAsync(readElementsText(page, sel)); 60 | } 61 | }; 62 | }; 63 | -------------------------------------------------------------------------------- /tests-ui/jest.config.js: -------------------------------------------------------------------------------- 1 | console.log('jest.config.js'); 2 | require('./envLoader'); 3 | module.exports = { 4 | verbose: true, 5 | setupFilesAfterEnv: [ 'jest-extended', './jest.setup.js' ], 6 | // transformIgnorePatterns: [ 'node_modules/(?!shared-package)' ], 7 | 'reporters': [ 8 | 'default', 9 | [ '/reporters/defaultReporter.js', { 10 | 'jest.config': 'tests-ui/jest.config.js' 11 | } ] 12 | ] 13 | }; 14 | -------------------------------------------------------------------------------- /tests-ui/jest.dev.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "--source": "source: https://jestjs.io/docs/en/troubleshooting#debugging-in-vs-code", 4 | "configurations": [ 5 | { 6 | "name": "Debug CRA Tests", 7 | "type": "node", 8 | "request": "launch", 9 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts", 10 | "args": ["test", "--runInBand", "--no-cache", "--env=jsdom"], 11 | "cwd": "${workspaceRoot}", 12 | "protocol": "inspector", 13 | "console": "integratedTerminal", 14 | "internalConsoleOptions": "neverOpen", 15 | "reporters": [ 16 | "default", 17 | ["/reporters/defaultReporter.js", {"banana": "yes", "pineapple": "no", "json": 6 }] 18 | ] 19 | } 20 | ] 21 | } -------------------------------------------------------------------------------- /tests-ui/jest.setup.js: -------------------------------------------------------------------------------- 1 | export const DEFAULT_TIMEOUT = 30000; 2 | jest.setTimeout(DEFAULT_TIMEOUT); 3 | console.log('jest.setup.js'); 4 | -------------------------------------------------------------------------------- /tests-ui/navigation.js: -------------------------------------------------------------------------------- 1 | import { safelyExecuteAsync } from '../src/shared/promises'; 2 | import { ensureEnvVariable } from '../src/shared/env'; 3 | import { injectHelperScripts, waitForPathnameLocation, waitForSelector } from './puppeteerExtensions'; 4 | import { SEL } from './selectors'; 5 | 6 | const throwIfUndefined = (arg) => { 7 | if (arg === undefined) { 8 | throw new Error(); 9 | } 10 | return arg; 11 | } 12 | export const urlPatterns = { 13 | landing: /^\/start$/i, 14 | }; 15 | 16 | export const appPaths = { 17 | loginPage: '/login', 18 | landing: '/apps', 19 | emptyResetPage: '/reset' 20 | }; 21 | 22 | export const APP_URL = ensureEnvVariable('TEST_UI_URL'); 23 | 24 | const navContext = { 25 | requestsTracker: undefined 26 | }; 27 | 28 | export function initializeNavigationContext(props) { 29 | Object.assign(navContext, props); 30 | } 31 | 32 | /** 33 | * 34 | * @param page Puppeteer page handle 35 | * @param relativePath - address to navigate to within APP 36 | * @returns {Promise} 37 | */ 38 | export async function navigateToWithinApp(page, relativePath = '') { 39 | const url = removeDoubledSlashes(APP_URL + relativePath); 40 | console.log(`Navigating to URL: ${ url }`); 41 | const [ errNWI0 ] = await safelyExecuteAsync(page.goto(url, { waitUntil: 'networkidle0' })); 42 | if (errNWI0) { 43 | 44 | const inflight = navContext?.requestsTracker.inflightRequests() || []; 45 | console.log(inflight.map(request => ' ' + request.url()).join('\n')); 46 | 47 | const [ errNWI2 ] = await safelyExecuteAsync(page.goto(url, { waitUntil: 'networkidle2' })); 48 | if (errNWI2) { 49 | throw new Error(`Navigation to URL '${ url }' timed out. There are more than 2 open connections.`); 50 | } 51 | console.warn(`Navigation to URL '${ url }' has still not more than 2 open connections.`); 52 | } else { 53 | console.log(`Navigation to URL '${ url }' - Success`); 54 | } 55 | await injectHelperScripts(page); 56 | } 57 | 58 | export async function navigationToMissingApp(page, context) { 59 | const path = throwIfUndefined(context.store.get('sampleAppIdUrl')).replace(context.store.get('sampleAppId'), 'NONEXISTENT_APP'); 60 | await navigateToMissingEntitySteps(page, path, urlPatterns.landing); 61 | } 62 | 63 | export async function navigateToMissingServiceWithinMissingApp(page, context) { 64 | const path = `${ throwIfUndefined(context.store.get('sampleAppIdUrl')).replace(context.store.get('sampleAppId'), 'NONEXISTENT_APP') }/service/NONEXISTENT_SVC`; 65 | await navigateToMissingEntitySteps(page, path, urlPatterns.landing); 66 | } 67 | 68 | export async function navigateToMissingServiceWithinExistingApp(page, context) { 69 | const path = `${ throwIfUndefined(context.store.get('sampleAppIdUrl')) }/service/NONEXISTENT_SVC`; 70 | await navigateToMissingEntitySteps(page, path, urlPatterns.appItemPage); 71 | } 72 | 73 | async function navigateToMissingEntitySteps(page, path, urlPattern) { 74 | await navigateToWithinApp(page, path); 75 | await Promise.all([ 76 | waitForSelector(page, SEL.ALERT_INFO), 77 | waitForSelector(page, SEL.ALERT_DANGER) 78 | ]); 79 | await waitForPathnameLocation(page, urlPattern); 80 | } 81 | 82 | 83 | function removeDoubledSlashes(input) { 84 | return input.replace('://', '_PROTO_SEP_').replace('//', '/').replace('_PROTO_SEP_', '://'); 85 | } 86 | -------------------------------------------------------------------------------- /tests-ui/pages/landing.js: -------------------------------------------------------------------------------- 1 | import { waitForSelector, waitForTimeout } from '../puppeteerExtensions'; 2 | import { SEL } from '../selectors'; 3 | import { makeScreenshot } from '../testWrapper'; 4 | import { tagPageObject } from './utilities'; 5 | import { 6 | addressAndTimeForm, 7 | addressAndTimeFormSubmitButton, 8 | addressField, 9 | spinIcon, 10 | timeField 11 | } from './pageComponents'; 12 | import { safelyExecuteAsync } from '../../src/shared/promises'; 13 | 14 | export const landingPage = page => tagPageObject('landingPage', { 15 | 16 | expectVisitingSelf: () => waitForSelector(page, SEL.PAGE_LANDING), 17 | 18 | fillOutTheAddressAndTimeForm: async (testData) => { 19 | await addressAndTimeForm(page).ensurePresent(); 20 | await addressField(page).enter(testData.address); 21 | await timeField(page).enter(testData.time); 22 | 23 | await makeScreenshot(page, { label: 'time_entry' }); 24 | }, 25 | 26 | submitTheAddressAndTimeFormSuccessfully: async () => { 27 | await addressAndTimeFormSubmitButton(page).click(); 28 | await addressAndTimeFormSubmitButton(page).expectDisabled(); 29 | const [ err ] = await safelyExecuteAsync(spinIcon(page).ensurePresent({ timeout: 5000 })); 30 | 31 | err && console.warn('[submitTheAddressAndTimeFormSuccessfully] Spinner was absent') 32 | 33 | await waitForTimeout(page, 300); 34 | } 35 | 36 | }); 37 | -------------------------------------------------------------------------------- /tests-ui/pages/navigation.js: -------------------------------------------------------------------------------- 1 | import { navigateToWithinApp } from '../navigation'; 2 | import { waitForTimeout } from '../puppeteerExtensions'; 3 | import { tagPageObject } from './utilities'; 4 | 5 | export const navigation = page => tagPageObject('navigation', { 6 | 7 | visitTheSite: async () => { 8 | await navigateToWithinApp(page, '/'); 9 | await waitForTimeout(page, 1000); 10 | } 11 | 12 | }); 13 | -------------------------------------------------------------------------------- /tests-ui/pages/pageComponents.js: -------------------------------------------------------------------------------- 1 | //await addressField(page).enter(testData.address); 2 | 3 | import { element, textField } from '../helpers'; 4 | import { SEL } from '../selectors'; 5 | 6 | export const addressField = page => textField(page, SEL.FORM_FIELD_ADDRESS); 7 | export const timeField = page => textField(page, SEL.FORM_FIELD_TIME); 8 | export const addressAndTimeForm = page => element(page, SEL.FORM_PICK_ADDRESS_TIME) 9 | export const addressAndTimeFormSubmitButton = page => element(page, SEL.BTN_SUBMIT_FORM_PICK_ADDRESS_TIME); 10 | export const spinIcon = page => element(page, SEL.ICON_SPIN); 11 | -------------------------------------------------------------------------------- /tests-ui/pages/restaurantMenu.js: -------------------------------------------------------------------------------- 1 | import { 2 | waitForSelector, 3 | waitForSelectorAndClick, 4 | waitForSelectorNotPresent, 5 | waitForTimeout 6 | } from '../puppeteerExtensions'; 7 | import { SEL } from '../selectors'; 8 | import { tagPageObject } from './utilities'; 9 | import { cssSel } from '../../src/shared/e2e'; 10 | import { element } from '../helpers'; 11 | 12 | const restaurantMenuTable = page => element(page, SEL.TBL_RESTAURANT_MENU); 13 | const yourTrayTable = page => element(page, SEL.TBL_YOUR_TRAY); 14 | const toCheckoutButton = page => element(page, SEL.BTN_TO_CHECKOUT); 15 | const addToCartButton = page => element(page, SEL.BTN_ADD_TO_CART); 16 | 17 | export const restaurantMenuPage = page => tagPageObject('restaurantMenuPage', { 18 | 19 | expectVisitingSelf: () => waitForSelector(page, SEL.PAGE_RESTAURANT_MENU), 20 | 21 | checkStructure: async () => { 22 | await restaurantMenuTable(page).ensurePresent(); 23 | await yourTrayTable(page).ensurePresent(); 24 | await toCheckoutButton(page).ensurePresent(); 25 | }, 26 | 27 | putMenuItemIntoACart: async () => { 28 | await toCheckoutButton(page).expectDisabled(); 29 | 30 | await waitForSelector(page, cssSel(SEL.INFO_TRAY_IS_EMPTY)); 31 | await waitForSelector(page, cssSel(SEL.INFO_CART_VALUE_OF(0))); 32 | 33 | const paginationControlSel = cssSel(SEL.TBL_RESTAURANT_MENU).desc(SEL.CTL_PAGINATION_FOR_TABLE); 34 | await waitForSelector(page, paginationControlSel); 35 | await waitForSelector(page, 36 | paginationControlSel.desc('.page-item').attr('title', 'next page').child('a.page-link')); 37 | 38 | await waitForSelectorNotPresent(page, SEL.BTN_ADD_TO_CART_ADDED); 39 | await addToCartButton(page).ensurePresent(); 40 | await waitForSelector(page, SEL.BTN_ADD_TO_CART_FRESH); 41 | 42 | await waitForSelectorAndClick(page, SEL.BTN_ADD_TO_CART_FRESH); 43 | await addToCartButton(page).expectDisabled(); 44 | 45 | 46 | await waitForTimeout(page, 1000); 47 | await waitForSelector(page, SEL.BTN_ADD_TO_CART_ADDED); 48 | 49 | await toCheckoutButton(page).expectNotDisabled(); 50 | 51 | await waitForSelectorNotPresent(page, cssSel(SEL.INFO_CART_VALUE_OF(0))); 52 | 53 | }, 54 | 55 | proceedToCheckout: async () => { 56 | await toCheckoutButton(page).expectNotDisabled(); 57 | await toCheckoutButton(page).click(); 58 | } 59 | }); 60 | -------------------------------------------------------------------------------- /tests-ui/pages/restaurantsList.js: -------------------------------------------------------------------------------- 1 | import { waitForSelector, waitForSelectorAndClick, waitForSelectorWithText } from '../puppeteerExtensions'; 2 | import { SEL } from '../selectors'; 3 | import { tagPageObject } from './utilities'; 4 | import { cssSel } from '../../src/shared/e2e'; 5 | import { element } from '../helpers'; 6 | 7 | const tableRestaurantsList = page => element(page, SEL.PAGE_RESTAURANTS_LIST); 8 | 9 | export const restaurantsListPage = page => tagPageObject('restaurantsListPage', { 10 | 11 | expectVisitingSelf: () => tableRestaurantsList(page).ensurePresent(), 12 | 13 | browseForRestaurantWithMenuItems: async () => { 14 | 15 | await tableRestaurantsList(page).ensurePresent(); 16 | 17 | const paginationControlSel = cssSel(SEL.TBL_RESTAURANTS_LIST).desc(SEL.CTL_PAGINATION_FOR_TABLE); 18 | await waitForSelector(page, paginationControlSel); 19 | await waitForSelectorAndClick(page, 20 | paginationControlSel.desc('.page-item').attr('title', 'next page').child('a.page-link')); 21 | 22 | const el = await waitForSelectorWithText(page, 'td', 'All items'); 23 | await el.click(); 24 | 25 | }, 26 | 27 | }); 28 | -------------------------------------------------------------------------------- /tests-ui/pages/thankYou.js: -------------------------------------------------------------------------------- 1 | import { tagPageObject } from './utilities'; 2 | import { element } from '../helpers'; 3 | import { SEL } from '../../src/testability'; 4 | 5 | const thankYouPageEl = page => element(page, SEL.PAGE_THANKYOU); 6 | const textOrderId = page => element(page, SEL.TEXT_ORDER_ID); 7 | 8 | export const thankYouPage = (page, expect) => tagPageObject('thankYouPage', { 9 | expectVisitingSelf: () => thankYouPageEl(page).ensurePresent(), 10 | ensureOrderIdIsPresent: async () => { 11 | 12 | const [ err, orderIdText ] = await textOrderId(page).safelyGetText(); 13 | expect(err).toBeNull(); 14 | expect(orderIdText.replace('#', '')).toBeTruthy(); 15 | } 16 | }); 17 | -------------------------------------------------------------------------------- /tests-ui/pages/utilities.js: -------------------------------------------------------------------------------- 1 | const consoleOverload = [ 'log', 'group', 'groupEnd', 'warn', 'error', 'info', 'debug' ].reduce((memo, method) => 2 | Object.assign(memo, { 3 | [ method ]: function (...args) { 4 | console[ method ] && console[ method ](...args); 5 | if (this._messages) { 6 | this._messages.push({ 7 | timestamp: new Date().getTime(), 8 | method, 9 | args 10 | }); 11 | } 12 | } 13 | }), { 14 | _messages: [], 15 | flush() { 16 | if (this._messages) { 17 | const result = Array.from(this._messages); 18 | this._messages = []; 19 | return result; 20 | } 21 | }, 22 | restore() { 23 | return console; 24 | } 25 | }); 26 | 27 | /** 28 | * 29 | * @param { string } name 30 | * @param { Object} obj 31 | * @return { Object } 32 | */ 33 | export function tagPageObject(name, obj) { 34 | return tagAllFunctionalPairs(obj, createLoggedControlledExecution(consoleOverload), name); 35 | } 36 | 37 | /** 38 | * 39 | * @param { Object } object 40 | * @param {function} cb 41 | * @param extraArgs 42 | * @return { Object } 43 | */ 44 | function tagAllFunctionalPairs(object, cb, ...extraArgs) { 45 | return Object.fromEntries(Array.from(Object.entries(object), 46 | ([ key, value ]) => [ key, (...args) => cb(key, value, args, ...extraArgs) ])); 47 | } 48 | 49 | export function summarizePageObject(useOriginalConsole) { 50 | if (!('flush' in consoleOverload)) { 51 | return; 52 | } 53 | const messages = consoleOverload.flush(); 54 | if (useOriginalConsole) { 55 | messages.forEach(({ method, args }) => console[ method ](...args)); 56 | } else { 57 | console.log(messages); 58 | } 59 | } 60 | 61 | function createLoggedControlledExecution(console) { 62 | 63 | /** 64 | * 65 | * @param key 66 | * @param fn 67 | * @param args 68 | * @param name 69 | * @return {*} 70 | */ 71 | return function controlledExecution(key, fn, args, name = 'Unmarked object') { 72 | if (typeof fn !== 'function') { 73 | return fn; 74 | } 75 | const executionName = [ name, key ].filter(Boolean).map(camelCaseToSentenceCase).join(': '); 76 | console.group && console.group(); 77 | console.log(`[${ executionName }] Executing`); 78 | try { 79 | const result = fn(...args); 80 | if (result instanceof Promise) { 81 | result.then(() => { 82 | console.log(`[${ executionName }] Resolved`); 83 | console.groupEnd && console.groupEnd(); 84 | }, () => { 85 | console.log(`[${ executionName }] Rejected`); 86 | console.groupEnd && console.groupEnd(); 87 | }); 88 | } else { 89 | console.log(`[${ executionName }] Finished`); 90 | console.groupEnd && console.groupEnd(); 91 | } 92 | return result; 93 | } catch (ex) { 94 | console.log(`[${ executionName }] Threw`); 95 | console.groupEnd && console.groupEnd(); 96 | throw ex; 97 | } 98 | }; 99 | } 100 | 101 | /** 102 | * 103 | * @param {string} text 104 | * @return {string} 105 | */ 106 | function camelCaseToSentenceCase(text) { 107 | const result = text.replace(/([A-Z])/g, ' $1'); 108 | return result.charAt(0).toUpperCase() + result.slice(1); 109 | } 110 | -------------------------------------------------------------------------------- /tests-ui/reporters/.gitignore: -------------------------------------------------------------------------------- 1 | *.local.js 2 | -------------------------------------------------------------------------------- /tests-ui/reporters/defaultNotifier.js: -------------------------------------------------------------------------------- 1 | const { extendWithLocal } = require('./utilities'); 2 | 3 | class DefaultNotifier { 4 | notify() {} 5 | } 6 | 7 | const Notifier = extendWithLocal(DefaultNotifier, './localizedNotifier.local.js'); 8 | 9 | module.exports = new Notifier(); 10 | -------------------------------------------------------------------------------- /tests-ui/reporters/defaultReporter.js: -------------------------------------------------------------------------------- 1 | const { extendWithLocal } = require('./utilities'); 2 | 3 | console.log('hooksDefaultReporter.js'); 4 | 5 | class HooksDefaultReporter { 6 | constructor(globalConfig, options) { 7 | this._globalConfig = globalConfig; 8 | this._options = options; 9 | } 10 | onRunStart(results, options) { 11 | console.debug('HooksDefaultReporter: (onRunStart):'); 12 | } 13 | onTestFileStart(test) { 14 | console.debug('HooksDefaultReporter: (onTestFileStart):', test.path); 15 | } 16 | onTestStart(test) { 17 | console.debug('HooksDefaultReporter: (onTestStart):', test); 18 | } 19 | onTestResult(test) { 20 | console.debug('HooksDefaultReporter: (onTestResult):', test.path); 21 | } 22 | onTestFileResult(test, testResult, aggregatedResult) { 23 | console.debug('HooksDefaultReporter: (onTestFileResult):', test.path); 24 | } 25 | onTestCaseResult(test, testCaseResult) { 26 | console.debug('HooksDefaultReporter: (onTestCaseResult):', test.path); 27 | } 28 | onRunComplete(contexts, results) { 29 | console.debug('HooksDefaultReporter: (onRunComplete):'); 30 | // console.debug('GlobalConfig: ', this._globalConfig); 31 | // console.debug('Options: ', this._options); 32 | } 33 | getLastError() { 34 | if (this._shouldFail) { 35 | return new Error('HooksDefaultReporter reported an error'); 36 | } 37 | } 38 | } 39 | 40 | module.exports = extendWithLocal(HooksDefaultReporter, './localizedHooksReporter.local.js'); 41 | -------------------------------------------------------------------------------- /tests-ui/reporters/utilities.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function extendWithLocal(Klass, path) { 4 | try { 5 | const Subclass = require(path); 6 | Object.setPrototypeOf(Subclass.prototype, Klass.prototype); 7 | Object.setPrototypeOf(Subclass, Klass); 8 | return Subclass; 9 | } catch (e) { 10 | console.log(`[Not an error] Failed to extendWithLocal: ${ path }`, e); 11 | return Klass; 12 | } 13 | } 14 | 15 | function makeBroadcaster(...broadcasters) { 16 | return function broadcastMessage(msg) { 17 | return Promise.all(broadcasters.map(b => b(msg))); 18 | }; 19 | } 20 | 21 | module.exports.extendWithLocal = extendWithLocal; 22 | module.exports.makeBroadcaster = makeBroadcaster; 23 | -------------------------------------------------------------------------------- /tests-ui/selectors.js: -------------------------------------------------------------------------------- 1 | export { SEL } from '../src/testability'; 2 | 3 | export const MOD = { 4 | // ARIA_EXPANDED: `[aria-haspopup=true][aria-expanded=true]`, 5 | ATTR_NOT_DISABLED: ':not([disabled])', 6 | ATTR_DISABLED: '[disabled]', 7 | }; 8 | -------------------------------------------------------------------------------- /tests-ui/testInfoProvider.js: -------------------------------------------------------------------------------- 1 | import faker from 'faker'; 2 | import './ensure_env'; 3 | import { ensureEnvVariable } from '../src/shared/env'; 4 | import { getRandomEmail } from '../src/shared/email'; 5 | 6 | export function obtainTestInfo() { 7 | 8 | return { 9 | goodAddress: { 10 | address: `Testing Address: ${ faker.random.words(2) }`, 11 | timeRaw: new Date(new Date().setHours(0, 8)).toISOString() 12 | }, 13 | email: getUniqueEmailAddressForTests() 14 | //phone: faker.phone.phoneNumber(), 15 | //message: faker.random.words() 16 | }; 17 | } 18 | 19 | const testEmailAddress = ensureEnvVariable('FTGO_TEST_EMAIL_ADDRESS'); 20 | 21 | export function getUniqueEmailAddressForTests() { 22 | return getRandomEmail(testEmailAddress, () => faker.random.alphaNumeric(8)); 23 | } 24 | 25 | /** 26 | * @description Source: https://www.mattzeunert.com/2020/04/01/filling-out-a-date-input-with-puppeteer.html 27 | * Transforms a date into a string for typing-in into the input box 28 | * @param page 29 | * @param testInfo 30 | * @return {Promise} 31 | */ 32 | export async function ensureLocalizedTimeString(page, testInfo) { 33 | const timeRaw = testInfo.goodAddress.timeRaw; 34 | 35 | testInfo.goodAddress.time = (await page.evaluate( 36 | d => new Date(d).toLocaleTimeString(navigator.language, { 37 | hour: '2-digit', 38 | minute: '2-digit' 39 | }), 40 | timeRaw 41 | )).replace(' ', ''); 42 | 43 | } 44 | -------------------------------------------------------------------------------- /tests-ui/testWrapper.js: -------------------------------------------------------------------------------- 1 | import { existsSync, mkdirSync, writeFile, writeFileSync } from 'fs'; 2 | import path from 'path'; 3 | import { promisify } from 'util'; 4 | import { DEFAULT_TIMEOUT } from './jest.setup'; 5 | import { getQuicklyLocationPathnameAndSearch } from './puppeteerExtensions'; 6 | 7 | const started = new Date(); 8 | const memo = { 9 | testNumber: 1 10 | }; 11 | 12 | const artifactsPath = path.resolve(__dirname, '..', 'ci-artifacts'); 13 | if (!existsSync(artifactsPath)) { 14 | mkdirSync(artifactsPath, { recursive: true }); 15 | } 16 | 17 | let adHocScreenshotsBunchCount = 0; 18 | let adHocScreenshotsCount = 0; 19 | /** 20 | * Captures stack, etc. 21 | * @param _test 22 | * @param context 23 | * @returns {function(*=, *=, *=): *} 24 | */ 25 | export const testWrap = (_test, context, fallbackTimeout = 10) => { 26 | 27 | let errCounter = 0; 28 | 29 | process.on('unhandledRejection', (reason, promise) => { 30 | const savePath = `${ artifactsPath }/unhandledRejection_e2e_error_log_${ getTimestampPart(started) }_${ errCounter }.txt`; 31 | const savePathExtra = `${ artifactsPath }/unhandledRejection_e2e_error_log_${ getTimestampPart(started) }_${ errCounter++ }_ext.txt`; 32 | try { 33 | writeFileSync(savePath, reason); 34 | promise.catch((ex) => { 35 | writeFileSync(savePathExtra, `Exception: ${ ex }\nStack: ${ ex.stack }`); 36 | }); 37 | } catch (ex) {} 38 | }); 39 | 40 | let effectiveTest = _test; 41 | 42 | function only(...args) { 43 | effectiveTest = _test.only; 44 | return newTest(...args); 45 | } 46 | 47 | let newTest; 48 | return Object.assign(newTest = function newTest(name, afn, timeoutProduct = 50) { 49 | //console.log(`Setting a watched test(${ name }, async fn, ${ timeout })`); 50 | const effectiveTimeout = ((timeoutProduct !== undefined) ? (timeoutProduct <= 1000 ? (timeoutProduct * fallbackTimeout) : timeoutProduct) : fallbackTimeout || DEFAULT_TIMEOUT); 51 | return effectiveTest(name, function (...args) { 52 | //console.log(`Invoked a jest-test (${ name }, async fn, ${ timeout })`); 53 | context.consoleMsgs = []; 54 | let timeoutRef; 55 | const ts = new Date() - 0; 56 | return new Promise(async (rs, rj) => { 57 | timeoutRef = setTimeout(() => { 58 | try { 59 | console.log(`Elapsed ${ new Date() - ts } ms`); 60 | } catch (ex) {} 61 | rj(Object.assign(new Error('Test execution timeout, gathering stats'), { name: 'timeout' })); 62 | }, effectiveTimeout - 10); // just a bit earlier, that's all 63 | try { 64 | await afn(...args); 65 | } catch (ex) { 66 | clearTimeout(timeoutRef); 67 | return rj(ex); 68 | } 69 | clearTimeout(timeoutRef); 70 | rs(); 71 | }).catch(async ex => { 72 | const { testNumber } = memo; 73 | memo.testNumber++; 74 | const { page } = context; 75 | 76 | if (page) { 77 | 78 | try { 79 | console.log(`Test "${ name }" failed. #${ testNumber }`); 80 | const failedLocation = await getQuicklyLocationPathnameAndSearch(page); 81 | console.log(`Url: ${ failedLocation }`); 82 | 83 | await makeHtmlDump(page, { testNumber, name, failedLocation }); 84 | await makeScreenshot(page, { testNumber }); 85 | await makeBrowsersConsoleDump(page, { testNumber, ex }, context); 86 | 87 | } catch (ex) { 88 | console.log(`Gathering stats has failed. Reason: ${ ex }`); 89 | } 90 | 91 | } else { 92 | console.log(`Test: "${ name }" failed. Page dump is impossible. 'page' is not set.`); 93 | } 94 | throw ex; 95 | }); 96 | }, effectiveTimeout); 97 | }, { only }); 98 | }; 99 | 100 | async function makeBrowsersConsoleDump(page, { testNumber, ex }, memoObj) { 101 | try { 102 | const consoleDumpPath = `${ artifactsPath }/art_${ getTimestampPart(started) }_${ testNumber }_console.txt`; 103 | const consoleDump = memoObj.consoleMsgs 104 | .concat([ [ String(ex), ex?.message ?? 'unknown', ex?.stack ?? 'no stack' ] ]) 105 | .map(entry => entry.join(' ')).join('\r\n'); 106 | void await promisify(writeFile)(consoleDumpPath, consoleDump); 107 | console.log(`Browser's console dump saved: ${ consoleDumpPath }`); 108 | } catch (ex) { 109 | console.log(`Browser's console failed. Reason: ${ ex }`); 110 | } 111 | } 112 | 113 | export async function makeHtmlDump(page, { testNumber, name, failedLocation }) { 114 | 115 | try { 116 | const pageContentDumpPath = `${ artifactsPath }/art_${ getTimestampPart(started) }_${ testNumber }_dom.html`; 117 | const pageContent = await page.content(); 118 | const effectiveDumpInfo = [ 119 | ``, 120 | ``, 121 | pageContent 122 | ].join('\r\n').replace(new RegExp(']*>([\\S\\s]*?)<\/script\\s*>', 'img'), ''); 123 | 124 | void await promisify(writeFile)(pageContentDumpPath, effectiveDumpInfo); 125 | console.log(`Page dump saved: ${ pageContentDumpPath }`); 126 | } catch (ex) { 127 | console.log(`Page DOM dump not saved. Reason: ${ ex }`); 128 | } 129 | } 130 | 131 | export async function makeScreenshot(page, { testNumber, label, labelIndex, resetCount, skip, clip }) { 132 | if (skip === true) { 133 | return; 134 | } 135 | const isTestNumberPresent = testNumber !== undefined; 136 | if (resetCount) { 137 | adHocScreenshotsCount = 0; 138 | adHocScreenshotsBunchCount++; 139 | } 140 | const testItemLabel = isTestNumberPresent ? testNumber : `${ adHocScreenshotsBunchCount }_${ adHocScreenshotsCount++ }_${ label || 'adhoc' }${ 141 | (labelIndex == null ? '' : `_${ labelIndex }`) }`; 142 | try { 143 | const screenshotPath = `${ artifactsPath }/art_${ getTimestampPart(started) }_${ testItemLabel }_shot.png`; 144 | void await page.screenshot({ 145 | path: screenshotPath, 146 | ...(clip ? {} : { fullPage: true }) 147 | }); 148 | console.log(`Screenshot saved: ${ screenshotPath }`); 149 | } catch (ex) { 150 | console.log(`Screenshot taking has failed. Reason: ${ ex }`); 151 | } 152 | } 153 | 154 | function getTimestampPart(input) { 155 | const now = input || new Date(); 156 | const [ year, month, date ] = [ now.getFullYear(), now.getMonth(), now.getDate() ]; 157 | const remainder = now - new Date(year, month, date); 158 | const padding = [ undefined, 2, 2, 5 ]; 159 | return [ 160 | year, month + 1, date, Math.floor(remainder / 1000) 161 | ].map(String).map((str, idx) => padding[ idx ] ? str.padStart(padding[ idx ], '0') : str).join('_'); 162 | } 163 | -------------------------------------------------------------------------------- /wait-for-services.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | ./_wait-for-services.sh "/api" 5000 8080 4 | --------------------------------------------------------------------------------