diff --git a/media-store/.gitignore b/media-store/.gitignore index 73962f43..1b6ca866 100644 --- a/media-store/.gitignore +++ b/media-store/.gitignore @@ -9,7 +9,10 @@ target/ package-lock.json # html5Deployer -html5Deployer/resources/app/ +deployers/html5Deployer/resources/app/ + +# app +app/ # Web IDE, App Studio .che/ diff --git a/media-store/app/.gitignore b/media-store/app/.gitignore deleted file mode 100644 index 4d29575d..00000000 --- a/media-store/app/.gitignore +++ /dev/null @@ -1,23 +0,0 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. - -# dependencies -/node_modules -/.pnp -.pnp.js - -# testing -/coverage - -# production -/build - -# misc -.DS_Store -.env.local -.env.development.local -.env.test.local -.env.production.local - -npm-debug.log* -yarn-debug.log* -yarn-error.log* diff --git a/media-store/app/.vscode/launch.json b/media-store/app/.vscode/launch.json deleted file mode 100644 index d4e0b5d5..00000000 --- a/media-store/app/.vscode/launch.json +++ /dev/null @@ -1,13 +0,0 @@ - -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Chrome", - "type": "chrome", - "request": "launch", - "url": "http://localhost:3000", - "webRoot": "${workspaceRoot}/src" - } - ] -} \ No newline at end of file diff --git a/media-store/app/favicon.ico b/media-store/app/favicon.ico deleted file mode 100644 index bcd5dfd6..00000000 Binary files a/media-store/app/favicon.ico and /dev/null differ diff --git a/media-store/app/index.html b/media-store/app/index.html deleted file mode 100644 index 28e725c5..00000000 --- a/media-store/app/index.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - React App - - - - -
- - - - \ No newline at end of file diff --git a/media-store/app/logo192.png b/media-store/app/logo192.png deleted file mode 100644 index fc44b0a3..00000000 Binary files a/media-store/app/logo192.png and /dev/null differ diff --git a/media-store/app/logo512.png b/media-store/app/logo512.png deleted file mode 100644 index a4e47a65..00000000 Binary files a/media-store/app/logo512.png and /dev/null differ diff --git a/media-store/app/manifest.json b/media-store/app/manifest.json deleted file mode 100644 index 45979ace..00000000 --- a/media-store/app/manifest.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "short_name": "React App", - "name": "Create React App Sample", - "icons": [ - { - "src": "favicon.ico", - "sizes": "64x64 32x32 24x24 16x16", - "type": "image/x-icon" - }, - { - "src": "logo192.png", - "type": "image/png", - "sizes": "192x192" - }, - { - "src": "logo512.png", - "type": "image/png", - "sizes": "512x512" - } - ], - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "sap.app": { - "id": "mediastore", - "applicationVersion": { - "version": "1.0.0" - } - } -} diff --git a/media-store/app/package.json b/media-store/app/package.json deleted file mode 100644 index 6da78597..00000000 --- a/media-store/app/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "mediastore", - "version": "0.1.0", - "private": true, - "dependencies": { - "@testing-library/jest-dom": "^4.2.4", - "@testing-library/react": "^9.3.2", - "@testing-library/user-event": "^7.1.2", - "@umijs/hooks": "^1.9.3", - "antd": "^4.8.2", - "axios": "^0.20.0", - "events": "^3.2.0", - "lodash": "^4.17.20", - "moment": "^2.29.1", - "react": "^16.14.0", - "react-dom": "^16.14.0", - "react-inline-editing": "^1.0.10", - "react-router-dom": "^5.2.0", - "react-scripts": "^4.0.0" - }, - "scripts": { - "start": "react-scripts start --no-cache", - "build": "react-scripts build", - "test": "react-scripts test --no-cache", - "eject": "react-scripts eject" - }, - "eslintConfig": { - "extends": "react-app" - }, - "browserslist": { - "production": [ - ">0.2%", - "not dead", - "not op_mini all" - ], - "development": [ - "last 1 chrome version", - "last 1 firefox version", - "last 1 safari version" - ] - } -} diff --git a/media-store/app/public/favicon.ico b/media-store/app/public/favicon.ico deleted file mode 100644 index bcd5dfd6..00000000 Binary files a/media-store/app/public/favicon.ico and /dev/null differ diff --git a/media-store/app/public/index.html b/media-store/app/public/index.html deleted file mode 100644 index aa069f27..00000000 --- a/media-store/app/public/index.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - React App - - - -
- - - diff --git a/media-store/app/public/logo192.png b/media-store/app/public/logo192.png deleted file mode 100644 index fc44b0a3..00000000 Binary files a/media-store/app/public/logo192.png and /dev/null differ diff --git a/media-store/app/public/logo512.png b/media-store/app/public/logo512.png deleted file mode 100644 index a4e47a65..00000000 Binary files a/media-store/app/public/logo512.png and /dev/null differ diff --git a/media-store/app/public/manifest.json b/media-store/app/public/manifest.json deleted file mode 100644 index 45979ace..00000000 --- a/media-store/app/public/manifest.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "short_name": "React App", - "name": "Create React App Sample", - "icons": [ - { - "src": "favicon.ico", - "sizes": "64x64 32x32 24x24 16x16", - "type": "image/x-icon" - }, - { - "src": "logo192.png", - "type": "image/png", - "sizes": "192x192" - }, - { - "src": "logo512.png", - "type": "image/png", - "sizes": "512x512" - } - ], - "start_url": ".", - "display": "standalone", - "theme_color": "#000000", - "background_color": "#ffffff", - "sap.app": { - "id": "mediastore", - "applicationVersion": { - "version": "1.0.0" - } - } -} diff --git a/media-store/app/public/robots.txt b/media-store/app/public/robots.txt deleted file mode 100644 index e9e57dc4..00000000 --- a/media-store/app/public/robots.txt +++ /dev/null @@ -1,3 +0,0 @@ -# https://www.robotstxt.org/robotstxt.html -User-agent: * -Disallow: diff --git a/media-store/app/public/xs-app.json b/media-store/app/public/xs-app.json deleted file mode 100644 index 930c40ee..00000000 --- a/media-store/app/public/xs-app.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "welcomeFile": "/index.html", - "routes": [ - { - "source": "^(.*)", - "target": "$1", - "service": "html5-apps-repo-rt" - } - ] -} \ No newline at end of file diff --git a/media-store/app/robots.txt b/media-store/app/robots.txt deleted file mode 100644 index e9e57dc4..00000000 --- a/media-store/app/robots.txt +++ /dev/null @@ -1,3 +0,0 @@ -# https://www.robotstxt.org/robotstxt.html -User-agent: * -Disallow: diff --git a/media-store/app/src/App.css b/media-store/app/src/App.css deleted file mode 100644 index 1ec8f2fe..00000000 --- a/media-store/app/src/App.css +++ /dev/null @@ -1,57 +0,0 @@ -@import "~antd/dist/antd.css"; - -html { - overflow: hidden; -} -#root { - height: 100%; -} -section.ant-layout { - height: 100vh; - overflow: auto; -} - -/* Layout -*/ -.site-layout .site-layout-background { - background: #fff; -} - -.App { - text-align: center; -} - -.App-logo { - height: 40vmin; - pointer-events: none; -} - -@media (prefers-reduced-motion: no-preference) { - .App-logo { - animation: App-logo-spin infinite 20s linear; - } -} - -.App-header { - background-color: #282c34; - min-height: 100vh; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - font-size: calc(10px + 2vmin); - color: white; -} - -.App-link { - color: #61dafb; -} - -@keyframes App-logo-spin { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -} diff --git a/media-store/app/src/App.js b/media-store/app/src/App.js deleted file mode 100644 index c1794718..00000000 --- a/media-store/app/src/App.js +++ /dev/null @@ -1,18 +0,0 @@ -import React from "react"; -import "antd/dist/antd.css"; -import "./App.css"; -import { Layout } from "antd"; -import { MyRouter } from "./components/Router"; -import { AppStateContextProvider } from "./contexts/AppStateContext"; - -const App = () => { - return ( - - - - - - ); -}; - -export default App; diff --git a/media-store/app/src/api/axiosInstance.js b/media-store/app/src/api/axiosInstance.js deleted file mode 100644 index 49fd0fa6..00000000 --- a/media-store/app/src/api/axiosInstance.js +++ /dev/null @@ -1,21 +0,0 @@ -import axios from "axios"; -import { getUserFromLS, getLocaleFromLS } from "../util/localStorageService"; -import { - changeUserDefaults, - changeLocaleDefaults, -} from "./changeAxiosDefaults"; -import { API } from "../util/constants"; -import { responseErrorInterceptor } from "./responseErrorInterceptor"; - -const axiosInstance = axios.create({ - baseURL: API, - timeout: 2000, -}); -const user = getUserFromLS(); -const locale = getLocaleFromLS(); -changeUserDefaults(user); -changeLocaleDefaults(locale); - -axiosInstance.interceptors.response.use(null, responseErrorInterceptor); - -export { axiosInstance, changeLocaleDefaults, changeUserDefaults }; diff --git a/media-store/app/src/api/calls.js b/media-store/app/src/api/calls.js deleted file mode 100644 index fb35f412..00000000 --- a/media-store/app/src/api/calls.js +++ /dev/null @@ -1,188 +0,0 @@ -import { isEmpty } from "lodash"; -import { axiosInstance } from "./axiosInstance"; - -const BROWSE_TRACKS_SERVICE = "browse-tracks"; -const INVOICES_SERVICE = "browse-invoices"; -const USER_SERVICE = "users"; -const MANAGE_STORE = "manage-store"; - -const constructGenresQuery = (genreIds) => { - return !isEmpty(genreIds) - ? " and " + genreIds.map((value) => `genre_ID eq ${value}`).join(" or ") - : ""; -}; - -const fetchTacks = ({ - $top = 20, - $skip = 0, - genreIds = [], - substr = "", -} = {}) => { - const serializeTracksUrl = () => { - return `$expand=genre,album($expand=artist)&$top=${$top}&$skip=${$skip}&$filter=${ - `contains(name,'${substr}')` + constructGenresQuery(genreIds) - }`; - }; - - return axiosInstance.get( - `${BROWSE_TRACKS_SERVICE}/${axiosInstance.defaults.tracksEntity}`, - { - params: {}, - paramsSerializer: () => serializeTracksUrl(), - } - ); -}; - -const countTracks = ({ genreIds = [], substr = "" } = {}) => { - const tracksEntity = axiosInstance.defaults.tracksEntity; - - return axiosInstance.get( - `${BROWSE_TRACKS_SERVICE}/${tracksEntity}/$count?$filter=${ - `contains(name,'${substr}')` + constructGenresQuery(genreIds) - }` - ); -}; - -const fetchGenres = () => { - return axiosInstance.get(`${BROWSE_TRACKS_SERVICE}/Genres`); -}; - -const invoice = (tracks) => { - return axiosInstance.post( - `${INVOICES_SERVICE}/invoice`, - { - tracks: tracks.map(({ unitPrice, ID }) => ({ - unitPrice: `${unitPrice}`, - ID, - })), - }, - { - headers: { "content-type": "application/json;IEEE754Compatible=true" }, - } - ); -}; - -const fetchPerson = () => { - return axiosInstance.get( - `${USER_SERVICE}/${axiosInstance.defaults.userEntity}` - ); -}; - -const confirmPerson = (person) => { - return axiosInstance.put( - `${USER_SERVICE}/${axiosInstance.defaults.userEntity}`, - { - ...person, - }, - { - headers: { "content-type": "application/json" }, - } - ); -}; - -const fetchInvoices = () => { - return axiosInstance.get( - `${INVOICES_SERVICE}/Invoices?$expand=invoiceItems($expand=track($expand=album($expand=artist)))` - ); -}; - -const cancelInvoice = (ID) => { - return axiosInstance.post( - `${INVOICES_SERVICE}/cancelInvoice`, - { - ID, - }, - { - headers: { "content-type": "application/json" }, - } - ); -}; - -const fetchAlbumsByName = (substr = "", top) => { - return axiosInstance.get( - `${BROWSE_TRACKS_SERVICE}/Albums?$filter=${`contains(title,'${substr}')&$top=${top}`}` - ); -}; - -const addTrack = (data) => { - return axiosInstance.post(`${MANAGE_STORE}/Tracks`, data, { - headers: { "content-type": "application/json;IEEE754Compatible=true" }, - }); -}; - -const addArtist = (data) => { - return axiosInstance.post(`${MANAGE_STORE}/Artists`, data, { - headers: { "content-type": "application/json" }, - }); -}; - -const addAlbum = (data) => { - return axiosInstance.post(`${MANAGE_STORE}/Albums`, data, { - headers: { "content-type": "application/json" }, - }); -}; - -const fetchArtistsByName = (substr = "", top) => { - return axiosInstance.get( - `${MANAGE_STORE}/Artists?$filter=${`contains(name,'${substr}')&$top=${top}`}` - ); -}; - -const login = (data) => { - return axiosInstance.post(`${USER_SERVICE}/login`, data, { - headers: { "content-type": "application/json" }, - }); -}; - -const updateTrack = (track) => { - return axiosInstance.put( - `${MANAGE_STORE}/Tracks/${track.ID}`, - { - ...track, - }, - { - headers: { "content-type": "application/json;IEEE754Compatible=true" }, - } - ); -}; - -const getTrack = (ID) => { - return axiosInstance.get( - `${BROWSE_TRACKS_SERVICE}/${axiosInstance.defaults.tracksEntity}/${ID}?$expand=genre,album($expand=artist)` - ); -}; - -const deleteTrack = (ID) => { - return axiosInstance.delete(`${MANAGE_STORE}/Tracks(${ID})`); -}; - -const refreshTokens = (refreshToken) => { - return axiosInstance.post( - `${USER_SERVICE}/refreshTokens`, - { refreshToken }, - { - headers: { "content-type": "application/json" }, - } - ); -}; - -export { - fetchTacks, - countTracks, - fetchGenres, - invoice, - fetchPerson, - confirmPerson, - fetchInvoices, - cancelInvoice, - fetchAlbumsByName, - addTrack, - addArtist, - addAlbum, - fetchArtistsByName, - login, - updateTrack, - getTrack, - deleteTrack, - refreshTokens, -}; diff --git a/media-store/app/src/api/changeAxiosDefaults.js b/media-store/app/src/api/changeAxiosDefaults.js deleted file mode 100644 index be816790..00000000 --- a/media-store/app/src/api/changeAxiosDefaults.js +++ /dev/null @@ -1,27 +0,0 @@ -import { axiosInstance } from "./axiosInstance"; - -function changeUserDefaults(currentUser) { - if (currentUser) { - axiosInstance.defaults.headers.common[ - "Authorization" - ] = `Basic ${currentUser.accessToken}`; - axiosInstance.defaults.userID = currentUser.ID; - if (currentUser.roles.includes("customer")) { - axiosInstance.defaults.userEntity = `Customers/${currentUser.ID}`; - axiosInstance.defaults.tracksEntity = "MarkedTracks"; - } else { - axiosInstance.defaults.userEntity = `Employees/${currentUser.ID}`; - axiosInstance.defaults.tracksEntity = "Tracks"; - } - } else { - axiosInstance.defaults.tracksEntity = "Tracks"; - } -} - -function changeLocaleDefaults(locale) { - if (locale) { - axiosInstance.defaults.headers.common["Accept-language"] = locale; - } -} - -export { changeLocaleDefaults, changeUserDefaults }; diff --git a/media-store/app/src/api/responseErrorInterceptor.js b/media-store/app/src/api/responseErrorInterceptor.js deleted file mode 100644 index 40824e4d..00000000 --- a/media-store/app/src/api/responseErrorInterceptor.js +++ /dev/null @@ -1,62 +0,0 @@ -import { emitter } from "../util/EventEmitter"; -import { axiosInstance } from "./axiosInstance"; -import { refreshTokens } from "./calls"; -import { getUserFromLS } from "../util/localStorageService"; - -let isRefreshing = false; -let subscribers = []; - -function responseErrorInterceptor(error) { - const originalRequest = error.config; - const user = getUserFromLS(); - - if (error.response && error.response.status === 401 && !!user) { - if (originalRequest.url === "users/login") { - return Promise.reject(error); - } - - // if users/refreshTokens request failed - if (isRefreshing && originalRequest.url === "users/refreshTokens") { - subscribers.forEach((request) => request.reject(error)); - subscribers = []; - isRefreshing = false; - return Promise.reject(error); - } - - // if got a 401 error we sending users/refreshTokens request - if (!isRefreshing) { - isRefreshing = true; - - refreshTokens(user.refreshToken) - .then((response) => { - emitter.emit("UPDATE_USER", response.data); - subscribers.forEach((request) => - request.resolve(response.data.accessToken) - ); - subscribers = []; - isRefreshing = false; - }) - .catch(() => { - emitter.emit("UPDATE_USER", undefined); - }); - } - - // holding requests which should be sended after users/refreshTokens complete - // otherwise if users/refreshTokens failed an error will be thrown - return new Promise((resolve, reject) => { - subscribers.push({ - resolve: (newAccessToken) => { - originalRequest.headers.Authorization = "Basic " + newAccessToken; - resolve(axiosInstance(originalRequest)); - }, - reject: (err) => { - reject(err); - }, - }); - }); - } - - return Promise.reject(error); -} - -export { responseErrorInterceptor }; diff --git a/media-store/app/src/components/Header.css b/media-store/app/src/components/Header.css deleted file mode 100644 index 3d78184d..00000000 --- a/media-store/app/src/components/Header.css +++ /dev/null @@ -1,3 +0,0 @@ -.ant-menu-item .anticon { - margin: 0; -} diff --git a/media-store/app/src/components/Header.js b/media-store/app/src/components/Header.js deleted file mode 100644 index 495ef11b..00000000 --- a/media-store/app/src/components/Header.js +++ /dev/null @@ -1,158 +0,0 @@ -import React from "react"; -import { Menu, Badge, Spin } from "antd"; -import { isEmpty } from "lodash"; -import { - CreditCardOutlined, - LogoutOutlined, - LoginOutlined, - LoadingOutlined, -} from "@ant-design/icons"; -import { useHistory, useLocation } from "react-router-dom"; -import { useAppState } from "../hooks/useAppState"; -import { setLocaleToLS } from "../util/localStorageService"; -import { changeLocaleDefaults } from "../api/axiosInstance"; -import { emitter } from "../util/EventEmitter"; -import "./Header.css"; -import { requireEmployee, requireCustomer } from "../util/constants"; - -const { SubMenu } = Menu; - -const keys = ["/", "/person", "/login", "/manage", "/invoice", "/invoices"]; -const AVAILABLE_LOCALES = ["en", "fr", "de"]; -const RELOAD_LOCATION_NUMBER = 0; - -const Header = () => { - const history = useHistory(); - const location = useLocation(); - const { - user, - invoicedItems, - setInvoicedItems, - locale, - setLocale, - loading, - } = useAppState(); - const currentKey = [keys.find((key) => key === location.pathname)]; - const haveInvoicedItems = !isEmpty(invoicedItems); - const invoicedItemsLength = invoicedItems.length; - - const onChangeLocale = (value) => { - setLocaleToLS(value); - changeLocaleDefaults(value); - setLocale(value); - history.go(RELOAD_LOCATION_NUMBER); - }; - const localeElements = AVAILABLE_LOCALES.filter( - (localeName) => localeName !== locale - ).map((curLocale, index) => ( - onChangeLocale(curLocale)} - > - {curLocale} - - )); - - const onUserLogout = () => { - emitter.emit("UPDATE_USER", undefined); - history.go(0); - }; - - return ( -
- - history.push("/")}> - Browse - - - {!!user && ( - history.push("/person")}> - Profile - - )} - {requireCustomer(user) && ( - history.push("/invoices")}> - Invoices - - )} - {requireEmployee(user) && ( - history.push("/manage")}> - Manage - - )} - - {loading && ( - } - /> - )} - - - - - {haveInvoicedItems && ( - history.push("/invoice")} - key="/invoice" - > -
- - - -
-
- )} - - {localeElements} - - {!!user ? ( - } - > - ) : ( - history.push("/login")} - icon={} - > - )} -
-
- ); -}; - -export { Header }; diff --git a/media-store/app/src/components/Router.js b/media-store/app/src/components/Router.js deleted file mode 100644 index caa69a6e..00000000 --- a/media-store/app/src/components/Router.js +++ /dev/null @@ -1,58 +0,0 @@ -import React from "react"; -import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; -import { isEmpty } from "lodash"; -import { TracksContainer } from "../pages/TracksPage"; -import { Header } from "../components/Header"; -import { PersonPage } from "../pages/PersonPage"; -import { ErrorPage } from "../pages/ErrorPage"; -import { Login } from "../pages/Login"; -import { withRestrictions } from "../hocs/withRestrictions"; -import { InvoicePage } from "../pages/InvoicePage"; -import { ManageStore } from "../pages/ManageStore"; -import { MyInvoicesPage } from "../pages/MyInvoicesPage"; -import { requireEmployee } from "../util/constants"; - -const RestrictedLogin = withRestrictions(Login, ({ user }) => !user); -const RestrictedInvoicePage = withRestrictions( - InvoicePage, - ({ user, invoicedItems }) => !requireEmployee(user) && !isEmpty(invoicedItems) -); -const RestrictedPersonPage = withRestrictions(PersonPage, ({ user }) => !!user); -const RestrictedManageStore = withRestrictions(ManageStore, ({ user }) => - requireEmployee(user) -); - -const MyRouter = () => { - return ( - -
-
- - - - - - - - - - - - - - - - - - - - - - - -
- - ); -}; - -export { MyRouter }; diff --git a/media-store/app/src/contexts/AppStateContext.js b/media-store/app/src/contexts/AppStateContext.js deleted file mode 100644 index e0029d6e..00000000 --- a/media-store/app/src/contexts/AppStateContext.js +++ /dev/null @@ -1,71 +0,0 @@ -import React, { useMemo, createContext, useState, useEffect } from "react"; -import { - getUserFromLS, - getLocaleFromLS, - setUserToLS, -} from "../util/localStorageService"; -import { changeUserDefaults } from "../api/axiosInstance"; -import { emitter } from "../util/EventEmitter"; - -let counter = 0; - -const globalContext = { - error: {}, - loading: true, - user: { - ID: undefined, - roles: [], - email: undefined, - accessToken: undefined, - refreshToken: undefined, - }, - locale: undefined, - invoicedItems: [], - notifications: [], -}; -const AppStateContext = createContext(globalContext); - -const AppStateContextProvider = ({ children }) => { - const [invoicedItems, setInvoicedItems] = useState([]); - const [loading, setLoading] = useState(false); - const [error, setError] = useState({}); - const [user, setUser] = useState(getUserFromLS()); - const [locale, setLocale] = useState(getLocaleFromLS()); - - useEffect(() => { - const updateUser = (newUser) => { - console.log("USER_UPDATE WAS TRIGGERED", counter++); - changeUserDefaults(newUser); - setUserToLS(newUser); - setUser(newUser); - }; - emitter.on("UPDATE_USER", updateUser); - return () => { - emitter.removeListener("UPDATE_USER", updateUser); - }; - }, []); - - const value = useMemo( - () => ({ - error: error, - loading: loading, - invoicedItems: invoicedItems, - user: user, - locale: locale, - setLoading, - setError, - setInvoicedItems, - setUser: setUser, - setLocale: setLocale, - }), - [locale, user, loading, error, invoicedItems] - ); - - return ( - - {children} - - ); -}; - -export { AppStateContextProvider, AppStateContext }; diff --git a/media-store/app/src/hocs/withRestrictions.js b/media-store/app/src/hocs/withRestrictions.js deleted file mode 100644 index 525cbae7..00000000 --- a/media-store/app/src/hocs/withRestrictions.js +++ /dev/null @@ -1,16 +0,0 @@ -import React from "react"; -import { Redirect } from "react-router-dom"; -import { useAppState } from "../hooks/useAppState"; - -const withRestrictions = (Component, isUserMeetRestrictions) => { - return (props) => { - const { user, invoicedItems } = useAppState(); - return isUserMeetRestrictions({ user, invoicedItems }) ? ( - - ) : ( - - ); - }; -}; - -export { withRestrictions }; diff --git a/media-store/app/src/hooks/useAbortableEffect.js b/media-store/app/src/hooks/useAbortableEffect.js deleted file mode 100644 index 6fa18e87..00000000 --- a/media-store/app/src/hooks/useAbortableEffect.js +++ /dev/null @@ -1,22 +0,0 @@ -import { useEffect } from "react"; - -function useAbortableEffect(effect, dependencies) { - const status = {}; // mutable status object - useEffect(() => { - status.aborted = false; - // pass the mutable object to the effect callback - // store the returned value for cleanup - const cleanUpFn = effect(status); - return () => { - // mutate the object to signal the consumer - // this effect is cleaning up - status.aborted = true; - if (typeof cleanUpFn === "function") { - // run the cleanup function - cleanUpFn(); - } - }; - }, [...dependencies]); -} - -export { useAbortableEffect }; diff --git a/media-store/app/src/hooks/useAppState.js b/media-store/app/src/hooks/useAppState.js deleted file mode 100644 index 6ea35f5f..00000000 --- a/media-store/app/src/hooks/useAppState.js +++ /dev/null @@ -1,6 +0,0 @@ -import { useContext } from "react"; -import { AppStateContext } from "../contexts/AppStateContext"; - -const useAppState = () => useContext(AppStateContext); - -export { useAppState }; diff --git a/media-store/app/src/hooks/useErrors.js b/media-store/app/src/hooks/useErrors.js deleted file mode 100644 index 086a5a04..00000000 --- a/media-store/app/src/hooks/useErrors.js +++ /dev/null @@ -1,34 +0,0 @@ -import { useHistory } from "react-router-dom"; -import { useAppState } from "./useAppState"; - -const useErrors = () => { - const history = useHistory(); - const { setError } = useAppState(); - - const handleError = (error) => { - console.error("Error", error); - - if (error.response) { - const { status, statusText, data } = error.response; - setError({ - status, - statusText, - message: data.error ? data.error.message : data, - }); - } else { - setError({ - status: "", - statusText: "Error", - message: "Something went wrong. Seems like request is too long", - }); - } - - history.push("/error"); - }; - - return { - handleError, - }; -}; - -export { useErrors }; diff --git a/media-store/app/src/index.js b/media-store/app/src/index.js deleted file mode 100644 index c1684e83..00000000 --- a/media-store/app/src/index.js +++ /dev/null @@ -1,11 +0,0 @@ -import React from "react"; -import ReactDOM from "react-dom"; -import App from "./App"; -import * as serviceWorker from "./serviceWorker"; - -ReactDOM.render(, document.getElementById("root")); - -// If you want your app to work offline and load faster, you can change -// unregister() to register() below. Note this comes with some pitfalls. -// Learn more about service workers: https://bit.ly/CRA-PWA -serviceWorker.unregister(); diff --git a/media-store/app/src/logo.svg b/media-store/app/src/logo.svg deleted file mode 100644 index 6b60c104..00000000 --- a/media-store/app/src/logo.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/media-store/app/src/pages/ErrorPage.js b/media-store/app/src/pages/ErrorPage.js deleted file mode 100644 index 77a68af8..00000000 --- a/media-store/app/src/pages/ErrorPage.js +++ /dev/null @@ -1,50 +0,0 @@ -import React from "react"; -import { useHistory } from "react-router-dom"; -import { isEmpty } from "lodash"; -import { Result, Button } from "antd"; -import { useAppState } from "../hooks/useAppState"; - -const ErrorPage = () => { - const { error, setError } = useAppState(); - const history = useHistory(); - - const onGoHome = () => { - setError({}); - history.push("/"); - }; - - const goLoginPage = () => { - setError({}); - history.push("/login"); - }; - - const goHomeButton = ( - - ); - const goLoginButton = ( - - ); - - const errorResultProps = isEmpty(error) - ? { - status: 404, - title: "Not found", - subTitle: "Sorry, the page you visited does not exist.", - extra: goHomeButton, - } - : { - status: [404, 403, 500].includes(error.status) ? error.status : "error", - title: error.statusText, - subTitle: error.message, - extra: - error.status === 401 ? [goHomeButton, goLoginButton] : goHomeButton, - }; - - return ; -}; - -export { ErrorPage }; diff --git a/media-store/app/src/pages/InvoicePage.js b/media-store/app/src/pages/InvoicePage.js deleted file mode 100644 index a4644e97..00000000 --- a/media-store/app/src/pages/InvoicePage.js +++ /dev/null @@ -1,107 +0,0 @@ -import React from "react"; -import { Table, Button, message } from "antd"; -import { useAppState } from "../hooks/useAppState"; -import { useHistory } from "react-router-dom"; -import { invoice } from "../api/calls"; -import { useErrors } from "../hooks/useErrors"; -import { MESSAGE_TIMEOUT } from "../util/constants"; - -const columns = [ - { - title: "Name", - dataIndex: "name", - }, - { - title: "Artist", - dataIndex: "artist", - }, - { - title: "Album", - dataIndex: "albumTitle", - }, - { - title: "Price", - dataIndex: "unitPrice", - }, -]; - -const InvoicePage = () => { - const history = useHistory(); - const { handleError } = useErrors(); - const { user, invoicedItems, setInvoicedItems, setLoading } = useAppState(); - - const data = invoicedItems.map(({ ID, ...otherProps }) => ({ - key: `invoiceItem${ID}`, - ...otherProps, - })); - - const onBuy = () => { - setLoading(true); - invoice( - invoicedItems.map(({ ID, unitPrice }) => ({ - ID, - unitPrice, - })) - ) - .then(() => { - setInvoicedItems([]); - message.success("Invoice successfully completed", MESSAGE_TIMEOUT); - history.push("/invoices"); - }) - .catch(handleError) - .finally(() => setLoading(false)); - }; - const onCancel = () => { - setInvoicedItems([]); - history.push("/"); - }; - const goLogin = () => { - history.push("/login"); - }; - - return ( -
- ( -
- {user ? ( - <> - - - - ) : ( -
- - to buy selected -
- )} -
- )} - /> - - ); -}; - -export { InvoicePage }; diff --git a/media-store/app/src/pages/Login.js b/media-store/app/src/pages/Login.js deleted file mode 100644 index 3efd5a6d..00000000 --- a/media-store/app/src/pages/Login.js +++ /dev/null @@ -1,107 +0,0 @@ -import React from "react"; -import { Form, Input, Button, Checkbox, message } from "antd"; -import { login } from "../api/calls"; -import { useHistory } from "react-router-dom"; -import { useAppState } from "../hooks/useAppState"; -import { useErrors } from "../hooks/useErrors"; -import { MESSAGE_TIMEOUT } from "../util/constants"; -import { emitter } from "../util/EventEmitter"; - -const layout = { - labelCol: { - span: 8, - }, - wrapperCol: { - span: 8, - }, -}; -const tailLayout = { - wrapperCol: { - offset: 8, - span: 8, - }, -}; - -const Login = () => { - const [form] = Form.useForm(); - const history = useHistory(); - const { setLoading, setInvoicedItems } = useAppState(); - const { handleError } = useErrors(); - - const onFinish = (values) => { - setLoading(true); - login({ email: values.email, password: values.password }) - .then(({ data: user }) => { - emitter.emit("UPDATE_USER", user); - if (user.roles.includes("employee")) { - setInvoicedItems([]); - } - history.push("/"); - }) - .catch((error) => { - console.log(error); - if (error.response && error.response.status === 401) { - form.resetFields(); - message.error("Invalid credentials!", MESSAGE_TIMEOUT); - } else { - handleError(error); - } - }) - .finally(() => setLoading(false)); - }; - - const onFinishFailed = (errorInfo) => { - console.log("Validation Failed:", errorInfo); - }; - - return ( - - - - - - - - - - - Remember me - - - - - - - ); -}; - -export { Login }; diff --git a/media-store/app/src/pages/ManageStore.js b/media-store/app/src/pages/ManageStore.js deleted file mode 100644 index c23c2e33..00000000 --- a/media-store/app/src/pages/ManageStore.js +++ /dev/null @@ -1,115 +0,0 @@ -import React, { useState, useMemo, useEffect } from "react"; -import { Form, Radio, Button, message } from "antd"; -import { TrackForm } from "./manage-store/TrackForm"; -import { AddArtistForm } from "./manage-store/AddArtistForm"; -import { AddAlbumForm } from "./manage-store/AddAlbumForm"; -import { useErrors } from "../hooks/useErrors"; -import { useAppState } from "../hooks/useAppState"; -import { addTrack, addArtist, addAlbum } from "../api/calls"; -import { MESSAGE_TIMEOUT } from "../util/constants"; - -const FORM_TYPES = { - track: "track", - artist: "artist", - album: "album", - playlist: "", -}; - -const chooseForm = (type) => { - return ( - (type === "track" && ) || - (type === "artist" && ) || - (type === "album" && ) - ); -}; - -const ManageStore = () => { - const [form] = Form.useForm(); - const { handleError } = useErrors(); - const { setLoading } = useAppState(); - const [formType, setFormType] = useState("track"); - - useEffect(() => { - form.resetFields(); - }, [formType]); - - const formElement = useMemo(() => { - return chooseForm(formType); - }, [formType]); - - const onChangeForm = (event) => { - setFormType(event.target.value); - }; - - const sendCreateRequest = ({ type, ...data }) => { - setLoading(true); - - let promise; - switch (type) { - case FORM_TYPES.track: - promise = addTrack({ - name: data.name, - composer: data.composer, - album: { ID: data.albumID }, - genre: { ID: data.genreID }, - unitPrice: data.unitPrice.toString(), - }); - break; - case FORM_TYPES.artist: - promise = addArtist(data); - break; - case FORM_TYPES.album: - promise = addAlbum({ title: data.name, artist: { ID: data.artistID } }); - break; - default: - } - - promise - .then(() => { - message.success("Entity successfully created", MESSAGE_TIMEOUT); - form.resetFields(); - }) - .catch(handleError) - .finally(() => setLoading(false)); - }; - - return ( -
console.log("Not valid params provided")} - > - - - Track - Album - Artist - - - {formElement} - - - - - ); -}; - -export { ManageStore }; diff --git a/media-store/app/src/pages/MyInvoicesPage.js b/media-store/app/src/pages/MyInvoicesPage.js deleted file mode 100644 index fb7053e8..00000000 --- a/media-store/app/src/pages/MyInvoicesPage.js +++ /dev/null @@ -1,185 +0,0 @@ -import React, { useState, useEffect, useMemo, useCallback } from "react"; -import { Button, message, Tag, Collapse, Table, Spin } from "antd"; -import moment from "moment"; -import { useErrors } from "../hooks/useErrors"; -import { useAppState } from "../hooks/useAppState"; -import { cancelInvoice, fetchInvoices } from "../api/calls"; -import { MESSAGE_TIMEOUT } from "../util/constants"; - -const { Panel } = Collapse; -const INVOICE_STATUS = { - 2: { - tagTitle: "Shipped", - color: "green", - }, - 1: { - tagTitle: "Submitted", - color: "processing", - canCancel: true, - }, - ["-1"]: { - tagTitle: "Cancelled", - color: "default", - }, -}; -const CANCELLED_STATUS = -1; -const DATE_TIME_FORMAT_PATTERN = "LLLL"; -const UTC_DATE_TIME_FORMAT = "YYYY-MM-DDThh:mm:ss"; -const INVOICE_ITEMS_COLUMNS = [ - { - title: "Track name", - dataIndex: "name", - }, - { - title: "Artist", - dataIndex: "artistName", - }, - { - title: "Album", - dataIndex: "albumTitle", - }, - { - title: "Price", - dataIndex: "unitPrice", - }, -]; -const LEVERAGE_DURATION = 1; // in hours -const STATUSES = { submitted: 1, shipped: 2, canceled: -1 }; - -const isLeverageTimeExpired = (utcNowTimestamp, invoiceDate) => { - const duration = moment.duration( - moment(utcNowTimestamp).diff(moment(invoiceDate).valueOf()) - ); - return duration.asHours() > LEVERAGE_DURATION; -}; - -const chooseStatus = (utcNowTimestamp, invoiceDate, statusFromDb) => { - if ( - isLeverageTimeExpired(utcNowTimestamp, invoiceDate) && - statusFromDb !== STATUSES.canceled - ) { - return INVOICE_STATUS[STATUSES.shipped]; - } - return INVOICE_STATUS[statusFromDb]; -}; - -const ExtraHeader = ({ ID, invoiceDate, status: initialStatus }) => { - const { loading, setLoading } = useAppState(); - const { handleError } = useErrors(); - const [loadingHeaderId, setLoadingHeaderId] = useState(); - const [status, setStatus] = useState(initialStatus); - - const statusConfig = useMemo(() => { - const utcNowTimestamp = moment( - moment().utc().format(UTC_DATE_TIME_FORMAT) - ).valueOf(); - return chooseStatus(utcNowTimestamp, invoiceDate, status); - }, [status]); - - const onCancelInvoice = (event, ID) => { - event.stopPropagation(); - setLoading(true); - setLoadingHeaderId(ID); - cancelInvoice(ID) - .then(() => { - message.success("Invoice successfully cancelled", MESSAGE_TIMEOUT); - setLoadingHeaderId(undefined); - setStatus(CANCELLED_STATUS); - }) - .catch(handleError) - .finally(() => setLoading(false)); - }; - - return ( - - {statusConfig.tagTitle} - {statusConfig.canCancel && ( - - )} - - ); -}; - -const MyInvoicesPage = () => { - const { handleError } = useErrors(); - const { setLoading } = useAppState(); - const [invoices, setInvoices] = useState([]); - - useEffect(() => { - setLoading(true); - fetchInvoices() - .then(({ data: { value } }) => setInvoices(value)) - .catch(handleError) - .finally(() => setLoading(false)); - }, []); - - const genExtra = useCallback( - (ID, status, invoiceDate) => ( - - ), - [] - ); - const invoiceElements = useMemo(() => { - return invoices.map(({ ID, status, invoiceDate, total, invoiceItems }) => { - const invoiceItemsData = invoiceItems.map( - ({ - ID, - track: { - name, - unitPrice, - album: { - title: albumTitle, - artist: { name: artistName }, - }, - }, - }) => ({ - key: ID, - ID, - name, - unitPrice, - albumTitle, - artistName, - }) - ); - - return ( - -
-
( - {`Total price: ${total}`} - )} - /> - - - ); - }); - }, [invoices]); - - return ( -
- {invoiceElements && ( - {invoiceElements} - )} -
- ); -}; - -export { MyInvoicesPage }; diff --git a/media-store/app/src/pages/PersonPage.js b/media-store/app/src/pages/PersonPage.js deleted file mode 100644 index e941c4a6..00000000 --- a/media-store/app/src/pages/PersonPage.js +++ /dev/null @@ -1,108 +0,0 @@ -import React, { useState } from "react"; -import { Form, Button, message, Input } from "antd"; -import { omit, map } from "lodash"; -import { fetchPerson, confirmPerson } from "../api/calls"; -import { useErrors } from "../hooks/useErrors"; -import { useAppState } from "../hooks/useAppState"; -import { MESSAGE_TIMEOUT } from "../util/constants"; -import { useAbortableEffect } from "../hooks/useAbortableEffect"; - -const PERSON_PROP = { - address: "Address ", - city: "City ", - country: "Country ", - fax: "Fax: ", - firstName: "First name: ", - lastName: "Last name: ", - phone: "Phone: ", - postalCode: "Postal code: ", - state: "State", - email: "email", - company: "Company: ", -}; - -const PersonPage = () => { - const { setLoading } = useAppState(); - const { handleError } = useErrors(); - const [form] = Form.useForm(); - const [person, setPerson] = useState({ - lastName: "", - firstName: "", - city: "", - state: "", - address: "", - country: "", - phone: "", - postalCode: "", - fax: "", - email: "", - company: "", - }); - - useAbortableEffect((status) => { - setLoading(true); - - fetchPerson() - .then(({ data: personData }) => { - personData = omit(personData, "@odata.context", "ID"); - if (!status.aborted) { - setPerson(personData); - } - }) - .catch(handleError) - .finally(() => setLoading(false)); - }, []); - - const onConfirmChanges = (newPerson) => { - setLoading(true); - confirmPerson(newPerson) - .then(() => { - message.success("Person successfully updated", MESSAGE_TIMEOUT); - }) - .catch(handleError) - .finally(() => setLoading(false)); - }; - - const personProperties = map(Object.keys(person), (currentKey) => ( -
- - - -
- )); - - return ( - <> - {person.lastName !== "" && ( - console.log("Not valid params provided")} - initialValues={{ - ...person, - }} - > - {personProperties} - - - - - )} - - ); -}; - -export { PersonPage }; diff --git a/media-store/app/src/pages/TracksPage.css b/media-store/app/src/pages/TracksPage.css deleted file mode 100644 index c3855497..00000000 --- a/media-store/app/src/pages/TracksPage.css +++ /dev/null @@ -1,4 +0,0 @@ -.ant-select > div.ant-select-selector { - padding: 5px; - min-width: 300px; -} diff --git a/media-store/app/src/pages/TracksPage.js b/media-store/app/src/pages/TracksPage.js deleted file mode 100644 index f3842535..00000000 --- a/media-store/app/src/pages/TracksPage.js +++ /dev/null @@ -1,219 +0,0 @@ -import React, { useState } from "react"; -import { debounce } from "lodash"; -import { Input, Col, Row, Select, Pagination } from "antd"; -import { Track } from "./tracks/Track"; -import { ManagedTrack } from "./tracks/ManagedTrack"; -import { useAppState } from "../hooks/useAppState"; -import { useErrors } from "../hooks/useErrors"; -import { fetchTacks, countTracks, fetchGenres } from "../api/calls"; -import { useAbortableEffect } from "../hooks/useAbortableEffect"; -import { requireEmployee } from "../util/constants"; -import "./TracksPage.css"; - -const { Search } = Input; -const { Option } = Select; - -const DEBOUNCE_TIMER = 500; -const DEBOUNCE_OPTIONS = { - leading: true, - trailing: false, -}; - -const renderGenres = (genres) => - genres.map(({ ID, name }) => ( - - )); - -const TracksContainer = () => { - const { setLoading, user } = useAppState(); - const { handleError } = useErrors(); - const [state, setState] = useState({ - tracks: [], - genres: [], - pagination: { - currentPage: 1, - totalItems: 0, - pageSize: 20, - }, - searchOptions: { - substr: "", - genreIds: [], - }, - }); - - useAbortableEffect((status) => { - setLoading(true); - - const countTracksReq = countTracks(); - const getTracksRequest = fetchTacks(); - const getGenresReq = fetchGenres(); - - Promise.all([countTracksReq, getTracksRequest, getGenresReq]) - .then( - ([ - { data: totalItems }, - { - data: { value: tracks }, - }, - { - data: { value: genres }, - }, - ]) => { - if (!status.aborted) { - setState({ - ...state, - tracks, - genres, - pagination: { ...state.pagination, totalItems }, - }); - } - } - ) - .catch(handleError) - .finally(() => setLoading(false)); - }, []); - - const onSearch = debounce( - () => { - setLoading(true); - const options = { - $top: state.pagination.pageSize, - substr: state.searchOptions.substr, - genreIds: state.searchOptions.genreIds, - }; - - Promise.all([ - fetchTacks(options), - countTracks({ - substr: options.substr, - genreIds: options.genreIds, - }), - ]) - .then(([{ data: { value: tracks } }, { data: totalItems }]) => - setState({ - ...state, - tracks, - pagination: { ...state.pagination, totalItems }, - }) - ) - .catch(handleError) - .finally(() => setLoading(false)); - }, - DEBOUNCE_TIMER, - DEBOUNCE_OPTIONS - ); - const onSelectChange = (genres) => { - setState({ - ...state, - searchOptions: { - ...state.searchOptions, - genreIds: genres.map((value) => parseInt(value, 10)), - }, - }); - }; - const onSearchChange = (event) => { - setState({ - ...state, - searchOptions: { ...state.searchOptions, substr: event.target.value }, - }); - }; - const onChangePage = (pageNumber) => { - document - .querySelector("section.ant-layout") - .scrollTo({ top: 0, left: 0, behavior: "smooth" }); - setLoading(true); - - const options = { - $top: state.pagination.pageSize, - substr: state.searchOptions.substr, - genreIds: state.searchOptions.genreIds, - $skip: (pageNumber - 1) * state.pagination.pageSize, - }; - fetchTacks(options) - .then((response) => - setState({ - ...state, - tracks: response.data.value, - pagination: { ...state.pagination, currentPage: pageNumber }, - }) - ) - .catch(handleError) - .finally(() => setLoading(false)); - }; - const deleteTrack = (ID) => { - setState({ - ...state, - tracks: state.tracks.filter(({ ID: curID }) => curID !== ID), - }); - }; - const renderTracks = (tracks) => { - const isEmployee = requireEmployee(user); - const TrackComponent = isEmployee ? ManagedTrack : Track; - return tracks.map((track) => { - const isAlreadyOrdered = !isEmployee && track.alreadyOrdered; - const onDeleteTrack = isEmployee && ((ID) => deleteTrack(ID)); - return ( - - - - ); - }); - }; - - const trackElements = renderTracks(state.tracks); - const genreElements = renderGenres(state.genres); - - return ( - <> -
- - -
-
- - {trackElements} - -
-
- -
- - ); -}; - -export { TracksContainer }; diff --git a/media-store/app/src/pages/manage-store/AddAlbumForm.js b/media-store/app/src/pages/manage-store/AddAlbumForm.js deleted file mode 100644 index 2aa219ac..00000000 --- a/media-store/app/src/pages/manage-store/AddAlbumForm.js +++ /dev/null @@ -1,62 +0,0 @@ -import React, { useEffect } from "react"; -import { Form, Input, Select } from "antd"; -import { useSearch } from "@umijs/hooks"; -import { useErrors } from "../../hooks/useErrors"; -import { fetchArtistsByName } from "../../api/calls"; - -const REQUIRED = [ - { - required: true, - message: "This filed is required!", - }, -]; -const ARTISTS_LIMIT = 10; - -const getArtists = function (value) { - return fetchArtistsByName(value, ARTISTS_LIMIT) - .then((response) => response.data.value) - .catch(this.handleError); -}; - -const AddAlbumForm = () => { - const { handleError } = useErrors(); - const { - data: artists, - loading: isArtistsLoading, - onChange: onChangeArtistInput, - cancel: onArtistCancel, - } = useSearch(getArtists.bind({ handleError })); - - useEffect(() => { - onChangeArtistInput(); - }, []); - - return ( - <> -

Add album

- - - - - - - - ); -}; - -export { AddAlbumForm }; diff --git a/media-store/app/src/pages/manage-store/AddArtistForm.js b/media-store/app/src/pages/manage-store/AddArtistForm.js deleted file mode 100644 index ed31f9d6..00000000 --- a/media-store/app/src/pages/manage-store/AddArtistForm.js +++ /dev/null @@ -1,22 +0,0 @@ -import React from "react"; -import { Form, Input } from "antd"; - -const REQUIRED = [ - { - required: true, - message: "This filed is required!", - }, -]; - -const AddArtistForm = () => { - return ( - <> -

Add artist

- - - - - ); -}; - -export { AddArtistForm }; diff --git a/media-store/app/src/pages/manage-store/TrackForm.js b/media-store/app/src/pages/manage-store/TrackForm.js deleted file mode 100644 index 3724dc85..00000000 --- a/media-store/app/src/pages/manage-store/TrackForm.js +++ /dev/null @@ -1,93 +0,0 @@ -import React, { useEffect, useState } from "react"; -import { Form, Input, Select, InputNumber } from "antd"; -import { head } from "lodash"; -import { useSearch } from "@umijs/hooks"; -import { useAppState } from "../../hooks/useAppState"; -import { fetchAlbumsByName, fetchGenres } from "../../api/calls"; -import { useErrors } from "../../hooks/useErrors"; - -const ALBUMS_LIMIT = 10; -const REQUIRED = [ - { - required: true, - message: "This filed is required!", - }, -]; - -const getAlbums = function (value) { - return fetchAlbumsByName(value, ALBUMS_LIMIT) - .then((response) => response.data.value) - .catch(this.handleError); -}; - -const TrackForm = ({ initialAlbumTitle }) => { - const { handleError } = useErrors(); - const { - data: albums, - loading: isAlbumsLoading, - onChange: onChangeAlbumInput, - cancel: onAlbumCancel, - } = useSearch(getAlbums.bind({ handleError })); - const { setLoading } = useAppState(); - const [genres, setGenres] = useState([]); - - useEffect(() => { - setLoading(true); - Promise.all([fetchGenres(), onChangeAlbumInput(initialAlbumTitle)]) - .then((responses) => setGenres(head(responses).data.value)) - .catch(handleError) - .finally(() => setLoading(false)); - }, []); - - return ( -
- - - - - - - - - - - - - - value.replace(/\$\s?|(,*)/g, "")} - /> - -
- ); -}; - -export { TrackForm }; diff --git a/media-store/app/src/pages/tracks/DeleteAction.js b/media-store/app/src/pages/tracks/DeleteAction.js deleted file mode 100644 index 34e8cd33..00000000 --- a/media-store/app/src/pages/tracks/DeleteAction.js +++ /dev/null @@ -1,43 +0,0 @@ -import React, { useState } from "react"; -import { Modal, message } from "antd"; -import { DeleteOutlined } from "@ant-design/icons"; -import { deleteTrack } from "../../api/calls"; -import { useErrors } from "../../hooks/useErrors"; -import { MESSAGE_TIMEOUT } from "../../util/constants"; - -const DeleteAction = ({ ID, onDeleteTrack }) => { - const [modalVisible, setModalVisible] = useState(false); - const { handleError } = useErrors(); - - const onOk = () => { - setModalVisible(false); - deleteTrack(ID) - .then(() => { - onDeleteTrack(); - setModalVisible(false); - message.success("Track successfully deleted!", MESSAGE_TIMEOUT); - }) - .catch(handleError); - }; - - const onCancel = () => setModalVisible(false); - const onOpenModal = () => { - setModalVisible(true); - }; - - return ( - <> - Delete - -

Are You really want to delete this track?

-
- - ); -}; - -export { DeleteAction }; diff --git a/media-store/app/src/pages/tracks/EditAction.js b/media-store/app/src/pages/tracks/EditAction.js deleted file mode 100644 index a469c018..00000000 --- a/media-store/app/src/pages/tracks/EditAction.js +++ /dev/null @@ -1,119 +0,0 @@ -import React from "react"; -import { Button, Modal, Form, message } from "antd"; -import { EditOutlined, LoadingOutlined } from "@ant-design/icons"; -import { useErrors } from "../../hooks/useErrors"; -import { TrackForm } from "../manage-store/TrackForm"; -import { updateTrack, getTrack } from "../../api/calls"; -import { MESSAGE_TIMEOUT } from "../../util/constants"; - -const EditAction = ({ - ID, - name, - composer, - genre, - unitPrice, - album, - afterTrackUpdate, -}) => { - const [visible, setVisible] = React.useState(false); - const [confirmLoading, setConfirmLoading] = React.useState(false); - const [updateLoading, setUpdateLoading] = React.useState(false); - const [form] = Form.useForm(); - const { handleError } = useErrors(); - - const onShowModal = () => { - setVisible(true); - }; - - const onFinish = (value) => { - setConfirmLoading(true); - updateTrack({ - ID, - name: value.name, - composer: value.composer, - album: { ID: value.albumID }, - genre: { ID: value.genreID }, - unitPrice: value.unitPrice.toString(), - }) - .then(() => { - message.success("Track successfully updated!", MESSAGE_TIMEOUT); - setConfirmLoading(false); - setVisible(false); - afterCloseModal(); - }) - .catch(handleError); - }; - - const handleOk = () => { - form.submit(); - }; - - const handleCancel = () => { - setVisible(false); - }; - - const afterCloseModal = () => { - setUpdateLoading(true); - getTrack(ID) - .then((response) => { - afterTrackUpdate(response.data); - setUpdateLoading(false); - }) - .catch(handleError); - }; - - return ( - <> - {updateLoading ? ( - - ) : ( - - )} - - Cancel - , - , - ]} - > -
console.log("Not valid params provided")} - initialValues={{ - name: name, - composer: composer, - genreID: genre.ID, - albumID: album.ID, - unitPrice: unitPrice, - }} - > - - -
- - ); -}; - -export { EditAction }; diff --git a/media-store/app/src/pages/tracks/ManagedTrack.css b/media-store/app/src/pages/tracks/ManagedTrack.css deleted file mode 100644 index e2107b16..00000000 --- a/media-store/app/src/pages/tracks/ManagedTrack.css +++ /dev/null @@ -1,7 +0,0 @@ -span > span.anticon.anticon-delete:hover { - color: #ff4d4f; -} - -.card-element { - transition: opacity 0.5s ease-in-out; -} diff --git a/media-store/app/src/pages/tracks/ManagedTrack.js b/media-store/app/src/pages/tracks/ManagedTrack.js deleted file mode 100644 index 8beaa37c..00000000 --- a/media-store/app/src/pages/tracks/ManagedTrack.js +++ /dev/null @@ -1,42 +0,0 @@ -import React, { useState, useRef } from "react"; -import { Card } from "antd"; -import { EditAction } from "./EditAction"; -import { DeleteAction } from "./DeleteAction"; -import { TrackCardBody } from "./TrackCardBody"; -import "./ManagedTrack.css"; - -const ManagedTrack = ({ initialTrack, onDeleteTrack }) => { - const trackElement = useRef(); - const [track, setTrack] = useState(initialTrack); - - return ( -
- { - trackElement.current.style.opacity = 0; - setTimeout(() => onDeleteTrack(track.ID), 500); - }} - />, - setTrack(value)} - />, - ]} - title={track.name} - bordered={false} - > - - -
- ); -}; - -export { ManagedTrack }; diff --git a/media-store/app/src/pages/tracks/Track.js b/media-store/app/src/pages/tracks/Track.js deleted file mode 100644 index ff88e565..00000000 --- a/media-store/app/src/pages/tracks/Track.js +++ /dev/null @@ -1,56 +0,0 @@ -import React, { useState, useRef } from "react"; -import { Card, Button } from "antd"; -import { PlusOutlined, MinusOutlined } from "@ant-design/icons"; -import { useAppState } from "../../hooks/useAppState"; -import { TrackCardBody } from "./TrackCardBody"; - -const Track = ({ initialTrack, isAlreadyOrdered }) => { - const trackElement = useRef(); - const { setInvoicedItems, invoicedItems } = useAppState(); - const [isJustInvoiced, setIsJustInvoiced] = useState( - invoicedItems.find((curTrack) => curTrack.ID === initialTrack.ID) - ); - - const onChangedStatus = () => { - const newIsJustInvoiced = !isJustInvoiced; - if (newIsJustInvoiced) { - setInvoicedItems([ - ...invoicedItems, - { - ID: initialTrack.ID, - name: initialTrack.name, - artist: initialTrack.album.artist.name, - albumTitle: initialTrack.album.title, - unitPrice: initialTrack.unitPrice, - }, - ]); - } else { - setInvoicedItems( - invoicedItems.filter(({ ID: curID }) => curID !== initialTrack.ID) - ); - } - setIsJustInvoiced(newIsJustInvoiced); - }; - - return ( -
- - {!isAlreadyOrdered && ( - - )} - , - ]} - title={initialTrack.name} - bordered={false} - > - - -
- ); -}; - -export { Track }; diff --git a/media-store/app/src/pages/tracks/TrackCardBody.js b/media-store/app/src/pages/tracks/TrackCardBody.js deleted file mode 100644 index d3174e2f..00000000 --- a/media-store/app/src/pages/tracks/TrackCardBody.js +++ /dev/null @@ -1,33 +0,0 @@ -import React from "react"; - -const TrackCardBody = ({ track }) => { - return ( - <> -
- Artist:{" "} - {track.album.artist.name} -
-
- Album: {track.album.title} -
-
- Genre: {track.genre.name} -
-
- {track.composer && ( - - Compositor:{" "} - {track.composer} - - )} -
-
- - Price: {track.unitPrice} - -
- - ); -}; - -export { TrackCardBody }; diff --git a/media-store/app/src/serviceWorker.js b/media-store/app/src/serviceWorker.js deleted file mode 100644 index b04b771a..00000000 --- a/media-store/app/src/serviceWorker.js +++ /dev/null @@ -1,141 +0,0 @@ -// This optional code is used to register a service worker. -// register() is not called by default. - -// This lets the app load faster on subsequent visits in production, and gives -// it offline capabilities. However, it also means that developers (and users) -// will only see deployed updates on subsequent visits to a page, after all the -// existing tabs open on the page have been closed, since previously cached -// resources are updated in the background. - -// To learn more about the benefits of this model and instructions on how to -// opt-in, read https://bit.ly/CRA-PWA - -const isLocalhost = Boolean( - window.location.hostname === 'localhost' || - // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || - // 127.0.0.0/8 are considered localhost for IPv4. - window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ - ) -); - -export function register(config) { - if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { - // The URL constructor is available in all browsers that support SW. - const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); - if (publicUrl.origin !== window.location.origin) { - // Our service worker won't work if PUBLIC_URL is on a different origin - // from what our page is served on. This might happen if a CDN is used to - // serve assets; see https://github.com/facebook/create-react-app/issues/2374 - return; - } - - window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; - - if (isLocalhost) { - // This is running on localhost. Let's check if a service worker still exists or not. - checkValidServiceWorker(swUrl, config); - - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log( - 'This web app is being served cache-first by a service ' + - 'worker. To learn more, visit https://bit.ly/CRA-PWA' - ); - }); - } else { - // Is not localhost. Just register service worker - registerValidSW(swUrl, config); - } - }); - } -} - -function registerValidSW(swUrl, config) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated precached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all ' + - 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' - ); - - // Execute callback - if (config && config.onUpdate) { - config.onUpdate(registration); - } - } else { - // At this point, everything has been precached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - - // Execute callback - if (config && config.onSuccess) { - config.onSuccess(registration); - } - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); -} - -function checkValidServiceWorker(swUrl, config) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl, { - headers: { 'Service-Worker': 'script' }, - }) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); -} - -export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready - .then(registration => { - registration.unregister(); - }) - .catch(error => { - console.error(error.message); - }); - } -} diff --git a/media-store/app/src/setupTests.js b/media-store/app/src/setupTests.js deleted file mode 100644 index 74b1a275..00000000 --- a/media-store/app/src/setupTests.js +++ /dev/null @@ -1,5 +0,0 @@ -// jest-dom adds custom jest matchers for asserting on DOM nodes. -// allows you to do things like: -// expect(element).toHaveTextContent(/react/i) -// learn more: https://github.com/testing-library/jest-dom -import '@testing-library/jest-dom/extend-expect'; diff --git a/media-store/app/src/util/EventEmitter.js b/media-store/app/src/util/EventEmitter.js deleted file mode 100644 index 370e9777..00000000 --- a/media-store/app/src/util/EventEmitter.js +++ /dev/null @@ -1,5 +0,0 @@ -import EventEmitter from "events"; - -const emitter = new EventEmitter(); - -export { emitter }; diff --git a/media-store/app/src/util/constants.js b/media-store/app/src/util/constants.js deleted file mode 100644 index c844c903..00000000 --- a/media-store/app/src/util/constants.js +++ /dev/null @@ -1,14 +0,0 @@ -export const AVAILABLE_LOCALES = ["en", "fr", "de"]; - -export const MESSAGE_TIMEOUT = 2; - -// in dev mode using provided api -// in prod mode using proxy -export const API = - process.env.NODE_ENV === "development" ? "http://localhost:4004/" : "api/"; - -export const requireEmployee = (user) => - !!user && user.roles.includes("employee"); - -export const requireCustomer = (user) => - !!user && user.roles.includes("customer"); diff --git a/media-store/app/src/util/localStorageService.js b/media-store/app/src/util/localStorageService.js deleted file mode 100644 index 2f0fca17..00000000 --- a/media-store/app/src/util/localStorageService.js +++ /dev/null @@ -1,35 +0,0 @@ -import { isValidUser } from "./validateUser"; -import { AVAILABLE_LOCALES } from "./constants"; - -const setUserToLS = (user) => { - if (user) { - localStorage.setItem("user", JSON.stringify(user)); - } else { - localStorage.removeItem("user"); - } -}; - -const getUserFromLS = () => { - let userFromLS; - try { - userFromLS = JSON.parse(localStorage.getItem("user")); - if (isValidUser(userFromLS)) { - return userFromLS; - } - } catch (e) {} -}; - -const getLocaleFromLS = () => { - const localeFromLS = localStorage.getItem("locale"); - return localeFromLS && - localeFromLS !== "undefined" && - AVAILABLE_LOCALES.includes(localeFromLS) - ? localeFromLS - : "en"; -}; - -const setLocaleToLS = (locale) => { - localStorage.setItem("locale", locale); -}; - -export { setLocaleToLS, getLocaleFromLS, getUserFromLS, setUserToLS }; diff --git a/media-store/app/src/util/validateUser.js b/media-store/app/src/util/validateUser.js deleted file mode 100644 index 160740b8..00000000 --- a/media-store/app/src/util/validateUser.js +++ /dev/null @@ -1,20 +0,0 @@ -import { isArray, isEmpty, isString, isNumber } from "lodash"; - -const CUSTOMER_ROLE = "customer"; -const EMPLOYEE_ROLE = "employee"; - -const isValidUser = (user) => { - return ( - !isEmpty(user) && - isNumber(user.ID) && - isArray(user.roles) && - !!user.roles.some( - (role) => role === CUSTOMER_ROLE || role === EMPLOYEE_ROLE - ) && - isString(user.email) && - isString(user.accessToken) && - isString(user.refreshToken) - ); -}; - -export { isValidUser }; diff --git a/media-store/app/xs-app.json b/media-store/app/xs-app.json deleted file mode 100644 index 930c40ee..00000000 --- a/media-store/app/xs-app.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "welcomeFile": "/index.html", - "routes": [ - { - "source": "^(.*)", - "target": "$1", - "service": "html5-apps-repo-rt" - } - ] -} \ No newline at end of file diff --git a/media-store/approuter/package.json b/media-store/approuter/package.json deleted file mode 100644 index d9a4cd89..00000000 --- a/media-store/approuter/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "media-store-approuter", - "description": "Approuter", - "version": "1.0.0", - "dependencies": { - "@sap/approuter": "^6.8.2" - }, - "scripts": { - "start": "node node_modules/@sap/approuter/approuter.js" - } -} diff --git a/media-store/approuter/xs-app.json b/media-store/approuter/xs-app.json deleted file mode 100644 index 4270e0cb..00000000 --- a/media-store/approuter/xs-app.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "welcomeFile": "/index.html", - "authenticationMethod": "none", - "routes": [ - { - "source": "/api/(.*)", - "target": "$1", - "destination": "srv-binding", - "authenticationType": "none" - }, - { - "source": "^(.*)", - "target": "mediastore/$1", - "service": "html5-apps-repo-rt" - } - ] -} diff --git a/media-store/html5Deployer/package.json b/media-store/html5Deployer/package.json deleted file mode 100644 index 09f597b2..00000000 --- a/media-store/html5Deployer/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "media-store-html5deployer", - "engines": { - "node": ">=6.0.0" - }, - "dependencies": { - "@sap/html5-app-deployer": "^2.0.0" - }, - "scripts": { - "start": "node node_modules/@sap/html5-app-deployer/index.js" - } -}