clean up things

This commit is contained in:
Dzmitry_Tamashevich@epam.com
2020-11-24 22:40:15 +03:00
committed by Daniel Hutzel
parent 6454019713
commit 58af1879f7
24 changed files with 256 additions and 278 deletions

View File

@@ -16,6 +16,6 @@ const locale = getLocaleFromLS();
changeUserDefaults(user); changeUserDefaults(user);
changeLocaleDefaults(locale); changeLocaleDefaults(locale);
// axiosInstance.interceptors.response.use(null, responseErrorInterceptor); axiosInstance.interceptors.response.use(null, responseErrorInterceptor);
export { axiosInstance, changeLocaleDefaults, changeUserDefaults }; export { axiosInstance, changeLocaleDefaults, changeUserDefaults };

View File

@@ -8,8 +8,9 @@ let subscribers = [];
function responseErrorInterceptor(error) { function responseErrorInterceptor(error) {
const originalRequest = error.config; const originalRequest = error.config;
const user = getUserFromLS();
if (error.response && error.response.status === 401) { if (error.response && error.response.status === 401 && !!user) {
if (originalRequest.url === "users/login") { if (originalRequest.url === "users/login") {
return Promise.reject(error); return Promise.reject(error);
} }
@@ -26,21 +27,18 @@ function responseErrorInterceptor(error) {
if (!isRefreshing) { if (!isRefreshing) {
isRefreshing = true; isRefreshing = true;
refreshTokens(getUserFromLS().refreshToken) refreshTokens(user.refreshToken)
.then((response) => { .then((response) => {
emitter.emit("UPDATE_USER", response.data); emitter.emit("UPDATE_USER", response.data);
subscribers.forEach((request) => subscribers.forEach((request) =>
request.resolve(response.data.accessToken) request.resolve(response.data.accessToken)
); );
})
.catch(() => {
subscribers.forEach((request) => request.reject(error));
})
.finally(() => {
subscribers = []; subscribers = [];
isRefreshing = false; isRefreshing = false;
})
.catch(() => {
emitter.emit("UPDATE_USER", undefined);
}); });
return;
} }
// holding requests which should be sended after users/refreshTokens complete // holding requests which should be sended after users/refreshTokens complete

View File

@@ -1,30 +0,0 @@
import React from "react";
import { Breadcrumb, Spin } from "antd";
import { useLocation } from "react-router-dom";
import { useAppState } from "../hooks/useAppState";
const names = {
"/": "Browse / Tracks",
"/person": "Profile",
"/login": "Login form",
"/invoice": "Requested items",
"/manage": "Manage store",
};
const CurrentPageHeader = () => {
const location = useLocation();
const { loading } = useAppState();
return (
<Breadcrumb
style={{ height: 50, paddingBottom: 20, fontWeight: 600, fontSize: 20 }}
>
<Breadcrumb.Item>
{names[location.pathname]}
<span style={{ padding: 10 }}>{loading && <Spin />}</span>
</Breadcrumb.Item>
</Breadcrumb>
);
};
export { CurrentPageHeader };

View File

@@ -1,10 +1,11 @@
import React from "react"; import React from "react";
import { Menu, Badge } from "antd"; import { Menu, Badge, Spin } from "antd";
import { isEmpty } from "lodash"; import { isEmpty } from "lodash";
import { import {
CreditCardOutlined, CreditCardOutlined,
LogoutOutlined, LogoutOutlined,
LoginOutlined, LoginOutlined,
LoadingOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { useHistory, useLocation } from "react-router-dom"; import { useHistory, useLocation } from "react-router-dom";
import { useAppState } from "../hooks/useAppState"; import { useAppState } from "../hooks/useAppState";
@@ -12,17 +13,18 @@ import { setLocaleToLS } from "../util/localStorageService";
import { changeLocaleDefaults } from "../api/axiosInstance"; import { changeLocaleDefaults } from "../api/axiosInstance";
import { emitter } from "../util/EventEmitter"; import { emitter } from "../util/EventEmitter";
import "./Header.css"; import "./Header.css";
import { requireEmployee, requireCustomer } from "../util/constants";
const { SubMenu } = Menu; const { SubMenu } = Menu;
const keys = ["/", "/person", "/login", "/manage", "/invoice"]; const keys = ["/", "/person", "/login", "/manage", "/invoice", "/invoices"];
const AVAILABLE_LOCALES = ["en", "fr", "de"]; const AVAILABLE_LOCALES = ["en", "fr", "de"];
const RELOAD_LOCATION_NUMBER = 0; const RELOAD_LOCATION_NUMBER = 0;
const Header = () => { const Header = () => {
const history = useHistory(); const history = useHistory();
const location = useLocation(); const location = useLocation();
const { user, invoicedItems, locale, setLocale } = useAppState(); const { user, invoicedItems, locale, setLocale, loading } = useAppState();
const currentKey = [keys.find((key) => key === location.pathname)]; const currentKey = [keys.find((key) => key === location.pathname)];
const haveInvoicedItems = !isEmpty(invoicedItems); const haveInvoicedItems = !isEmpty(invoicedItems);
const invoicedItemsLength = invoicedItems.length; const invoicedItemsLength = invoicedItems.length;
@@ -46,7 +48,6 @@ const Header = () => {
const onUserLogout = () => { const onUserLogout = () => {
emitter.emit("UPDATE_USER", undefined); emitter.emit("UPDATE_USER", undefined);
history.push("/"); history.push("/");
}; };
@@ -54,7 +55,8 @@ const Header = () => {
<div <div
style={{ style={{
display: "flex", display: "flex",
justifyContent: "center", justifyContent: "baseline",
alignItems: "center",
paddingLeft: "15vh", paddingLeft: "15vh",
paddingRight: "15vh", paddingRight: "15vh",
background: "white", background: "white",
@@ -75,11 +77,23 @@ const Header = () => {
Profile Profile
</Menu.Item> </Menu.Item>
)} )}
{!!user && user.roles.includes("employee") && ( {requireCustomer(user) && (
<Menu.Item key="/invoices" onClick={() => history.push("/invoices")}>
Invoices
</Menu.Item>
)}
{requireEmployee(user) && (
<Menu.Item key="/manage" onClick={() => history.push("/manage")}> <Menu.Item key="/manage" onClick={() => history.push("/manage")}>
Manage Manage
</Menu.Item> </Menu.Item>
)} )}
<span>
{loading && (
<Spin
indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
/>
)}
</span>
</Menu> </Menu>
<Menu <Menu
@@ -88,7 +102,7 @@ const Header = () => {
mode="horizontal" mode="horizontal"
selectedKeys={currentKey} selectedKeys={currentKey}
> >
{haveInvoicedItems && !!user && user.roles.includes("customer") && ( {haveInvoicedItems && (
<Menu.Item <Menu.Item
style={{ style={{
width: 40, width: 40,

View File

@@ -1,35 +1,25 @@
import React from "react"; import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { isEmpty } from "lodash"; import { isEmpty } from "lodash";
import { TracksContainer } from "../pages/tracks/TracksPage"; import { TracksContainer } from "../pages/TracksPage";
import { CurrentPageHeader } from "./CurrentPageHeader";
import { Header } from "../components/Header"; import { Header } from "../components/Header";
import { PersonPage } from "../pages/person/PersonPage"; import { PersonPage } from "../pages/PersonPage";
import { ErrorPage } from "../pages/ErrorPage"; import { ErrorPage } from "../pages/ErrorPage";
import { Login } from "../pages/login/Login"; import { Login } from "../pages/Login";
import { import { withRestrictions } from "../hocs/withRestrictions";
withRestrictions, import { InvoicePage } from "../pages/InvoicePage";
withRestrictedSection, import { ManageStore } from "../pages/ManageStore";
} from "../hocs/withRestrictions"; import { MyInvoicesPage } from "../pages/MyInvoicesPage";
import { InvoicePage } from "../pages/invoice/InvoicePage"; import { requireEmployee } from "../util/constants";
import { ManageStore } from "../pages/manage-store/ManageStore";
import { MyInvoices } from "../pages/person/MyInvoices";
const needCustomer = ({ user }) => !!user && user.roles.includes("customer");
const RestrictedLogin = withRestrictions(Login, ({ user }) => !user); const RestrictedLogin = withRestrictions(Login, ({ user }) => !user);
const RestrictedInvoicePage = withRestrictions( const RestrictedInvoicePage = withRestrictions(
InvoicePage, InvoicePage,
({ user, invoicedItems }) => needCustomer({ user }) && !isEmpty(invoicedItems) ({ user, invoicedItems }) => !requireEmployee(user) && !isEmpty(invoicedItems)
);
const RestrictedMyInvoicesSection = withRestrictedSection(
MyInvoices,
needCustomer
); );
const RestrictedPersonPage = withRestrictions(PersonPage, ({ user }) => !!user); const RestrictedPersonPage = withRestrictions(PersonPage, ({ user }) => !!user);
const RestrictedManageStore = withRestrictions( const RestrictedManageStore = withRestrictions(ManageStore, ({ user }) =>
ManageStore, requireEmployee(user)
({ user }) => !!user && user.roles.includes("employee")
); );
const MyRouter = () => { const MyRouter = () => {
@@ -37,15 +27,12 @@ const MyRouter = () => {
<Router> <Router>
<Header /> <Header />
<div style={{ padding: "2em 20vh" }}> <div style={{ padding: "2em 20vh" }}>
<CurrentPageHeader />
<Switch> <Switch>
<Route exact path={["/", "/tracks"]}> <Route exact path={["/", "/tracks"]}>
<TracksContainer /> <TracksContainer />
</Route> </Route>
<Route exact path="/person"> <Route exact path="/person">
<RestrictedPersonPage <RestrictedPersonPage />
myInvoicesSection={<RestrictedMyInvoicesSection />}
/>
</Route> </Route>
<Route exact path="/login"> <Route exact path="/login">
<RestrictedLogin /> <RestrictedLogin />
@@ -53,6 +40,9 @@ const MyRouter = () => {
<Route exact path="/invoice"> <Route exact path="/invoice">
<RestrictedInvoicePage /> <RestrictedInvoicePage />
</Route> </Route>
<Route exact path="/invoices">
<MyInvoicesPage />
</Route>
<Route exact path="/manage"> <Route exact path="/manage">
<RestrictedManageStore /> <RestrictedManageStore />
</Route> </Route>

View File

@@ -13,15 +13,4 @@ const withRestrictions = (Component, isUserMeetRestrictions) => {
}; };
}; };
const withRestrictedSection = (Component, isUserMeetRestrictions) => { export { withRestrictions };
return (props) => {
const { user, invoicedItems } = useAppState();
return (
isUserMeetRestrictions({ user, invoicedItems }) && (
<Component {...props} />
)
);
};
};
export { withRestrictions, withRestrictedSection };

View File

@@ -1,8 +1,5 @@
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { useAppState } from "./useAppState"; import { useAppState } from "./useAppState";
import { emitter } from "../util/EventEmitter";
import { message } from "antd";
import { MESSAGE_TIMEOUT } from "../util/constants";
const useErrors = () => { const useErrors = () => {
const history = useHistory(); const history = useHistory();
@@ -12,11 +9,6 @@ const useErrors = () => {
console.error("Error", error); console.error("Error", error);
if (error.response) { if (error.response) {
if (error.response.status === 401) {
emitter.emit("UPDATE_USER", undefined);
message.error("You are unauthorized, try login again", MESSAGE_TIMEOUT);
}
const { status, statusText, data } = error.response; const { status, statusText, data } = error.response;
setError({ setError({
status, status,

View File

@@ -5,7 +5,7 @@ import { Result, Button } from "antd";
import { useAppState } from "../hooks/useAppState"; import { useAppState } from "../hooks/useAppState";
const ErrorPage = () => { const ErrorPage = () => {
const { user, error, setError } = useAppState(); const { error, setError } = useAppState();
const history = useHistory(); const history = useHistory();
const onGoHome = () => { const onGoHome = () => {
@@ -18,32 +18,33 @@ const ErrorPage = () => {
history.push("/login"); history.push("/login");
}; };
const goHomeButton = (
<Button onClick={onGoHome} key={1} type="primary">
Back Home
</Button>
);
const goLoginButton = (
<Button onClick={goLoginPage} key={2} type="primary">
Login
</Button>
);
const errorResultProps = isEmpty(error) const errorResultProps = isEmpty(error)
? { ? {
status: 404, status: 404,
title: "Not found", title: "Not found",
subTitle: "Sorry, the page you visited does not exist.", subTitle: "Sorry, the page you visited does not exist.",
extra: goHomeButton,
} }
: { : {
status: [404, 403, 500].includes(error.status) status: [404, 403, 500].includes(error.status) ? error.status : "error",
? error.status title: error.statusText,
: undefined,
title: `${error.status} ${error.statusText}`,
subTitle: error.message, subTitle: error.message,
extra:
error.status === 401 ? [goHomeButton, goLoginButton] : goHomeButton,
}; };
return ( return <Result {...errorResultProps} />;
<Result
{...errorResultProps}
extra={
<>
<Button onClick={onGoHome} type="primary">
Back Home
</Button>
</>
}
/>
);
}; };
export { ErrorPage }; export { ErrorPage };

View File

@@ -1,12 +1,10 @@
import React from "react"; import React from "react";
import { Table, Button, message } from "antd"; import { Table, Button, message } from "antd";
import { useAppState } from "../../hooks/useAppState"; import { useAppState } from "../hooks/useAppState";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { invoice } from "../../api/calls"; import { invoice } from "../api/calls";
import { useErrors } from "../../hooks/useErrors"; import { useErrors } from "../hooks/useErrors";
import { MESSAGE_TIMEOUT } from "../../util/constants"; import { MESSAGE_TIMEOUT } from "../util/constants";
import "./InvoicePage.css";
const columns = [ const columns = [
{ {
@@ -30,7 +28,7 @@ const columns = [
const InvoicePage = () => { const InvoicePage = () => {
const history = useHistory(); const history = useHistory();
const { handleError } = useErrors(); const { handleError } = useErrors();
const { invoicedItems, setInvoicedItems, setLoading } = useAppState(); const { user, invoicedItems, setInvoicedItems, setLoading } = useAppState();
const data = invoicedItems.map(({ ID: key, ...otherProps }) => ({ const data = invoicedItems.map(({ ID: key, ...otherProps }) => ({
key, key,
@@ -48,7 +46,7 @@ const InvoicePage = () => {
.then(() => { .then(() => {
setInvoicedItems([]); setInvoicedItems([]);
message.success("Invoice successfully completed", MESSAGE_TIMEOUT); message.success("Invoice successfully completed", MESSAGE_TIMEOUT);
history.push("/person"); history.push("/invoices");
}) })
.catch(handleError) .catch(handleError)
.finally(() => setLoading(false)); .finally(() => setLoading(false));
@@ -57,6 +55,9 @@ const InvoicePage = () => {
setInvoicedItems([]); setInvoicedItems([]);
history.push("/"); history.push("/");
}; };
const goLogin = () => {
history.push("/login");
};
return ( return (
<div style={{ backgroundColor: "white", padding: 10 }}> <div style={{ backgroundColor: "white", padding: 10 }}>
@@ -74,17 +75,28 @@ const InvoicePage = () => {
padding: 5, padding: 5,
}} }}
> >
<Button type="primary" size="large" onClick={onBuy}> {user ? (
Buy <>
</Button> <Button type="primary" size="large" onClick={onBuy}>
<Button Buy
size="large" </Button>
style={{ marginLeft: 5 }} <Button
onClick={onCancel} size="large"
danger style={{ marginLeft: 5 }}
> onClick={onCancel}
Cancel danger
</Button> >
Cancel
</Button>
</>
) : (
<section>
<Button type="primary" size="large" onClick={goLogin}>
Login
</Button>
<span> to buy selected</span>
</section>
)}
</div> </div>
)} )}
/> />

View File

@@ -1,11 +1,11 @@
import React from "react"; import React from "react";
import { Form, Input, Button, Checkbox, message } from "antd"; import { Form, Input, Button, Checkbox, message } from "antd";
import { login } from "../../api/calls"; import { login } from "../api/calls";
import { useHistory } from "react-router-dom"; import { useHistory } from "react-router-dom";
import { useAppState } from "../../hooks/useAppState"; import { useAppState } from "../hooks/useAppState";
import { useErrors } from "../../hooks/useErrors"; import { useErrors } from "../hooks/useErrors";
import { MESSAGE_TIMEOUT } from "../../util/constants"; import { MESSAGE_TIMEOUT } from "../util/constants";
import { emitter } from "../../util/EventEmitter"; import { emitter } from "../util/EventEmitter";
const layout = { const layout = {
labelCol: { labelCol: {

View File

@@ -1,13 +1,12 @@
import React, { useState, useMemo, useEffect } from "react"; import React, { useState, useMemo, useEffect } from "react";
import { Form, Radio, Button, message } from "antd"; import { Form, Radio, Button, message } from "antd";
import { TrackForm } from "./TrackForm"; import { TrackForm } from "./manage-store/TrackForm";
import { AddArtistForm } from "./AddArtistForm"; import { AddArtistForm } from "./manage-store/AddArtistForm";
import { AddAlbumForm } from "./AddAlbumForm"; import { AddAlbumForm } from "./manage-store/AddAlbumForm";
import { useErrors } from "../../hooks/useErrors"; import { useErrors } from "../hooks/useErrors";
import { useAppState } from "../../hooks/useAppState"; import { useAppState } from "../hooks/useAppState";
import { addTrack, addArtist, addAlbum } from "../../api/calls"; import { addTrack, addArtist, addAlbum } from "../api/calls";
import { MESSAGE_TIMEOUT } from "../../util/constants"; import { MESSAGE_TIMEOUT } from "../util/constants";
import "./ManageStore.css";
const FORM_TYPES = { const FORM_TYPES = {
track: "track", track: "track",

View File

@@ -1,10 +1,10 @@
import React, { useState, useEffect, useMemo, useCallback } from "react"; import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Button, message, Divider, Tag, Collapse, Table, Spin } from "antd"; import { Button, message, Divider, Tag, Collapse, Table, Spin } from "antd";
import moment from "moment"; import moment from "moment";
import { useErrors } from "../../hooks/useErrors"; import { useErrors } from "../hooks/useErrors";
import { useAppState } from "../../hooks/useAppState"; import { useAppState } from "../hooks/useAppState";
import { cancelInvoice, fetchInvoices } from "../../api/calls"; import { cancelInvoice, fetchInvoices } from "../api/calls";
import { MESSAGE_TIMEOUT } from "../../util/constants"; import { MESSAGE_TIMEOUT } from "../util/constants";
const { Panel } = Collapse; const { Panel } = Collapse;
const INVOICE_STATUS = { const INVOICE_STATUS = {
@@ -106,7 +106,7 @@ const ExtraHeader = ({ ID, invoiceDate, status: initialStatus }) => {
); );
}; };
const MyInvoices = () => { const MyInvoicesPage = () => {
const { handleError } = useErrors(); const { handleError } = useErrors();
const { setLoading } = useAppState(); const { setLoading } = useAppState();
const [invoices, setInvoices] = useState([]); const [invoices, setInvoices] = useState([]);
@@ -176,13 +176,11 @@ const MyInvoices = () => {
return ( return (
<div> <div>
{invoiceElements && ( {invoiceElements && (
<> <Collapse expandIconPosition="left">{invoiceElements}</Collapse>
<Divider orientation="left">My invoices</Divider>
<Collapse expandIconPosition="left">{invoiceElements}</Collapse>
</>
)} )}
{"Pagination steel needed"}
</div> </div>
); );
}; };
export { MyInvoices }; export { MyInvoicesPage };

View File

@@ -1,12 +1,12 @@
import React, { useState, useMemo } from "react"; import React, { useState, useMemo } from "react";
import { Card, Button, message } from "antd"; import { Card, Button, message } from "antd";
import { omit } from "lodash"; import { omit } from "lodash";
import { fetchPerson, confirmPerson } from "../../api/calls"; import { fetchPerson, confirmPerson } from "../api/calls";
import { useErrors } from "../../hooks/useErrors"; import { useErrors } from "../hooks/useErrors";
import { useAppState } from "../../hooks/useAppState"; import { useAppState } from "../hooks/useAppState";
import { Editable } from "../../components/Editable"; import { Editable } from "../components/Editable";
import { MESSAGE_TIMEOUT } from "../../util/constants"; import { MESSAGE_TIMEOUT } from "../util/constants";
import { useAbortableEffect } from "../../hooks/useAbortableEffect"; import { useAbortableEffect } from "../hooks/useAbortableEffect";
const PERSON_PROP = { const PERSON_PROP = {
address: "Address ", address: "Address ",
@@ -22,7 +22,7 @@ const PERSON_PROP = {
company: "Company: ", company: "Company: ",
}; };
const PersonPage = ({ myInvoicesSection }) => { const PersonPage = () => {
const { setLoading } = useAppState(); const { setLoading } = useAppState();
const { handleError } = useErrors(); const { handleError } = useErrors();
const [initialPerson, setInitialPerson] = useState({}); const [initialPerson, setInitialPerson] = useState({});
@@ -46,7 +46,6 @@ const PersonPage = ({ myInvoicesSection }) => {
fetchPerson() fetchPerson()
.then(({ data: personData }) => { .then(({ data: personData }) => {
personData = omit(personData, "@odata.context", "ID"); personData = omit(personData, "@odata.context", "ID");
console.log("personData", personData);
if (!status.aborted) { if (!status.aborted) {
setInitialPerson(personData); setInitialPerson(personData);
setPerson(personData); setPerson(personData);
@@ -117,7 +116,6 @@ const PersonPage = ({ myInvoicesSection }) => {
</Button> </Button>
)} )}
</Card> </Card>
{myInvoicesSection}
</> </>
); );
}; };

View File

@@ -1,12 +1,14 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { debounce } from "lodash"; import { debounce } from "lodash";
import { Input, Col, Row, Select, Pagination } from "antd"; import { Input, Col, Row, Select, Pagination } from "antd";
import { Track } from "./Track"; 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"; import "./TracksPage.css";
import { useAppState } from "../../hooks/useAppState";
import { useErrors } from "../../hooks/useErrors";
import { fetchTacks, countTracks, fetchGenres } from "../../api/calls";
import { useAbortableEffect } from "../../hooks/useAbortableEffect";
let counter = 0; let counter = 0;
@@ -27,7 +29,7 @@ const renderGenres = (genres) =>
)); ));
const TracksContainer = () => { const TracksContainer = () => {
const { setLoading, invoicedItems } = useAppState(); const { setLoading, user } = useAppState();
const { handleError } = useErrors(); const { handleError } = useErrors();
const [state, setState] = useState({ const [state, setState] = useState({
tracks: [], tracks: [],
@@ -149,29 +151,25 @@ const TracksContainer = () => {
tracks: state.tracks.filter(({ ID: curID }) => curID !== ID), tracks: state.tracks.filter(({ ID: curID }) => curID !== ID),
}); });
}; };
const renderTracks = (tracks, invoicedItems) => const renderTracks = (tracks) => {
tracks.map( const isEmployee = requireEmployee(user);
({ ID, name, composer, genre, unitPrice, alreadyOrdered, album }) => ( const TrackComponent = isEmployee ? ManagedTrack : Track;
<Col key={ID} className="gutter-row" span={8}> return tracks.map((track) => {
<Track const isAlreadyOrdered = !isEmployee && track.alreadyOrdered;
initialTrack={{ const onDeleteTrack = isEmployee && ((ID) => deleteTrack(ID));
ID, return (
name, <Col key={track.ID} className="gutter-row" span={8}>
genre, <TrackComponent
album, initialTrack={track}
artist: album.artist.name, onDeleteTrack={onDeleteTrack}
composer, isAlreadyOrdered={isAlreadyOrdered}
unitPrice,
}}
isButtonVisible={!alreadyOrdered}
isInvoiced={invoicedItems.find(({ ID: curID }) => curID === ID)}
onDeleteTrack={(ID) => deleteTrack(ID)}
/> />
</Col> </Col>
) );
); });
};
const trackElements = renderTracks(state.tracks, invoicedItems); const trackElements = renderTracks(state.tracks);
const genreElements = renderGenres(state.genres); const genreElements = renderGenres(state.genres);
return ( return (

View File

@@ -1,4 +0,0 @@
.ant-table-cell,
.ant-table-footer {
background: white !important;
}

View File

@@ -0,0 +1,42 @@
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 (
<div className="card-element" ref={trackElement}>
<Card
actions={[
<DeleteAction
ID={track.ID}
onDeleteTrack={() => {
trackElement.current.style.opacity = 0;
setTimeout(() => onDeleteTrack(track.ID), 500);
}}
/>,
<EditAction
ID={track.ID}
name={track.name}
composer={track.composer}
album={track.album}
genre={track.genre}
unitPrice={track.unitPrice}
afterTrackUpdate={(value) => setTrack(value)}
/>,
]}
title={track.name}
bordered={false}
>
<TrackCardBody track={track} />
</Card>
</div>
);
};
export { ManagedTrack };

View File

@@ -2,114 +2,52 @@ import React, { useState, useRef } from "react";
import { Card, Button } from "antd"; import { Card, Button } from "antd";
import { PlusOutlined, MinusOutlined } from "@ant-design/icons"; import { PlusOutlined, MinusOutlined } from "@ant-design/icons";
import { useAppState } from "../../hooks/useAppState"; import { useAppState } from "../../hooks/useAppState";
import { withRestrictedSection } from "../../hocs/withRestrictions"; import { TrackCardBody } from "./TrackCardBody";
import { EditAction } from "./EditAction";
import { DeleteAction } from "./DeleteAction";
import "./Track.css";
const RestrictedButton = withRestrictedSection(Button, ({ user }) => { const Track = ({ initialTrack, isAlreadyOrdered }) => {
return !!user && user.roles.includes("customer");
});
const RestrictedEditAction = withRestrictedSection(
EditAction,
({ user }) => !!user && user.roles.includes("employee")
);
const RestrictedDeleteAction = withRestrictedSection(
DeleteAction,
({ user }) => !!user && user.roles.includes("employee")
);
const Track = ({
initialTrack,
isButtonVisible,
isInvoiced: isInvoicedProp,
onDeleteTrack,
}) => {
const trackElement = useRef(); const trackElement = useRef();
const { setInvoicedItems, invoicedItems } = useAppState(); const { setInvoicedItems, invoicedItems } = useAppState();
const [isInvoiced, setIsInvoiced] = useState(isInvoicedProp); const [isJustInvoiced, setIsJustInvoiced] = useState(
const [track, setTrack] = useState(initialTrack); invoicedItems.find((curTrack) => curTrack.ID === initialTrack.ID)
);
const onChangedStatus = () => { const onChangedStatus = () => {
const newInvoiced = !isInvoiced; const newIsJustInvoiced = !isJustInvoiced;
if (newInvoiced) { if (newIsJustInvoiced) {
setInvoicedItems([ setInvoicedItems([
...invoicedItems, ...invoicedItems,
{ {
ID: track.ID, ID: initialTrack.ID,
name: track.name, name: initialTrack.name,
artist: track.album.artist.name, artist: initialTrack.album.artist.name,
albumTitle: track.album.title, albumTitle: initialTrack.album.title,
unitPrice: track.unitPrice, unitPrice: initialTrack.unitPrice,
}, },
]); ]);
} else { } else {
setInvoicedItems( setInvoicedItems(
invoicedItems.filter(({ ID: curID }) => curID !== track.ID) invoicedItems.filter(({ ID: curID }) => curID !== initialTrack.ID)
); );
} }
setIsInvoiced(newInvoiced); setIsJustInvoiced(newIsJustInvoiced);
}; };
return ( return (
<div className="card-element" ref={trackElement}> <div className="card-element" ref={trackElement}>
<Card <Card
actions={[ actions={[
<RestrictedDeleteAction <>
ID={track.ID} {!isAlreadyOrdered && (
onDeleteTrack={() => { <Button onClick={onChangedStatus} danger={isJustInvoiced}>
trackElement.current.style.opacity = 0; {isJustInvoiced ? <MinusOutlined /> : <PlusOutlined />}
setTimeout(() => onDeleteTrack(track.ID), 500); </Button>
}} )}
/>, </>,
<RestrictedEditAction
ID={track.ID}
name={track.name}
composer={track.composer}
album={track.album}
genre={track.genre}
unitPrice={track.unitPrice}
afterTrackUpdate={(value) => setTrack(value)}
/>,
]} ]}
title={track.name} title={initialTrack.name}
bordered={false} bordered={false}
> >
<div> <TrackCardBody track={initialTrack} />
Artist:{" "}
<span style={{ fontWeight: 600 }}>{track.album.artist.name}</span>
</div>
<div>
Album: <span style={{ fontWeight: 600 }}>{track.album.title}</span>
</div>
<div>
Genre: <span style={{ fontWeight: 600 }}>{track.genre.name}</span>
</div>
<div>
{track.composer && (
<span>
Compositor:{" "}
<span style={{ fontWeight: 600 }}>{track.composer}</span>
</span>
)}
</div>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<span>
Price: <span style={{ fontWeight: 600 }}>{track.unitPrice}</span>
</span>
{isButtonVisible && (
<RestrictedButton
type="primary"
size="small"
shape="circle"
onClick={onChangedStatus}
danger={isInvoiced}
>
{isInvoiced ? <MinusOutlined /> : <PlusOutlined />}
</RestrictedButton>
)}
</div>
</Card> </Card>
</div> </div>
); );

View File

@@ -0,0 +1,33 @@
import React from "react";
const TrackCardBody = ({ track }) => {
return (
<>
<div>
Artist:{" "}
<span style={{ fontWeight: 600 }}>{track.album.artist.name}</span>
</div>
<div>
Album: <span style={{ fontWeight: 600 }}>{track.album.title}</span>
</div>
<div>
Genre: <span style={{ fontWeight: 600 }}>{track.genre.name}</span>
</div>
<div>
{track.composer && (
<span>
Compositor:{" "}
<span style={{ fontWeight: 600 }}>{track.composer}</span>
</span>
)}
</div>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<span>
Price: <span style={{ fontWeight: 600 }}>{track.unitPrice}</span>
</span>
</div>
</>
);
};
export { TrackCardBody };

View File

@@ -6,3 +6,9 @@ export const MESSAGE_TIMEOUT = 2;
// in prod mode using proxy // in prod mode using proxy
export const API = export const API =
process.env.NODE_ENV === "development" ? "http://localhost:4004/" : "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");

View File

@@ -30,11 +30,15 @@
"REFRESH_TOKEN_SECRET": "refresh-secret", "REFRESH_TOKEN_SECRET": "refresh-secret",
"requires": { "requires": {
"db": { "db": {
"kind": "hana" "kind": "sqlite",
"model": "*",
"credentials": {
"database": "mychinook.db"
}
}, },
"auth": { "auth": {
"impl": "srv/auth.js" "impl": "srv/auth.js"
} }
} }
} }
} }

View File

@@ -3,8 +3,8 @@ const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs"); const bcrypt = require("bcryptjs");
const { ACCESS_TOKEN_SECRET, REFRESH_TOKEN_SECRET } = cds.env; const { ACCESS_TOKEN_SECRET, REFRESH_TOKEN_SECRET } = cds.env;
const ACCESS_TOKEN_EXP_IN = "10m"; const ACCESS_TOKEN_EXP_IN = "10s";
const REFRESH_TOKEN_EXPIRES_IN = "20m"; const REFRESH_TOKEN_EXPIRES_IN = "16s";
const comparePasswords = async (password, hashedPassword) => { const comparePasswords = async (password, hashedPassword) => {
return new Promise((resolve, reject) => return new Promise((resolve, reject) =>