edit person page. remove invoicedItems on logout

This commit is contained in:
Dzmitry_Tamashevich@epam.com
2020-11-25 12:17:41 +03:00
committed by Daniel Hutzel
parent 58af1879f7
commit fe0562f38b
6 changed files with 56 additions and 62 deletions

View File

@@ -24,7 +24,14 @@ 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, loading } = useAppState(); const {
user,
invoicedItems,
setInvoicedItems,
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;
@@ -48,7 +55,7 @@ const Header = () => {
const onUserLogout = () => { const onUserLogout = () => {
emitter.emit("UPDATE_USER", undefined); emitter.emit("UPDATE_USER", undefined);
history.push("/"); history.go(0);
}; };
return ( return (

View File

@@ -29,7 +29,6 @@ const Login = () => {
const { handleError } = useErrors(); const { handleError } = useErrors();
const onFinish = (values) => { const onFinish = (values) => {
console.log("Validation Success:", values);
setLoading(true); setLoading(true);
login({ email: values.email, password: values.password }) login({ email: values.email, password: values.password })
.then((response) => { .then((response) => {

View File

@@ -1,10 +1,9 @@
import React, { useState, useMemo } from "react"; import React, { useState } from "react";
import { Card, Button, message } from "antd"; import { Form, Button, message, Input } from "antd";
import { omit } from "lodash"; import { omit, map } 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 { MESSAGE_TIMEOUT } from "../util/constants"; import { MESSAGE_TIMEOUT } from "../util/constants";
import { useAbortableEffect } from "../hooks/useAbortableEffect"; import { useAbortableEffect } from "../hooks/useAbortableEffect";
@@ -25,7 +24,7 @@ const PERSON_PROP = {
const PersonPage = () => { const PersonPage = () => {
const { setLoading } = useAppState(); const { setLoading } = useAppState();
const { handleError } = useErrors(); const { handleError } = useErrors();
const [initialPerson, setInitialPerson] = useState({}); const [form] = Form.useForm();
const [person, setPerson] = useState({ const [person, setPerson] = useState({
lastName: "", lastName: "",
firstName: "", firstName: "",
@@ -47,7 +46,6 @@ const PersonPage = () => {
.then(({ data: personData }) => { .then(({ data: personData }) => {
personData = omit(personData, "@odata.context", "ID"); personData = omit(personData, "@odata.context", "ID");
if (!status.aborted) { if (!status.aborted) {
setInitialPerson(personData);
setPerson(personData); setPerson(personData);
} }
}) })
@@ -55,67 +53,58 @@ const PersonPage = () => {
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, []); }, []);
const onConfirmChanges = () => { const onConfirmChanges = (newPerson) => {
setLoading(true); setLoading(true);
confirmPerson(person) confirmPerson(newPerson)
.then(() => { .then(() => {
setInitialPerson(person);
message.success("Person successfully updated", MESSAGE_TIMEOUT); message.success("Person successfully updated", MESSAGE_TIMEOUT);
}) })
.catch(handleError) .catch(handleError)
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}; };
const isPersonChanged = useMemo(() => {
const keysOne = Object.keys(initialPerson);
const keysTwo = Object.keys(person);
if (keysOne.length !== keysTwo.length) {
return true;
}
for (let key of keysOne) { const personProperties = map(Object.keys(person), (currentKey) => (
if (initialPerson[key] !== person[key]) { <Form.Item
return true; key={currentKey}
} label={PERSON_PROP[currentKey]}
} name={currentKey}
>
<Input />
</Form.Item>
));
return false; console.log(person, "person");
}, [person, initialPerson]);
const personProperties = Object.keys(person).reduce((acc, currentKey) => {
if (currentKey === "email") {
return acc;
}
return acc.concat([
<div key={currentKey}>
{PERSON_PROP[currentKey]}
<Editable
type="text"
value={person[currentKey]}
onChange={(value) =>
setPerson({ ...person, [`${currentKey}`]: value })
}
/>
</div>,
]);
}, []);
return ( return (
<> <>
<Card title={`${person.lastName} ${person.firstName}`}> {person.lastName !== "" && (
{personProperties} <Form
<div> form={form}
Email: <span style={{ fontWeight: 600 }}>{person.email}</span> labelCol={{
</div> span: 4,
{isPersonChanged && ( }}
<Button wrapperCol={{
span: 14,
}}
layout="horizontal"
onFinish={onConfirmChanges}
onFinishFailed={() => console.log("Not valid params provided")}
initialValues={{
...person,
}}
>
{personProperties}
<Form.Item
type="primary" type="primary"
style={{ margin: 10 }} wrapperCol={{
onClick={onConfirmChanges} span: 14,
offset: 4,
}}
> >
Confirm changes <Button onClick={() => form.submit()}>Confirm changes</Button>
</Button> </Form.Item>
)} </Form>
</Card> )}
</> </>
); );
}; };

View File

@@ -13,10 +13,6 @@ const REQUIRED = [
message: "This filed is required!", message: "This filed is required!",
}, },
]; ];
const PRICE_INPUT_RULE = {
pattern: /^(?:\d*\.\d\d)$/,
message: "Price should have precision 2 and dot separator!",
};
const getAlbums = function (value) { const getAlbums = function (value) {
return fetchAlbumsByName(value, ALBUMS_LIMIT) return fetchAlbumsByName(value, ALBUMS_LIMIT)

View File

@@ -23,6 +23,7 @@ module.exports = async function () {
this.on("invoice", async (req) => { this.on("invoice", async (req) => {
const { tracks } = req.data; const { tracks } = req.data;
const trackIds = tracks.map(({ ID }) => ID);
const customerId = req.user.attr.ID; const customerId = req.user.attr.ID;
const total = tracks.reduce( const total = tracks.reduce(
(acc, { unitPrice }) => acc + Number(unitPrice), (acc, { unitPrice }) => acc + Number(unitPrice),
@@ -32,14 +33,15 @@ module.exports = async function () {
const transaction = await db.tx(req); const transaction = await db.tx(req);
// getting last ids for new records
let { ID: lastInvoiceId } = await transaction.run( let { ID: lastInvoiceId } = await transaction.run(
SELECT.one(Invoices).columns("ID").orderBy({ ID: "desc" }) SELECT.one(Invoices).columns("ID").orderBy({ ID: "desc" })
); );
let { ID: lastInvoiceItemId } = await transaction.run( let { ID: lastInvoiceItemId } = await transaction.run(
SELECT.one(InvoiceItems).columns("ID").orderBy({ ID: "desc" }) SELECT.one(InvoiceItems).columns("ID").orderBy({ ID: "desc" })
); );
// creating invoice
const { const {
results: [{ lastID: invoiceID }], results: [{ lastID: invoiceID }],
} = await transaction.run( } = await transaction.run(
@@ -48,6 +50,7 @@ module.exports = async function () {
.values(++lastInvoiceId, customerId, total, utcNowDateTime) .values(++lastInvoiceId, customerId, total, utcNowDateTime)
); );
// creating invoice items
await transaction.run( await transaction.run(
INSERT.into(InvoiceItems) INSERT.into(InvoiceItems)
.columns("ID", "invoice_ID", "track_ID", "unitPrice") .columns("ID", "invoice_ID", "track_ID", "unitPrice")

View File

@@ -4,7 +4,7 @@ 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 = "10s"; const ACCESS_TOKEN_EXP_IN = "10s";
const REFRESH_TOKEN_EXPIRES_IN = "16s"; const REFRESH_TOKEN_EXPIRES_IN = "30s";
const comparePasswords = async (password, hashedPassword) => { const comparePasswords = async (password, hashedPassword) => {
return new Promise((resolve, reject) => return new Promise((resolve, reject) =>