fix cart
This commit is contained in:
parent
fb552952a3
commit
9332a0f115
20
src/api/cart.ts
Normal file
20
src/api/cart.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
|
||||
|
||||
const apiUrl = process.env.NODE_ENV === "production" ? "/customer" : "https://hub.pena.digital/customer";
|
||||
|
||||
export function patchCart(tariffId: string) {
|
||||
return makeRequest<never, string[]>({
|
||||
url: apiUrl + `/cart?id=${tariffId}`,
|
||||
method: "PATCH",
|
||||
useToken: true,
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteCart(tariffId: string) {
|
||||
return makeRequest<never, string[]>({
|
||||
url: apiUrl + `/cart?id=${tariffId}`,
|
||||
method: "DELETE",
|
||||
useToken: true,
|
||||
});
|
||||
}
|
@ -1,15 +1,21 @@
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import { CustomTariff } from "@root/model/customTariffs";
|
||||
import { PrivilegeWithoutPrice } from "@root/model/privilege";
|
||||
import { CreateTariffBody, CustomTariff } from "@root/model/customTariffs";
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
|
||||
|
||||
export function createTariff<
|
||||
T = Omit<CustomTariff, "privilegies"> & { privilegies: PrivilegeWithoutPrice[]; }
|
||||
>(tariff: T) {
|
||||
return makeRequest<T, CustomTariff>({
|
||||
export function createTariff(tariff: CreateTariffBody) {
|
||||
return makeRequest<CreateTariffBody, CustomTariff>({
|
||||
url: `https://admin.pena.digital/strator/tariff`,
|
||||
method: "post",
|
||||
useToken: true,
|
||||
body: tariff,
|
||||
});
|
||||
}
|
||||
|
||||
export function getTariffById(tariffId:string){
|
||||
return makeRequest<never, Tariff>({
|
||||
url: `https://admin.pena.digital/strator/tariff/${tariffId}`,
|
||||
method: "get",
|
||||
useToken: true,
|
||||
});
|
||||
}
|
@ -2,156 +2,159 @@ import { useState } from "react";
|
||||
import { Box, SvgIcon, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
|
||||
import ClearIcon from "@mui/icons-material/Clear";
|
||||
import { basketStore } from "@root/stores/BasketStore";
|
||||
import { cardShadow } from "@root/utils/themes/shadow";
|
||||
import { ServiceCartData } from "@root/model/cart";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
import { removeTariffFromCart } from "@root/stores/user";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { getMessageFromFetchError } from "@frontend/kitui";
|
||||
|
||||
|
||||
const name: Record<string, string> = { templategen: "Шаблонизатор", squiz: "Опросник", reducer: "Скоращатель ссылок" };
|
||||
|
||||
interface Props {
|
||||
type: "templ" | "squiz" | "reducer";
|
||||
content: {
|
||||
name: string;
|
||||
desc: string;
|
||||
id: string;
|
||||
privelegeid: string;
|
||||
amount: number;
|
||||
price: number;
|
||||
}[];
|
||||
serviceData: ServiceCartData;
|
||||
}
|
||||
|
||||
export default function CustomWrapperDrawer({ type, content }: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
export default function CustomWrapperDrawer({ serviceData }: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
|
||||
const { remove } = basketStore();
|
||||
function handleItemDeleteClick(tariffId: string) {
|
||||
removeTariffFromCart(tariffId).then(() => {
|
||||
enqueueSnackbar("Тариф удален");
|
||||
}).catch(error => {
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
});
|
||||
}
|
||||
|
||||
const totalSum = Object.values(content).reduce((accamulator, { price }) => (accamulator += price), 0);
|
||||
const name: Record<string, string> = { templ: "Шаблонизатор", squiz: "Опросник", reducer: "Скоращатель ссылок" };
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
overflow: "hidden",
|
||||
borderRadius: "12px",
|
||||
boxShadow: cardShadow,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: "white",
|
||||
"&:first-of-type": {
|
||||
borderTopLeftRadius: "12px",
|
||||
borderTopRightRadius: "12px",
|
||||
},
|
||||
"&:last-of-type": {
|
||||
borderBottomLeftRadius: "12px",
|
||||
borderBottomRightRadius: "12px",
|
||||
},
|
||||
"&:not(:last-of-type)": {
|
||||
borderBottom: `1px solid ${theme.palette.grey2.main}`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
return (
|
||||
<Box
|
||||
onClick={() => setIsExpanded((prev) => !prev)}
|
||||
sx={{
|
||||
height: "72px",
|
||||
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}}
|
||||
sx={{
|
||||
overflow: "hidden",
|
||||
borderRadius: "12px",
|
||||
boxShadow: cardShadow,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: upMd ? "20px" : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
fontWeight: 500,
|
||||
color: theme.palette.text.secondary,
|
||||
px: 0,
|
||||
}}
|
||||
>
|
||||
{name[type]}
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "flex-end",
|
||||
height: "100%",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{ pr: "11px", color: theme.palette.grey3.main, fontSize: upSm ? "20px" : "16px", fontWeight: 500 }}
|
||||
>
|
||||
{totalSum} руб.
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
paddingLeft: upSm ? "24px" : 0,
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
}}
|
||||
></Box>
|
||||
</Box>
|
||||
</Box>
|
||||
{isExpanded &&
|
||||
Object.values(content).map(({ desc, id, privelegeid, amount, price }, index) => (
|
||||
<Box
|
||||
key={index}
|
||||
sx={{
|
||||
py: upMd ? "10px" : undefined,
|
||||
pt: upMd ? undefined : "15px",
|
||||
pb: upMd ? undefined : "20px",
|
||||
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
gap: "15px",
|
||||
}}
|
||||
sx={{
|
||||
backgroundColor: "white",
|
||||
"&:first-of-type": {
|
||||
borderTopLeftRadius: "12px",
|
||||
borderTopRightRadius: "12px",
|
||||
},
|
||||
"&:last-of-type": {
|
||||
borderBottomLeftRadius: "12px",
|
||||
borderBottomRightRadius: "12px",
|
||||
},
|
||||
"&:not(:last-of-type)": {
|
||||
borderBottom: `1px solid ${theme.palette.grey2.main}`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
width: "200px",
|
||||
fontSize: upMd ? undefined : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
color: theme.palette.grey3.main,
|
||||
}}
|
||||
>
|
||||
{desc}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
gap: "10px",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
color: theme.palette.grey3.main,
|
||||
fontSize: "20px",
|
||||
fontWeight: 500,
|
||||
}}
|
||||
<Box
|
||||
onClick={() => setIsExpanded((prev) => !prev)}
|
||||
sx={{
|
||||
height: "72px",
|
||||
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}}
|
||||
>
|
||||
{price} руб.
|
||||
</Typography>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: upMd ? "20px" : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
fontWeight: 500,
|
||||
color: theme.palette.text.secondary,
|
||||
px: 0,
|
||||
}}
|
||||
>
|
||||
{name[serviceData.serviceKey]}
|
||||
</Typography>
|
||||
|
||||
<SvgIcon
|
||||
sx={{ cursor: "pointer", color: "#7E2AEA" }}
|
||||
onClick={() => remove(type, id)}
|
||||
component={ClearIcon}
|
||||
/>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "flex-end",
|
||||
height: "100%",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{ pr: "11px", color: theme.palette.grey3.main, fontSize: upSm ? "20px" : "16px", fontWeight: 500 }}
|
||||
>
|
||||
{currencyFormatter.format(serviceData.price / 100)}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
paddingLeft: upSm ? "24px" : 0,
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
}}
|
||||
></Box>
|
||||
</Box>
|
||||
</Box>
|
||||
{isExpanded &&
|
||||
serviceData.privileges.map(privilege => (
|
||||
<Box
|
||||
key={privilege.tariffId + privilege.privilegeId}
|
||||
sx={{
|
||||
py: upMd ? "10px" : undefined,
|
||||
pt: upMd ? undefined : "15px",
|
||||
pb: upMd ? undefined : "20px",
|
||||
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
gap: "15px",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
width: "200px",
|
||||
fontSize: upMd ? undefined : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
color: theme.palette.grey3.main,
|
||||
}}
|
||||
>
|
||||
{privilege.name}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
gap: "10px",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
color: theme.palette.grey3.main,
|
||||
fontSize: "20px",
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{currencyFormatter.format(privilege.price / 100)}
|
||||
</Typography>
|
||||
|
||||
<SvgIcon
|
||||
sx={{ cursor: "pointer", color: "#7E2AEA" }}
|
||||
onClick={() => handleItemDeleteClick(privilege.tariffId)}
|
||||
component={ClearIcon}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
@ -1,228 +1,185 @@
|
||||
import React, { useEffect } from "react";
|
||||
import { Typography, Drawer, useMediaQuery, useTheme, Box, IconButton, SvgIcon, Icon } from "@mui/material";
|
||||
import { IconsCreate } from "@root/lib/IconsCreate";
|
||||
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
||||
import ClearIcon from "@mui/icons-material/Clear";
|
||||
|
||||
import { basketStore } from "@root/stores/BasketStore";
|
||||
import { useState } from "react";
|
||||
|
||||
import BasketIcon from "../assets/Icons/BasketIcon.svg";
|
||||
import SectionWrapper from "./SectionWrapper";
|
||||
import CustomWrapperDrawer from "./CustomWrapperDrawer";
|
||||
import CustomButton from "./CustomButton";
|
||||
import { useNavigate } from "react-router";
|
||||
import { useCart } from "@root/utils/hooks/useCart";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
import { closeCartDrawer, openCartDrawer, useCartStore } from "@root/stores/cart";
|
||||
|
||||
interface TabPanelProps {
|
||||
index: number;
|
||||
value: number;
|
||||
children?: React.ReactNode;
|
||||
mt: string;
|
||||
}
|
||||
|
||||
type BasketItem = {
|
||||
name: string;
|
||||
desc: string;
|
||||
id: string;
|
||||
privelegeid: string;
|
||||
amount: number;
|
||||
price: number;
|
||||
}[];
|
||||
|
||||
function TabPanel({ index, value, children, mt }: TabPanelProps) {
|
||||
return (
|
||||
<Box hidden={index !== value} sx={{ mt }}>
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Drawers() {
|
||||
const [tabIndex, setTabIndex] = useState<number>(0);
|
||||
const [basketQuantity, setBasketQuantity] = useState<number>();
|
||||
const navigate = useNavigate();
|
||||
const { templ, squiz, reducer, open, openDrawer } = basketStore();
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const isDrawerOpen = useCartStore(state => state.isDrawerOpen);
|
||||
const cart = useCart();
|
||||
|
||||
const newArray: BasketItem = [...Object.values(templ), ...Object.values(squiz), ...Object.values(reducer)];
|
||||
const sum = newArray.reduce((accamulator, { price }) => (accamulator += price), 0);
|
||||
|
||||
useEffect(() => {
|
||||
setBasketQuantity(Object.keys(templ).length + Object.keys(squiz).length + Object.keys(reducer).length);
|
||||
}, [templ, squiz, reducer]);
|
||||
|
||||
return (
|
||||
<IconButton sx={{ p: 0 }}>
|
||||
<Typography onClick={open(true)} component="div" sx={{ position: "absolute" }}>
|
||||
<IconsCreate svg={BasketIcon} bgcolor="#F2F3F7" />
|
||||
</Typography>
|
||||
{basketQuantity && (
|
||||
<Icon
|
||||
component="div"
|
||||
sx={{
|
||||
position: "relative",
|
||||
left: "8px",
|
||||
bottom: "7px",
|
||||
|
||||
width: "16px",
|
||||
height: "16px",
|
||||
backgroundColor: "#7E2AEA",
|
||||
borderRadius: "12px",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
component="div"
|
||||
sx={{
|
||||
display: "flex",
|
||||
fontSize: "12px",
|
||||
mt: "4.5px",
|
||||
width: "100%",
|
||||
height: "9px",
|
||||
color: "white",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{basketQuantity}
|
||||
</Typography>
|
||||
</Icon>
|
||||
)}
|
||||
|
||||
<Drawer anchor={"right"} open={openDrawer} onClose={open(false)}>
|
||||
<SectionWrapper
|
||||
maxWidth="lg"
|
||||
sx={{
|
||||
pl: "0px",
|
||||
pr: "0px",
|
||||
width: "450px",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: "100%",
|
||||
pt: "20px",
|
||||
pb: "20px",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
bgcolor: "#F2F3F7",
|
||||
gap: "10px",
|
||||
pl: "20px",
|
||||
pr: "20px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<IconButton sx={{ p: 0, height: "28px", width: "28px", color: "black" }}>
|
||||
<ArrowBackIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
<Typography
|
||||
component="div"
|
||||
sx={{
|
||||
fontSize: "18px",
|
||||
lineHeight: "21px",
|
||||
font: "Rubick",
|
||||
}}
|
||||
>
|
||||
Корзина
|
||||
return (
|
||||
<IconButton sx={{ p: 0 }}>
|
||||
<Typography onClick={openCartDrawer} component="div" sx={{ position: "absolute" }}>
|
||||
<IconsCreate svg={BasketIcon} bgcolor="#F2F3F7" />
|
||||
</Typography>
|
||||
<SvgIcon onClick={open(false)} sx={{ cursor: "pointer" }} component={ClearIcon} />
|
||||
</Box>
|
||||
<Box sx={{ pl: "20px", pr: "20px" }}>
|
||||
<TabPanel value={tabIndex} index={0} mt={"10px"}>
|
||||
{Object.keys(templ).length > 0 ? (
|
||||
<CustomWrapperDrawer type="templ" content={Object.values(templ)} />
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
{Object.keys(squiz).length > 0 ? (
|
||||
<CustomWrapperDrawer type="squiz" content={Object.values(squiz)} />
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
{Object.keys(reducer).length > 0 ? (
|
||||
<CustomWrapperDrawer type="reducer" content={Object.values(reducer)} />
|
||||
) : (
|
||||
<></>
|
||||
)}
|
||||
</TabPanel>
|
||||
<Box
|
||||
sx={{
|
||||
mt: "40px",
|
||||
pt: upMd ? "30px" : undefined,
|
||||
borderTop: upMd ? `1px solid ${theme.palette.grey2.main}` : undefined,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: upMd ? "100%" : undefined,
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4" mb={upMd ? "18px" : "30px"}>
|
||||
Итоговая цена
|
||||
</Typography>
|
||||
<Typography color={theme.palette.grey3.main}>
|
||||
Текст-заполнитель — это текст, который имеет Текст-заполнитель — это текст, который имеет
|
||||
Текст-заполнитель — это текст, который имеет Текст-заполнитель — это текст, который имеет
|
||||
Текст-заполнитель
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
color: theme.palette.grey3.main,
|
||||
pb: "100px",
|
||||
pt: "38px",
|
||||
pl: upMd ? "20px" : undefined,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: upMd ? "column" : "row",
|
||||
alignItems: upMd ? "start" : "center",
|
||||
mt: upMd ? "10px" : "30px",
|
||||
gap: "15px",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
color={theme.palette.orange.main}
|
||||
{cart.itemCount && (
|
||||
<Icon
|
||||
component="div"
|
||||
sx={{
|
||||
textDecoration: "line-through",
|
||||
order: upMd ? 1 : 2,
|
||||
position: "relative",
|
||||
left: "8px",
|
||||
bottom: "7px",
|
||||
width: "16px",
|
||||
height: "16px",
|
||||
backgroundColor: "#7E2AEA",
|
||||
borderRadius: "12px",
|
||||
}}
|
||||
>
|
||||
20 190 руб.
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="p1"
|
||||
sx={{
|
||||
fontWeight: 500,
|
||||
fontSize: "26px",
|
||||
lineHeight: "31px",
|
||||
order: upMd ? 2 : 1,
|
||||
}}
|
||||
>
|
||||
{sum} руб.
|
||||
</Typography>
|
||||
</Box>
|
||||
<CustomButton
|
||||
variant="contained"
|
||||
onClick={() => navigate("/basket")}
|
||||
sx={{
|
||||
mt: "25px",
|
||||
backgroundColor: theme.palette.brightPurple.main,
|
||||
}}
|
||||
>
|
||||
Оплатить
|
||||
</CustomButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</SectionWrapper>
|
||||
</Drawer>
|
||||
</IconButton>
|
||||
);
|
||||
<Typography
|
||||
component="div"
|
||||
sx={{
|
||||
display: "flex",
|
||||
fontSize: "12px",
|
||||
mt: "4.5px",
|
||||
width: "100%",
|
||||
height: "9px",
|
||||
color: "white",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{cart.itemCount}
|
||||
</Typography>
|
||||
</Icon>
|
||||
)}
|
||||
|
||||
<Drawer anchor={"right"} open={isDrawerOpen} onClose={closeCartDrawer}>
|
||||
<SectionWrapper
|
||||
maxWidth="lg"
|
||||
sx={{
|
||||
pl: "0px",
|
||||
pr: "0px",
|
||||
width: "450px",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: "100%",
|
||||
pt: "20px",
|
||||
pb: "20px",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
bgcolor: "#F2F3F7",
|
||||
gap: "10px",
|
||||
pl: "20px",
|
||||
pr: "20px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<IconButton sx={{ p: 0, height: "28px", width: "28px", color: "black" }}>
|
||||
<ArrowBackIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
<Typography
|
||||
component="div"
|
||||
sx={{
|
||||
fontSize: "18px",
|
||||
lineHeight: "21px",
|
||||
font: "Rubick",
|
||||
}}
|
||||
>
|
||||
Корзина
|
||||
</Typography>
|
||||
<IconButton onClick={closeCartDrawer} sx={{ p: 0 }}>
|
||||
<SvgIcon component={ClearIcon} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
<Box sx={{ pl: "20px", pr: "20px" }}>
|
||||
{cart.services.map(serviceData =>
|
||||
<CustomWrapperDrawer
|
||||
key={serviceData.serviceKey}
|
||||
serviceData={serviceData}
|
||||
/>
|
||||
)}
|
||||
<Box
|
||||
sx={{
|
||||
mt: "40px",
|
||||
pt: upMd ? "30px" : undefined,
|
||||
borderTop: upMd ? `1px solid ${theme.palette.grey2.main}` : undefined,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: upMd ? "100%" : undefined,
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<Typography variant="h4" mb={upMd ? "18px" : "30px"}>
|
||||
Итоговая цена
|
||||
</Typography>
|
||||
<Typography color={theme.palette.grey3.main}>
|
||||
Текст-заполнитель — это текст, который имеет Текст-заполнитель — это текст, который имеет
|
||||
Текст-заполнитель — это текст, который имеет Текст-заполнитель — это текст, который имеет
|
||||
Текст-заполнитель
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
color: theme.palette.grey3.main,
|
||||
pb: "100px",
|
||||
pt: "38px",
|
||||
pl: upMd ? "20px" : undefined,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: upMd ? "column" : "row",
|
||||
alignItems: upMd ? "start" : "center",
|
||||
mt: upMd ? "10px" : "30px",
|
||||
gap: "15px",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
color={theme.palette.orange.main}
|
||||
sx={{
|
||||
textDecoration: "line-through",
|
||||
order: upMd ? 1 : 2,
|
||||
}}
|
||||
>
|
||||
{currencyFormatter.format(cart.priceBeforeDiscounts / 100)}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="p1"
|
||||
sx={{
|
||||
fontWeight: 500,
|
||||
fontSize: "26px",
|
||||
lineHeight: "31px",
|
||||
order: upMd ? 2 : 1,
|
||||
}}
|
||||
>
|
||||
{currencyFormatter.format(cart.priceAfterDiscounts / 100)}
|
||||
</Typography>
|
||||
</Box>
|
||||
<CustomButton
|
||||
variant="contained"
|
||||
onClick={() => navigate("/basket")}
|
||||
sx={{
|
||||
mt: "25px",
|
||||
backgroundColor: theme.palette.brightPurple.main,
|
||||
}}
|
||||
>
|
||||
Оплатить
|
||||
</CustomButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</SectionWrapper>
|
||||
</Drawer>
|
||||
</IconButton>
|
||||
);
|
||||
}
|
||||
|
@ -1,10 +1,6 @@
|
||||
import { Link, useLocation, useNavigate } from "react-router-dom";
|
||||
import { useEffect } from "react";
|
||||
import { Box, Button, Container, IconButton, Typography, useTheme } from "@mui/material";
|
||||
|
||||
import SectionWrapper from "../SectionWrapper";
|
||||
import { basketStore } from "@stores/BasketStore";
|
||||
|
||||
import LogoutIcon from "../icons/LogoutIcon";
|
||||
import WalletIcon from "../icons/WalletIcon";
|
||||
import CustomAvatar from "./Avatar";
|
||||
@ -26,14 +22,6 @@ export default function NavbarFull({ isLoggedIn }: Props) {
|
||||
const navigate = useNavigate();
|
||||
const user = useUserStore((state) => state.user);
|
||||
|
||||
const { open } = basketStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (location.pathname === "/basket") {
|
||||
open(false);
|
||||
}
|
||||
}, [location.pathname, open]);
|
||||
|
||||
async function handleLogoutClick() {
|
||||
try {
|
||||
await logout();
|
||||
|
@ -1,25 +1,16 @@
|
||||
import { Box, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
import { basketStore } from "@root/stores/BasketStore";
|
||||
|
||||
import CustomButton from "./CustomButton";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
|
||||
export default function TotalPrice() {
|
||||
interface Props {
|
||||
price: number;
|
||||
priceWithDiscounts: number;
|
||||
}
|
||||
|
||||
export default function TotalPrice({price,priceWithDiscounts}:Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const { templ, squiz, reducer } = basketStore();
|
||||
|
||||
type BasketItem = {
|
||||
name: string;
|
||||
desc: string;
|
||||
id: string;
|
||||
privelegeid: string;
|
||||
amount: number;
|
||||
price: number;
|
||||
}[];
|
||||
|
||||
const newArray: BasketItem = [...Object.values(templ), ...Object.values(squiz), ...Object.values(reducer)];
|
||||
|
||||
const sum = newArray.reduce((accamulator, { price }) => (accamulator += price), 0);
|
||||
|
||||
return (
|
||||
<Box
|
||||
@ -71,7 +62,7 @@ export default function TotalPrice() {
|
||||
order: upMd ? 1 : 2,
|
||||
}}
|
||||
>
|
||||
20 190 руб.
|
||||
{currencyFormatter.format(price / 100)}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="p1"
|
||||
@ -82,7 +73,7 @@ export default function TotalPrice() {
|
||||
order: upMd ? 2 : 1,
|
||||
}}
|
||||
>
|
||||
{sum} руб.
|
||||
{currencyFormatter.format(priceWithDiscounts / 100)}
|
||||
</Typography>
|
||||
</Box>
|
||||
<CustomButton
|
||||
|
19
src/model/cart.ts
Normal file
19
src/model/cart.ts
Normal file
@ -0,0 +1,19 @@
|
||||
export type PrivilegeCartData = {
|
||||
tariffId: string;
|
||||
privilegeId: string;
|
||||
name: string;
|
||||
price: number;
|
||||
};
|
||||
|
||||
export type ServiceCartData = {
|
||||
serviceKey: string;
|
||||
privileges: PrivilegeCartData[];
|
||||
price: number;
|
||||
};
|
||||
|
||||
export type CartData = {
|
||||
services: ServiceCartData[];
|
||||
priceBeforeDiscounts: number;
|
||||
priceAfterDiscounts: number;
|
||||
itemCount: number;
|
||||
};
|
@ -1,4 +1,4 @@
|
||||
import { PrivilegeWithAmount } from "./privilege";
|
||||
import { PrivilegeWithAmount, PrivilegeWithoutPrice } from "./privilege";
|
||||
|
||||
|
||||
export type CustomTariffUserValues = Record<string, number>;
|
||||
@ -15,4 +15,6 @@ export interface CustomTariff {
|
||||
updatedAt?: string;
|
||||
isDeleted?: boolean;
|
||||
createdAt?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export type CreateTariffBody = Omit<CustomTariff, "privilegies"> & { privilegies: PrivilegeWithoutPrice[]; };
|
@ -1,72 +1,54 @@
|
||||
import { Box, IconButton, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
import SectionWrapper from "@components/SectionWrapper";
|
||||
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
||||
import { useState } from "react";
|
||||
import TotalPrice from "@components/TotalPrice";
|
||||
import { basketStore } from "@root/stores/BasketStore";
|
||||
import CustomWrapper from "./CustomWrapper";
|
||||
import ComplexNavText from "@root/components/ComplexNavText";
|
||||
import { useCart } from "@root/utils/hooks/useCart";
|
||||
|
||||
interface TabPanelProps {
|
||||
index: number;
|
||||
value: number;
|
||||
children?: React.ReactNode;
|
||||
mt: string;
|
||||
}
|
||||
|
||||
function TabPanel({ index, value, children, mt }: TabPanelProps) {
|
||||
return (
|
||||
<Box hidden={index !== value} sx={{ mt }}>
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Basket() {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const cart = useCart();
|
||||
|
||||
const [tabIndex, setTabIndex] = useState<number>(0);
|
||||
const { templ, squiz, reducer, open } = basketStore();
|
||||
|
||||
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
|
||||
setTabIndex(newValue);
|
||||
};
|
||||
|
||||
open(false);
|
||||
|
||||
return (
|
||||
<SectionWrapper
|
||||
maxWidth="lg"
|
||||
sx={{
|
||||
mt: upMd ? "25px" : "20px",
|
||||
mb: upMd ? "70px" : "37px",
|
||||
}}
|
||||
>
|
||||
{upMd && <ComplexNavText text1="Все тарифы — " text2="Корзина" />}
|
||||
<Box
|
||||
sx={{
|
||||
mt: "20px",
|
||||
mb: upMd ? "40px" : "20px",
|
||||
display: "flex",
|
||||
gap: "10px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<IconButton sx={{ p: 0, height: "28px", width: "28px", color: "black" }}>
|
||||
<ArrowBackIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
<Typography component="h4" variant="h4">
|
||||
Корзина
|
||||
</Typography>
|
||||
</Box>
|
||||
<TabPanel value={tabIndex} index={0} mt={upMd ? "27px" : "10px"}>
|
||||
{Object.keys(templ).length > 0 ? <CustomWrapper type="templ" content={templ} /> : <></>}
|
||||
{Object.keys(squiz).length > 0 ? <CustomWrapper type="squiz" content={squiz} /> : <></>}
|
||||
{Object.keys(reducer).length > 0 ? <CustomWrapper type="reducer" content={reducer} /> : <></>}
|
||||
</TabPanel>
|
||||
<TotalPrice />
|
||||
</SectionWrapper>
|
||||
);
|
||||
return (
|
||||
<SectionWrapper
|
||||
maxWidth="lg"
|
||||
sx={{
|
||||
mt: upMd ? "25px" : "20px",
|
||||
mb: upMd ? "70px" : "37px",
|
||||
}}
|
||||
>
|
||||
{upMd && <ComplexNavText text1="Все тарифы — " text2="Корзина" />}
|
||||
<Box
|
||||
sx={{
|
||||
mt: "20px",
|
||||
mb: upMd ? "40px" : "20px",
|
||||
display: "flex",
|
||||
gap: "10px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<IconButton sx={{ p: 0, height: "28px", width: "28px", color: "black" }}>
|
||||
<ArrowBackIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
<Typography component="h4" variant="h4">
|
||||
Корзина
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box sx={{
|
||||
mt: upMd ? "27px" : "10px",
|
||||
}}>
|
||||
{cart.services.map(serviceData =>
|
||||
<CustomWrapper
|
||||
key={serviceData.serviceKey}
|
||||
serviceData={serviceData}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<TotalPrice price={cart.priceBeforeDiscounts} priceWithDiscounts={cart.priceAfterDiscounts} />
|
||||
</SectionWrapper>
|
||||
);
|
||||
}
|
||||
|
@ -1,177 +1,176 @@
|
||||
import { useState } from "react";
|
||||
import { Box, SvgIcon, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
|
||||
import ExpandIcon from "@components/icons/ExpandIcon";
|
||||
|
||||
import ClearIcon from "@mui/icons-material/Clear";
|
||||
import { basketStore } from "@root/stores/BasketStore";
|
||||
import { cardShadow } from "@root/utils/themes/shadow";
|
||||
import { ServiceCartData } from "@root/model/cart";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
import { removeTariffFromCart } from "@root/stores/user";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { getMessageFromFetchError } from "@frontend/kitui";
|
||||
|
||||
interface Templ {
|
||||
name: string;
|
||||
desc: string;
|
||||
id: string;
|
||||
privelegeid?: string;
|
||||
amount: number;
|
||||
price: number;
|
||||
}
|
||||
|
||||
const name: Record<string, string> = { templategen: "Шаблонизатор", squiz: "Опросник", reducer: "Сокращатель ссылок" };
|
||||
|
||||
interface Props {
|
||||
type: "templ" | "squiz" | "reducer";
|
||||
content: Record<string, Templ>;
|
||||
serviceData: ServiceCartData;
|
||||
}
|
||||
|
||||
export default function CustomWrapper({ type, content }: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
export default function CustomWrapper({ serviceData }: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const upSm = useMediaQuery(theme.breakpoints.up("sm"));
|
||||
const [isExpanded, setIsExpanded] = useState<boolean>(false);
|
||||
|
||||
const { remove } = basketStore();
|
||||
function handleItemDeleteClick(tariffId: string) {
|
||||
removeTariffFromCart(tariffId).then(() => {
|
||||
enqueueSnackbar("Тариф удален");
|
||||
}).catch(error => {
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
});
|
||||
}
|
||||
|
||||
const totalSum = Object.values(content).reduce((accamulator, { price }) => (accamulator += price), 0);
|
||||
const name: Record<string, string> = { templ: "Шаблонизатор", squiz: "Опросник", reducer: "Скоращатель ссылок" };
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
overflow: "hidden",
|
||||
borderRadius: "12px",
|
||||
boxShadow: cardShadow,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
backgroundColor: "white",
|
||||
"&:first-of-type": {
|
||||
borderTopLeftRadius: "12px",
|
||||
borderTopRightRadius: "12px",
|
||||
},
|
||||
"&:last-of-type": {
|
||||
borderBottomLeftRadius: "12px",
|
||||
borderBottomRightRadius: "12px",
|
||||
},
|
||||
"&:not(:last-of-type)": {
|
||||
borderBottom: `1px solid ${theme.palette.grey2.main}`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
return (
|
||||
<Box
|
||||
onClick={() => setIsExpanded((prev) => !prev)}
|
||||
sx={{
|
||||
height: "72px",
|
||||
px: "20px",
|
||||
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}}
|
||||
sx={{
|
||||
overflow: "hidden",
|
||||
borderRadius: "12px",
|
||||
boxShadow: cardShadow,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: upMd ? "20px" : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
fontWeight: 500,
|
||||
color: theme.palette.text.secondary,
|
||||
px: 0,
|
||||
}}
|
||||
>
|
||||
{name[type]}
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "flex-end",
|
||||
height: "100%",
|
||||
alignItems: "center",
|
||||
gap: upSm ? "111px" : "17px",
|
||||
}}
|
||||
>
|
||||
<Typography sx={{ color: theme.palette.grey3.main, fontSize: upSm ? "20px" : "16px", fontWeight: 500 }}>
|
||||
{totalSum} руб.
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
borderLeft: upSm ? "1px solid #9A9AAF" : "none",
|
||||
paddingLeft: upSm ? "24px" : 0,
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<ExpandIcon isExpanded={isExpanded} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
{isExpanded &&
|
||||
Object.values(content).map(({ desc, id, privelegeid, amount, price }, index) => (
|
||||
<Box
|
||||
key={index}
|
||||
sx={{
|
||||
px: "20px",
|
||||
py: upMd ? "25px" : undefined,
|
||||
pt: upMd ? undefined : "15px",
|
||||
pb: upMd ? undefined : "25px",
|
||||
backgroundColor: "#F1F2F6",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
gap: "15px",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: upMd ? undefined : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
color: theme.palette.grey3.main,
|
||||
backgroundColor: "white",
|
||||
"&:first-of-type": {
|
||||
borderTopLeftRadius: "12px",
|
||||
borderTopRightRadius: "12px",
|
||||
},
|
||||
"&:last-of-type": {
|
||||
borderBottomLeftRadius: "12px",
|
||||
borderBottomRightRadius: "12px",
|
||||
},
|
||||
"&:not(:last-of-type)": {
|
||||
borderBottom: `1px solid ${theme.palette.grey2.main}`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{desc}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
gap: "10px",
|
||||
alignItems: "center",
|
||||
width: upSm ? "195px" : "123px",
|
||||
marginRight: upSm ? "65px" : 0,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
color: theme.palette.grey3.main,
|
||||
fontSize: upSm ? "20px" : "16px",
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{price} руб.
|
||||
</Typography>
|
||||
{upSm ? (
|
||||
<Typography
|
||||
component="div"
|
||||
onClick={() => remove(type, id)}
|
||||
>
|
||||
<Box
|
||||
onClick={() => setIsExpanded((prev) => !prev)}
|
||||
sx={{
|
||||
color: theme.palette.text.secondary,
|
||||
borderBottom: `1px solid ${theme.palette.text.secondary}`,
|
||||
width: "max-content",
|
||||
lineHeight: "19px",
|
||||
cursor: "pointer",
|
||||
height: "72px",
|
||||
px: "20px",
|
||||
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
cursor: "pointer",
|
||||
userSelect: "none",
|
||||
}}
|
||||
>
|
||||
Удалить
|
||||
</Typography>
|
||||
) : (
|
||||
<SvgIcon onClick={() => remove(type, id)} component={ClearIcon}></SvgIcon>
|
||||
)}
|
||||
</Box>
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: upMd ? "20px" : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
fontWeight: 500,
|
||||
color: theme.palette.text.secondary,
|
||||
px: 0,
|
||||
}}
|
||||
>
|
||||
{name[serviceData.serviceKey]}
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "flex-end",
|
||||
height: "100%",
|
||||
alignItems: "center",
|
||||
gap: upSm ? "111px" : "17px",
|
||||
}}
|
||||
>
|
||||
<Typography sx={{ color: theme.palette.grey3.main, fontSize: upSm ? "20px" : "16px", fontWeight: 500 }}>
|
||||
{currencyFormatter.format(serviceData.price / 100)}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
borderLeft: upSm ? "1px solid #9A9AAF" : "none",
|
||||
paddingLeft: upSm ? "24px" : 0,
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<ExpandIcon isExpanded={isExpanded} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
{isExpanded &&
|
||||
serviceData.privileges.map(privilege => (
|
||||
<Box
|
||||
key={privilege.tariffId + privilege.privilegeId}
|
||||
sx={{
|
||||
px: "20px",
|
||||
py: upMd ? "25px" : undefined,
|
||||
pt: upMd ? undefined : "15px",
|
||||
pb: upMd ? undefined : "25px",
|
||||
backgroundColor: "#F1F2F6",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
gap: "15px",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
fontSize: upMd ? undefined : "16px",
|
||||
lineHeight: upMd ? undefined : "19px",
|
||||
color: theme.palette.grey3.main,
|
||||
}}
|
||||
>
|
||||
{privilege.name}
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
gap: "10px",
|
||||
alignItems: "center",
|
||||
width: upSm ? "195px" : "123px",
|
||||
marginRight: upSm ? "65px" : 0,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
sx={{
|
||||
color: theme.palette.grey3.main,
|
||||
fontSize: upSm ? "20px" : "16px",
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{currencyFormatter.format(privilege.price / 100)}
|
||||
</Typography>
|
||||
{upSm ? (
|
||||
<Typography
|
||||
component="div"
|
||||
onClick={() => handleItemDeleteClick(privilege.tariffId)}
|
||||
sx={{
|
||||
color: theme.palette.text.secondary,
|
||||
borderBottom: `1px solid ${theme.palette.text.secondary}`,
|
||||
width: "max-content",
|
||||
lineHeight: "19px",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
Удалить
|
||||
</Typography>
|
||||
) : (
|
||||
<SvgIcon onClick={() => handleItemDeleteClick(privilege.tariffId)} component={ClearIcon}></SvgIcon>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
@ -1,10 +1,10 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { Box, Tabs, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
import SectionWrapper from "@components/SectionWrapper";
|
||||
import ComplexNavText from "@root/components/ComplexNavText";
|
||||
import { useTariffs } from "@root/utils/hooks/useTariffs";
|
||||
import { setTariffs, useTariffStore } from "@root/stores/tariffs";
|
||||
import { updateTariffs, useTariffStore } from "@root/stores/tariffs";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { CustomTab } from "@root/components/CustomTab";
|
||||
import TariffCard from "./TariffCard";
|
||||
@ -13,6 +13,7 @@ import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
import { calcTariffPrices } from "@root/utils/calcTariffPrices";
|
||||
import { getMessageFromFetchError } from "@frontend/kitui";
|
||||
import FreeTariffCard from "./FreeTariffCard";
|
||||
import { addTariffToCart } from "@root/stores/user";
|
||||
|
||||
|
||||
export default function TariffPage() {
|
||||
@ -27,16 +28,24 @@ export default function TariffPage() {
|
||||
const StepperText: Record<string, string> = { volume: "Тарифы на объём", time: "Тарифы на время" };
|
||||
|
||||
useTariffs({
|
||||
url: "https://admin.pena.digital/strator/tariff",
|
||||
apiPage: 0,
|
||||
tariffsPerPage: 100,
|
||||
onNewTariffs: setTariffs,
|
||||
onError: useCallback(error => {
|
||||
onNewTariffs: updateTariffs,
|
||||
onError: error => {
|
||||
const errorMessage = getMessageFromFetchError(error);
|
||||
if (errorMessage) enqueueSnackbar(errorMessage);
|
||||
}, [])
|
||||
}
|
||||
});
|
||||
|
||||
function handleTariffItemClick(tariffId: string) {
|
||||
addTariffToCart(tariffId).then(() => {
|
||||
enqueueSnackbar("Тариф добавлен в корзину");
|
||||
}).catch(error => {
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
});
|
||||
}
|
||||
|
||||
const filteredTariffs = tariffs.filter(tariff => {
|
||||
return tariff.privilegies.map(p => p.type).includes("day") === (unit === "time");
|
||||
});
|
||||
@ -55,7 +64,7 @@ export default function TariffPage() {
|
||||
buttonText="Выбрать"
|
||||
headerText={tariff.name}
|
||||
text={tariff.privilegies.map(p => `${p.name} - ${p.amount}`)}
|
||||
onButtonClick={undefined}
|
||||
onButtonClick={() => handleTariffItemClick(tariff._id)}
|
||||
price={<>
|
||||
{price !== undefined && price !== priceWithDiscounts &&
|
||||
<Typography variant="oldPrice">{currencyFormatter.format(price / 100)}</Typography>
|
||||
@ -68,8 +77,8 @@ export default function TariffPage() {
|
||||
);
|
||||
});
|
||||
|
||||
if (tariffElements.length < 6) tariffElements.push(<FreeTariffCard />);
|
||||
else tariffElements.splice(5, 0, <FreeTariffCard />);
|
||||
if (tariffElements.length < 6) tariffElements.push(<FreeTariffCard key="free_tariff_card" />);
|
||||
else tariffElements.splice(5, 0, <FreeTariffCard key="free_tariff_card" />);
|
||||
|
||||
return (
|
||||
<SectionWrapper
|
||||
|
80
src/stores/cart.ts
Normal file
80
src/stores/cart.ts
Normal file
@ -0,0 +1,80 @@
|
||||
import { CartData } from "@root/model/cart";
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
import { calcCart } from "@root/utils/calcCart";
|
||||
import { produce } from "immer";
|
||||
import { create } from "zustand";
|
||||
import { devtools } from "zustand/middleware";
|
||||
|
||||
|
||||
interface CartStore {
|
||||
cartTariffMap: Record<string, Tariff | "loading" | "not found">;
|
||||
cart: CartData;
|
||||
isDrawerOpen: boolean;
|
||||
}
|
||||
|
||||
export const useCartStore = create<CartStore>()(
|
||||
devtools(
|
||||
(get, set) => ({
|
||||
cartTariffMap: {},
|
||||
cart: {
|
||||
services: [],
|
||||
priceBeforeDiscounts: 0,
|
||||
priceAfterDiscounts: 0,
|
||||
itemCount: 0,
|
||||
},
|
||||
isDrawerOpen: false,
|
||||
}),
|
||||
{
|
||||
name: "Cart",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
trace: true,
|
||||
actionsBlacklist: "rejected",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const setCartTariffStatus = (tariffId: string, status: "loading" | "not found") => useCartStore.setState(
|
||||
produce<CartStore>(state => {
|
||||
state.cartTariffMap[tariffId] = status;
|
||||
}),
|
||||
false,
|
||||
{
|
||||
type: "setCartTariffStatus",
|
||||
tariffId,
|
||||
status,
|
||||
}
|
||||
);
|
||||
|
||||
export const addCartTariffs = (tariffs: Tariff[]) => useCartStore.setState(
|
||||
produce<CartStore>(state => {
|
||||
tariffs.forEach(tariff => {
|
||||
state.cartTariffMap[tariff._id] = tariff;
|
||||
});
|
||||
const cartTariffs = Object.values(state.cartTariffMap).filter((tariff): tariff is Tariff => typeof tariff === "object");
|
||||
state.cart = calcCart(cartTariffs);
|
||||
}),
|
||||
false,
|
||||
{
|
||||
type: tariffs.length > 0 ? "addCartTariffs" : "rejected",
|
||||
tariffIds: tariffs.map(tariff => tariff._id),
|
||||
}
|
||||
);
|
||||
|
||||
export const removeMissingTariffs = (tariffIds: string[]) => useCartStore.setState(
|
||||
produce<CartStore>(state => {
|
||||
for (const key in state.cartTariffMap) {
|
||||
if (!tariffIds.includes(key)) delete state.cartTariffMap[key];
|
||||
}
|
||||
const cartTariffs = Object.values(state.cartTariffMap).filter((tariff): tariff is Tariff => typeof tariff === "object");
|
||||
state.cart = calcCart(cartTariffs);
|
||||
}),
|
||||
false,
|
||||
{
|
||||
type: "removeMissingTariffs",
|
||||
tariffIds,
|
||||
}
|
||||
);
|
||||
|
||||
export const openCartDrawer = () => useCartStore.setState({ isDrawerOpen: true });
|
||||
|
||||
export const closeCartDrawer = () => useCartStore.setState({ isDrawerOpen: false });
|
@ -13,10 +13,34 @@ export const useTariffStore = create<TariffStore>()(
|
||||
tariffs: [],
|
||||
}),
|
||||
{
|
||||
name: "Tariff store",
|
||||
name: "Tariffs",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
trace: true,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const setTariffs = (tariffs: Tariff[]) => useTariffStore.setState({tariffs})
|
||||
export const updateTariffs = (tariffs: TariffStore["tariffs"]) => useTariffStore.setState(
|
||||
state => {
|
||||
const tariffMap: Record<string, Tariff> = {};
|
||||
|
||||
[...state.tariffs, ...tariffs].forEach(tariff => tariffMap[tariff._id] = tariff);
|
||||
|
||||
const sortedTariffs = Object.values(tariffMap).sort(sortTariffsByCreatedAt);
|
||||
|
||||
return { tariffs: sortedTariffs };
|
||||
},
|
||||
false,
|
||||
{
|
||||
type: "updateTariffs",
|
||||
tariffsLength: tariffs.length,
|
||||
}
|
||||
);
|
||||
|
||||
function sortTariffsByCreatedAt(tariff1: Tariff, tariff2: Tariff) {
|
||||
if (!tariff1.createdAt || !tariff2.createdAt) throw new Error("Trying to sort tariffs without createdAt field");
|
||||
|
||||
const date1 = new Date(tariff1.createdAt).getTime();
|
||||
const date2 = new Date(tariff2.createdAt).getTime();
|
||||
return date1 - date2;
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ import { StringSchema, string } from "yup";
|
||||
import { patchUser } from "@root/api/user";
|
||||
import { UserAccount, UserAccountSettingsFieldStatus, UserName, VerificationStatus } from "@root/model/account";
|
||||
import { patchUserAccount } from "@root/api/account";
|
||||
import { deleteCart, patchCart } from "@root/api/cart";
|
||||
|
||||
|
||||
interface UserStore {
|
||||
@ -60,7 +61,7 @@ const initialState: UserStore = {
|
||||
"ИНН": { ...defaultDocument },
|
||||
"Устав": { ...defaultDocument },
|
||||
"Свидетельство о регистрации НКО": { ...defaultDocument },
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export const useUserStore = create<UserStore>()(
|
||||
@ -68,8 +69,9 @@ export const useUserStore = create<UserStore>()(
|
||||
devtools(
|
||||
(set, get) => initialState,
|
||||
{
|
||||
name: "User store",
|
||||
name: "User",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
trace: true,
|
||||
}
|
||||
),
|
||||
{
|
||||
@ -108,6 +110,17 @@ export const setUserAccount = (user: UserAccount) => useUserStore.setState(
|
||||
state.settingsFields.secondname.value = user?.name.secondname ?? "";
|
||||
state.settingsFields.middlename.value = user?.name.middlename ?? "";
|
||||
state.settingsFields.orgname.value = user?.name.orgname ?? "";
|
||||
}),
|
||||
false,
|
||||
{
|
||||
type: "setUserAccount",
|
||||
payload: user,
|
||||
}
|
||||
);
|
||||
|
||||
export const setCart = (cart: string[]) => useUserStore.setState(
|
||||
produce<UserStore>(state => {
|
||||
if (state.userAccount) state.userAccount.cart = cart;
|
||||
})
|
||||
);
|
||||
|
||||
@ -203,7 +216,7 @@ export const setSettingsField = (
|
||||
state.settingsFields[fieldName].error = errorMessage;
|
||||
|
||||
state.settingsFields.hasError = Object.values(state.settingsFields).reduce((acc: boolean, field) => {
|
||||
if (typeof field == "boolean") return acc;
|
||||
if (typeof field === "boolean") return acc;
|
||||
|
||||
if (field.error !== null) return true;
|
||||
return acc;
|
||||
@ -239,13 +252,20 @@ export const sendUserData = async () => {
|
||||
orgname: state.settingsFields.orgname.value,
|
||||
};
|
||||
|
||||
const [user, userAccount] = await Promise.all([
|
||||
await Promise.all([
|
||||
isPatchingUser && patchUser(userPayload),
|
||||
isPatchingUserAccount && patchUserAccount(userAccountPayload),
|
||||
]);
|
||||
};
|
||||
|
||||
// if (user) setUser(user);
|
||||
// if (userAccount) setUserAccount(userAccount);
|
||||
export const addTariffToCart = async (tariffId: string) => {
|
||||
const result = await patchCart(tariffId);
|
||||
setCart(result);
|
||||
};
|
||||
|
||||
export const removeTariffFromCart = async (tariffId: string) => {
|
||||
const result = await deleteCart(tariffId);
|
||||
setCart(result);
|
||||
};
|
||||
|
||||
const validators: Record<UserSettingsField | keyof UserName, StringSchema> = {
|
||||
@ -256,18 +276,18 @@ const validators: Record<UserSettingsField | keyof UserName, StringSchema> = {
|
||||
skipAbsent: true,
|
||||
test(value, ctx) {
|
||||
if (value !== undefined) {
|
||||
if (value.length == 0) return true
|
||||
if (value.length === 0) return true;
|
||||
if (!/^[.,:;-_+\d\w]+$/.test(value)) {
|
||||
return ctx.createError({ message: 'Некорректные символы в пароле' })
|
||||
return ctx.createError({ message: 'Некорректные символы в пароле' });
|
||||
}
|
||||
if (value.length > 0 && value.length < 8) {
|
||||
return ctx.createError({ message: 'Минимум 8 символов' })
|
||||
return ctx.createError({ message: 'Минимум 8 символов' });
|
||||
}
|
||||
}
|
||||
return true
|
||||
return true;
|
||||
}
|
||||
}),
|
||||
// min(8, "Минимум 8 символов").matches(/^[.,:;-_+\d\w]+$/, "Некорректные символы в пароле"),
|
||||
}),
|
||||
// min(8, "Минимум 8 символов").matches(/^[.,:;-_+\d\w]+$/, "Некорректные символы в пароле"),
|
||||
firstname: string(),
|
||||
secondname: string(),
|
||||
middlename: string(),
|
||||
|
55
src/utils/calcCart.ts
Normal file
55
src/utils/calcCart.ts
Normal file
@ -0,0 +1,55 @@
|
||||
import { mockDiscounts } from "@root/__mocks__/discounts";
|
||||
import { CartData, PrivilegeCartData } from "@root/model/cart";
|
||||
import { AnyDiscount } from "@root/model/discount";
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
import { findPrivilegeDiscount, findServiceDiscount } from "./calcTariffPrices";
|
||||
|
||||
|
||||
export function calcCart(tariffs: Tariff[], discounts: AnyDiscount[] = mockDiscounts): CartData {
|
||||
const cartData: CartData = {
|
||||
services: [],
|
||||
priceBeforeDiscounts: 0,
|
||||
priceAfterDiscounts: 0,
|
||||
itemCount: 0,
|
||||
};
|
||||
|
||||
tariffs.forEach(tariff => {
|
||||
if (tariff.price && tariff.price > 0) cartData.priceBeforeDiscounts += tariff.price;
|
||||
|
||||
tariff.privilegies.forEach(privilege => {
|
||||
let serviceData = cartData.services.find(service => service.serviceKey === privilege.serviceKey);
|
||||
if (!serviceData) {
|
||||
serviceData = {
|
||||
serviceKey: privilege.serviceKey,
|
||||
privileges: [],
|
||||
price: 0,
|
||||
};
|
||||
cartData.services.push(serviceData);
|
||||
}
|
||||
|
||||
let privilegePrice = privilege.amount * privilege.price;
|
||||
|
||||
if (!tariff.price) cartData.priceBeforeDiscounts += privilegePrice;
|
||||
|
||||
const privilegeDiscount = findPrivilegeDiscount(privilege, discounts);
|
||||
if (privilegeDiscount) privilegePrice *= privilegeDiscount.target.products[0].factor;
|
||||
|
||||
const serviceDiscount = findServiceDiscount(privilege.serviceKey, privilegePrice, discounts);
|
||||
if (serviceDiscount) privilegePrice *= serviceDiscount.target.factor;
|
||||
|
||||
const privilegeData: PrivilegeCartData = {
|
||||
tariffId: tariff._id,
|
||||
privilegeId: privilege.privilegeId,
|
||||
name: privilege.description,
|
||||
price: privilegePrice,
|
||||
};
|
||||
|
||||
serviceData.privileges.push(privilegeData);
|
||||
serviceData.price += privilegePrice;
|
||||
cartData.priceAfterDiscounts += privilegePrice;
|
||||
cartData.itemCount++;
|
||||
});
|
||||
});
|
||||
|
||||
return cartData;
|
||||
}
|
@ -1,22 +1,22 @@
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
import { mockDiscounts } from "../__mocks__/discounts";
|
||||
import { PrivilegeWithAmount } from "@root/model/privilege";
|
||||
import { PrivilegeDiscount, ServiceDiscount } from "../model/discount";
|
||||
import { AnyDiscount, PrivilegeDiscount, ServiceDiscount } from "../model/discount";
|
||||
|
||||
|
||||
export function calcTariffPrices(tariff: Tariff): {
|
||||
export function calcTariffPrices(tariff: Tariff, discounts: AnyDiscount[] = mockDiscounts): {
|
||||
price: number | undefined;
|
||||
priceWithDiscounts: number | undefined;
|
||||
} {
|
||||
let price = tariff.price ?? tariff.privilegies.reduce((sum, privilege) => sum + privilege.amount * privilege.price, 0);
|
||||
let price = tariff.price || tariff.privilegies.reduce((sum, privilege) => sum + privilege.amount * privilege.price, 0);
|
||||
|
||||
const priceWithDiscounts = tariff.privilegies.reduce((sum, privilege) => {
|
||||
let privilegePrice = privilege.amount * privilege.price;
|
||||
|
||||
const privilegeDiscount = findPrivilegeDiscount(privilege);
|
||||
const privilegeDiscount = findPrivilegeDiscount(privilege, discounts);
|
||||
if (privilegeDiscount) privilegePrice *= privilegeDiscount.target.products[0].factor;
|
||||
|
||||
const serviceDiscount = findServiceDiscount(privilege.serviceKey, privilegePrice);
|
||||
const serviceDiscount = findServiceDiscount(privilege.serviceKey, privilegePrice, discounts);
|
||||
if (serviceDiscount) privilegePrice *= serviceDiscount.target.factor;
|
||||
|
||||
return sum + privilegePrice;
|
||||
@ -28,8 +28,8 @@ export function calcTariffPrices(tariff: Tariff): {
|
||||
};
|
||||
}
|
||||
|
||||
function findPrivilegeDiscount(privilege: PrivilegeWithAmount): PrivilegeDiscount | null {
|
||||
const applicableDiscounts = mockDiscounts.filter((discount): discount is PrivilegeDiscount => {
|
||||
export function findPrivilegeDiscount(privilege: PrivilegeWithAmount, discounts: AnyDiscount[]): PrivilegeDiscount | null {
|
||||
const applicableDiscounts = discounts.filter((discount): discount is PrivilegeDiscount => {
|
||||
return (
|
||||
discount.conditionType === "privilege" &&
|
||||
privilege.privilegeId === discount.condition.privilege.id &&
|
||||
@ -46,11 +46,12 @@ function findPrivilegeDiscount(privilege: PrivilegeWithAmount): PrivilegeDiscoun
|
||||
return maxValueDiscount;
|
||||
}
|
||||
|
||||
function findServiceDiscount(
|
||||
export function findServiceDiscount(
|
||||
serviceKey: string,
|
||||
currentPrice: number,
|
||||
discounts: AnyDiscount[],
|
||||
): ServiceDiscount | null {
|
||||
const discountsForTariffService = mockDiscounts.filter((discount): discount is ServiceDiscount => {
|
||||
const discountsForTariffService = discounts.filter((discount): discount is ServiceDiscount => {
|
||||
return (
|
||||
discount.conditionType === "service" &&
|
||||
discount.condition.service.id === serviceKey &&
|
||||
|
46
src/utils/hooks/useCart.ts
Normal file
46
src/utils/hooks/useCart.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import { devlog } from "@frontend/kitui";
|
||||
import { getTariffById } from "@root/api/tariff";
|
||||
import { useTariffStore } from "@root/stores/tariffs";
|
||||
import { useUserStore } from "@root/stores/user";
|
||||
import { useEffect } from "react";
|
||||
import { addCartTariffs, removeMissingTariffs, setCartTariffStatus, useCartStore } from "@root/stores/cart";
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
|
||||
|
||||
export function useCart() {
|
||||
const tariffs = useTariffStore(state => state.tariffs);
|
||||
const cartTariffMap = useCartStore(state => state.cartTariffMap);
|
||||
const cartTariffIds = useUserStore(state => state.userAccount?.cart);
|
||||
const cart = useCartStore(state => state.cart);
|
||||
|
||||
useEffect(function addTariffsToCart() {
|
||||
const knownTariffs: Tariff[] = [];
|
||||
|
||||
cartTariffIds?.forEach(tariffId => {
|
||||
if (typeof cartTariffMap[tariffId] === "object") return;
|
||||
|
||||
const tariff = tariffs.find(tariff => tariff._id === tariffId);
|
||||
if (tariff) return knownTariffs.push(tariff);
|
||||
|
||||
if (!cartTariffMap[tariffId]) {
|
||||
setCartTariffStatus(tariffId, "loading");
|
||||
|
||||
getTariffById(tariffId).then(tariff => {
|
||||
devlog("Unlisted tariff", tariff);
|
||||
addCartTariffs([tariff]);
|
||||
}).catch(error => {
|
||||
devlog(`Error fetching unlisted tariff ${tariffId}`, error);
|
||||
setCartTariffStatus(tariffId, "not found");
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (knownTariffs.length > 0) addCartTariffs(knownTariffs);
|
||||
}, [cartTariffIds, cartTariffMap, tariffs]);
|
||||
|
||||
useEffect(function cleanUpCart() {
|
||||
if (cartTariffIds) removeMissingTariffs(cartTariffIds);
|
||||
}, [cartTariffIds]);
|
||||
|
||||
return cart;
|
||||
}
|
@ -1,39 +1,36 @@
|
||||
import { devlog, makeRequest } from "@frontend/kitui";
|
||||
import { GetTariffsResponse, Tariff } from "@root/model/tariff";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
|
||||
export function useTariffs({ url, tariffsPerPage, apiPage, onNewTariffs, onError }: {
|
||||
url: string;
|
||||
export function useTariffs({ baseUrl = "https://admin.pena.digital/strator/tariff", tariffsPerPage, apiPage, onNewTariffs, onError }: {
|
||||
baseUrl?: string;
|
||||
tariffsPerPage: number;
|
||||
apiPage: number;
|
||||
onNewTariffs: (response: Tariff[]) => void;
|
||||
onError: (error: Error) => void;
|
||||
}) {
|
||||
const [fetchState, setFetchState] = useState<"fetching" | "idle" | "all fetched">("idle");
|
||||
const onNewTariffsRef = useRef<(response: Tariff[]) => void>(onNewTariffs);
|
||||
const onErrorRef = useRef<(error: Error) => void>(onError);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
setFetchState("fetching");
|
||||
makeRequest<never, GetTariffsResponse>({
|
||||
url,
|
||||
url: baseUrl + `?page=${apiPage}&limit=${tariffsPerPage}`,
|
||||
method: "get",
|
||||
useToken: true,
|
||||
signal: controller.signal,
|
||||
}).then((result) => {
|
||||
devlog("GetTicketsResponse", result);
|
||||
devlog("Tariffs", result);
|
||||
if (result.tariffs.length > 0) {
|
||||
onNewTariffs(result.tariffs);
|
||||
setFetchState("idle");
|
||||
} else setFetchState("all fetched");
|
||||
onNewTariffsRef.current(result.tariffs);
|
||||
}
|
||||
}).catch(error => {
|
||||
devlog("Error fetching tariffs", error);
|
||||
onError(error);
|
||||
onErrorRef.current(error);
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [onError, onNewTariffs, apiPage, tariffsPerPage, url]);
|
||||
|
||||
return fetchState;
|
||||
}, [apiPage, tariffsPerPage, baseUrl]);
|
||||
}
|
Loading…
Reference in New Issue
Block a user