upgrade kitui
use cart calc functions from kitui fix cart discount list display fix types
This commit is contained in:
parent
1f133351e5
commit
473f77568c
@ -6,7 +6,7 @@
|
|||||||
"@date-io/dayjs": "^2.15.0",
|
"@date-io/dayjs": "^2.15.0",
|
||||||
"@emotion/react": "^11.10.4",
|
"@emotion/react": "^11.10.4",
|
||||||
"@emotion/styled": "^11.10.4",
|
"@emotion/styled": "^11.10.4",
|
||||||
"@frontend/kitui": "^1.0.59",
|
"@frontend/kitui": "^1.0.77",
|
||||||
"@material-ui/pickers": "^3.3.10",
|
"@material-ui/pickers": "^3.3.10",
|
||||||
"@mui/icons-material": "^5.10.3",
|
"@mui/icons-material": "^5.10.3",
|
||||||
"@mui/material": "^5.10.5",
|
"@mui/material": "^5.10.5",
|
||||||
@ -36,6 +36,7 @@
|
|||||||
"numeral": "^2.0.6",
|
"numeral": "^2.0.6",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
|
"react-error-boundary": "^4.0.13",
|
||||||
"react-numeral": "^1.1.1",
|
"react-numeral": "^1.1.1",
|
||||||
"react-router-dom": "^6.3.0",
|
"react-router-dom": "^6.3.0",
|
||||||
"react-scripts": "^5.0.1",
|
"react-scripts": "^5.0.1",
|
||||||
|
@ -8,6 +8,8 @@ import type {
|
|||||||
DiscountType,
|
DiscountType,
|
||||||
GetDiscountResponse,
|
GetDiscountResponse,
|
||||||
} from "@root/model/discount";
|
} from "@root/model/discount";
|
||||||
|
import useSWR from "swr";
|
||||||
|
import { enqueueSnackbar } from "notistack";
|
||||||
|
|
||||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/price"
|
const baseUrl = process.env.REACT_APP_DOMAIN + "/price"
|
||||||
|
|
||||||
@ -213,3 +215,33 @@ export const requestDiscounts = async (): Promise<
|
|||||||
return [null, `Ошибка получения скидок. ${error}`];
|
return [null, `Ошибка получения скидок. ${error}`];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
async function getDiscounts() {
|
||||||
|
try {
|
||||||
|
const discountsResponse = await makeRequest<never, GetDiscountResponse>({
|
||||||
|
url: baseUrl + "/discounts",
|
||||||
|
method: "get",
|
||||||
|
useToken: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return discountsResponse.Discounts.filter((discount) => !discount.Deprecated);
|
||||||
|
} catch (nativeError) {
|
||||||
|
const [error] = parseAxiosError(nativeError);
|
||||||
|
|
||||||
|
throw new Error(`Ошибка получения списка скидок. ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDiscounts() {
|
||||||
|
const { data } = useSWR("discounts", getDiscounts, {
|
||||||
|
keepPreviousData: true,
|
||||||
|
suspense: true,
|
||||||
|
onError: (error) => {
|
||||||
|
if (!(error instanceof Error)) return;
|
||||||
|
|
||||||
|
enqueueSnackbar(error.message, { variant: "error" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import { makeRequest } from "@frontend/kitui";
|
import { CustomPrivilege, makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
import { parseAxiosError } from "@root/utils/parse-error";
|
import { parseAxiosError } from "@root/utils/parse-error";
|
||||||
|
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { Privilege } from "@frontend/kitui";
|
||||||
import type { TMockData } from "./roles";
|
import type { TMockData } from "./roles";
|
||||||
|
|
||||||
type SeverPrivilegesResponse = {
|
type SeverPrivilegesResponse = {
|
||||||
templategen: PrivilegeWithAmount[];
|
templategen: CustomPrivilege[];
|
||||||
squiz: PrivilegeWithAmount[];
|
squiz: CustomPrivilege[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator"
|
const baseUrl = process.env.REACT_APP_DOMAIN + "/strator"
|
||||||
@ -28,11 +28,11 @@ export const getRoles = async (): Promise<[TMockData | null, string?]> => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const putPrivilege = async (
|
export const putPrivilege = async (
|
||||||
body: Omit<PrivilegeWithAmount, "_id" | "updatedAt">
|
body: Omit<Privilege, "_id" | "updatedAt">
|
||||||
): Promise<[unknown, string?]> => {
|
): Promise<[unknown, string?]> => {
|
||||||
try {
|
try {
|
||||||
const putedPrivilege = await makeRequest<
|
const putedPrivilege = await makeRequest<
|
||||||
Omit<PrivilegeWithAmount, "_id" | "updatedAt">,
|
Omit<Privilege, "_id" | "updatedAt">,
|
||||||
unknown
|
unknown
|
||||||
>({
|
>({
|
||||||
url: baseUrl + "/privilege",
|
url: baseUrl + "/privilege",
|
||||||
@ -70,9 +70,9 @@ export const requestServicePrivileges = async (): Promise<
|
|||||||
|
|
||||||
export const requestPrivileges = async (
|
export const requestPrivileges = async (
|
||||||
signal: AbortSignal | undefined
|
signal: AbortSignal | undefined
|
||||||
): Promise<[PrivilegeWithAmount[], string?]> => {
|
): Promise<[CustomPrivilege[], string?]> => {
|
||||||
try {
|
try {
|
||||||
const privilegesResponse = await makeRequest<never, PrivilegeWithAmount[]>(
|
const privilegesResponse = await makeRequest<never, CustomPrivilege[]>(
|
||||||
{
|
{
|
||||||
url: baseUrl + "/privilege",
|
url: baseUrl + "/privilege",
|
||||||
method: "get",
|
method: "get",
|
||||||
|
@ -2,7 +2,7 @@ import { makeRequest } from "@frontend/kitui";
|
|||||||
|
|
||||||
import { parseAxiosError } from "@root/utils/parse-error";
|
import { parseAxiosError } from "@root/utils/parse-error";
|
||||||
|
|
||||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
import type { Privilege } from "@frontend/kitui";
|
||||||
import type { Tariff } from "@frontend/kitui";
|
import type { Tariff } from "@frontend/kitui";
|
||||||
import type { EditTariffRequestBody } from "@root/model/tariff";
|
import type { EditTariffRequestBody } from "@root/model/tariff";
|
||||||
|
|
||||||
@ -12,7 +12,7 @@ type CreateTariffBackendRequest = {
|
|||||||
order: number;
|
order: number;
|
||||||
price: number;
|
price: number;
|
||||||
isCustom: boolean;
|
isCustom: boolean;
|
||||||
privileges: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
privileges: Omit<Privilege, "_id" | "updatedAt">[];
|
||||||
};
|
};
|
||||||
|
|
||||||
type GetTariffsResponse = {
|
type GetTariffsResponse = {
|
||||||
@ -52,7 +52,7 @@ export const putTariff = async (tariff: Tariff): Promise<[null, string?]> => {
|
|||||||
price: tariff.price ?? 0,
|
price: tariff.price ?? 0,
|
||||||
isCustom: false,
|
isCustom: false,
|
||||||
order: tariff.order || 1,
|
order: tariff.order || 1,
|
||||||
description: tariff.description,
|
description: tariff.description ?? "",
|
||||||
privileges: tariff.privileges,
|
privileges: tariff.privileges,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
@ -1,36 +1,35 @@
|
|||||||
|
import { calcCart } from "@frontend/kitui";
|
||||||
|
import Input from "@kitUI/input";
|
||||||
import {
|
import {
|
||||||
Button,
|
|
||||||
Paper,
|
|
||||||
Box,
|
|
||||||
Typography,
|
|
||||||
TableHead,
|
|
||||||
TableRow,
|
|
||||||
TableCell,
|
|
||||||
TableBody,
|
|
||||||
Table,
|
|
||||||
Alert,
|
Alert,
|
||||||
|
Box,
|
||||||
|
Button,
|
||||||
Checkbox,
|
Checkbox,
|
||||||
FormControlLabel,
|
FormControlLabel,
|
||||||
useTheme, useMediaQuery
|
Paper,
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
Typography,
|
||||||
|
useMediaQuery,
|
||||||
|
useTheme
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import Input from "@kitUI/input";
|
import { requestDiscounts } from "@root/services/discounts.service";
|
||||||
import { useState } from "react";
|
import { requestPrivileges } from "@root/services/privilegies.service";
|
||||||
import { setCartData, useCartStore } from "@root/stores/cart";
|
import { setCartData, useCartStore } from "@root/stores/cart";
|
||||||
import { useTariffStore } from "@root/stores/tariffs";
|
import { useTariffStore } from "@root/stores/tariffs";
|
||||||
import { useDiscountStore } from "@root/stores/discounts";
|
|
||||||
import { requestPrivileges } from "@root/services/privilegies.service";
|
|
||||||
import { requestDiscounts } from "@root/services/discounts.service";
|
|
||||||
import { DiscountTooltip } from "./DiscountTooltip";
|
|
||||||
import CartItemRow from "./CartItemRow";
|
|
||||||
import { calcCart, formatDiscountFactor } from "@root/utils/calcCart/calcCart";
|
|
||||||
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
|
||||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||||
|
import { useState } from "react";
|
||||||
|
import CartItemRow from "./CartItemRow";
|
||||||
|
import { useDiscounts } from "@root/api/discounts";
|
||||||
|
|
||||||
|
|
||||||
export default function Cart() {
|
export default function Cart() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const mobile = useMediaQuery(theme.breakpoints.down(400));
|
const mobile = useMediaQuery(theme.breakpoints.down(400));
|
||||||
let discounts = useDiscountStore(state => state.discounts);
|
const discounts = useDiscounts();
|
||||||
const cartData = useCartStore((store) => store.cartData);
|
const cartData = useCartStore((store) => store.cartData);
|
||||||
const tariffs = useTariffStore(state => state.tariffs);
|
const tariffs = useTariffStore(state => state.tariffs);
|
||||||
const [couponField, setCouponField] = useState<string>("");
|
const [couponField, setCouponField] = useState<string>("");
|
||||||
@ -39,10 +38,6 @@ export default function Cart() {
|
|||||||
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||||
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
||||||
|
|
||||||
const cartDiscounts = [cartData?.appliedCartPurchasesDiscount, cartData?.appliedLoyaltyDiscount].filter((d): d is Discount => !!d);
|
|
||||||
|
|
||||||
const cartDiscountsResultFactor = findDiscountFactor(cartData?.appliedCartPurchasesDiscount) * findDiscountFactor(cartData?.appliedLoyaltyDiscount);
|
|
||||||
|
|
||||||
async function handleCalcCartClick() {
|
async function handleCalcCartClick() {
|
||||||
await requestPrivileges();
|
await requestPrivileges();
|
||||||
await requestDiscounts();
|
await requestDiscounts();
|
||||||
@ -224,45 +219,22 @@ export default function Cart() {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHead>
|
</TableHead>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{cartData.services.flatMap(service => service.tariffs.map(taroffCartData => (
|
{cartData.services.flatMap(service => service.tariffs.map(tariffCartData => {
|
||||||
|
const appliedDiscounts = tariffCartData.privileges.flatMap(
|
||||||
|
privilege => Array.from(privilege.appliedDiscounts)
|
||||||
|
).sort((a, b) => a.Layer - b.Layer);
|
||||||
|
|
||||||
|
return (
|
||||||
<CartItemRow
|
<CartItemRow
|
||||||
tariffCartData={taroffCartData}
|
key={tariffCartData.id}
|
||||||
appliedServiceDiscount={service.appliedServiceDiscount}
|
tariffCartData={tariffCartData}
|
||||||
|
appliedDiscounts={appliedDiscounts}
|
||||||
/>
|
/>
|
||||||
)))}
|
);
|
||||||
|
}))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
|
|
||||||
<Typography
|
|
||||||
id="transition-modal-title"
|
|
||||||
variant="h6"
|
|
||||||
sx={{
|
|
||||||
fontWeight: "normal",
|
|
||||||
textAlign: "center",
|
|
||||||
marginTop: "15px",
|
|
||||||
fontSize: "16px",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Скидки корзины:
|
|
||||||
{cartDiscounts && (
|
|
||||||
<Box
|
|
||||||
sx={{
|
|
||||||
display: "inline-flex",
|
|
||||||
flexWrap: "wrap",
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{cartDiscounts?.map((discount, index, arr) => (
|
|
||||||
<span key={discount.ID}>
|
|
||||||
<DiscountTooltip discount={discount} />
|
|
||||||
{index < arr.length - 1 && <span>, </span>}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
|
|
||||||
{cartDiscountsResultFactor && `= ${formatDiscountFactor(cartDiscountsResultFactor)}`}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</Typography>
|
|
||||||
|
|
||||||
<Typography
|
<Typography
|
||||||
id="transition-modal-title"
|
id="transition-modal-title"
|
||||||
variant="h6"
|
variant="h6"
|
||||||
|
@ -7,14 +7,12 @@ import { useEffect } from "react";
|
|||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
tariffCartData: TariffCartData;
|
tariffCartData: TariffCartData;
|
||||||
appliedServiceDiscount: Discount | null;
|
appliedDiscounts: Discount[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CartItemRow({ tariffCartData, appliedServiceDiscount }: Props) {
|
export default function CartItemRow({ tariffCartData, appliedDiscounts }: Props) {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
const envolvedDiscounts = [tariffCartData.privileges[0].appliedPrivilegeDiscount, appliedServiceDiscount].filter((d): d is Discount => !!d);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (tariffCartData.privileges.length > 1) {
|
if (tariffCartData.privileges.length > 1) {
|
||||||
console.warn(`Количество привилегий в тарифе ${tariffCartData.name}(${tariffCartData.id}) больше одного`);
|
console.warn(`Количество привилегий в тарифе ${tariffCartData.name}(${tariffCartData.id}) больше одного`);
|
||||||
@ -39,22 +37,17 @@ export default function CartItemRow({ tariffCartData, appliedServiceDiscount }:
|
|||||||
{tariffCartData.privileges[0].description}
|
{tariffCartData.privileges[0].description}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
{envolvedDiscounts.map((discount, index, arr) => (
|
{appliedDiscounts.map((discount, index, arr) => (
|
||||||
<span key={discount.ID}>
|
<span key={discount.ID}>
|
||||||
<DiscountTooltip discount={discount} />
|
<DiscountTooltip discount={discount} />
|
||||||
{index < arr.length - (appliedServiceDiscount ? 0 : 1) && (
|
{index < arr.length - 1 && (
|
||||||
<span>, </span>
|
<span>, </span>
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
))}
|
))}
|
||||||
{appliedServiceDiscount && (
|
|
||||||
<span>
|
|
||||||
<DiscountTooltip discount={appliedServiceDiscount} />
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
{currencyFormatter.format(tariffCartData.price)}
|
{currencyFormatter.format(tariffCartData.price / 100)}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
);
|
);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { Tooltip, Typography } from "@mui/material";
|
import { Tooltip, Typography } from "@mui/material";
|
||||||
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
import { Discount, findDiscountFactor } from "@frontend/kitui";
|
||||||
import { formatDiscountFactor } from "@root/utils/calcCart/calcCart";
|
import { formatDiscountFactor } from "@root/utils/formatDiscountFactor";
|
||||||
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@ -14,8 +14,9 @@ export function DiscountTooltip({ discount }: Props) {
|
|||||||
<Tooltip
|
<Tooltip
|
||||||
title={
|
title={
|
||||||
<>
|
<>
|
||||||
<Typography>Скидка: {discount?.Name}</Typography>
|
<Typography>Слой: {discount.Layer}</Typography>
|
||||||
<Typography>{discount?.Description}</Typography>
|
<Typography>Название: {discount.Name}</Typography>
|
||||||
|
<Typography>Описание: {discount.Description}</Typography>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { Privilege } from "@frontend/kitui";
|
||||||
|
|
||||||
export const SERVICE_LIST = [
|
export const SERVICE_LIST = [
|
||||||
{
|
{
|
||||||
@ -25,5 +25,5 @@ export type EditTariffRequestBody = {
|
|||||||
order: number;
|
order: number;
|
||||||
price: number;
|
price: number;
|
||||||
isCustom: boolean;
|
isCustom: boolean;
|
||||||
privileges: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
privileges: Omit<Privilege, "_id" | "updatedAt">[];
|
||||||
};
|
};
|
||||||
|
@ -2,14 +2,14 @@ import { KeyboardEvent, useRef, useState } from "react";
|
|||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import {Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme} from "@mui/material";
|
import {Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme} from "@mui/material";
|
||||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { CustomPrivilege } from "@frontend/kitui";
|
||||||
import { putPrivilege } from "@root/api/privilegies";
|
import { putPrivilege } from "@root/api/privilegies";
|
||||||
import SaveIcon from '@mui/icons-material/Save';
|
import SaveIcon from '@mui/icons-material/Save';
|
||||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||||
|
|
||||||
|
|
||||||
interface CardPrivilege {
|
interface CardPrivilege {
|
||||||
privilege: PrivilegeWithAmount;
|
privilege: CustomPrivilege;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
||||||
@ -27,7 +27,7 @@ export const СardPrivilege = ({ privilege }: CardPrivilege) => {
|
|||||||
|
|
||||||
const putPrivileges = async () => {
|
const putPrivileges = async () => {
|
||||||
|
|
||||||
const [_, putedPrivilegeError] = await putPrivilege({
|
const [, putedPrivilegeError] = await putPrivilege({
|
||||||
name: privilege.name,
|
name: privilege.name,
|
||||||
privilegeId: privilege.privilegeId,
|
privilegeId: privilege.privilegeId,
|
||||||
serviceKey: privilege.serviceKey,
|
serviceKey: privilege.serviceKey,
|
||||||
|
@ -6,6 +6,7 @@ import { changeDiscount } from "@root/api/discounts";
|
|||||||
import { findDiscountsById } from "@root/stores/discounts";
|
import { findDiscountsById } from "@root/stores/discounts";
|
||||||
|
|
||||||
import { requestDiscounts } from "@root/services/discounts.service";
|
import { requestDiscounts } from "@root/services/discounts.service";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
selectedRows: GridSelectionModel;
|
selectedRows: GridSelectionModel;
|
||||||
@ -24,7 +25,7 @@ export default function DiscountDataGrid({ selectedRows }: Props) {
|
|||||||
return enqueueSnackbar("Скидка не найдена");
|
return enqueueSnackbar("Скидка не найдена");
|
||||||
}
|
}
|
||||||
|
|
||||||
const [_, changedDiscountError] = await changeDiscount(String(id), {
|
const [, changedDiscountError] = await changeDiscount(String(id), {
|
||||||
...discount,
|
...discount,
|
||||||
Deprecated: isActive,
|
Deprecated: isActive,
|
||||||
});
|
});
|
||||||
@ -34,6 +35,7 @@ export default function DiscountDataGrid({ selectedRows }: Props) {
|
|||||||
} else {
|
} else {
|
||||||
fatal += 1;
|
fatal += 1;
|
||||||
}
|
}
|
||||||
|
mutate("discounts");
|
||||||
}
|
}
|
||||||
|
|
||||||
await requestDiscounts();
|
await requestDiscounts();
|
||||||
|
@ -23,6 +23,7 @@ import { DiscountType, discountTypes } from "@root/model/discount";
|
|||||||
import { createDiscount } from "@root/api/discounts";
|
import { createDiscount } from "@root/api/discounts";
|
||||||
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||||
import { Formik, Field, Form, FormikHelpers } from "formik";
|
import { Formik, Field, Form, FormikHelpers } from "formik";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
interface Values {
|
interface Values {
|
||||||
discountNameField: string,
|
discountNameField: string,
|
||||||
@ -92,6 +93,7 @@ export default function CreateDiscount() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (createdDiscountResponse) {
|
if (createdDiscountResponse) {
|
||||||
|
mutate("discounts");
|
||||||
addDiscount(createdDiscountResponse);
|
addDiscount(createdDiscountResponse);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,8 @@ import { deleteDiscount } from "@root/api/discounts";
|
|||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
import { requestDiscounts } from "@root/services/discounts.service";
|
import { requestDiscounts } from "@root/services/discounts.service";
|
||||||
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||||
import { formatDiscountFactor } from "@root/utils/calcCart/calcCart";
|
import { formatDiscountFactor } from "@root/utils/formatDiscountFactor";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
// {
|
// {
|
||||||
@ -93,6 +94,7 @@ const columns: GridColDef[] = [
|
|||||||
disabled={row.deleted}
|
disabled={row.deleted}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
deleteDiscount(row.id).then(([discount]) => {
|
deleteDiscount(row.id).then(([discount]) => {
|
||||||
|
mutate("discounts");
|
||||||
if (discount) {
|
if (discount) {
|
||||||
updateDiscount(discount);
|
updateDiscount(discount);
|
||||||
}
|
}
|
||||||
|
@ -31,6 +31,7 @@ import { getDiscountTypeFromLayer } from "@root/utils/discount";
|
|||||||
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
import usePrivileges from "@root/utils/hooks/usePrivileges";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { mutate } from "swr";
|
||||||
|
|
||||||
export default function EditDiscountDialog() {
|
export default function EditDiscountDialog() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
@ -59,17 +60,17 @@ export default function EditDiscountDialog() {
|
|||||||
function setDiscountFields() {
|
function setDiscountFields() {
|
||||||
if (!discount) return;
|
if (!discount) return;
|
||||||
|
|
||||||
setServiceType(discount.Condition.Group);
|
setServiceType(discount.Condition.Group ?? "");
|
||||||
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
|
setDiscountType(getDiscountTypeFromLayer(discount.Layer));
|
||||||
setDiscountNameField(discount.Name);
|
setDiscountNameField(discount.Name);
|
||||||
setDiscountDescriptionField(discount.Description);
|
setDiscountDescriptionField(discount.Description);
|
||||||
setPrivilegeIdField(discount.Condition.Product);
|
setPrivilegeIdField(discount.Condition.Product ?? "");
|
||||||
setDiscountFactorField(((1 - discount.Target.Factor) * 100).toFixed(2));
|
setDiscountFactorField(((1 - discount.Target.Factor) * 100).toFixed(2));
|
||||||
setPurchasesAmountField(discount.Condition.PurchasesAmount.toString());
|
setPurchasesAmountField(discount.Condition.PurchasesAmount ?? "");
|
||||||
setCartPurchasesAmountField(
|
setCartPurchasesAmountField(
|
||||||
discount.Condition.CartPurchasesAmount.toString()
|
discount.Condition.CartPurchasesAmount ?? ""
|
||||||
);
|
);
|
||||||
setDiscountMinValueField(discount.Condition.PriceFrom.toString());
|
setDiscountMinValueField(discount.Condition.PriceFrom ?? "");
|
||||||
},
|
},
|
||||||
[discount]
|
[discount]
|
||||||
);
|
);
|
||||||
@ -137,6 +138,7 @@ export default function EditDiscountDialog() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (patchedDiscountResponse) {
|
if (patchedDiscountResponse) {
|
||||||
|
mutate("discounts");
|
||||||
updateDiscount(patchedDiscountResponse);
|
updateDiscount(patchedDiscountResponse);
|
||||||
closeEditDiscountDialog();
|
closeEditDiscountDialog();
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@ import {
|
|||||||
findPrivilegeById,
|
findPrivilegeById,
|
||||||
usePrivilegeStore,
|
usePrivilegeStore,
|
||||||
} from "@root/stores/privilegesStore";
|
} from "@root/stores/privilegesStore";
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { Privilege } from "@frontend/kitui";
|
||||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||||
import { Formik, Field, Form, FormikHelpers } from "formik";
|
import { Formik, Field, Form, FormikHelpers } from "formik";
|
||||||
|
|
||||||
@ -28,7 +28,7 @@ interface Values {
|
|||||||
customPriceField: string,
|
customPriceField: string,
|
||||||
privilegeIdField: string,
|
privilegeIdField: string,
|
||||||
orderField: number,
|
orderField: number,
|
||||||
privilege: PrivilegeWithAmount | null
|
privilege: Privilege | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CreateTariff() {
|
export default function CreateTariff() {
|
||||||
@ -68,7 +68,7 @@ export default function CreateTariff() {
|
|||||||
formikHelpers: FormikHelpers<Values>
|
formikHelpers: FormikHelpers<Values>
|
||||||
) => {
|
) => {
|
||||||
if (values.privilege !== null) {
|
if (values.privilege !== null) {
|
||||||
const [_, createdTariffError] = await createTariff({
|
const [, createdTariffError] = await createTariff({
|
||||||
name: values.nameField,
|
name: values.nameField,
|
||||||
price: Number(values.customPriceField) * 100,
|
price: Number(values.customPriceField) * 100,
|
||||||
order: values.orderField,
|
order: values.orderField,
|
||||||
@ -185,7 +185,7 @@ export default function CreateTariff() {
|
|||||||
{privileges.map((privilege) => (
|
{privileges.map((privilege) => (
|
||||||
<MenuItem
|
<MenuItem
|
||||||
data-cy={`select-option-${privilege.description}`}
|
data-cy={`select-option-${privilege.description}`}
|
||||||
key={privilege.description}
|
key={privilege._id}
|
||||||
value={privilege._id}
|
value={privilege._id}
|
||||||
sx={{whiteSpace: "normal", wordBreak: "break-world"}}
|
sx={{whiteSpace: "normal", wordBreak: "break-world"}}
|
||||||
>
|
>
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
import { Typography } from "@mui/material";
|
import { CircularProgress, Typography } from "@mui/material";
|
||||||
import Cart from "@root/kitUI/Cart/Cart";
|
import Cart from "@root/kitUI/Cart/Cart";
|
||||||
import TariffsDG from "./tariffsDG";
|
import TariffsDG from "./tariffsDG";
|
||||||
|
import { Suspense } from "react";
|
||||||
|
import { ErrorBoundary } from "react-error-boundary";
|
||||||
|
|
||||||
|
|
||||||
export default function TariffsInfo() {
|
export default function TariffsInfo() {
|
||||||
@ -11,7 +13,11 @@ export default function TariffsInfo() {
|
|||||||
Список тарифов
|
Список тарифов
|
||||||
</Typography>
|
</Typography>
|
||||||
<TariffsDG />
|
<TariffsDG />
|
||||||
|
<ErrorBoundary fallback={<Typography>Что-то пошло не так</Typography>}>
|
||||||
|
<Suspense fallback={<CircularProgress />}>
|
||||||
<Cart />
|
<Cart />
|
||||||
|
</Suspense>
|
||||||
|
</ErrorBoundary>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -34,7 +34,7 @@ const columns: GridColDef<Tariff, string | number>[] = [
|
|||||||
{ field: "type", headerName: "Единица", width: 100, valueGetter: ({ row }) => row.privileges[0].type },
|
{ field: "type", headerName: "Единица", width: 100, valueGetter: ({ row }) => row.privileges[0].type },
|
||||||
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100, valueGetter: ({ row }) => currencyFormatter.format(row.privileges[0].price / 100) },
|
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100, valueGetter: ({ row }) => currencyFormatter.format(row.privileges[0].price / 100) },
|
||||||
{ field: "isCustom", headerName: "Кастомная цена", width: 130, valueGetter: ({ row }) => row.isCustom ? "Да" : "Нет" },
|
{ field: "isCustom", headerName: "Кастомная цена", width: 130, valueGetter: ({ row }) => row.isCustom ? "Да" : "Нет" },
|
||||||
{ field: "total", headerName: "Сумма", width: 60, valueGetter: ({ row }) => currencyFormatter.format(getTariffPrice(row) / 100) },
|
{ field: "total", headerName: "Сумма", width: 100, valueGetter: ({ row }) => currencyFormatter.format(getTariffPrice(row) / 100) },
|
||||||
{
|
{
|
||||||
field: "delete",
|
field: "delete",
|
||||||
headerName: "Удаление",
|
headerName: "Удаление",
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
||||||
import { requestServicePrivileges } from "@root/api/privilegies";
|
import { requestServicePrivileges } from "@root/api/privilegies";
|
||||||
|
|
||||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
import type { CustomPrivilege } from "@frontend/kitui";
|
||||||
|
|
||||||
const mutatePrivileges = (privileges: PrivilegeWithAmount[]) => {
|
const mutatePrivileges = (privileges: CustomPrivilege[]) => {
|
||||||
let extracted: PrivilegeWithAmount[] = [];
|
let extracted: CustomPrivilege[] = [];
|
||||||
for (let serviceKey in privileges) {
|
for (let serviceKey in privileges) {
|
||||||
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
||||||
extracted = extracted.concat(privileges[serviceKey]);
|
extracted = extracted.concat(privileges[serviceKey]);
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { devtools } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
import { CustomPrivilege } from "@frontend/kitui";
|
||||||
|
|
||||||
|
|
||||||
interface PrivilegeStore {
|
interface PrivilegeStore {
|
||||||
privileges: PrivilegeWithAmount[];
|
privileges: CustomPrivilege[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -1,82 +0,0 @@
|
|||||||
import { CartData, Discount, PrivilegeCartData, Tariff, TariffCartData, applyCartDiscount, applyLoyaltyDiscount, applyPrivilegeDiscounts, applyServiceDiscounts } from "@frontend/kitui";
|
|
||||||
|
|
||||||
|
|
||||||
export function calcCart(
|
|
||||||
tariffs: Tariff[],
|
|
||||||
discounts: Discount[],
|
|
||||||
purchasesAmount: number,
|
|
||||||
coupon?: string,
|
|
||||||
): CartData {
|
|
||||||
const cartData: CartData = {
|
|
||||||
services: [],
|
|
||||||
priceBeforeDiscounts: 0,
|
|
||||||
priceAfterDiscounts: 0,
|
|
||||||
itemCount: 0,
|
|
||||||
appliedCartPurchasesDiscount: null,
|
|
||||||
appliedLoyaltyDiscount: null,
|
|
||||||
allAppliedDiscounts: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
const serviceTariffType: Record<string, number> = {};
|
|
||||||
|
|
||||||
tariffs.forEach(tariff => {
|
|
||||||
let serviceData = cartData.services.find(service => service.serviceKey === tariff.privileges[0].serviceKey);
|
|
||||||
if (!serviceData) {
|
|
||||||
serviceData = {
|
|
||||||
serviceKey: tariff.privileges[0].serviceKey,
|
|
||||||
tariffs: [],
|
|
||||||
price: 0,
|
|
||||||
appliedServiceDiscount: null,
|
|
||||||
};
|
|
||||||
cartData.services.push(serviceData);
|
|
||||||
}
|
|
||||||
|
|
||||||
const tariffCartData: TariffCartData = {
|
|
||||||
price: tariff.price ?? 0,
|
|
||||||
isCustom: tariff.isCustom,
|
|
||||||
privileges: [],
|
|
||||||
id: tariff._id,
|
|
||||||
name: tariff.name,
|
|
||||||
};
|
|
||||||
serviceData.tariffs.push(tariffCartData);
|
|
||||||
|
|
||||||
tariff.privileges.forEach(privilege => {
|
|
||||||
serviceTariffType[privilege.serviceKey] ??= +tariff.isCustom;
|
|
||||||
const isIncompatibleTariffs = serviceTariffType[privilege.serviceKey] ^ +tariff.isCustom;
|
|
||||||
if (isIncompatibleTariffs) throw new Error("Если взят готовый тариф, то кастомный на этот сервис сделать уже нельзя");
|
|
||||||
|
|
||||||
const privilegePrice = privilege.amount * privilege.price;
|
|
||||||
|
|
||||||
if (!tariff.price) tariffCartData.price += privilegePrice;
|
|
||||||
|
|
||||||
const privilegeCartData: PrivilegeCartData = {
|
|
||||||
serviceKey: privilege.serviceKey,
|
|
||||||
amount: privilege.amount,
|
|
||||||
privilegeId: privilege.privilegeId,
|
|
||||||
description: privilege.description,
|
|
||||||
price: privilegePrice,
|
|
||||||
appliedPrivilegeDiscount: null,
|
|
||||||
};
|
|
||||||
|
|
||||||
tariffCartData.privileges.push(privilegeCartData);
|
|
||||||
cartData.priceAfterDiscounts += privilegePrice;
|
|
||||||
cartData.itemCount++;
|
|
||||||
});
|
|
||||||
|
|
||||||
cartData.priceBeforeDiscounts += tariffCartData.price;
|
|
||||||
serviceData.price += tariffCartData.price;
|
|
||||||
});
|
|
||||||
|
|
||||||
applyPrivilegeDiscounts(cartData, discounts);
|
|
||||||
applyServiceDiscounts(cartData, discounts);
|
|
||||||
applyCartDiscount(cartData, discounts);
|
|
||||||
applyLoyaltyDiscount(cartData, discounts, purchasesAmount);
|
|
||||||
|
|
||||||
cartData.allAppliedDiscounts = Array.from(new Set(cartData.allAppliedDiscounts));
|
|
||||||
|
|
||||||
return cartData;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatDiscountFactor(factor: number): string {
|
|
||||||
return `${((1 - factor) * 100).toFixed(1)}%`;
|
|
||||||
}
|
|
3
src/utils/formatDiscountFactor.ts
Normal file
3
src/utils/formatDiscountFactor.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export function formatDiscountFactor(factor: number): string {
|
||||||
|
return `${((1 - factor) * 100).toFixed(1)}%`;
|
||||||
|
}
|
@ -2,13 +2,13 @@ import { useEffect } from "react";
|
|||||||
|
|
||||||
import { requestPrivileges } from "@root/api/privilegies";
|
import { requestPrivileges } from "@root/api/privilegies";
|
||||||
|
|
||||||
import type { PrivilegeWithAmount } from "@frontend/kitui";
|
import type { CustomPrivilege } from "@frontend/kitui";
|
||||||
|
|
||||||
export default function usePrivileges({
|
export default function usePrivileges({
|
||||||
onError,
|
onError,
|
||||||
onNewPrivileges,
|
onNewPrivileges,
|
||||||
}: {
|
}: {
|
||||||
onNewPrivileges: (response: PrivilegeWithAmount[]) => void;
|
onNewPrivileges: (response: CustomPrivilege[]) => void;
|
||||||
onError?: (error: any) => void;
|
onError?: (error: any) => void;
|
||||||
}) {
|
}) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -19,7 +19,6 @@ export default function usePrivileges({
|
|||||||
if (privilegesError) {
|
if (privilegesError) {
|
||||||
return onError?.(privilegesError);
|
return onError?.(privilegesError);
|
||||||
}
|
}
|
||||||
|
|
||||||
onNewPrivileges(privilegesResponse);
|
onNewPrivileges(privilegesResponse);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
15
yarn.lock
15
yarn.lock
@ -1433,10 +1433,10 @@
|
|||||||
lodash.isundefined "^3.0.1"
|
lodash.isundefined "^3.0.1"
|
||||||
lodash.uniq "^4.5.0"
|
lodash.uniq "^4.5.0"
|
||||||
|
|
||||||
"@frontend/kitui@^1.0.59":
|
"@frontend/kitui@^1.0.77":
|
||||||
version "1.0.59"
|
version "1.0.77"
|
||||||
resolved "https://penahub.gitlab.yandexcloud.net/api/v4/projects/21/packages/npm/@frontend/kitui/-/@frontend/kitui-1.0.59.tgz#c4584506bb5cab4fc1df35f5b1d0d66ec379a9a1"
|
resolved "https://penahub.gitlab.yandexcloud.net/api/v4/projects/21/packages/npm/@frontend/kitui/-/@frontend/kitui-1.0.77.tgz#a749dee0e7622b4c4509e8354ace47299b0606f7"
|
||||||
integrity sha1-xFhFBrtcq0/B3zX1sdDWbsN5qaE=
|
integrity sha1-p0ne4OdiK0xFCeg1Ss5HKZsGBvc=
|
||||||
dependencies:
|
dependencies:
|
||||||
immer "^10.0.2"
|
immer "^10.0.2"
|
||||||
reconnecting-eventsource "^1.6.2"
|
reconnecting-eventsource "^1.6.2"
|
||||||
@ -10472,6 +10472,13 @@ react-dom@^18.2.0:
|
|||||||
loose-envify "^1.1.0"
|
loose-envify "^1.1.0"
|
||||||
scheduler "^0.23.0"
|
scheduler "^0.23.0"
|
||||||
|
|
||||||
|
react-error-boundary@^4.0.13:
|
||||||
|
version "4.0.13"
|
||||||
|
resolved "https://registry.yarnpkg.com/react-error-boundary/-/react-error-boundary-4.0.13.tgz#80386b7b27b1131c5fbb7368b8c0d983354c7947"
|
||||||
|
integrity sha512-b6PwbdSv8XeOSYvjt8LpgpKrZ0yGdtZokYwkwV2wlcZbxgopHX/hgPl5VgpnoVOWd868n1hktM8Qm4b+02MiLQ==
|
||||||
|
dependencies:
|
||||||
|
"@babel/runtime" "^7.12.5"
|
||||||
|
|
||||||
react-error-overlay@^6.0.11:
|
react-error-overlay@^6.0.11:
|
||||||
version "6.0.11"
|
version "6.0.11"
|
||||||
resolved "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-6.0.11.tgz"
|
resolved "https://registry.npmjs.org/react-error-overlay/-/react-error-overlay-6.0.11.tgz"
|
||||||
|
Loading…
Reference in New Issue
Block a user