use kitui package
This commit is contained in:
parent
3cbcac35b9
commit
3de7db153b
1
.yarnrc
Normal file
1
.yarnrc
Normal file
@ -0,0 +1 @@
|
||||
"@frontend:registry" "https://penahub.gitlab.yandexcloud.net/api/v4/packages/npm/"
|
38015
package-lock.json
generated
38015
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -6,6 +6,7 @@
|
||||
"@date-io/dayjs": "^2.15.0",
|
||||
"@emotion/react": "^11.10.4",
|
||||
"@emotion/styled": "^11.10.4",
|
||||
"@frontend/kitui": "^1.0.17",
|
||||
"@material-ui/pickers": "^3.3.10",
|
||||
"@mui/icons-material": "^5.10.3",
|
||||
"@mui/material": "^5.10.5",
|
||||
@ -22,7 +23,7 @@
|
||||
"@types/react": "^18.0.18",
|
||||
"@types/react-dom": "^18.0.6",
|
||||
"@types/react-router-dom": "^5.3.3",
|
||||
"axios": "^1.3.4",
|
||||
"axios": "^1.4.0",
|
||||
"craco": "^0.0.3",
|
||||
"dayjs": "^1.11.5",
|
||||
"formik": "^2.2.9",
|
||||
@ -40,7 +41,7 @@
|
||||
"styled-components": "^5.3.5",
|
||||
"typescript": "^4.8.2",
|
||||
"web-vitals": "^2.1.4",
|
||||
"zustand": "^4.1.1"
|
||||
"zustand": "^4.3.8"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "craco start",
|
||||
|
@ -1,12 +1,9 @@
|
||||
import { CreateDiscountBody, Discount, DiscountType } from "@root/model/discount";
|
||||
import { ServiceType } from "@root/model/tariff";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { Discount, makeRequest } from "@frontend/kitui";
|
||||
import { CreateDiscountBody, DiscountType } from "@root/model/discount";
|
||||
|
||||
|
||||
const baseUrl = process.env.NODE_ENV === "production" ? "/price" : "https://admin.pena.digital/price";
|
||||
|
||||
const makeRequest = authStore.getState().makeRequest;
|
||||
|
||||
export function createDiscount(discountParams: CreateDiscountParams) {
|
||||
const discount = createDiscountObject(discountParams);
|
||||
|
||||
@ -14,7 +11,6 @@ export function createDiscount(discountParams: CreateDiscountParams) {
|
||||
url: baseUrl + "/discount",
|
||||
method: "post",
|
||||
useToken: true,
|
||||
bearer: true,
|
||||
body: discount,
|
||||
});
|
||||
};
|
||||
@ -24,7 +20,6 @@ export function deleteDiscount(discountId: string) {
|
||||
url: baseUrl + "/discount/" + discountId,
|
||||
method: "delete",
|
||||
useToken: true,
|
||||
bearer: true,
|
||||
});
|
||||
}
|
||||
|
||||
@ -35,7 +30,6 @@ export function patchDiscount(discountId: string, discountParams: CreateDiscount
|
||||
url: baseUrl + "/discount/" + discountId,
|
||||
method: "patch",
|
||||
useToken: true,
|
||||
bearer: true,
|
||||
body: discount,
|
||||
});
|
||||
}
|
||||
@ -51,7 +45,7 @@ interface CreateDiscountParams {
|
||||
startDate: string;
|
||||
/** ISO string */
|
||||
endDate: string;
|
||||
serviceType: ServiceType;
|
||||
serviceType: string;
|
||||
discountType: DiscountType;
|
||||
privilegeId: string;
|
||||
}
|
||||
@ -134,12 +128,11 @@ export function createDiscountObject({
|
||||
return discount;
|
||||
}
|
||||
|
||||
export function changeDiscount (discountId:string, discount:Discount) {
|
||||
export function changeDiscount(discountId: string, discount: Discount) {
|
||||
return makeRequest<Discount>({
|
||||
url: baseUrl + "/discount/" + discountId,
|
||||
method: "patch",
|
||||
useToken: true,
|
||||
bearer: true,
|
||||
body: discount,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
44
src/api/tariffs.ts
Normal file
44
src/api/tariffs.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { Tariff, makeRequest } from "@frontend/kitui";
|
||||
import { EditTariffRequestBody } from "@root/model/tariff";
|
||||
|
||||
|
||||
const baseUrl = process.env.NODE_ENV === "production" ? "/strator" : "https://admin.pena.digital/strator";
|
||||
|
||||
export function putTariff(tariff: Tariff) {
|
||||
return makeRequest<EditTariffRequestBody, never>({
|
||||
method: "put",
|
||||
url: baseUrl + `/tariff/${tariff._id}`,
|
||||
body: {
|
||||
name: tariff.name,
|
||||
price: tariff.price ?? 0,
|
||||
isCustom: false,
|
||||
privilegies: tariff.privilegies,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteTariff(tariffId: string) {
|
||||
return makeRequest<{ id: string; }, never>({
|
||||
method: "delete",
|
||||
url: baseUrl + "/tariff",
|
||||
body: { id: tariffId },
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteManyTariffs(tariffIds: string[]) {
|
||||
const results = await Promise.allSettled(tariffIds.map(tariffId => deleteTariff(tariffId)));
|
||||
|
||||
let deletedCount = 0;
|
||||
let errorCount = 0;
|
||||
const errors: unknown[] = [];
|
||||
|
||||
results.forEach(result => {
|
||||
if (result.status === "fulfilled") deletedCount++;
|
||||
else {
|
||||
errorCount++;
|
||||
errors.push(result.reason);
|
||||
}
|
||||
});
|
||||
|
||||
return { deletedCount, errorCount, errors };
|
||||
}
|
@ -1,88 +1,9 @@
|
||||
import {
|
||||
GetMessagesRequest,
|
||||
GetMessagesResponse,
|
||||
GetTicketsRequest,
|
||||
GetTicketsResponse,
|
||||
SendTicketMessageRequest,
|
||||
} from "@root/model/ticket";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import ReconnectingEventSource from "reconnecting-eventsource";
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
import { SendTicketMessageRequest } from "@root/model/ticket";
|
||||
|
||||
|
||||
const supportApiUrl = "https://admin.pena.digital/heruvym";
|
||||
|
||||
const makeRequest = authStore.getState().makeRequest;
|
||||
|
||||
export function subscribeToAllTickets({
|
||||
onMessage,
|
||||
onError,
|
||||
accessToken,
|
||||
}: {
|
||||
accessToken: string;
|
||||
onMessage: (e: MessageEvent) => void;
|
||||
onError: (e: Event) => void;
|
||||
}) {
|
||||
const url = `${supportApiUrl}/subscribe?Authorization=${accessToken}`;
|
||||
|
||||
const eventSource = createEventSource(onMessage, onError, url);
|
||||
|
||||
return () => {
|
||||
eventSource.close();
|
||||
};
|
||||
}
|
||||
|
||||
export function subscribeToTicketMessages({
|
||||
onMessage,
|
||||
onError,
|
||||
accessToken,
|
||||
ticketId,
|
||||
}: {
|
||||
accessToken: string;
|
||||
ticketId: string;
|
||||
onMessage: (e: MessageEvent) => void;
|
||||
onError: (e: Event) => void;
|
||||
}) {
|
||||
const url = `${supportApiUrl}/ticket?ticket=${ticketId}&Authorization=${accessToken}`;
|
||||
|
||||
const eventSource = createEventSource(onMessage, onError, url);
|
||||
|
||||
return () => {
|
||||
eventSource.close();
|
||||
};
|
||||
}
|
||||
|
||||
export async function getTickets({
|
||||
body,
|
||||
signal,
|
||||
}: {
|
||||
body: GetTicketsRequest;
|
||||
signal: AbortSignal;
|
||||
}): Promise<GetTicketsResponse> {
|
||||
return makeRequest<GetTicketsRequest, GetTicketsResponse>({
|
||||
url: `${supportApiUrl}/getTickets`,
|
||||
method: "POST",
|
||||
useToken: true,
|
||||
body,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTicketMessages({
|
||||
body,
|
||||
signal,
|
||||
}: {
|
||||
body: GetMessagesRequest;
|
||||
signal: AbortSignal;
|
||||
}): Promise<GetMessagesResponse> {
|
||||
return makeRequest<GetMessagesRequest, GetMessagesResponse>({
|
||||
url: `${supportApiUrl}/getMessages`,
|
||||
method: "POST",
|
||||
useToken: true,
|
||||
body,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendTicketMessage({ body }: { body: SendTicketMessageRequest; }) {
|
||||
return makeRequest({
|
||||
url: `${supportApiUrl}/send`,
|
||||
@ -91,14 +12,3 @@ export async function sendTicketMessage({ body }: { body: SendTicketMessageReque
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
function createEventSource(onMessage: (e: MessageEvent) => void, onError: (e: Event) => void, url: string) {
|
||||
const eventSource = new ReconnectingEventSource(url);
|
||||
|
||||
eventSource.addEventListener("open", () => console.log(`EventSource connected with ${url}`));
|
||||
eventSource.addEventListener("close", () => console.log(`EventSource closed with ${url}`));
|
||||
eventSource.addEventListener("message", onMessage);
|
||||
eventSource.addEventListener("error", onError);
|
||||
|
||||
return eventSource;
|
||||
}
|
||||
|
@ -1,439 +1,287 @@
|
||||
import theme from "@theme";
|
||||
import {
|
||||
Button,
|
||||
Paper,
|
||||
Box,
|
||||
Typography,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableBody,
|
||||
Table,
|
||||
Tooltip,
|
||||
Alert,
|
||||
Checkbox,
|
||||
FormControlLabel,
|
||||
Button,
|
||||
Paper,
|
||||
Box,
|
||||
Typography,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableBody,
|
||||
Table,
|
||||
Alert,
|
||||
Checkbox,
|
||||
FormControlLabel,
|
||||
useTheme
|
||||
} from "@mui/material";
|
||||
import Input from "@kitUI/input";
|
||||
import { useState } from "react";
|
||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||
|
||||
import {
|
||||
calcCartData,
|
||||
createCartItem,
|
||||
findDiscountFactor,
|
||||
formatDiscountFactor,
|
||||
} from "./calc";
|
||||
|
||||
import { CartItemTotal } from "@root/model/cart";
|
||||
import { Privilege } from "@root/model/tariff";
|
||||
|
||||
import { useCartStore } from "@root/stores/cart";
|
||||
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||
import { testUser } from "@root/stores/mocks/user";
|
||||
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||
import { Discount } from "@root/model/discount";
|
||||
import { setCartData, useCartStore } from "@root/stores/cart";
|
||||
import { useTariffStore } from "@root/stores/tariffs";
|
||||
import { useDiscountStore } from "@root/stores/discounts";
|
||||
import { requestPrivilegies } from "@root/services/privilegies.service";
|
||||
import { requestDiscounts } from "@root/services/discounts.service";
|
||||
import { DiscountTooltip } from "./DiscountTooltip";
|
||||
import CartItemRow from "./CartItemRow";
|
||||
import { calcCart, findDiscountFactor, formatDiscountFactor } from "@root/utils/calcCart";
|
||||
import { Discount } from "@frontend/kitui";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
|
||||
interface Props {
|
||||
selectedTariffs: GridSelectionModel;
|
||||
}
|
||||
|
||||
interface MergedTariff {
|
||||
_id: string;
|
||||
id: string;
|
||||
name: string;
|
||||
privilegeId: string;
|
||||
serviceName: string;
|
||||
price: number;
|
||||
isCustom: boolean;
|
||||
createdAt: string;
|
||||
isDeleted: boolean;
|
||||
amount: number;
|
||||
customPricePerUnit?: number;
|
||||
privilegies: Privilege[];
|
||||
isFront: boolean;
|
||||
}
|
||||
export default function Cart() {
|
||||
const theme = useTheme();
|
||||
let discounts = useDiscountStore(state => state.discounts);
|
||||
const cartData = useCartStore((store) => store.cartData);
|
||||
const tariffs = useTariffStore(state => state.tariffs);
|
||||
const [couponField, setCouponField] = useState<string>("");
|
||||
const [loyaltyField, setLoyaltyField] = useState<string>("");
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
||||
|
||||
export default function Cart({ selectedTariffs }: Props) {
|
||||
let cartTariffs = Object.values(useTariffStore().tariffs);
|
||||
const discounts = useDiscountStore((store) => store.discounts);
|
||||
const cartTotal = useCartStore((state) => state.cartTotal);
|
||||
const setCartTotal = useCartStore((store) => store.setCartTotal);
|
||||
const [couponField, setCouponField] = useState<string>("");
|
||||
const [loyaltyField, setLoyaltyField] = useState<string>("");
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||
const cartDiscounts = [cartData?.appliedCartPurchasesDiscount, cartData?.appliedLoyaltyDiscount].filter((d): d is Discount => !!d);
|
||||
|
||||
const cartRows = cartTotal?.items.map((cartItemTotal) => {
|
||||
const privilege = findPrivilegeById(cartItemTotal.tariff.privilegeId);
|
||||
const cartDiscountsResultFactor = findDiscountFactor(cartData?.appliedCartPurchasesDiscount) * findDiscountFactor(cartData?.appliedLoyaltyDiscount);
|
||||
|
||||
const service = privilege?.serviceKey;
|
||||
const serviceDiscount = service
|
||||
? cartTotal.discountsByService[privilege?.serviceKey]
|
||||
: null;
|
||||
async function handleCalcCartClick() {
|
||||
await requestPrivilegies();
|
||||
try {
|
||||
discounts = await requestDiscounts();
|
||||
} catch { }
|
||||
|
||||
console.log(cartTotal.discountsByService);
|
||||
console.log(serviceDiscount);
|
||||
console.log(cartItemTotal);
|
||||
const cartTariffs = tariffs.filter(tariff => selectedTariffIds.includes(tariff._id));
|
||||
|
||||
const envolvedDiscountsElement = (
|
||||
<Box>
|
||||
{cartItemTotal.envolvedDiscounts.map((discount, index, arr) => (
|
||||
<span key={discount.ID}>
|
||||
<DiscountTooltip
|
||||
discount={discount}
|
||||
cartItemTotal={cartItemTotal}
|
||||
/>
|
||||
{index < arr.length - (serviceDiscount ? 0 : 1) && (
|
||||
<span>, </span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
{serviceDiscount && (
|
||||
<span>
|
||||
<DiscountTooltip
|
||||
discount={serviceDiscount}
|
||||
cartItemTotal={cartItemTotal}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
let loyaltyValue = parseInt(loyaltyField);
|
||||
|
||||
const totalIncludingServiceDiscount =
|
||||
cartItemTotal.totalPrice * (serviceDiscount?.Target.Factor || 1);
|
||||
console.log(cartItemTotal.totalPrice);
|
||||
console.log(serviceDiscount?.Target.Factor);
|
||||
console.log(serviceDiscount);
|
||||
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
|
||||
|
||||
return {
|
||||
id: cartItemTotal.tariff.id,
|
||||
tariffName: cartItemTotal.tariff.name,
|
||||
privilegeDesc: privilege?.description ?? "Привилегия не найдена",
|
||||
envolvedDiscounts: envolvedDiscountsElement,
|
||||
price: totalIncludingServiceDiscount,
|
||||
};
|
||||
});
|
||||
try {
|
||||
const cartData = calcCart(cartTariffs, discounts, loyaltyValue, couponField);
|
||||
|
||||
const cartDiscounts = cartTotal?.envolvedCartDiscounts;
|
||||
const cartDiscountsResultFactor =
|
||||
cartDiscounts &&
|
||||
cartDiscounts?.length > 1 &&
|
||||
cartDiscounts.reduce(
|
||||
(acc, discount) => acc * findDiscountFactor(discount),
|
||||
1
|
||||
);
|
||||
|
||||
const envolvedCartDiscountsElement = 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>
|
||||
);
|
||||
|
||||
async function handleCalcCartClick() {
|
||||
await requestPrivilegies();
|
||||
await requestDiscounts();
|
||||
|
||||
const cartItems = cartTariffs
|
||||
.filter((tariff) => selectedTariffs.includes(tariff.id))
|
||||
.map((tariff) => createCartItem(tariff));
|
||||
|
||||
console.log(cartItems);
|
||||
|
||||
let loyaltyValue = parseInt(loyaltyField);
|
||||
|
||||
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
|
||||
|
||||
const cartData = calcCartData({
|
||||
user: testUser,
|
||||
purchasesAmount: loyaltyValue,
|
||||
cartItems,
|
||||
discounts,
|
||||
isNonCommercial,
|
||||
coupon: couponField,
|
||||
});
|
||||
|
||||
if (cartData instanceof Error) {
|
||||
setErrorMessage(cartData.message);
|
||||
return setCartTotal(null);
|
||||
setErrorMessage(null);
|
||||
setCartData(cartData);
|
||||
} catch (error: any) {
|
||||
setErrorMessage(error.message);
|
||||
setCartData(null);
|
||||
}
|
||||
}
|
||||
|
||||
setErrorMessage(null);
|
||||
setCartTotal(cartData);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
component="section"
|
||||
sx={{
|
||||
border: "1px solid white",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
width: "100%",
|
||||
pb: "20px",
|
||||
borderRadius: "4px",
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption">корзина</Typography>
|
||||
<Paper
|
||||
variant="bar"
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "20px",
|
||||
}}
|
||||
>
|
||||
<FormControlLabel
|
||||
checked={isNonCommercial}
|
||||
onChange={(e, checked) => setIsNonCommercial(checked)}
|
||||
control={
|
||||
<Checkbox
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
"&.Mui-checked": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
}
|
||||
label="НКО"
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
/>
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
border: "1px solid white",
|
||||
padding: "3px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
label="промокод"
|
||||
size="small"
|
||||
value={couponField}
|
||||
onChange={(e) => setCouponField(e.target.value)}
|
||||
InputProps={{
|
||||
style: {
|
||||
backgroundColor: theme.palette.content.main,
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
InputLabelProps={{
|
||||
style: {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
{cartTotal?.couponState &&
|
||||
(cartTotal.couponState === "applied" ? (
|
||||
<Alert severity="success">Купон применен!</Alert>
|
||||
) : (
|
||||
<Alert severity="error">Подходящий купон не найден!</Alert>
|
||||
))}
|
||||
<Box
|
||||
sx={{
|
||||
border: "1px solid white",
|
||||
padding: "3px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
ml: "auto",
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
label="лояльность"
|
||||
size="small"
|
||||
type="number"
|
||||
value={loyaltyField}
|
||||
onChange={(e) => setLoyaltyField(e.target.value)}
|
||||
InputProps={{
|
||||
style: {
|
||||
backgroundColor: theme.palette.content.main,
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
InputLabelProps={{
|
||||
style: {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Button onClick={handleCalcCartClick}>рассчитать</Button>
|
||||
</Paper>
|
||||
|
||||
{cartTotal?.items && cartTotal.items.length > 0 && (
|
||||
<>
|
||||
<Table
|
||||
component="section"
|
||||
sx={{
|
||||
width: "90%",
|
||||
margin: "5px",
|
||||
border: "2px solid",
|
||||
borderColor: theme.palette.secondary.main,
|
||||
border: "1px solid white",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
width: "100%",
|
||||
pb: "20px",
|
||||
borderRadius: "4px",
|
||||
}}
|
||||
aria-label="simple table"
|
||||
>
|
||||
<TableHead>
|
||||
<TableRow
|
||||
>
|
||||
<Typography variant="caption">корзина</Typography>
|
||||
<Paper
|
||||
variant="bar"
|
||||
sx={{
|
||||
borderBottom: "2px solid",
|
||||
borderColor: theme.palette.grayLight.main,
|
||||
height: "100px",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: "20px",
|
||||
}}
|
||||
>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
Имя
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
Описание
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
Скидки
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
стоимость
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{cartRows?.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
sx={{
|
||||
borderBottom: "2px solid",
|
||||
borderColor: theme.palette.grayLight.main,
|
||||
}}
|
||||
>
|
||||
<FormControlLabel
|
||||
checked={isNonCommercial}
|
||||
onChange={(e, checked) => setIsNonCommercial(checked)}
|
||||
control={
|
||||
<Checkbox
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
"&.Mui-checked": {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
}
|
||||
label="НКО"
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
/>
|
||||
<Box
|
||||
sx={{
|
||||
border: "1px solid white",
|
||||
padding: "3px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<TableCell
|
||||
<Input
|
||||
label="промокод"
|
||||
size="small"
|
||||
value={couponField}
|
||||
onChange={(e) => setCouponField(e.target.value)}
|
||||
InputProps={{
|
||||
style: {
|
||||
backgroundColor: theme.palette.content.main,
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
InputLabelProps={{
|
||||
style: {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
{/* {cartTotal?.couponState &&
|
||||
(cartTotal.couponState === "applied" ? (
|
||||
<Alert severity="success">Купон применен!</Alert>
|
||||
) : (
|
||||
<Alert severity="error">Подходящий купон не найден!</Alert>
|
||||
))
|
||||
} */}
|
||||
<Box
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
border: "1px solid white",
|
||||
padding: "3px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
ml: "auto",
|
||||
}}
|
||||
>
|
||||
{row.tariffName}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
{row.privilegeDesc}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
{row.envolvedDiscounts}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
sx={{
|
||||
color: theme.palette.secondary.main,
|
||||
}}
|
||||
>
|
||||
{(row.price / 100).toFixed(2)} ₽
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
>
|
||||
<Input
|
||||
label="лояльность"
|
||||
size="small"
|
||||
type="number"
|
||||
value={loyaltyField}
|
||||
onChange={(e) => setLoyaltyField(e.target.value)}
|
||||
InputProps={{
|
||||
style: {
|
||||
backgroundColor: theme.palette.content.main,
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
InputLabelProps={{
|
||||
style: {
|
||||
color: theme.palette.secondary.main,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Button onClick={handleCalcCartClick}>рассчитать</Button>
|
||||
</Paper>
|
||||
|
||||
<Typography
|
||||
id="transition-modal-title"
|
||||
variant="h6"
|
||||
sx={{
|
||||
fontWeight: "normal",
|
||||
textAlign: "center",
|
||||
marginTop: "15px",
|
||||
fontSize: "16px",
|
||||
}}
|
||||
>
|
||||
Скидки корзины: {envolvedCartDiscountsElement}
|
||||
</Typography>
|
||||
{cartData?.services.length && (
|
||||
<>
|
||||
<Table
|
||||
sx={{
|
||||
width: "90%",
|
||||
margin: "5px",
|
||||
border: "2px solid",
|
||||
borderColor: theme.palette.secondary.main,
|
||||
}}
|
||||
aria-label="simple table"
|
||||
>
|
||||
<TableHead>
|
||||
<TableRow
|
||||
sx={{
|
||||
borderBottom: "2px solid",
|
||||
borderColor: theme.palette.grayLight.main,
|
||||
height: "100px",
|
||||
}}
|
||||
>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
Имя
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
Описание
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
Скидки
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography
|
||||
variant="h4"
|
||||
sx={{ color: theme.palette.secondary.main }}
|
||||
>
|
||||
стоимость
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{cartData.services.flatMap(service => service.privileges.map(privilegeCartData => (
|
||||
<CartItemRow
|
||||
privilegeCartData={privilegeCartData}
|
||||
appliedServiceDiscount={service.appliedServiceDiscount}
|
||||
/>
|
||||
)))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<Typography
|
||||
id="transition-modal-title"
|
||||
variant="h6"
|
||||
sx={{
|
||||
fontWeight: "normal",
|
||||
textAlign: "center",
|
||||
marginTop: "10px",
|
||||
}}
|
||||
>
|
||||
ИТОГО: <span>{(cartTotal?.totalPrice / 100).toFixed(2)} ₽</span>
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
<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>
|
||||
|
||||
{errorMessage !== null && (
|
||||
<Alert variant="filled" severity="error" sx={{ mt: "20px" }}>
|
||||
{errorMessage}
|
||||
</Alert>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function DiscountTooltip({
|
||||
discount,
|
||||
cartItemTotal,
|
||||
}: {
|
||||
discount: Discount;
|
||||
cartItemTotal?: CartItemTotal;
|
||||
}) {
|
||||
const discountText = formatDiscountFactor(findDiscountFactor(discount));
|
||||
|
||||
return discountText ? (
|
||||
<Tooltip
|
||||
title={
|
||||
<>
|
||||
<Typography>Скидка: {discount?.Name}</Typography>
|
||||
<Typography>{discount?.Description}</Typography>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<span>{discountText}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span>Ошибка поиска значения скидки</span>
|
||||
);
|
||||
<Typography
|
||||
id="transition-modal-title"
|
||||
variant="h6"
|
||||
sx={{
|
||||
fontWeight: "normal",
|
||||
textAlign: "center",
|
||||
marginTop: "10px",
|
||||
}}
|
||||
>
|
||||
ИТОГО: <span>{currencyFormatter.format(cartData.priceAfterDiscounts / 100)}</span>
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
|
||||
{errorMessage !== null && (
|
||||
<Alert variant="filled" severity="error" sx={{ mt: "20px" }}>
|
||||
{errorMessage}
|
||||
</Alert>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
54
src/kitUI/Cart/CartItemRow.tsx
Normal file
54
src/kitUI/Cart/CartItemRow.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
import { TableCell, TableRow, useTheme } from "@mui/material";
|
||||
import { DiscountTooltip } from "./DiscountTooltip";
|
||||
import { Discount, PrivilegeCartData } from "@frontend/kitui";
|
||||
import { currencyFormatter } from "@root/utils/currencyFormatter";
|
||||
|
||||
|
||||
interface Props {
|
||||
privilegeCartData: PrivilegeCartData;
|
||||
appliedServiceDiscount: Discount | null;
|
||||
}
|
||||
|
||||
export default function CartItemRow({ privilegeCartData, appliedServiceDiscount }: Props) {
|
||||
const theme = useTheme();
|
||||
|
||||
const envolvedDiscounts = [privilegeCartData.appliedPrivilegeDiscount, appliedServiceDiscount].filter((d): d is Discount => !!d);
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={privilegeCartData.tariffId}
|
||||
sx={{
|
||||
borderBottom: "2px solid",
|
||||
borderColor: theme.palette.grayLight.main,
|
||||
".MuiTableCell-root": {
|
||||
color: theme.palette.secondary.main,
|
||||
}
|
||||
}}
|
||||
>
|
||||
<TableCell>
|
||||
{privilegeCartData.tariffName}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{privilegeCartData.description}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{envolvedDiscounts.map((discount, index, arr) => (
|
||||
<span key={discount.ID}>
|
||||
<DiscountTooltip discount={discount} />
|
||||
{index < arr.length - (appliedServiceDiscount ? 0 : 1) && (
|
||||
<span>, </span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
{appliedServiceDiscount && (
|
||||
<span>
|
||||
<DiscountTooltip discount={appliedServiceDiscount} />
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{currencyFormatter.format(privilegeCartData.price)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
27
src/kitUI/Cart/DiscountTooltip.tsx
Normal file
27
src/kitUI/Cart/DiscountTooltip.tsx
Normal file
@ -0,0 +1,27 @@
|
||||
import { Tooltip, Typography } from "@mui/material";
|
||||
import { Discount } from "@frontend/kitui";
|
||||
import { formatDiscountFactor, findDiscountFactor } from "@root/utils/calcCart";
|
||||
|
||||
|
||||
interface Props {
|
||||
discount: Discount;
|
||||
}
|
||||
|
||||
export function DiscountTooltip({ discount }: Props) {
|
||||
const discountText = formatDiscountFactor(findDiscountFactor(discount));
|
||||
|
||||
return discountText ? (
|
||||
<Tooltip
|
||||
title={
|
||||
<>
|
||||
<Typography>Скидка: {discount?.Name}</Typography>
|
||||
<Typography>{discount?.Description}</Typography>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<span>{discountText}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span>Ошибка поиска значения скидки</span>
|
||||
);
|
||||
}
|
@ -1,321 +0,0 @@
|
||||
import { CartItem, CartTotal } from "../../model/cart";
|
||||
import { SERVICE_LIST, Tariff } from "../../model/tariff";
|
||||
import { User } from "../../model/user";
|
||||
import { exampleCartValues, TestCase } from "../../stores/mocks/exampleCartValues";
|
||||
import { calcCartData, createCartItem } from "./calc";
|
||||
|
||||
|
||||
const MAX_PRICE_ERROR = 0.01;
|
||||
const discounts = exampleCartValues.discounts;
|
||||
|
||||
// describe("cart tests", () => {
|
||||
// it("без скидок", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[0]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("сумма в корзине достигла 5к, поэтому применилась скидка", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[1]);
|
||||
|
||||
// // работает если не учитывать скидки id26, id27 (скидка на templategen от 1000/5000 р.)
|
||||
// const discountsWithoutTemplategen = discounts.filter(discount => {
|
||||
// return !(
|
||||
// discount.conditionType === "service" &&
|
||||
// discount.condition.service.id === "templategen"
|
||||
// );
|
||||
// });
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts: discountsWithoutTemplategen,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("добавил кастомный тариф такой, чтобы пофвилась скидка на продукт", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[2]);
|
||||
|
||||
// // работает если не учитывать скидки id26, id27 (скидка на templategen от 1000/5000 р.)
|
||||
// const discountsWithoutTemplategen = discounts.filter(discount => {
|
||||
// return !(
|
||||
// discount.conditionType === "service" &&
|
||||
// discount.condition.service.id === "templategen"
|
||||
// );
|
||||
// });
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts: discountsWithoutTemplategen,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("т.е. применилась не id14, а id15, потому что применяется наибольшая подходящая. в то же время, на скидку за лояльность ещё не хватает", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[3]);
|
||||
|
||||
// // работает если не учитывать скидки id26, id27 (скидка на templategen от 1000/5000 р.)
|
||||
// const discountsWithoutTemplategen = discounts.filter(discount => {
|
||||
// return !(
|
||||
// discount.conditionType === "service" &&
|
||||
// discount.condition.service.id === "templategen"
|
||||
// );
|
||||
// });
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts: discountsWithoutTemplategen,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("case 5", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[4]);
|
||||
|
||||
// // работает если не учитывать скидки id26, id27 (скидка на templategen от 1000/5000 р.)
|
||||
// const discountsWithoutTemplategen = discounts.filter(discount => {
|
||||
// return !(
|
||||
// discount.conditionType === "service" &&
|
||||
// discount.condition.service.id === "templategen"
|
||||
// );
|
||||
// });
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts: discountsWithoutTemplategen,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("история про то, как скидки за привилегии помешали получить скидку за сервис", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[5]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("то же что и выше, но без лояльности", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[6]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("история про то, как получилось получить скидку за сервис", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[7]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("две скидки за сервис", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[8]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("юзер использовал промокод id33. он заменяет скидку на p6 собой. в один момент времени может быть активирован только 1 промокод, т.е. после активации следующего, предыдущий заменяется. но в промокоде может быть несколько скидок. промокоды имеют скидки только на привелеги", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[9]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// isNonCommercial: false,
|
||||
// coupon: "ABCD",
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("юзер подтвердил свой статус НКО, поэтому, не смотря на то что он достиг по лояльности уровня скидки id2, она не применилась, а применилась id32", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[10]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// isNonCommercial: true,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// it("case 12", () => {
|
||||
// const testCase = prepareTestCase(exampleCartValues.testCases[11]);
|
||||
|
||||
// const cartTotal = calcCartData({
|
||||
// user: testCase.user,
|
||||
// purchasesAmount: testCase.user.PurchasesAmount,
|
||||
// cartItems: testCase.cartItems,
|
||||
// discounts,
|
||||
// }) as CartTotal;
|
||||
// const allEnvolvedDiscounts: string[] = [...cartTotal.envolvedCartDiscounts.map(discount => discount._id)];
|
||||
// cartTotal.items.forEach(cartItem => {
|
||||
// allEnvolvedDiscounts.push(...cartItem.envolvedDiscounts.map(discount => discount._id));
|
||||
// });
|
||||
// SERVICE_LIST.map(service => service.serviceKey).forEach(service => {
|
||||
// if (cartTotal.discountsByService[service]) allEnvolvedDiscounts.push(cartTotal.discountsByService[service]!._id);
|
||||
// });
|
||||
|
||||
// expect(allEnvolvedDiscounts.sort()).toEqual(testCase.expect.envolvedDiscounts.sort());
|
||||
// expect(cartTotal.totalPrice).toBeGreaterThan(testCase.expect.price - MAX_PRICE_ERROR);
|
||||
// expect(cartTotal.totalPrice).toBeLessThan(testCase.expect.price + MAX_PRICE_ERROR);
|
||||
// });
|
||||
// });
|
||||
|
||||
|
||||
function prepareTestCase(testCase: TestCase): ({
|
||||
expect: {
|
||||
price: number;
|
||||
envolvedDiscounts: string[];
|
||||
};
|
||||
user: User;
|
||||
cartItems: CartItem[];
|
||||
}) {
|
||||
const user = testCase.input.UserInformation;
|
||||
const tariffs = testCase.input.Products.map((testProduct): Tariff => ({
|
||||
id: "someId",
|
||||
name: "someName",
|
||||
amount: testProduct.Amount,
|
||||
customPricePerUnit: testProduct.Price && testProduct.Price / testProduct.Amount, // приводим price из сниппета к pricePerUnit
|
||||
privilegeId: testProduct.ID,
|
||||
}));
|
||||
const cartItems: CartItem[] = tariffs.map(createCartItem);
|
||||
|
||||
return { expect: testCase.expect, user, cartItems };
|
||||
}
|
@ -1,305 +0,0 @@
|
||||
import {
|
||||
CartItem, CartTotal,
|
||||
CartItemTotal, ServiceToPriceMap
|
||||
} from "@root/model/cart";
|
||||
import { Discount } from "@root/model/discount";
|
||||
import { User } from "../../model/user";
|
||||
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||
import { SERVICE_LIST, ServiceType, Tariff } from "@root/model/tariff";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
|
||||
export function calcCartData({
|
||||
user,
|
||||
purchasesAmount,
|
||||
cartItems,
|
||||
discounts,
|
||||
isNonCommercial = false,
|
||||
coupon,
|
||||
}: {
|
||||
user: User;
|
||||
purchasesAmount: number;
|
||||
cartItems: CartItem[];
|
||||
discounts: Discount[];
|
||||
isNonCommercial?: boolean;
|
||||
coupon?: string;
|
||||
}): CartTotal | Error | null {
|
||||
let isIncompatibleTariffs = false;
|
||||
console.log(discounts)
|
||||
const defaultTariffTypePresent: { [Key in ServiceType]: boolean } = {
|
||||
dwarfener: false,
|
||||
squiz: false,
|
||||
templategen: false,
|
||||
};
|
||||
|
||||
cartItems.forEach((cartItem) => {
|
||||
const privilege = findPrivilegeById(cartItem.tariff.privilegeId);
|
||||
if (!privilege)
|
||||
throw new Error(
|
||||
`Привилегия с id ${cartItem.tariff.privilegeId} не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}`
|
||||
);
|
||||
|
||||
if (cartItem.tariff.customPricePerUnit === undefined)
|
||||
return (defaultTariffTypePresent[privilege.serviceKey] = true);
|
||||
|
||||
if (defaultTariffTypePresent[privilege.serviceKey] && cartItem.tariff.customPricePerUnit !== undefined)
|
||||
isIncompatibleTariffs = true;
|
||||
});
|
||||
|
||||
if (isIncompatibleTariffs)
|
||||
return new Error("Если взят готовый тариф, то кастомный на этот сервис сделать уже нельзя");
|
||||
|
||||
if (!cartItems.length) return null;
|
||||
|
||||
const cartTotal: CartTotal = {
|
||||
items: [],
|
||||
totalPrice: 0,
|
||||
priceByService: {
|
||||
templategen: 0,
|
||||
squiz: 0,
|
||||
dwarfener: 0,
|
||||
},
|
||||
discountsByService: {
|
||||
templategen: null,
|
||||
squiz: null,
|
||||
dwarfener: null,
|
||||
},
|
||||
envolvedCartDiscounts: [],
|
||||
couponState: coupon ? "not found" : null,
|
||||
};
|
||||
|
||||
// layer 0
|
||||
for (const discount of discounts) {
|
||||
if (discount.Condition.UserType.length !== 0 || !isNonCommercial) continue;
|
||||
|
||||
cartItems.forEach((cartItem) => {
|
||||
cartTotal.items.push({
|
||||
envolvedDiscounts: [],
|
||||
tariff: cartItem.tariff,
|
||||
totalPrice: cartItem.price,
|
||||
});
|
||||
|
||||
const privilege = findPrivilegeById(cartItem.tariff.privilegeId);
|
||||
if (!privilege)
|
||||
throw new Error(`Привилегия не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}`);
|
||||
|
||||
cartTotal.priceByService[privilege.serviceKey] += cartItem.price;
|
||||
cartTotal.totalPrice += cartItem.price;
|
||||
});
|
||||
|
||||
cartTotal.totalPrice *= discount.Target.Factor;
|
||||
cartTotal.envolvedCartDiscounts.push(discount);
|
||||
|
||||
return cartTotal;
|
||||
}
|
||||
|
||||
const couponDiscount = coupon ? findUserDiscount(discounts, user, coupon) : null;
|
||||
|
||||
// layer 1
|
||||
for (const cartItem of cartItems) {
|
||||
const cartItemTotal: CartItemTotal = {
|
||||
tariff: cartItem.tariff,
|
||||
envolvedDiscounts: [],
|
||||
totalPrice: cartItem.price,
|
||||
};
|
||||
|
||||
const tariff = cartItem.tariff;
|
||||
const privilegesAffectedByCoupon: string[] = [];
|
||||
|
||||
couponDiscount?.Target.Products.forEach((product) => {
|
||||
if (product.ID !== tariff.privilegeId ) return;
|
||||
if (tariff.customPricePerUnit !== undefined && !couponDiscount?.Target.Overhelm) return;
|
||||
|
||||
cartItemTotal.totalPrice *= product.Factor;
|
||||
cartItemTotal.envolvedDiscounts.push(couponDiscount);
|
||||
cartTotal.couponState = "applied";
|
||||
privilegesAffectedByCoupon.push(couponDiscount.Condition.Product);
|
||||
});
|
||||
|
||||
const privilege = findPrivilegeById(cartItem.tariff.privilegeId);
|
||||
const privilegeDiscount = findMaxApplicablePrivilegeDiscount(discounts, tariff);
|
||||
|
||||
privilegeDiscount?.Target.Products.forEach((product) => {
|
||||
console.log( privilegeDiscount.Condition.Product !== privilege?.privilegeId)
|
||||
if (privilegeDiscount.Condition.Product !== privilege?.privilegeId) return;
|
||||
if (tariff.customPricePerUnit !== 0) return;
|
||||
if (privilegesAffectedByCoupon.includes(privilegeDiscount.Condition.Product)) return;
|
||||
|
||||
cartItemTotal.totalPrice *= product.Factor;
|
||||
cartItemTotal.envolvedDiscounts.push(privilegeDiscount);
|
||||
});
|
||||
|
||||
if (!privilege)
|
||||
throw new Error(`Привилегия не найдена в тарифе ${cartItem.tariff.name} с id ${cartItem.tariff.id}`);
|
||||
|
||||
cartTotal.items.push(cartItemTotal);
|
||||
cartTotal.priceByService[privilege.serviceKey] += cartItemTotal.totalPrice;
|
||||
console.log("cartTotal.priceByService")
|
||||
console.log(cartTotal.priceByService)
|
||||
}
|
||||
|
||||
// layer 2
|
||||
console.log("l2")
|
||||
SERVICE_LIST.map((service) => service.serviceKey).forEach((service) => {
|
||||
const serviceDiscount = findMaxServiceDiscount(service, discounts, cartTotal.priceByService);
|
||||
console.log(serviceDiscount)
|
||||
if (serviceDiscount) {
|
||||
cartTotal.priceByService[service] *= serviceDiscount.Target.Factor;
|
||||
cartTotal.discountsByService[service] = serviceDiscount;
|
||||
console.log(cartTotal.discountsByService)
|
||||
}
|
||||
console.log(cartTotal.totalPrice)
|
||||
console.log(cartTotal.priceByService[service])
|
||||
|
||||
cartTotal.totalPrice += cartTotal.priceByService[service];
|
||||
});
|
||||
|
||||
// layer 3
|
||||
const cartPurchasesAmountDiscount = findMaxCartPurchasesAmountDiscount(discounts, cartTotal);
|
||||
console.log(cartPurchasesAmountDiscount)
|
||||
if (cartPurchasesAmountDiscount) {
|
||||
cartTotal.totalPrice *= cartPurchasesAmountDiscount.Target.Factor;
|
||||
cartTotal.envolvedCartDiscounts.push(cartPurchasesAmountDiscount);
|
||||
}
|
||||
|
||||
// layer 4
|
||||
const totalPurchasesAmountDiscount = findMaxTotalPurchasesAmountDiscount(discounts, purchasesAmount);
|
||||
console.log(totalPurchasesAmountDiscount)
|
||||
if (totalPurchasesAmountDiscount) {
|
||||
cartTotal.totalPrice *= totalPurchasesAmountDiscount.Target.Factor;
|
||||
cartTotal.envolvedCartDiscounts.push(totalPurchasesAmountDiscount);
|
||||
}
|
||||
|
||||
return cartTotal;
|
||||
}
|
||||
|
||||
function findMaxApplicablePrivilegeDiscount(discounts: Discount[], tariff: Tariff): Discount | null {
|
||||
const applicableDiscounts = discounts.filter((discount): discount is Discount => {
|
||||
|
||||
return (
|
||||
discount.Condition.Product !== "" &&
|
||||
findPrivilegeById(tariff.privilegeId)?.privilegeId === discount.Condition.Product &&
|
||||
tariff.amount >= Number(discount.Condition.Term)
|
||||
);
|
||||
});
|
||||
|
||||
if (!applicableDiscounts.length) return null;
|
||||
const maxValueDiscount = applicableDiscounts.reduce((prev, current) =>
|
||||
Number(current.Condition.Term) > Number(prev.Condition.Term) ? current : prev
|
||||
);
|
||||
|
||||
return maxValueDiscount;
|
||||
}
|
||||
|
||||
function findMaxCartPurchasesAmountDiscount(
|
||||
discounts: Discount[],
|
||||
cartTotal: CartTotal
|
||||
): Discount | null {
|
||||
const applicableDiscounts = discounts.filter((discount): discount is Discount => {
|
||||
return (
|
||||
discount.Condition.CartPurchasesAmount > 0 && cartTotal.totalPrice >= Number(discount.Condition.CartPurchasesAmount)
|
||||
);
|
||||
});
|
||||
console.log(applicableDiscounts)
|
||||
|
||||
if (!applicableDiscounts.length) return null;
|
||||
|
||||
const maxValueDiscount = applicableDiscounts.reduce((prev, current) =>
|
||||
Number(current.Condition.CartPurchasesAmount) > Number(prev.Condition.CartPurchasesAmount) ? current : prev
|
||||
);
|
||||
|
||||
return maxValueDiscount;
|
||||
}
|
||||
|
||||
function findMaxTotalPurchasesAmountDiscount(
|
||||
discounts: Discount[],
|
||||
purchasesAmount: number
|
||||
): Discount | null {
|
||||
const applicableDiscounts = discounts.filter((discount): discount is Discount => {
|
||||
return discount.Condition.PurchasesAmount > 0 && purchasesAmount >= Number(discount.Condition.PurchasesAmount);
|
||||
});
|
||||
console.log(discounts)
|
||||
|
||||
if (!applicableDiscounts.length) return null;
|
||||
|
||||
const maxValueDiscount = applicableDiscounts.reduce((prev, current) =>
|
||||
Number(current.Condition.PurchasesAmount) > Number(prev.Condition.PurchasesAmount) ? current : prev
|
||||
);
|
||||
|
||||
return maxValueDiscount;
|
||||
}
|
||||
|
||||
function findMaxServiceDiscount(
|
||||
service: ServiceType,
|
||||
discounts: Discount[],
|
||||
priceByService: ServiceToPriceMap
|
||||
): Discount | null {
|
||||
console.log(discounts,service)
|
||||
const discountsForTariffService = discounts.filter((discount): discount is Discount => {
|
||||
return (
|
||||
discount.Condition.Group === service &&
|
||||
priceByService[service] >= Number(discount.Condition.PriceFrom)
|
||||
);
|
||||
});
|
||||
|
||||
if (!discountsForTariffService.length) return null;
|
||||
|
||||
const maxValueDiscount = discountsForTariffService.reduce((prev, current) => {
|
||||
return Number(current.Condition.PriceFrom) > Number(prev.Condition.PriceFrom) ? current : prev;
|
||||
});
|
||||
|
||||
return maxValueDiscount;
|
||||
}
|
||||
|
||||
function findUserDiscount(discounts: Discount[], user: User, coupon: string): Discount | null {
|
||||
const userDiscount = discounts.find((discount): discount is Discount => {
|
||||
return (
|
||||
discount.Condition.User.length !== 0 && discount.Condition.User === user.ID && discount.Condition.Coupon === coupon
|
||||
);
|
||||
});
|
||||
|
||||
return userDiscount ?? null;
|
||||
}
|
||||
|
||||
export function createCartItem(tariff: Tariff): CartItem {
|
||||
|
||||
const privilege = findPrivilegeById(tariff.privilegeId)?.price || 0
|
||||
|
||||
if (!privilege) {
|
||||
enqueueSnackbar(
|
||||
`Привилегия с id ${tariff.privilegeId} не найдена в тарифе ${tariff.name} с id ${tariff.id}`
|
||||
);
|
||||
}
|
||||
|
||||
const price = tariff.isCustom ? (tariff.price || 0) : privilege * tariff.amount || 0
|
||||
|
||||
return { tariff, price, id: tariff.id };
|
||||
}
|
||||
|
||||
export function findDiscountFactor(discount: Discount): any {
|
||||
if (discount.Condition.CartPurchasesAmount > 0)
|
||||
return Number(discount.Target.Factor);
|
||||
|
||||
if (discount.Condition.PurchasesAmount > 0)
|
||||
return Number(discount.Target.Factor);
|
||||
|
||||
if (discount.Condition.Product !== "") {
|
||||
const product = discount.Target.Products[0];
|
||||
if (!product) throw new Error("Discount target product not found");
|
||||
return Number(product.Factor);
|
||||
}
|
||||
|
||||
if ((discount.Condition.Group as string) !== "")
|
||||
return Number(discount.Target.Factor);
|
||||
if (discount.Condition.UserType)
|
||||
return Number(discount.Target.Factor);
|
||||
if (discount.Condition.User !== "") {
|
||||
const product = discount.Target.Products[0];
|
||||
if (!product) throw new Error("Discount target product not found");
|
||||
|
||||
return Number(product.Factor);
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDiscountFactor(factor: number): string {
|
||||
return `${((1 - factor) * 100).toFixed(1)}%`;
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
import { DataGrid } from "@mui/x-data-grid";
|
||||
import { styled } from "@mui/material/styles";
|
||||
|
||||
|
||||
export default styled(DataGrid)(({ theme }) => ({
|
||||
width: "100%",
|
||||
minHeight: "400px",
|
||||
@ -23,4 +25,4 @@ export default styled(DataGrid)(({ theme }) => ({
|
||||
"& .MuiButton-text": {
|
||||
color: theme.palette.secondary.main
|
||||
},
|
||||
}));
|
||||
})) as typeof DataGrid;
|
||||
|
@ -1,9 +1,9 @@
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { useToken } from "@frontend/kitui";
|
||||
import * as React from "react";
|
||||
import { useLocation, Navigate } from "react-router-dom";
|
||||
|
||||
export default ({ children }: any) => {
|
||||
const { token } = authStore();
|
||||
const token = useToken();
|
||||
const location = useLocation();
|
||||
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
|
||||
if (token) {
|
||||
|
@ -1,10 +1,10 @@
|
||||
import { useLocation, Navigate } from "react-router-dom";
|
||||
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { useToken } from "@frontend/kitui";
|
||||
|
||||
const PublicRoute = ({ children }: any) => {
|
||||
const location = useLocation();
|
||||
const { token } = authStore();
|
||||
const token = useToken();
|
||||
|
||||
if (token) {
|
||||
return <Navigate to="/users" state={{ from: location }} />;
|
||||
|
@ -1,46 +1,8 @@
|
||||
import { ServiceType, Privilege, Tariff } from "./tariff";
|
||||
import { Discount } from "@root/model/discount";
|
||||
|
||||
|
||||
export interface Promocode {
|
||||
id: string;
|
||||
name: string;
|
||||
endless: boolean;
|
||||
from: string;
|
||||
dueTo: string;
|
||||
privileges: Privilege[];
|
||||
}
|
||||
|
||||
export interface CartItem {
|
||||
id: string;
|
||||
tariff: Tariff;
|
||||
/** Посчитанная цена пункта корзины */
|
||||
price: number;
|
||||
}
|
||||
|
||||
/** Пункт корзины с уже примененными скидками */
|
||||
export interface CartItemTotal {
|
||||
/** Массив с id примененных скидок */
|
||||
envolvedDiscounts: Discount[];
|
||||
totalPrice: number;
|
||||
tariff: Tariff;
|
||||
}
|
||||
|
||||
export type ServiceToPriceMap = {
|
||||
[Key in ServiceType]: number;
|
||||
};
|
||||
|
||||
export type ServiceToDiscountMap = {
|
||||
[Key in ServiceType]: Discount | null;
|
||||
};
|
||||
|
||||
export interface CartTotal {
|
||||
items: CartItemTotal[];
|
||||
totalPrice: number;
|
||||
priceByService: ServiceToPriceMap;
|
||||
/** Скидки по сервисам */
|
||||
discountsByService: ServiceToDiscountMap;
|
||||
/** Учтенные скидки типов userType, cartPurchasesAmount, totalPurchasesAmount */
|
||||
envolvedCartDiscounts: (Discount)[];
|
||||
couponState: "applied" | "not found" | null;
|
||||
id: string;
|
||||
name: string;
|
||||
endless: boolean;
|
||||
from: string;
|
||||
dueTo: string;
|
||||
privileges: string[];
|
||||
}
|
||||
|
@ -1,47 +1,6 @@
|
||||
import { ServiceType } from "./tariff";
|
||||
import { Discount } from "@frontend/kitui";
|
||||
|
||||
|
||||
export type Discount = {
|
||||
ID: string;
|
||||
Name: string;
|
||||
Layer: number;
|
||||
Description: string;
|
||||
Condition: {
|
||||
Period: {
|
||||
From: string;
|
||||
To: string;
|
||||
};
|
||||
User: string;
|
||||
UserType: string;
|
||||
Coupon: string;
|
||||
PurchasesAmount: number;
|
||||
CartPurchasesAmount: number;
|
||||
Product: string;
|
||||
Term: string;
|
||||
Usage: string;
|
||||
PriceFrom: number;
|
||||
Group: ServiceType;
|
||||
};
|
||||
Target: {
|
||||
Products: [{
|
||||
ID: string;
|
||||
Factor: number;
|
||||
Overhelm: boolean;
|
||||
}];
|
||||
Factor: number;
|
||||
TargetScope: string;
|
||||
TargetGroup: ServiceType;
|
||||
Overhelm: boolean;
|
||||
};
|
||||
Audit: {
|
||||
UpdatedAt: string;
|
||||
CreatedAt: string;
|
||||
DeletedAt?: string;
|
||||
Deleted: boolean;
|
||||
};
|
||||
Deprecated: boolean;
|
||||
};
|
||||
|
||||
export type GetDiscountResponse = {
|
||||
Discounts: Discount[];
|
||||
};
|
||||
@ -75,13 +34,13 @@ export type CreateDiscountBody = {
|
||||
Term: number;
|
||||
Usage: number;
|
||||
PriceFrom: number;
|
||||
Group: ServiceType | "";
|
||||
Group: string;
|
||||
};
|
||||
Target: {
|
||||
Factor: number;
|
||||
TargetScope: "Sum" | "Group" | "Each";
|
||||
Overhelm: boolean;
|
||||
TargetGroup: ServiceType | "";
|
||||
TargetGroup: string;
|
||||
Products: [{
|
||||
ID: string;
|
||||
Factor: number;
|
||||
|
@ -12,38 +12,5 @@ export const SERVICE_LIST = [
|
||||
displayName: "Аналитика сокращателя",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export interface RealPrivilege {
|
||||
createdAt: string;
|
||||
description: string;
|
||||
isDeleted: boolean;
|
||||
name: string;
|
||||
price: number;
|
||||
privilegeId: string;
|
||||
serviceKey: ServiceType;
|
||||
type: "count" | "day" | "mb";
|
||||
updatedAt: string;
|
||||
value: string;
|
||||
_id: string;
|
||||
};
|
||||
|
||||
export interface mergedBackFrontPrivilege {
|
||||
serviceKey: ServiceType;
|
||||
privilegeId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
type: "count" | "day" | "mb";
|
||||
amount?: number;
|
||||
price: number;
|
||||
isDeleted?: boolean;
|
||||
value?: string
|
||||
id?: string
|
||||
}
|
||||
|
||||
export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"];
|
||||
// export type PrivilegeMap = Record<string, RealPrivilege[]>;
|
||||
|
||||
// export type PrivilegeValueType = "шаблон" | "день" | "МБ";
|
||||
|
||||
// export type PrivilegeWithAmount = Omit<RealPrivilege, "_id"> & { amount: number; };
|
||||
|
||||
// export type PrivilegeWithoutPrice = Omit<PrivilegeWithAmount, "price">;
|
||||
|
@ -1,3 +1,5 @@
|
||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
|
||||
export const SERVICE_LIST = [
|
||||
{
|
||||
serviceKey: "templategen",
|
||||
@ -17,58 +19,9 @@ export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"];
|
||||
|
||||
export type PrivilegeType = "unlim" | "gencount" | "activequiz" | "abcount" | "extended";
|
||||
|
||||
export interface Privilege_BACKEND {
|
||||
export type EditTariffRequestBody = {
|
||||
name: string;
|
||||
privilegeId: string;
|
||||
serviceKey: "templategen" | "squiz" | "dwarfener";
|
||||
amount: number;
|
||||
description: string;
|
||||
price: number;
|
||||
type: "count" | "day" | "mb";
|
||||
value: string;
|
||||
updatedAt: string;
|
||||
_id: string;
|
||||
}
|
||||
|
||||
export type Tariff_FRONTEND = {
|
||||
id: string,
|
||||
name: string,
|
||||
amount: number,
|
||||
privilegeId: string,
|
||||
customPricePerUnit?: number;
|
||||
isCustom: boolean;
|
||||
privilegies: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
||||
};
|
||||
|
||||
/** @deprecated */
|
||||
export interface Privilege {
|
||||
serviceKey: ServiceType;
|
||||
name: PrivilegeType;
|
||||
privilegeId: string;
|
||||
description: string;
|
||||
/** Единица измерения привелегии: время в днях/кол-во */
|
||||
type: "day" | "count";
|
||||
/** Стоимость одной единицы привелегии */
|
||||
price: number;
|
||||
}
|
||||
|
||||
export type Tariff_BACKEND = {
|
||||
_id: string,
|
||||
name: string,
|
||||
price: number,
|
||||
isCustom: boolean,
|
||||
isFront: false,
|
||||
privilegies: Privilege_BACKEND[],
|
||||
isDeleted: boolean,
|
||||
createdAt: string,
|
||||
updatedAt: string;
|
||||
};
|
||||
export type Tariff = {
|
||||
id: string;
|
||||
name: string;
|
||||
isCustom?: boolean;
|
||||
price?: number;
|
||||
privilegeId: string;
|
||||
amount: number; //Количество единиц привелегии
|
||||
customPricePerUnit?: number; //Кастомная цена, если есть, то используется вместо privilege.price
|
||||
isDeleted?: boolean,
|
||||
isFront?: boolean;
|
||||
}
|
||||
|
@ -16,20 +16,7 @@ export interface SendTicketMessageRequest {
|
||||
files: string[];
|
||||
};
|
||||
|
||||
export type TicketStatus = "open"; // TODO
|
||||
|
||||
export interface GetTicketsRequest {
|
||||
amt: number;
|
||||
/** Пагинация начинается с индекса 0 */
|
||||
page: number;
|
||||
srch?: string;
|
||||
status?: TicketStatus;
|
||||
};
|
||||
|
||||
export interface GetTicketsResponse {
|
||||
count: number;
|
||||
data: Ticket[] | null;
|
||||
};
|
||||
export type TicketStatus = "open";
|
||||
|
||||
export interface Ticket {
|
||||
id: string;
|
||||
@ -55,12 +42,3 @@ export interface TicketMessage {
|
||||
request_screenshot: string,
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export interface GetMessagesRequest {
|
||||
amt: number;
|
||||
page: number;
|
||||
srch?: string;
|
||||
ticket: string;
|
||||
};
|
||||
|
||||
export type GetMessagesResponse = TicketMessage[];
|
||||
|
@ -9,14 +9,12 @@ import CleverButton from "@kitUI/cleverButton";
|
||||
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
||||
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
||||
import OutlinedInput from "@kitUI/outlinedInput";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
|
||||
export default () => {
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
const [restore, setRestore] = React.useState(true);
|
||||
const [isReady, setIsReady] = React.useState(true);
|
||||
const { makeRequest } = authStore();
|
||||
if (restore) {
|
||||
return (
|
||||
<Formik
|
||||
|
@ -8,7 +8,7 @@ import Logo from "@pages/Logo";
|
||||
import OutlinedInput from "@kitUI/outlinedInput";
|
||||
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
||||
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
|
||||
interface Values {
|
||||
email: string;
|
||||
@ -37,8 +37,6 @@ const SigninForm = () => {
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { makeRequest } = authStore();
|
||||
|
||||
const initialValues: Values = {
|
||||
email: "",
|
||||
password: "",
|
||||
|
@ -9,7 +9,8 @@ import OutlinedInput from "@kitUI/outlinedInput";
|
||||
import Logo from "@pages/Logo/index";
|
||||
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
||||
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
|
||||
interface Values {
|
||||
email: string;
|
||||
password: string;
|
||||
@ -33,7 +34,6 @@ function validate(values: Values) {
|
||||
const SignUp = () => {
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
const { makeRequest } = authStore();
|
||||
|
||||
return (
|
||||
<Formik
|
||||
@ -148,4 +148,4 @@ const SignUp = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default SignUp;
|
||||
export default SignUp;
|
||||
|
@ -2,180 +2,163 @@ import { useRef, useState } from "react";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { Box, IconButton, TextField, Tooltip, Typography } from "@mui/material";
|
||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { PrivilegeWithAmount, makeRequest } from "@frontend/kitui";
|
||||
|
||||
import type { Privilege_BACKEND } from "@root/model/tariff";
|
||||
|
||||
interface CardPrivilegie {
|
||||
name: string;
|
||||
type: "count" | "day" | "mb";
|
||||
price: string | number;
|
||||
description: string;
|
||||
value?: string;
|
||||
privilegeId: string;
|
||||
serviceKey: "templategen" | "squiz" | "dwarfener";
|
||||
amount: number;
|
||||
privilege: PrivilegeWithAmount;
|
||||
}
|
||||
|
||||
const baseUrl =
|
||||
process.env.NODE_ENV === "production"
|
||||
? "/strator"
|
||||
: "https://admin.pena.digital/strator";
|
||||
process.env.NODE_ENV === "production"
|
||||
? "/strator"
|
||||
: "https://admin.pena.digital/strator";
|
||||
|
||||
export const СardPrivilegie = ({
|
||||
name,
|
||||
type,
|
||||
price,
|
||||
description,
|
||||
value = "",
|
||||
privilegeId,
|
||||
serviceKey,
|
||||
}: CardPrivilegie) => {
|
||||
const [inputOpen, setInputOpen] = useState<boolean>(false);
|
||||
const [inputValue, setInputValue] = useState<string>("");
|
||||
const priceRef = useRef<any>(null);
|
||||
const { makeRequest } = authStore.getState();
|
||||
export const СardPrivilegie = ({ privilege }: CardPrivilegie) => {
|
||||
const [inputOpen, setInputOpen] = useState<boolean>(false);
|
||||
const [inputValue, setInputValue] = useState<string>("");
|
||||
const priceRef = useRef<any>(null);
|
||||
|
||||
const translationType = {
|
||||
count: "за единицу",
|
||||
day: "за день",
|
||||
mb: "за МБ",
|
||||
};
|
||||
const translationType = {
|
||||
count: "за единицу",
|
||||
day: "за день",
|
||||
mb: "за МБ",
|
||||
};
|
||||
|
||||
const PutPrivilegies = () => {
|
||||
makeRequest<Omit<Privilege_BACKEND, "_id" | "updatedAt">>({
|
||||
url: baseUrl + "/privilege/",
|
||||
method: "put",
|
||||
body: {
|
||||
name: name,
|
||||
privilegeId: privilegeId,
|
||||
serviceKey: serviceKey,
|
||||
description: description,
|
||||
amount: 1,
|
||||
type: type,
|
||||
value: value,
|
||||
price: Number(inputValue),
|
||||
},
|
||||
})
|
||||
.then(() => {
|
||||
priceRef.current.innerText = "price: " + inputValue;
|
||||
setInputValue("");
|
||||
setInputOpen(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
enqueueSnackbar(error.message);
|
||||
});
|
||||
};
|
||||
const PutPrivilegies = () => {
|
||||
makeRequest<Omit<PrivilegeWithAmount, "_id" | "updatedAt">>({
|
||||
url: baseUrl + "/privilege/",
|
||||
method: "put",
|
||||
body: {
|
||||
name: privilege.name,
|
||||
privilegeId: privilege.privilegeId,
|
||||
serviceKey: privilege.serviceKey,
|
||||
description: privilege.description,
|
||||
amount: 1,
|
||||
type: privilege.type,
|
||||
value: privilege.value,
|
||||
price: Number(inputValue),
|
||||
},
|
||||
})
|
||||
.then(() => {
|
||||
priceRef.current.innerText = "price: " + inputValue;
|
||||
setInputValue("");
|
||||
setInputOpen(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
enqueueSnackbar(error.message);
|
||||
});
|
||||
};
|
||||
|
||||
const requestOnclickEnter = (event: any) => {
|
||||
if (event.key === "Enter" && inputValue !== "") {
|
||||
PutPrivilegies();
|
||||
setInputOpen(false);
|
||||
}
|
||||
};
|
||||
const requestOnclickEnter = (event: any) => {
|
||||
if (event.key === "Enter" && inputValue !== "") {
|
||||
PutPrivilegies();
|
||||
setInputOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onCloseInput = (event: any) => {
|
||||
if (event.key === "Escape") {
|
||||
setInputOpen(false);
|
||||
}
|
||||
};
|
||||
const onCloseInput = (event: any) => {
|
||||
if (event.key === "Escape") {
|
||||
setInputOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={type}
|
||||
sx={{
|
||||
px: "20px",
|
||||
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
border: "1px solid gray",
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", borderRight: "1px solid gray" }}>
|
||||
<Box sx={{ width: "200px", py: "25px" }}>
|
||||
<Typography
|
||||
variant="h6"
|
||||
return (
|
||||
<Box
|
||||
key={privilege.type}
|
||||
sx={{
|
||||
color: "#fe9903",
|
||||
overflowWrap: "break-word",
|
||||
overflow: "hidden",
|
||||
px: "20px",
|
||||
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
border: "1px solid gray",
|
||||
}}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
<Tooltip
|
||||
sx={{
|
||||
span: {
|
||||
fontSize: "1rem",
|
||||
},
|
||||
}}
|
||||
placement="top"
|
||||
title={
|
||||
<Typography sx={{ fontSize: "16px" }}>{description}</Typography>
|
||||
}
|
||||
>
|
||||
<IconButton disableRipple>
|
||||
<svg
|
||||
width="40"
|
||||
height="40"
|
||||
viewBox="0 0 20 20"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M9.25 9.25H10V14.5H10.75"
|
||||
stroke="#7E2AEA"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
|
||||
fill="#7E2AEA"
|
||||
/>
|
||||
</svg>
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<IconButton onClick={() => setInputOpen(!inputOpen)}>
|
||||
<ModeEditOutlineOutlinedIcon sx={{ color: "gray" }} />
|
||||
</IconButton>
|
||||
>
|
||||
<Box sx={{ display: "flex", borderRight: "1px solid gray" }}>
|
||||
<Box sx={{ width: "200px", py: "25px" }}>
|
||||
<Typography
|
||||
variant="h6"
|
||||
sx={{
|
||||
color: "#fe9903",
|
||||
overflowWrap: "break-word",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
{privilege.name}
|
||||
</Typography>
|
||||
<Tooltip
|
||||
sx={{
|
||||
span: {
|
||||
fontSize: "1rem",
|
||||
},
|
||||
}}
|
||||
placement="top"
|
||||
title={
|
||||
<Typography sx={{ fontSize: "16px" }}>{privilege.description}</Typography>
|
||||
}
|
||||
>
|
||||
<IconButton disableRipple>
|
||||
<svg
|
||||
width="40"
|
||||
height="40"
|
||||
viewBox="0 0 20 20"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M9.25 9.25H10V14.5H10.75"
|
||||
stroke="#7E2AEA"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<path
|
||||
d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
|
||||
fill="#7E2AEA"
|
||||
/>
|
||||
</svg>
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<IconButton onClick={() => setInputOpen(!inputOpen)}>
|
||||
<ModeEditOutlineOutlinedIcon sx={{ color: "gray" }} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{ width: "600px", display: "flex", justifyContent: "space-around" }}
|
||||
>
|
||||
{inputOpen ? (
|
||||
<TextField
|
||||
type="number"
|
||||
onKeyDown={onCloseInput}
|
||||
onKeyPress={requestOnclickEnter}
|
||||
placeholder="введите число"
|
||||
fullWidth
|
||||
onChange={(event) => setInputValue(event.target.value)}
|
||||
sx={{
|
||||
alignItems: "center",
|
||||
width: "400px",
|
||||
"& .MuiInputBase-root": {
|
||||
backgroundColor: "#F2F3F7",
|
||||
height: "48px",
|
||||
},
|
||||
}}
|
||||
inputProps={{
|
||||
sx: {
|
||||
borderRadius: "10px",
|
||||
fontSize: "18px",
|
||||
lineHeight: "21px",
|
||||
py: 0,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div ref={priceRef} style={{ color: "white", marginRight: "5px" }}>
|
||||
price: {privilege.price}
|
||||
</div>
|
||||
)}
|
||||
<Typography sx={{ color: "white" }}>{translationType[privilege.type]}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box
|
||||
sx={{ width: "600px", display: "flex", justifyContent: "space-around" }}
|
||||
>
|
||||
{inputOpen ? (
|
||||
<TextField
|
||||
type="number"
|
||||
onKeyDown={onCloseInput}
|
||||
onKeyPress={requestOnclickEnter}
|
||||
placeholder="введите число"
|
||||
fullWidth
|
||||
onChange={(event) => setInputValue(event.target.value)}
|
||||
sx={{
|
||||
alignItems: "center",
|
||||
width: "400px",
|
||||
"& .MuiInputBase-root": {
|
||||
backgroundColor: "#F2F3F7",
|
||||
height: "48px",
|
||||
},
|
||||
}}
|
||||
inputProps={{
|
||||
sx: {
|
||||
borderRadius: "10px",
|
||||
fontSize: "18px",
|
||||
lineHeight: "21px",
|
||||
py: 0,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<div ref={priceRef} style={{ color: "white", marginRight: "5px" }}>
|
||||
price: {price}
|
||||
</div>
|
||||
)}
|
||||
<Typography sx={{ color: "white" }}>{translationType[type]}</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
@ -10,7 +10,7 @@ import {
|
||||
TextField,
|
||||
} from "@mui/material";
|
||||
import { MOCK_DATA_USERS } from "@root/api/roles";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
|
||||
const ITEM_HEIGHT = 48;
|
||||
const ITEM_PADDING_TOP = 8;
|
||||
@ -28,7 +28,6 @@ const baseUrl =
|
||||
export default function DeleteForm() {
|
||||
const [personName, setPersonName] = useState<string[]>([]);
|
||||
const [roleId, setRoleId] = useState<string>();
|
||||
const { makeRequest } = authStore.getState();
|
||||
|
||||
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
|
||||
const {
|
||||
|
@ -6,39 +6,21 @@ import { requestPrivilegies } from "@root/services/privilegies.service";
|
||||
import { СardPrivilegie } from "./CardPrivilegie";
|
||||
|
||||
export default function ListPrivilegie() {
|
||||
const privileges = usePrivilegeStore((state) => state.privileges);
|
||||
const privileges = usePrivilegeStore((state) => state.privileges);
|
||||
|
||||
useEffect(() => {
|
||||
requestPrivilegies();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
requestPrivilegies();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{privileges.map(
|
||||
({
|
||||
name,
|
||||
type,
|
||||
price,
|
||||
description,
|
||||
value,
|
||||
privilegeId,
|
||||
serviceKey,
|
||||
id,
|
||||
amount,
|
||||
}) => (
|
||||
<СardPrivilegie
|
||||
key={privilegeId}
|
||||
name={name}
|
||||
type={type}
|
||||
amount={1}
|
||||
price={price}
|
||||
value={value}
|
||||
privilegeId={privilegeId}
|
||||
serviceKey={serviceKey}
|
||||
description={description}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
{privileges.map(privilege => (
|
||||
<СardPrivilegie
|
||||
key={privilege._id}
|
||||
privilege={privilege}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
@ -6,7 +6,6 @@ import {
|
||||
GridRowsProp,
|
||||
GridToolbar,
|
||||
} from "@mui/x-data-grid";
|
||||
import { formatDiscountFactor } from "@root/kitUI/Cart/calc";
|
||||
import {
|
||||
openEditDiscountDialog,
|
||||
setSelectedDiscountIds,
|
||||
@ -19,6 +18,7 @@ import { deleteDiscount } from "@root/api/discounts";
|
||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||
import { requestDiscounts } from "@root/services/discounts.service";
|
||||
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||
import { formatDiscountFactor } from "@root/utils/calcCart";
|
||||
|
||||
const columns: GridColDef[] = [
|
||||
// {
|
||||
@ -118,7 +118,6 @@ export default function DiscountDataGrid({ selectedRowsHC }: Props) {
|
||||
(state) => state.selectedDiscountIds
|
||||
);
|
||||
const realDiscounts = useDiscountStore((state) => state.discounts);
|
||||
const editDiscountId = useDiscountStore((state) => state.editDiscountId);
|
||||
|
||||
useEffect(() => {
|
||||
requestDiscounts();
|
||||
|
@ -16,7 +16,7 @@ export default function EditDiscountDialog() {
|
||||
const editDiscountId = useDiscountStore(state => state.editDiscountId);
|
||||
const discounts = useDiscountStore(state => state.discounts);
|
||||
const privileges = usePrivilegeStore(state => state.privileges);
|
||||
const [serviceType, setServiceType] = useState<ServiceType>("templategen");
|
||||
const [serviceType, setServiceType] = useState<string>("templategen");
|
||||
const [discountType, setDiscountType] = useState<DiscountType>("purchasesAmount");
|
||||
const [discountNameField, setDiscountNameField] = useState<string>("");
|
||||
const [discountDescriptionField, setDiscountDescriptionField] = useState<string>("");
|
||||
@ -322,4 +322,4 @@ export default function EditDiscountDialog() {
|
||||
</Box>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,20 +1,20 @@
|
||||
import { Box, IconButton, InputAdornment, TextField, Typography, useMediaQuery, useTheme } from "@mui/material";
|
||||
import { addOrUpdateMessages, clearMessageState, incrementMessageApiPage, setIsPreventAutoscroll, setMessageFetchState, useMessageStore } from "@root/stores/messages";
|
||||
import { addOrUpdateMessages, clearMessageState, incrementMessageApiPage, setIsPreventAutoscroll, useMessageStore } from "@root/stores/messages";
|
||||
import Message from "./Message";
|
||||
import SendIcon from "@mui/icons-material/Send";
|
||||
import AttachFileIcon from "@mui/icons-material/AttachFile";
|
||||
import { KeyboardEvent, useEffect, useRef, useState } from "react";
|
||||
import { KeyboardEvent, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { GetMessagesRequest, TicketMessage } from "@root/model/ticket";
|
||||
import { getTicketMessages, sendTicketMessage, subscribeToTicketMessages } from "@root/api/tickets";
|
||||
import { TicketMessage } from "@root/model/ticket";
|
||||
import { sendTicketMessage } from "@root/api/tickets";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { useTicketStore } from "@root/stores/tickets";
|
||||
import { throttle } from "@root/utils/throttle";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { getMessageFromFetchError, useEventListener, useSSESubscription, useTicketMessages, useToken } from "@frontend/kitui";
|
||||
|
||||
|
||||
export default function Chat() {
|
||||
const token = authStore(state => state.token);
|
||||
const token = useToken();
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const tickets = useTicketStore(state => state.tickets);
|
||||
@ -24,95 +24,53 @@ export default function Chat() {
|
||||
const chatBoxRef = useRef<HTMLDivElement>(null);
|
||||
const messageApiPage = useMessageStore(state => state.apiPage);
|
||||
const messagesPerPage = useMessageStore(state => state.messagesPerPage);
|
||||
const messagesFetchStateRef = useRef(useMessageStore.getState().fetchState);
|
||||
const isPreventAutoscroll = useMessageStore(state => state.isPreventAutoscroll);
|
||||
const lastMessageId = useMessageStore(state => state.lastMessageId);
|
||||
|
||||
const ticket = tickets.find(ticket => ticket.id === ticketId);
|
||||
|
||||
useEffect(function fetchTicketMessages() {
|
||||
if (!ticketId) return;
|
||||
|
||||
const getTicketsBody: GetMessagesRequest = {
|
||||
amt: messagesPerPage,
|
||||
page: messageApiPage,
|
||||
ticket: ticketId,
|
||||
};
|
||||
const controller = new AbortController();
|
||||
|
||||
setMessageFetchState("fetching");
|
||||
getTicketMessages({
|
||||
body: getTicketsBody,
|
||||
signal: controller.signal,
|
||||
}).then(result => {
|
||||
if (result?.length > 0) {
|
||||
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
|
||||
addOrUpdateMessages(result);
|
||||
setMessageFetchState("idle");
|
||||
} else setMessageFetchState("all fetched");
|
||||
}).catch(error => {
|
||||
console.log("Error fetching messages", error);
|
||||
enqueueSnackbar(error.message);
|
||||
});
|
||||
|
||||
return () => {
|
||||
controller.abort();
|
||||
};
|
||||
}, [messageApiPage, messagesPerPage, ticketId]);
|
||||
|
||||
useEffect(function subscribeToMessages() {
|
||||
if (!ticketId) return;
|
||||
|
||||
if (!token) return;
|
||||
|
||||
const unsubscribe = subscribeToTicketMessages({
|
||||
const fetchState = useTicketMessages({
|
||||
url: "https://admin.pena.digital/heruvym/getMessages",
|
||||
ticketId,
|
||||
accessToken: token,
|
||||
onMessage(event) {
|
||||
try {
|
||||
const newMessage = JSON.parse(event.data) as TicketMessage;
|
||||
console.log("SSE: parsed newMessage:", newMessage);
|
||||
addOrUpdateMessages([newMessage]);
|
||||
} catch (error) {
|
||||
console.log("SSE: couldn't parse:", event.data);
|
||||
console.log("Error parsing message SSE", error);
|
||||
}
|
||||
messagesPerPage,
|
||||
messageApiPage,
|
||||
onNewMessages: messages => {
|
||||
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
|
||||
addOrUpdateMessages(messages);
|
||||
},
|
||||
onError(event) {
|
||||
console.log("SSE Error:", event);
|
||||
onError: (error: Error) => {
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
useSSESubscription<TicketMessage>({
|
||||
enabled: Boolean(token) && Boolean(ticketId),
|
||||
url: `https://admin.pena.digital/heruvym/ticket?ticket=${ticketId}&Authorization=${token}`,
|
||||
onNewData: addOrUpdateMessages,
|
||||
onDisconnect: () => {
|
||||
clearMessageState();
|
||||
setIsPreventAutoscroll(false);
|
||||
};
|
||||
}, [ticketId, token]);
|
||||
|
||||
useEffect(function attachScrollHandler() {
|
||||
if (!chatBoxRef.current) return;
|
||||
},
|
||||
marker: "ticket message"
|
||||
});
|
||||
|
||||
const throttledScrollHandler = useMemo(() => throttle(() => {
|
||||
const chatBox = chatBoxRef.current;
|
||||
const scrollHandler = () => {
|
||||
const scrollBottom = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight;
|
||||
const isPreventAutoscroll = scrollBottom > chatBox.clientHeight;
|
||||
setIsPreventAutoscroll(isPreventAutoscroll);
|
||||
if (!chatBox) return;
|
||||
|
||||
if (messagesFetchStateRef.current !== "idle") return;
|
||||
const scrollBottom = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight;
|
||||
const isPreventAutoscroll = scrollBottom > chatBox.clientHeight * 20;
|
||||
setIsPreventAutoscroll(isPreventAutoscroll);
|
||||
|
||||
if (chatBox.scrollTop < chatBox.clientHeight) {
|
||||
incrementMessageApiPage();
|
||||
}
|
||||
};
|
||||
if (fetchState !== "idle") return;
|
||||
|
||||
const throttledScrollHandler = throttle(scrollHandler, 200);
|
||||
chatBox.addEventListener("scroll", throttledScrollHandler);
|
||||
if (chatBox.scrollTop < chatBox.clientHeight) {
|
||||
incrementMessageApiPage();
|
||||
}
|
||||
}, 200), [fetchState]);
|
||||
|
||||
return () => {
|
||||
chatBox.removeEventListener("scroll", throttledScrollHandler);
|
||||
};
|
||||
}, []);
|
||||
useEventListener("scroll", throttledScrollHandler, chatBoxRef);
|
||||
|
||||
useEffect(function scrollOnNewMessage() {
|
||||
if (!chatBoxRef.current) return;
|
||||
@ -125,8 +83,6 @@ export default function Chat() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [lastMessageId]);
|
||||
|
||||
useEffect(() => useMessageStore.subscribe(state => (messagesFetchStateRef.current = state.fetchState)), []);
|
||||
|
||||
function scrollToBottom(behavior?: ScrollBehavior) {
|
||||
if (!chatBoxRef.current) return;
|
||||
|
||||
|
@ -1,99 +1,60 @@
|
||||
import { Box, useMediaQuery, useTheme } from "@mui/material";
|
||||
import { useEffect } from "react";
|
||||
import Chat from "./Chat/Chat";
|
||||
import Collapse from "./Collapse";
|
||||
import TicketList from "./TicketList/TicketList";
|
||||
import { getTickets, subscribeToAllTickets } from "@root/api/tickets";
|
||||
import { GetTicketsRequest, Ticket } from "@root/model/ticket";
|
||||
import { clearTickets, setTicketsFetchState, updateTickets, useTicketStore } from "@root/stores/tickets";
|
||||
import { Ticket } from "@root/model/ticket";
|
||||
import { clearTickets, updateTickets, useTicketStore } from "@root/stores/tickets";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { clearMessageState } from "@root/stores/messages";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { getMessageFromFetchError, useSSESubscription, useTickets, useToken } from "@frontend/kitui";
|
||||
|
||||
export default function Support() {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
|
||||
const ticketApiPage = useTicketStore((state) => state.apiPage);
|
||||
const token = authStore((state) => state.token);
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
|
||||
const ticketApiPage = useTicketStore((state) => state.apiPage);
|
||||
const token = useToken();
|
||||
|
||||
useEffect(
|
||||
function fetchTickets() {
|
||||
const getTicketsBody: GetTicketsRequest = {
|
||||
amt: ticketsPerPage,
|
||||
page: ticketApiPage,
|
||||
status: "open",
|
||||
};
|
||||
const controller = new AbortController();
|
||||
|
||||
setTicketsFetchState("fetching");
|
||||
getTickets({
|
||||
body: getTicketsBody,
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((result) => {
|
||||
console.log("GetTicketsResponse", result);
|
||||
if (result.data) {
|
||||
updateTickets(result.data);
|
||||
setTicketsFetchState("idle");
|
||||
} else setTicketsFetchState("all fetched");
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log("Error fetching tickets", error);
|
||||
enqueueSnackbar(error.message);
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
},
|
||||
[ticketApiPage, ticketsPerPage]
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function subscribeToTickets() {
|
||||
if (!token) return;
|
||||
|
||||
const unsubscribe = subscribeToAllTickets({
|
||||
accessToken: token,
|
||||
onMessage(event) {
|
||||
try {
|
||||
const newTicket = JSON.parse(event.data) as Ticket;
|
||||
console.log("SSE: parsed newTicket:", newTicket);
|
||||
updateTickets([newTicket]);
|
||||
} catch (error) {
|
||||
console.log("SSE: couldn't parse:", event.data);
|
||||
console.log("Error parsing ticket SSE", error);
|
||||
}
|
||||
const ticketsFetchState = useTickets({
|
||||
url: "https://admin.pena.digital/heruvym/getTickets",
|
||||
ticketsPerPage,
|
||||
ticketApiPage,
|
||||
onNewTickets: result => {
|
||||
if (result.data) updateTickets(result.data);
|
||||
},
|
||||
onError(event) {
|
||||
console.log("SSE Error:", event);
|
||||
onError: (error: Error) => {
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
clearMessageState();
|
||||
clearTickets();
|
||||
};
|
||||
},
|
||||
[token]
|
||||
);
|
||||
useSSESubscription<Ticket>({
|
||||
enabled: Boolean(token),
|
||||
url: `https://admin.pena.digital/heruvym/subscribe?Authorization=${token}`,
|
||||
onNewData: updateTickets,
|
||||
onDisconnect: () => {
|
||||
clearMessageState();
|
||||
clearTickets();
|
||||
},
|
||||
marker: "ticket"
|
||||
});
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
width: "100%",
|
||||
flexDirection: upMd ? "row" : "column",
|
||||
gap: "12px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<Collapse headerText="Тикеты">
|
||||
<TicketList />
|
||||
</Collapse>
|
||||
)}
|
||||
<Chat />
|
||||
{upMd && <TicketList />}
|
||||
</Box>
|
||||
);
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
width: "100%",
|
||||
flexDirection: upMd ? "row" : "column",
|
||||
gap: "12px",
|
||||
}}
|
||||
>
|
||||
{!upMd && (
|
||||
<Collapse headerText="Тикеты">
|
||||
<TicketList ticketsFetchState={ticketsFetchState} />
|
||||
</Collapse>
|
||||
)}
|
||||
<Chat />
|
||||
{upMd && <TicketList ticketsFetchState={ticketsFetchState} />}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
@ -6,13 +6,17 @@ import { incrementTicketsApiPage, useTicketStore } from "@root/stores/tickets";
|
||||
import { throttle } from '@root/utils/throttle';
|
||||
import { useEffect, useRef } from "react";
|
||||
import TicketItem from "./TicketItem";
|
||||
import { useTickets } from '@frontend/kitui';
|
||||
|
||||
|
||||
export default function TicketList() {
|
||||
interface Props {
|
||||
ticketsFetchState: ReturnType<typeof useTickets>;
|
||||
}
|
||||
|
||||
export default function TicketList({ ticketsFetchState }: Props) {
|
||||
const theme = useTheme();
|
||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||
const tickets = useTicketStore(state => state.tickets);
|
||||
const ticketsFetchStateRef = useRef(useTicketStore.getState().fetchState);
|
||||
const ticketsBoxRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(function updateCurrentPageOnScroll() {
|
||||
@ -23,7 +27,7 @@ export default function TicketList() {
|
||||
const scrollBottom = ticketsBox.scrollHeight - ticketsBox.scrollTop - ticketsBox.clientHeight;
|
||||
if (
|
||||
scrollBottom < ticketsBox.clientHeight &&
|
||||
ticketsFetchStateRef.current === "idle"
|
||||
ticketsFetchState === "idle"
|
||||
) incrementTicketsApiPage();
|
||||
};
|
||||
|
||||
@ -33,9 +37,7 @@ export default function TicketList() {
|
||||
return () => {
|
||||
ticketsBox.removeEventListener("scroll", throttledScrollHandler);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => useTicketStore.subscribe(state => (ticketsFetchStateRef.current = state.fetchState)), []);
|
||||
}, [ticketsFetchState]);
|
||||
|
||||
const sortedTickets = tickets.sort(sortTicketsByUpdateTime).sort(sortTicketsByUnread);
|
||||
|
||||
@ -121,4 +123,4 @@ function sortTicketsByUnread(ticket1: Ticket, ticket2: Ticket) {
|
||||
const isUnread1 = ticket1.user === ticket1.top_message.user_id;
|
||||
const isUnread2 = ticket2.user === ticket2.top_message.user_id;
|
||||
return Number(isUnread2) - Number(isUnread1);
|
||||
}
|
||||
}
|
||||
|
@ -15,19 +15,18 @@ import { enqueueSnackbar } from "notistack";
|
||||
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
||||
import { requestTariffs } from "@root/services/tariffs.service";
|
||||
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import {
|
||||
findPrivilegeById,
|
||||
usePrivilegeStore,
|
||||
} from "@root/stores/privilegesStore";
|
||||
import { PrivilegeWithAmount, makeRequest } from "@frontend/kitui";
|
||||
|
||||
import type { Privilege_BACKEND } from "@root/model/tariff";
|
||||
|
||||
type CreateTariffBackendRequest = {
|
||||
name: string;
|
||||
price: number;
|
||||
isCustom: boolean;
|
||||
privilegies: Omit<Privilege_BACKEND, "_id" | "updatedAt">[];
|
||||
privilegies: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
||||
};
|
||||
|
||||
const baseUrl =
|
||||
@ -36,7 +35,6 @@ const baseUrl =
|
||||
: "https://admin.pena.digital/strator";
|
||||
|
||||
export default function CreateTariff() {
|
||||
const { makeRequest } = authStore();
|
||||
const theme = useTheme();
|
||||
|
||||
const privileges = usePrivilegeStore((store) => store.privileges);
|
||||
@ -73,7 +71,6 @@ export default function CreateTariff() {
|
||||
makeRequest<CreateTariffBackendRequest>({
|
||||
url: baseUrl + "/tariff/",
|
||||
method: "post",
|
||||
bearer: true,
|
||||
body: {
|
||||
name: nameField,
|
||||
price: Number(customPriceField) * 100,
|
||||
@ -81,7 +78,7 @@ export default function CreateTariff() {
|
||||
privilegies: [
|
||||
{
|
||||
name: privilege.name,
|
||||
privilegeId: privilege.id ?? "",
|
||||
privilegeId: privilege.privilegeId ?? "",
|
||||
serviceKey: privilege.serviceKey,
|
||||
description: privilege.description,
|
||||
type: privilege.type,
|
||||
@ -170,7 +167,7 @@ export default function CreateTariff() {
|
||||
inputProps={{ sx: { pt: "12px" } }}
|
||||
>
|
||||
{privileges.map((privilege) => (
|
||||
<MenuItem key={privilege.description} value={privilege.id}>
|
||||
<MenuItem key={privilege.description} value={privilege._id}>
|
||||
{privilege.description}
|
||||
</MenuItem>
|
||||
))}
|
||||
|
@ -1,117 +1,74 @@
|
||||
import * as React from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Modal from "@mui/material/Modal";
|
||||
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||
import { closeDeleteTariffDialog, useTariffStore } from "@root/stores/tariffs";
|
||||
import { requestTariffs } from "@root/services/tariffs.service";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { deleteManyTariffs } from "@root/api/tariffs";
|
||||
import { devlog } from "@frontend/kitui";
|
||||
|
||||
type DeleteModalProps = {
|
||||
open: boolean | string;
|
||||
handleClose: () => void;
|
||||
selectedTariffs: any;
|
||||
};
|
||||
|
||||
type DeleteTariffRequest = {
|
||||
id: string;
|
||||
};
|
||||
export default function DeleteModal() {
|
||||
const deleteTariffIds = useTariffStore(state => state.deleteTariffIds);
|
||||
|
||||
const baseUrl =
|
||||
process.env.NODE_ENV === "production"
|
||||
? "/strator"
|
||||
: "https://admin.pena.digital/strator";
|
||||
async function handleTariffDeleteClick() {
|
||||
if (!deleteTariffIds?.length) return;
|
||||
|
||||
export default function DeleteModal({
|
||||
open,
|
||||
handleClose,
|
||||
selectedTariffs,
|
||||
}: DeleteModalProps) {
|
||||
const { makeRequest } = authStore();
|
||||
const tariffs = useTariffStore((state) => state.tariffs);
|
||||
const results = await deleteManyTariffs(deleteTariffIds);
|
||||
|
||||
const deleteTariff = async (id: string): Promise<void> => {
|
||||
const currentTariff = tariffs[id];
|
||||
enqueueSnackbar(`Тарифов удалено: ${results.deletedCount}, ошибок: ${results.errorCount}`);
|
||||
if (results.errors.length) devlog("Errors deleting tariffs", results.errors);
|
||||
closeDeleteTariffDialog();
|
||||
|
||||
if (!currentTariff) {
|
||||
enqueueSnackbar("Тариф не найден");
|
||||
return;
|
||||
}
|
||||
requestTariffs();
|
||||
};
|
||||
|
||||
try {
|
||||
await makeRequest<DeleteTariffRequest>({
|
||||
url: baseUrl + "/tariff/",
|
||||
method: "delete",
|
||||
bearer: true,
|
||||
body: { id },
|
||||
});
|
||||
} catch {
|
||||
enqueueSnackbar("Ошибка при удалении тарифа на бэкэнде");
|
||||
}
|
||||
};
|
||||
|
||||
const onClickTariffDelete = () => {
|
||||
if (typeof open === "string") {
|
||||
deleteTariff(open);
|
||||
requestTariffs();
|
||||
handleClose();
|
||||
return;
|
||||
}
|
||||
selectedTariffs.forEach((id: string) => {
|
||||
deleteTariff(id);
|
||||
});
|
||||
handleClose();
|
||||
requestTariffs();
|
||||
};
|
||||
return (
|
||||
<div>
|
||||
<Modal
|
||||
open={Boolean(open)}
|
||||
onClose={handleClose}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
position: "absolute",
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
width: 400,
|
||||
bgcolor: "background.paper",
|
||||
border: "2px solid gray",
|
||||
borderRadius: "6px",
|
||||
boxShadow: 24,
|
||||
p: 4,
|
||||
}}
|
||||
return (
|
||||
<Modal
|
||||
open={Boolean(deleteTariffIds?.length)}
|
||||
onClose={closeDeleteTariffDialog}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
<Typography id="modal-modal-title" variant="h6" component="h2">
|
||||
Вы уверены, что хотите удалить{" "}
|
||||
{typeof open === "string" ? "тариф" : "тарифы"} ?
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
mt: "20px",
|
||||
display: "flex",
|
||||
width: "332px",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
onClick={() => onClickTariffDelete()}
|
||||
sx={{ width: "40px", height: "25px" }}
|
||||
<Box
|
||||
sx={{
|
||||
position: "absolute",
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
width: 400,
|
||||
bgcolor: "background.paper",
|
||||
border: "2px solid gray",
|
||||
borderRadius: "6px",
|
||||
boxShadow: 24,
|
||||
p: 4,
|
||||
}}
|
||||
>
|
||||
Да
|
||||
</Button>
|
||||
{/* <Typography>Тариф:</Typography>
|
||||
<Typography id="modal-modal-title" variant="h6" component="h2">
|
||||
Вы уверены, что хотите удалить тариф(ы)?
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
mt: "20px",
|
||||
display: "flex",
|
||||
width: "332px",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
onClick={() => handleTariffDeleteClick()}
|
||||
sx={{ width: "40px", height: "25px" }}
|
||||
>
|
||||
Да
|
||||
</Button>
|
||||
{/* <Typography>Тариф:</Typography>
|
||||
{tariffName.map((name, index) => (
|
||||
<Typography key={index}>{name};</Typography>
|
||||
))} */}
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
</Box>
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
@ -1,182 +1,113 @@
|
||||
// @ts-nocheck
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import Button from "@mui/material/Button";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import Modal from "@mui/material/Modal";
|
||||
import TextField from "@mui/material/TextField";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { Privilege, Tariff } from "@root/model/tariff";
|
||||
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||
import { requestTariffs } from "@root/services/tariffs.service";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { devlog, getMessageFromFetchError } from "@frontend/kitui";
|
||||
import { closeEditTariffDialog, useTariffStore } from "@root/stores/tariffs";
|
||||
import { putTariff } from "@root/api/tariffs";
|
||||
import { requestTariffs } from "@root/services/tariffs.service";
|
||||
|
||||
interface EditProps {
|
||||
tarifIid: string;
|
||||
tariffName: string;
|
||||
tariffPrice: number;
|
||||
privilege: Privilege;
|
||||
}
|
||||
|
||||
type EditTariffBackendRequest = {
|
||||
name: string;
|
||||
price: number;
|
||||
isCustom: boolean;
|
||||
privilegies: Omit<Privilege_BACKEND, "_id" | "updatedAt">[];
|
||||
};
|
||||
export default function EditModal() {
|
||||
const [nameField, setNameField] = useState("");
|
||||
const [priceField, setPriceField] = useState("");
|
||||
const tariffs = useTariffStore((state) => state.tariffs);
|
||||
const editTariffId = useTariffStore(state => state.editTariffId);
|
||||
|
||||
const baseUrl =
|
||||
process.env.NODE_ENV === "production"
|
||||
? "/strator"
|
||||
: "https://admin.pena.digital/strator";
|
||||
const tariff = tariffs.find(tariff => tariff._id === editTariffId);
|
||||
|
||||
const editTariff = ({
|
||||
tarifIid,
|
||||
tariffName,
|
||||
tariffPrice,
|
||||
privilege,
|
||||
}: EditProps): Promise<unknown> => {
|
||||
const { makeRequest } = authStore.getState();
|
||||
useEffect(function setCurrentTariffFields() {
|
||||
if (!tariff) return;
|
||||
|
||||
return makeRequest<EditTariffBackendRequest>({
|
||||
method: "put",
|
||||
url: baseUrl + `/tariff/${tarifIid}`,
|
||||
bearer: true,
|
||||
body: {
|
||||
name: tariffName,
|
||||
price: tariffPrice,
|
||||
isCustom: false,
|
||||
privilegies: [privilege],
|
||||
},
|
||||
});
|
||||
};
|
||||
interface Props {
|
||||
tariff: Tariff;
|
||||
}
|
||||
setNameField(tariff.name);
|
||||
setPriceField((tariff.price || 0).toString());
|
||||
}, [tariff]);
|
||||
|
||||
export default function EditModal({ tariff = undefined }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [price, setPrice] = useState("");
|
||||
const tariffs = useTariffStore((state) => state.tariffs);
|
||||
const currentTariff = tariff ? tariffs[tariff.id] : undefined;
|
||||
async function handleEditClick() {
|
||||
if (!tariff) return enqueueSnackbar(`Тариф ${editTariffId} не найден`);
|
||||
|
||||
useEffect(() => {
|
||||
setOpen(tariff !== undefined);
|
||||
}, [tariff]);
|
||||
const price = parseFloat(priceField);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
position: "absolute",
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
width: 400,
|
||||
bgcolor: "background.paper",
|
||||
border: "2px solid gray",
|
||||
borderRadius: "6px",
|
||||
boxShadow: 24,
|
||||
p: 4,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
id="modal-modal-title"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
sx={{ whiteSpace: "nowrap" }}
|
||||
if (!isFinite(price)) return enqueueSnackbar("Поле \"Цена за единицу\" не число");
|
||||
if (!nameField) return enqueueSnackbar("Поле \"Имя\" пустое");
|
||||
|
||||
const updatedTariff = structuredClone(tariff);
|
||||
updatedTariff.name = nameField;
|
||||
updatedTariff.price = price;
|
||||
try {
|
||||
await putTariff(updatedTariff);
|
||||
closeEditTariffDialog();
|
||||
|
||||
requestTariffs();
|
||||
} catch (error) {
|
||||
devlog("Error updating tariff", error);
|
||||
const message = getMessageFromFetchError(error);
|
||||
if (message) enqueueSnackbar(message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={editTariffId !== null}
|
||||
onClose={closeEditTariffDialog}
|
||||
aria-labelledby="modal-modal-title"
|
||||
aria-describedby="modal-modal-description"
|
||||
>
|
||||
Редактирование тариффа
|
||||
</Typography>
|
||||
|
||||
{currentTariff !== undefined && (
|
||||
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
||||
<Typography>Название Тарифа: {currentTariff.name}</Typography>
|
||||
<TextField
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
label="Имя"
|
||||
name="name"
|
||||
value={name}
|
||||
sx={{ marginBottom: "10px" }}
|
||||
/>
|
||||
<Typography>
|
||||
Цена за единицу: {currentTariff.pricePerUnit}
|
||||
</Typography>
|
||||
<TextField
|
||||
onChange={(event) => setPrice(event.target.value)}
|
||||
label="Цена за единицу"
|
||||
name="price"
|
||||
value={price}
|
||||
sx={{ marginBottom: "10px" }}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!currentTariff.isFront) {
|
||||
const privilege = findPrivilegeById(
|
||||
currentTariff.privilegeId
|
||||
);
|
||||
privilege.privilegeId = privilege.id;
|
||||
console.log(privilege);
|
||||
|
||||
//back
|
||||
if (privilege !== null) {
|
||||
privilege.amount = tariff.amount;
|
||||
privilege.privilegeName = privilege.name;
|
||||
privilege.privilegeId = privilege.id;
|
||||
privilege.serviceName = privilege.serviceKey;
|
||||
console.log(privilege);
|
||||
|
||||
editTariff({
|
||||
tarifIid: currentTariff.id,
|
||||
tariffName: name ? name : currentTariff.name,
|
||||
tariffPrice: price
|
||||
? Number(price)
|
||||
: currentTariff.price
|
||||
? currentTariff.price
|
||||
: privilege.price,
|
||||
isDeleted: currentTariff.isDeleted,
|
||||
customPricePerUnit: currentTariff.price,
|
||||
privilege: privilege,
|
||||
}).then(() => {
|
||||
setOpen(false);
|
||||
requestTariffs();
|
||||
});
|
||||
} else {
|
||||
enqueueSnackbar(
|
||||
`Привилегия с id ${currentTariff.privilegeId} не найдена в тарифе ${currentTariff.name} с id ${currentTariff.id}`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
//front/store
|
||||
|
||||
let array = tariffs;
|
||||
let index;
|
||||
tariffs.forEach((p: any, i: number) => {
|
||||
if (currentTariff.id == p.id) index = i;
|
||||
});
|
||||
if (index !== undefined) {
|
||||
array[index].name = name;
|
||||
array[index].amount = Number(price);
|
||||
updateTariffs(array);
|
||||
setOpen(false);
|
||||
} else {
|
||||
console.log("не нашел такой тариф в сторе");
|
||||
}
|
||||
}
|
||||
}}
|
||||
<Box
|
||||
sx={{
|
||||
position: "absolute",
|
||||
top: "50%",
|
||||
left: "50%",
|
||||
transform: "translate(-50%, -50%)",
|
||||
width: 400,
|
||||
bgcolor: "background.paper",
|
||||
border: "2px solid gray",
|
||||
borderRadius: "6px",
|
||||
boxShadow: 24,
|
||||
p: 4,
|
||||
}}
|
||||
>
|
||||
Редактировать
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
<Typography
|
||||
id="modal-modal-title"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
sx={{ whiteSpace: "nowrap" }}
|
||||
>
|
||||
Редактирование тариффа
|
||||
</Typography>
|
||||
|
||||
{tariff && (
|
||||
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
||||
<Typography>Название Тарифа: {tariff.name}</Typography>
|
||||
<TextField
|
||||
onChange={(event) => setNameField(event.target.value)}
|
||||
label="Имя"
|
||||
name="name"
|
||||
value={nameField}
|
||||
sx={{ marginBottom: "10px" }}
|
||||
/>
|
||||
<Typography>
|
||||
Цена за единицу: {tariff.privilegies[0].price}
|
||||
</Typography>
|
||||
<TextField
|
||||
type="number"
|
||||
onChange={(event) => setPriceField(event.target.value)}
|
||||
label="Цена за единицу"
|
||||
name="price"
|
||||
value={priceField}
|
||||
sx={{ marginBottom: "10px" }}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleEditClick}
|
||||
>
|
||||
Редактировать
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
@ -1,26 +1,17 @@
|
||||
import { useState } from "react";
|
||||
import { Typography } from "@mui/material";
|
||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||
|
||||
import Cart from "@root/kitUI/Cart/Cart";
|
||||
import TariffsDG from "./tariffsDG";
|
||||
|
||||
|
||||
export default function TariffsInfo() {
|
||||
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>(
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography variant="h6" mt="20px">
|
||||
Список тарифов
|
||||
</Typography>
|
||||
<TariffsDG
|
||||
selectedTariffs={selectedTariffs}
|
||||
handleSelectionChange={setSelectedTariffs}
|
||||
/>
|
||||
|
||||
<Cart selectedTariffs={selectedTariffs} />
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Typography variant="h6" mt="20px">
|
||||
Список тарифов
|
||||
</Typography>
|
||||
<TariffsDG />
|
||||
<Cart />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
@ -1,164 +1,96 @@
|
||||
// @ts-nocheck
|
||||
import React, { useEffect } from "react";
|
||||
import { useState } from "react";
|
||||
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
|
||||
import { GridColDef, GridToolbar } from "@mui/x-data-grid";
|
||||
import { Box, Button, IconButton, Tooltip } from "@mui/material";
|
||||
import BackspaceIcon from "@mui/icons-material/Backspace";
|
||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
||||
|
||||
import DataGrid from "@kitUI/datagrid";
|
||||
|
||||
import { useTariffStore } from "@root/stores/tariffsStore";
|
||||
import { findPrivilegeById } from "@root/stores/privilegesStore";
|
||||
|
||||
import DeleteModal from "@root/pages/dashboard/Content/Tariffs/DeleteModal";
|
||||
import EditModal from "./EditModal";
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||
import { requestTariffs } from "@root/services/tariffs.service";
|
||||
import { openDeleteTariffDialog, openEditTariffDialog, setSelectedTariffIds, useTariffStore } from "@root/stores/tariffs";
|
||||
import { Tariff } from "@frontend/kitui";
|
||||
import { getTariffPrice } from "@root/utils/tariffPrice";
|
||||
|
||||
interface Props {
|
||||
selectedTariffs: GridSelectionModel;
|
||||
handleSelectionChange: (selectionModel: GridSelectionModel) => void;
|
||||
}
|
||||
|
||||
export default function TariffsDG({
|
||||
selectedTariffs,
|
||||
handleSelectionChange,
|
||||
}: Props) {
|
||||
const tariffs = useTariffStore((state) => state.tariffs);
|
||||
const [openDeleteModal, setOpenDeleteModal] = useState(false);
|
||||
const [changingTariff, setChangingTariff] = useState<Tariff | undefined>();
|
||||
const [gridData, setGridData] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const data = Object.values(tariffs)
|
||||
?.map((tariff) => {
|
||||
console.log(tariff);
|
||||
const privilege = findPrivilegeById(tariff.privilegeId);
|
||||
return {
|
||||
id: tariff.id,
|
||||
name: tariff.name,
|
||||
serviceName:
|
||||
privilege?.serviceKey == "templategen"
|
||||
? "Шаблонизатор"
|
||||
: privilege?.serviceKey,
|
||||
privilegeName: privilege?.name,
|
||||
amount: tariff.amount,
|
||||
pricePerUnit: tariff.isCustom
|
||||
? (tariff.customPricePerUnit || 0) / 100
|
||||
: (tariff?.price || 0) / 100,
|
||||
type:
|
||||
findPrivilegeById(tariff.privilegeId)?.value === "шаблон"
|
||||
? "штука"
|
||||
: findPrivilegeById(tariff.privilegeId)?.value,
|
||||
customPricePerUnit: tariff.customPricePerUnit === 0 ? "Нет" : "Да",
|
||||
total: tariff.amount
|
||||
? (tariff.amount *
|
||||
(tariff.isCustom
|
||||
? tariff.customPricePerUnit || 0 * tariff.amount
|
||||
: findPrivilegeById(tariff.privilegeId)?.price || 0)) /
|
||||
100
|
||||
: 0,
|
||||
};
|
||||
})
|
||||
.sort((item, previous) => (!item?.isFront && previous?.isFront ? 1 : -1));
|
||||
|
||||
setGridData(data);
|
||||
}, [tariffs]);
|
||||
|
||||
console.log(selectedTariffs);
|
||||
|
||||
const closeDeleteModal = () => {
|
||||
setOpenDeleteModal(false);
|
||||
};
|
||||
|
||||
const columns: GridColDef[] = [
|
||||
{ field: "id", headerName: "ID", width: 100 },
|
||||
const columns: GridColDef<Tariff, string | number>[] = [
|
||||
{ field: "_id", headerName: "ID", width: 100, valueGetter: ({ row }) => row._id },
|
||||
{
|
||||
field: "edit",
|
||||
headerName: "Изменение",
|
||||
width: 60,
|
||||
renderCell: ({ row }) => {
|
||||
return (
|
||||
<IconButton onClick={() => setChangingTariff(row)}>
|
||||
<ModeEditOutlineOutlinedIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
field: "edit",
|
||||
headerName: "Изменение",
|
||||
width: 60,
|
||||
renderCell: ({ row }) => {
|
||||
return (
|
||||
<IconButton onClick={() => openEditTariffDialog(row._id)}>
|
||||
<ModeEditOutlineOutlinedIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
},
|
||||
{ field: "name", headerName: "Название тарифа", width: 150 },
|
||||
{ field: "amount", headerName: "Количество", width: 110 },
|
||||
{ field: "serviceName", headerName: "Сервис", width: 150 }, //инфо из гитлаба.
|
||||
{ field: "privilegeName", headerName: "Привилегия", width: 150 },
|
||||
{ field: "type", headerName: "Единица", width: 100 },
|
||||
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100 },
|
||||
{ field: "customPricePerUnit", headerName: "Кастомная цена", width: 130 },
|
||||
{ field: "total", headerName: "Сумма", width: 60 },
|
||||
{ field: "name", headerName: "Название тарифа", width: 150, valueGetter: ({ row }) => row.name },
|
||||
{ field: "amount", headerName: "Количество", width: 110, valueGetter: ({ row }) => row.privilegies[0].amount },
|
||||
{ field: "serviceName", headerName: "Сервис", width: 150, valueGetter: ({ row }) => row.privilegies[0].serviceKey },
|
||||
{ field: "privilegeName", headerName: "Привилегия", width: 150, valueGetter: ({ row }) => row.privilegies[0].name },
|
||||
{ field: "type", headerName: "Единица", width: 100, valueGetter: ({ row }) => row.privilegies[0].type },
|
||||
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100, valueGetter: ({ row }) => row.privilegies[0].price },
|
||||
{ field: "customPricePerUnit", headerName: "Кастомная цена", width: 130, valueGetter: ({ row }) => row.isCustom ? "Да" : "Нет" },
|
||||
{ field: "total", headerName: "Сумма", width: 60, valueGetter: ({ row }) => getTariffPrice(row) },
|
||||
{
|
||||
field: "delete",
|
||||
headerName: "Удаление",
|
||||
width: 60,
|
||||
renderCell: ({ row }) => {
|
||||
return (
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
setOpenDeleteModal(row.id);
|
||||
}}
|
||||
>
|
||||
<BackspaceIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
field: "delete",
|
||||
headerName: "Удаление",
|
||||
width: 60,
|
||||
renderCell: ({ row }) => {
|
||||
return (
|
||||
<IconButton onClick={() => openDeleteTariffDialog([row._id])}>
|
||||
<BackspaceIcon />
|
||||
</IconButton>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
];
|
||||
|
||||
// console.log(gridData)
|
||||
export default function TariffsDG() {
|
||||
const tariffs = useTariffStore((state) => state.tariffs);
|
||||
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tooltip title="обновить список тарифов">
|
||||
<IconButton onClick={() => requestTariffs()}>
|
||||
<AutorenewIcon sx={{ color: "white" }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<DataGrid
|
||||
disableSelectionOnClick={true}
|
||||
checkboxSelection={true}
|
||||
rows={gridData}
|
||||
columns={columns}
|
||||
getRowId={(row) => row.id}
|
||||
components={{ Toolbar: GridToolbar }}
|
||||
onSelectionModelChange={handleSelectionChange}
|
||||
/>
|
||||
{selectedTariffs.length ? (
|
||||
<Box
|
||||
component="section"
|
||||
sx={{
|
||||
width: "100%",
|
||||
display: "flex",
|
||||
justifyContent: "start",
|
||||
mb: "30px",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
onClick={() => setOpenDeleteModal(true)}
|
||||
sx={{ mr: "20px", zIndex: "10000" }}
|
||||
>
|
||||
Удаление
|
||||
</Button>
|
||||
</Box>
|
||||
) : (
|
||||
<React.Fragment />
|
||||
)}
|
||||
<DeleteModal
|
||||
open={openDeleteModal}
|
||||
handleClose={() => {
|
||||
closeDeleteModal();
|
||||
}}
|
||||
selectedTariffs={selectedTariffs}
|
||||
/>
|
||||
<EditModal tariff={changingTariff} />
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Tooltip title="обновить список тарифов">
|
||||
<IconButton onClick={() => requestTariffs()}>
|
||||
<AutorenewIcon sx={{ color: "white" }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<DataGrid
|
||||
disableSelectionOnClick={true}
|
||||
checkboxSelection={true}
|
||||
rows={tariffs}
|
||||
columns={columns}
|
||||
getRowId={(row) => row._id}
|
||||
components={{ Toolbar: GridToolbar }}
|
||||
onSelectionModelChange={setSelectedTariffIds}
|
||||
sx={{
|
||||
minHeight: "600px",
|
||||
}}
|
||||
/>
|
||||
{selectedTariffIds.length ? (
|
||||
<Box
|
||||
component="section"
|
||||
sx={{
|
||||
width: "100%",
|
||||
display: "flex",
|
||||
justifyContent: "start",
|
||||
mb: "30px",
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
onClick={() => openDeleteTariffDialog(selectedTariffIds.map(s => s.toString()))}
|
||||
sx={{ mr: "20px", zIndex: "10000" }}
|
||||
>
|
||||
Удалить выделенные
|
||||
</Button>
|
||||
</Box>
|
||||
) : null}
|
||||
<DeleteModal />
|
||||
<EditModal />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
@ -24,19 +24,17 @@ import ClearIcon from "@mui/icons-material/Clear";
|
||||
import ConditionalRender from "@root/pages/Setting/ConditionalRender";
|
||||
import ServiceUsersDG from "./ServiceUsersDG";
|
||||
|
||||
import { authStore } from "@stores/auth";
|
||||
|
||||
import { getRoles_mock, TMockData } from "../../../api/roles";
|
||||
|
||||
import theme from "../../../theme";
|
||||
|
||||
import type { UsersType } from "../../../api/roles";
|
||||
import { makeRequest } from "@frontend/kitui";
|
||||
|
||||
const baseUrl =
|
||||
process.env.NODE_ENV === "production" ? "" : "https://admin.pena.digital";
|
||||
|
||||
const Users: React.FC = () => {
|
||||
const { makeRequest } = authStore();
|
||||
// makeRequest({
|
||||
// url: "https://admin.pena.digital/strator/account",
|
||||
// method: "get",
|
||||
|
@ -3,11 +3,11 @@ import { Box, IconButton, Typography } from "@mui/material";
|
||||
import theme from "../../../theme";
|
||||
import ExitToAppOutlinedIcon from "@mui/icons-material/ExitToAppOutlined";
|
||||
import Logo from "../../Logo";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { clearAuthToken, makeRequest } from "@frontend/kitui";
|
||||
|
||||
const Header: React.FC = () => {
|
||||
const { makeRequest, clearToken } = authStore();
|
||||
return (
|
||||
|
||||
return (
|
||||
<React.Fragment>
|
||||
<Box
|
||||
sx={{
|
||||
@ -55,7 +55,7 @@ const Header: React.FC = () => {
|
||||
makeRequest({
|
||||
url: "https://admin.pena.digital/auth/logout",
|
||||
contentType: true,
|
||||
}).then(() => clearToken());
|
||||
}).then(() => clearAuthToken());
|
||||
}}
|
||||
sx={{
|
||||
display: "flex",
|
||||
|
@ -1,31 +1,30 @@
|
||||
import { setDiscounts } from "@root/stores/discounts";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
|
||||
import type { GetDiscountResponse, Discount } from "@root/model/discount";
|
||||
import type { GetDiscountResponse } from "@root/model/discount";
|
||||
import { Discount, makeRequest } from "@frontend/kitui";
|
||||
|
||||
const baseUrl =
|
||||
process.env.NODE_ENV === "production"
|
||||
? "/price"
|
||||
: "https://admin.pena.digital/price";
|
||||
|
||||
const { makeRequest } = authStore.getState();
|
||||
|
||||
const filterDiscounts = (discounts: Discount[]) => {
|
||||
const activeDiscounts = discounts.filter((discount) => !discount.Deprecated);
|
||||
|
||||
setDiscounts(activeDiscounts);
|
||||
};
|
||||
|
||||
export const requestDiscounts = async (): Promise<void> => {
|
||||
export const requestDiscounts = async (): Promise<Discount[]> => {
|
||||
try {
|
||||
const { Discounts } = await makeRequest<never, GetDiscountResponse>({
|
||||
url: baseUrl + "/discounts",
|
||||
method: "get",
|
||||
useToken: true,
|
||||
bearer: true,
|
||||
});
|
||||
|
||||
filterDiscounts(Discounts);
|
||||
|
||||
return Discounts
|
||||
} catch {
|
||||
throw new Error("Ошибка при получении скидок");
|
||||
}
|
||||
|
@ -1,26 +1,10 @@
|
||||
import { authStore } from "@root/stores/auth";
|
||||
|
||||
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
||||
import { exampleCartValues } from "@stores/mocks/exampleCartValues";
|
||||
|
||||
import type { RealPrivilege } from "@root/model/privilege";
|
||||
|
||||
export type Privilege = {
|
||||
createdAt: string;
|
||||
description: string;
|
||||
isDeleted: boolean;
|
||||
name: string;
|
||||
price: number;
|
||||
privilegeId: string;
|
||||
serviceKey: string;
|
||||
type: "count" | "day" | "mb";
|
||||
updatedAt: string;
|
||||
value: string;
|
||||
_id: string;
|
||||
};
|
||||
import { PrivilegeWithAmount, makeRequest } from "@frontend/kitui";
|
||||
|
||||
type SeverPrivilegiesResponse = {
|
||||
templategen: RealPrivilege[];
|
||||
templategen: PrivilegeWithAmount[];
|
||||
};
|
||||
|
||||
const baseUrl =
|
||||
@ -28,10 +12,8 @@ const baseUrl =
|
||||
? "/strator"
|
||||
: "https://admin.pena.digital/strator";
|
||||
|
||||
const { makeRequest } = authStore.getState();
|
||||
|
||||
const mutatePrivilegies = (privilegies: RealPrivilege[]) => {
|
||||
let extracted: RealPrivilege[] = [];
|
||||
const mutatePrivilegies = (privilegies: PrivilegeWithAmount[]) => {
|
||||
let extracted: PrivilegeWithAmount[] = [];
|
||||
for (let serviceKey in privilegies) {
|
||||
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
||||
extracted = extracted.concat(privilegies[serviceKey]);
|
||||
@ -45,7 +27,7 @@ const mutatePrivilegies = (privilegies: RealPrivilege[]) => {
|
||||
type: privilege.type,
|
||||
price: privilege.price,
|
||||
value: privilege.value,
|
||||
id: privilege._id,
|
||||
_id: privilege._id,
|
||||
}));
|
||||
|
||||
resetPrivilegeArray([...readyArray, ...exampleCartValues.privileges]);
|
||||
|
@ -1,62 +1,43 @@
|
||||
import { resetTariffsStore } from "@root/stores/tariffsStore";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { Tariff, makeRequest } from "@frontend/kitui";
|
||||
import { updateTariffs } from "@root/stores/tariffs";
|
||||
|
||||
import type { Tariff, Tariff_BACKEND } from "@root/model/tariff";
|
||||
|
||||
type GetTariffsResponse = {
|
||||
totalPages: number;
|
||||
tariffs: Tariff_BACKEND[];
|
||||
totalPages: number;
|
||||
tariffs: Tariff[];
|
||||
};
|
||||
|
||||
const baseUrl =
|
||||
process.env.NODE_ENV === "production"
|
||||
? "/strator"
|
||||
: "https://admin.pena.digital/strator";
|
||||
process.env.NODE_ENV === "production"
|
||||
? "/strator"
|
||||
: "https://admin.pena.digital/strator";
|
||||
|
||||
const { makeRequest } = authStore.getState();
|
||||
const mutateTariffs = (tariffs: Tariff[]) => {
|
||||
const nonDeletedTariffs = tariffs
|
||||
.filter(({ isDeleted }) => !isDeleted);
|
||||
|
||||
const mutateTariffs = (tariffs: Tariff_BACKEND[]) => {
|
||||
const convertedTariffs: Record<string, Tariff> = {};
|
||||
|
||||
tariffs
|
||||
.filter(({ isDeleted }) => !isDeleted)
|
||||
.forEach((tariff) => {
|
||||
convertedTariffs[tariff._id] = {
|
||||
id: tariff._id,
|
||||
name: tariff.name,
|
||||
isCustom: tariff.price ? true : false,
|
||||
amount: tariff.privilegies[0].amount,
|
||||
isFront: false,
|
||||
privilegeId: tariff.privilegies[0].privilegeId,
|
||||
price: tariff.privilegies[0].price,
|
||||
isDeleted: tariff.isDeleted,
|
||||
customPricePerUnit: tariff.price,
|
||||
};
|
||||
});
|
||||
|
||||
resetTariffsStore(convertedTariffs);
|
||||
updateTariffs(nonDeletedTariffs);
|
||||
};
|
||||
|
||||
export const requestTariffs = async (
|
||||
page: number = 1,
|
||||
existingTariffs: Tariff_BACKEND[] = []
|
||||
page: number = 1,
|
||||
existingTariffs: Tariff[] = []
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const { tariffs, totalPages } = await makeRequest<
|
||||
never,
|
||||
GetTariffsResponse
|
||||
>({
|
||||
url: baseUrl + `/tariff/?page=${page}&limit=${100}`,
|
||||
method: "get",
|
||||
bearer: true,
|
||||
});
|
||||
try {
|
||||
const { tariffs, totalPages } = await makeRequest<
|
||||
never,
|
||||
GetTariffsResponse
|
||||
>({
|
||||
url: baseUrl + `/tariff/?page=${page}&limit=${100}`,
|
||||
method: "get",
|
||||
});
|
||||
|
||||
if (page < totalPages) {
|
||||
return requestTariffs(page + 1, [...existingTariffs, ...tariffs]);
|
||||
if (page < totalPages) {
|
||||
return requestTariffs(page + 1, [...existingTariffs, ...tariffs]);
|
||||
}
|
||||
|
||||
mutateTariffs([...existingTariffs, ...tariffs]);
|
||||
} catch {
|
||||
throw new Error("Ошибка при получении тарифов");
|
||||
}
|
||||
|
||||
mutateTariffs([...existingTariffs, ...tariffs]);
|
||||
} catch {
|
||||
throw new Error("Ошибка при получении тарифов");
|
||||
}
|
||||
};
|
||||
|
@ -1,102 +0,0 @@
|
||||
import axios, { AxiosError, AxiosResponse } from "axios";
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
|
||||
type Token = string;
|
||||
|
||||
interface AuthStore {
|
||||
token: Token;
|
||||
setToken: (data: Token) => void;
|
||||
makeRequest: <TRequest = unknown, TResponse = unknown>(props: FirstRequest<TRequest>) => Promise<TResponse>;
|
||||
clearToken: () => void;
|
||||
}
|
||||
|
||||
interface FirstRequest<T> {
|
||||
method?: string;
|
||||
url: string;
|
||||
body?: T;
|
||||
useToken?: boolean;
|
||||
contentType?: boolean;
|
||||
bearer?: boolean;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export const authStore = create<AuthStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
token: "",
|
||||
setToken: (newToken) => set({ token: newToken }),
|
||||
makeRequest: <TRequest, TResponse>(props: FirstRequest<TRequest>): Promise<TResponse> => {
|
||||
const newProps = { ...props, HC: (newToken: Token) => set({ token: newToken }), token: get().token };
|
||||
|
||||
return makeRequest<TRequest, TResponse>(newProps);
|
||||
},
|
||||
clearToken: () => set({ token: "" }),
|
||||
}),
|
||||
{
|
||||
name: "token",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
interface MakeRequest<T> extends FirstRequest<T> {
|
||||
HC: (newToken: Token) => void;
|
||||
token: Token;
|
||||
}
|
||||
|
||||
async function makeRequest<TRequest, TResponse>({
|
||||
method = "post",
|
||||
url,
|
||||
body,
|
||||
useToken = true,
|
||||
signal,
|
||||
contentType = false,
|
||||
bearer = false,
|
||||
HC,
|
||||
token,
|
||||
}: MakeRequest<TRequest>) {
|
||||
//В случае 401 рефреш должен попробовать вызваться 1 раз
|
||||
let headers: any = {};
|
||||
if (useToken) headers["Authorization"] = bearer ? "Bearer " + token : token;
|
||||
if (contentType) headers["Content-Type"] = "application/json";
|
||||
|
||||
try {
|
||||
const { data } = await axios<TRequest, AxiosResponse<TResponse & { accessToken?: string }>>({
|
||||
url,
|
||||
method,
|
||||
headers,
|
||||
data: body,
|
||||
signal,
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
if (data?.accessToken) {
|
||||
HC(data.accessToken);
|
||||
}
|
||||
|
||||
return data;
|
||||
} catch (nativeError: unknown) {
|
||||
const error = nativeError as AxiosError;
|
||||
|
||||
if (error?.response?.status === 401) {
|
||||
const refreshResponse = await refresh(token);
|
||||
if (refreshResponse.data?.accessToken) HC(refreshResponse.data.accessToken);
|
||||
|
||||
headers["Authorization"] = refreshResponse.data.accessToken;
|
||||
const response = await axios<TRequest, AxiosResponse<TResponse>>({ url, method, headers, data: body, signal });
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function refresh(token:Token) {
|
||||
return axios<never, AxiosResponse<{ accessToken: string }>>("https://admin.pena.digital/auth/refresh", {
|
||||
headers: {
|
||||
Authorization: token,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
@ -1,26 +1,24 @@
|
||||
import { create } from "zustand";
|
||||
import { devtools, persist } from "zustand/middleware";
|
||||
import { CartTotal } from "@root/model/cart";
|
||||
import { devtools } from "zustand/middleware";
|
||||
import { CartData } from "@frontend/kitui";
|
||||
|
||||
|
||||
interface CartStore {
|
||||
cartTotal: CartTotal | null;
|
||||
setCartTotal: (newCartTotal: CartTotal | null) => void;
|
||||
cartData: CartData | null;
|
||||
}
|
||||
|
||||
const initialState: CartStore = {
|
||||
cartData: null,
|
||||
};
|
||||
|
||||
export const useCartStore = create<CartStore>()(
|
||||
devtools(
|
||||
// persist(
|
||||
(set, get) => ({
|
||||
cartTotal: null,
|
||||
setCartTotal: (newCartTotal) => set({ cartTotal: newCartTotal }),
|
||||
}),
|
||||
// {
|
||||
// name: "cart",
|
||||
// getStorage: () => localStorage,
|
||||
// }
|
||||
// ),
|
||||
{
|
||||
name: "Cart store",
|
||||
}
|
||||
)
|
||||
devtools(
|
||||
(set, get) => initialState,
|
||||
{
|
||||
name: "Cart",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const setCartData = (cartData: CartStore["cartData"]) => useCartStore.setState({ cartData });
|
||||
|
@ -1,8 +1,8 @@
|
||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||
import { create } from "zustand";
|
||||
import { devtools } from "zustand/middleware";
|
||||
import { Discount } from "@root/model/discount";
|
||||
import { produce } from "immer";
|
||||
import { Discount } from "@frontend/kitui";
|
||||
|
||||
|
||||
interface DiscountStore {
|
||||
@ -19,15 +19,15 @@ export const useDiscountStore = create<DiscountStore>()(
|
||||
editDiscountId: null,
|
||||
}),
|
||||
{
|
||||
name: "Real discount store",
|
||||
enabled: process.env.NODE_ENV === "development"
|
||||
name: "Discount",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const setDiscounts = (discounts: DiscountStore["discounts"]) => useDiscountStore.setState({ discounts });
|
||||
|
||||
export const findDiscountsById = (discountId: string):(Discount| null) => useDiscountStore.getState().discounts.find(discount => discount.ID === discountId) ?? null;
|
||||
export const findDiscountsById = (discountId: string): (Discount | null) => useDiscountStore.getState().discounts.find(discount => discount.ID === discountId) ?? null;
|
||||
|
||||
export const addDiscount = (discount: DiscountStore["discounts"][number]) => useDiscountStore.setState(
|
||||
state => ({ discounts: [...state.discounts, discount] })
|
||||
|
@ -24,7 +24,8 @@ export const useMessageStore = create<MessageStore>()(
|
||||
isPreventAutoscroll: false,
|
||||
}),
|
||||
{
|
||||
name: "Message store (admin)"
|
||||
name: "Messages",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
}
|
||||
)
|
||||
);
|
||||
@ -64,4 +65,4 @@ function sortMessagesByTime(ticket1: TicketMessage, ticket2: TicketMessage) {
|
||||
const date1 = new Date(ticket1.created_at).getTime();
|
||||
const date2 = new Date(ticket2.created_at).getTime();
|
||||
return date1 - date2;
|
||||
}
|
||||
}
|
||||
|
@ -1,29 +0,0 @@
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
|
||||
export const exampleTariffs: Tariff[] = [
|
||||
{
|
||||
id: "tariffId1",
|
||||
name: "Tariff 1",
|
||||
privilegeId: "p1",
|
||||
amount: 1000,
|
||||
},
|
||||
{
|
||||
id: "tariffId2",
|
||||
name: "Tariff 2",
|
||||
privilegeId: "p2",
|
||||
amount: 2000,
|
||||
customPricePerUnit: 3,
|
||||
},
|
||||
{
|
||||
id: "tariffId3",
|
||||
name: "Tariff 3",
|
||||
privilegeId: "p3",
|
||||
amount: 3000,
|
||||
},
|
||||
{
|
||||
id: "tariffId4",
|
||||
name: "Tariff 4",
|
||||
privilegeId: "p6",
|
||||
amount: 4000,
|
||||
},
|
||||
];
|
@ -1,11 +1,10 @@
|
||||
import { Privilege } from "@root/model/tariff";
|
||||
import { create } from "zustand";
|
||||
import { devtools } from "zustand/middleware";
|
||||
import { exampleCartValues } from "./mocks/exampleCartValues";
|
||||
import { mergedBackFrontPrivilege } from "@root/model/privilege";
|
||||
import { PrivilegeWithAmount } from "@frontend/kitui";
|
||||
|
||||
|
||||
interface PrivilegeStore {
|
||||
privileges: mergedBackFrontPrivilege[];
|
||||
privileges: PrivilegeWithAmount[];
|
||||
}
|
||||
|
||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||
@ -14,14 +13,14 @@ export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||
privileges: [],
|
||||
}),
|
||||
{
|
||||
name: "Privilege store",
|
||||
name: "Privileges",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const resetPrivilegeArray = (privileges: PrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges });
|
||||
|
||||
|
||||
export const findPrivilegeById = (privilegeId: string) => {
|
||||
return usePrivilegeStore.getState().privileges.find((privilege) => privilege.id === privilegeId || privilege.privilegeId === privilegeId) ?? null;
|
||||
return usePrivilegeStore.getState().privileges.find((privilege) => privilege._id === privilegeId || privilege.privilegeId === privilegeId) ?? null;
|
||||
};
|
||||
|
@ -1,50 +1,62 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import { Tariff_BACKEND, Tariff_FRONTEND } from "@root/model/tariff";
|
||||
import { devtools } from "zustand/middleware";
|
||||
import { Tariff } from "@frontend/kitui";
|
||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||
|
||||
|
||||
interface TariffStore {
|
||||
tariffs: Tariff_FRONTEND[]
|
||||
tariffs: Tariff[];
|
||||
editTariffId: string | null;
|
||||
deleteTariffIds: string[] | null;
|
||||
selectedTariffIds: GridSelectionModel;
|
||||
}
|
||||
|
||||
export const useTariffStore = create<TariffStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
tariffs: [],
|
||||
// tariffs: exampleTariffs,
|
||||
}),
|
||||
{
|
||||
name: "Tariff store",
|
||||
}
|
||||
)
|
||||
devtools(
|
||||
(set, get) => ({
|
||||
tariffs: [],
|
||||
editTariffId: null,
|
||||
deleteTariffIds: null,
|
||||
selectedTariffIds: [],
|
||||
}),
|
||||
{
|
||||
name: "Tariffs",
|
||||
enabled: process.env.NODE_ENV !== "production",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const updateTariffs = (tariffs: TariffStore["tariffs"], mode: "add" | "replace" = "replace") => useTariffStore.setState(
|
||||
state => {
|
||||
const tariffMap: Record<string, Tariff> = {};
|
||||
|
||||
export const resetTariffs = (newTariff: Tariff_FRONTEND[]) => useTariffStore.setState((state) => ({ tariffs: newTariff }));
|
||||
[...(mode === "add" ? state.tariffs : []), ...tariffs].forEach(tariff => tariffMap[tariff._id] = tariff);
|
||||
|
||||
export const updateTariff = (tariff: Tariff_FRONTEND) => {
|
||||
let stateTariffs = useTariffStore.getState().tariffs
|
||||
let index
|
||||
stateTariffs.forEach((e,i) => { //ищем такой тариф для замены на новый
|
||||
if (e.id == tariff.id) index = i
|
||||
})
|
||||
if (index === undefined) {// не нашли. Добавляем
|
||||
addTariffs([tariff])
|
||||
} else { //нашли. Заменяем
|
||||
stateTariffs[index] = tariff
|
||||
useTariffStore.setState(() => ({tariffs: stateTariffs}))
|
||||
const sortedTariffs = Object.values(tariffMap).sort(sortTariffsByCreatedAt);
|
||||
|
||||
return { tariffs: sortedTariffs };
|
||||
},
|
||||
false,
|
||||
{
|
||||
type: "updateTariffs",
|
||||
tariffsLength: tariffs.length,
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export const openEditTariffDialog = (editTariffId: TariffStore["editTariffId"]) => useTariffStore.setState({ editTariffId });
|
||||
|
||||
export const addTariffs = (newTariffs: Tariff_FRONTEND[]) => {
|
||||
let stateTariffs = useTariffStore.getState().tariffs
|
||||
let newArrayTariffs = [...stateTariffs, ...newTariffs]
|
||||
newArrayTariffs.forEach((tariff) => {
|
||||
updateTariff(tariff)
|
||||
})
|
||||
export const closeEditTariffDialog = () => useTariffStore.setState({ editTariffId: null });
|
||||
|
||||
export const openDeleteTariffDialog = (deleteTariffId: TariffStore["deleteTariffIds"]) => useTariffStore.setState({ deleteTariffIds: deleteTariffId });
|
||||
|
||||
export const closeDeleteTariffDialog = () => useTariffStore.setState({ deleteTariffIds: null });
|
||||
|
||||
export const setSelectedTariffIds = (selectedTariffIds: TariffStore["selectedTariffIds"]) => useTariffStore.setState({ selectedTariffIds });
|
||||
|
||||
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;
|
||||
}
|
||||
export const deleteTariffs = (tariffId: string) =>
|
||||
useTariffStore.setState((state) => ({
|
||||
tariffs: state.tariffs.filter((tariff) => tariff.id !== tariffId),
|
||||
}));
|
||||
|
Binary file not shown.
@ -1,39 +0,0 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import { Tariff } from "@root/model/tariff";
|
||||
|
||||
|
||||
interface TariffStore {
|
||||
tariffs: Record<string, Tariff>
|
||||
}
|
||||
|
||||
export const useTariffStore = create<TariffStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
tariffs: {},
|
||||
}),
|
||||
{
|
||||
name: "Tariff store",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
|
||||
export const updateTariffs = (newTariffs: Record<string, Tariff>) => {
|
||||
useTariffStore.setState((state) => ({
|
||||
tariffs: {...state.tariffs, ...newTariffs},
|
||||
}));
|
||||
};
|
||||
|
||||
export const deleteTariffs = (tariffId: string) => {
|
||||
let tariffs = useTariffStore.getState().tariffs
|
||||
delete tariffs[tariffId]
|
||||
useTariffStore.setState(() => ({tariffs: tariffs}));
|
||||
};
|
||||
|
||||
export const resetTariffsStore = (newTariffs: Record<string, Tariff>) => {
|
||||
useTariffStore.setState(() => ({tariffs: {}}));
|
||||
console.log(newTariffs)
|
||||
useTariffStore.setState(() => ({tariffs: newTariffs}));
|
||||
};
|
@ -5,7 +5,6 @@ import { devtools } from "zustand/middleware";
|
||||
|
||||
interface TicketStore {
|
||||
tickets: Ticket[];
|
||||
fetchState: "idle" | "fetching" | "all fetched";
|
||||
apiPage: number;
|
||||
ticketsPerPage: number;
|
||||
}
|
||||
@ -14,21 +13,18 @@ export const useTicketStore = create<TicketStore>()(
|
||||
devtools(
|
||||
(set, get) => ({
|
||||
tickets: [],
|
||||
fetchState: "idle",
|
||||
apiPage: 0,
|
||||
ticketsPerPage: 20,
|
||||
}),
|
||||
{
|
||||
name: "Tickets store (admin)"
|
||||
name: "Tickets",
|
||||
enabled: process.env.NODE_ENV === "development",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const setTicketsFetchState = (fetchState: TicketStore["fetchState"]) => useTicketStore.setState({ fetchState });
|
||||
|
||||
export const incrementTicketsApiPage = () => {
|
||||
const state = useTicketStore.getState();
|
||||
if (state.fetchState !== "idle") return;
|
||||
|
||||
useTicketStore.setState({ apiPage: state.apiPage + 1 });
|
||||
};
|
||||
@ -42,4 +38,4 @@ export const updateTickets = (receivedTickets: Ticket[]) => {
|
||||
useTicketStore.setState({ tickets: Object.values(ticketIdToTicketMap) });
|
||||
};
|
||||
|
||||
export const clearTickets = () => useTicketStore.setState({ tickets: [] });
|
||||
export const clearTickets = () => useTicketStore.setState({ tickets: [] });
|
||||
|
100
src/utils/calcCart.ts
Normal file
100
src/utils/calcCart.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { CartData, Discount, PrivilegeCartData, Tariff, 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 serviceHasNonCustomTariffMap: Record<string, boolean | undefined> = {};
|
||||
|
||||
tariffs.forEach(tariff => {
|
||||
if (tariff.price && tariff.price > 0) cartData.priceBeforeDiscounts += tariff.price;
|
||||
|
||||
tariff.privilegies.forEach(privilege => {
|
||||
if (
|
||||
serviceHasNonCustomTariffMap[privilege.serviceKey] === true
|
||||
&& tariff.isCustom
|
||||
) throw new Error("Если взят готовый тариф, то кастомный на этот сервис сделать уже нельзя");
|
||||
|
||||
let serviceData = cartData.services.find(service => service.serviceKey === privilege.serviceKey);
|
||||
if (!serviceData) {
|
||||
serviceData = {
|
||||
serviceKey: privilege.serviceKey,
|
||||
privileges: [],
|
||||
price: 0,
|
||||
appliedServiceDiscount: null,
|
||||
};
|
||||
cartData.services.push(serviceData);
|
||||
}
|
||||
|
||||
const privilegePrice = privilege.amount * privilege.price;
|
||||
|
||||
if (!tariff.price) cartData.priceBeforeDiscounts += privilegePrice;
|
||||
|
||||
const privilegeData: PrivilegeCartData = {
|
||||
tariffId: tariff._id,
|
||||
serviceKey: privilege.serviceKey,
|
||||
privilegeId: privilege.privilegeId,
|
||||
description: privilege.description,
|
||||
price: privilegePrice,
|
||||
appliedPrivilegeDiscount: null,
|
||||
tariffName: tariff.name,
|
||||
};
|
||||
|
||||
serviceData.privileges.push(privilegeData);
|
||||
serviceData.price += privilegePrice;
|
||||
cartData.priceAfterDiscounts += privilegePrice;
|
||||
cartData.itemCount++;
|
||||
});
|
||||
});
|
||||
|
||||
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 findDiscountFactor(discount: Discount | null | undefined): number {
|
||||
if (!discount) return 1;
|
||||
|
||||
if (discount.Condition.CartPurchasesAmount > 0) return Number(discount.Target.Factor);
|
||||
|
||||
if (discount.Condition.PurchasesAmount > 0) return Number(discount.Target.Factor);
|
||||
|
||||
if (discount.Condition.Product !== "") {
|
||||
const product = discount.Target.Products[0];
|
||||
if (!product) throw new Error("Discount target product not found");
|
||||
return Number(product.Factor);
|
||||
}
|
||||
|
||||
if ((discount.Condition.Group as string) !== "") return Number(discount.Target.Factor);
|
||||
if (discount.Condition.UserType) return Number(discount.Target.Factor);
|
||||
if (discount.Condition.User !== "") {
|
||||
const product = discount.Target.Products[0];
|
||||
if (!product) throw new Error("Discount target product not found");
|
||||
|
||||
return Number(product.Factor);
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
export function formatDiscountFactor(factor: number): string {
|
||||
return `${((1 - factor) * 100).toFixed(1)}%`;
|
||||
}
|
9
src/utils/currencyFormatter.ts
Normal file
9
src/utils/currencyFormatter.ts
Normal file
@ -0,0 +1,9 @@
|
||||
export const currencyFormatter = new Intl.NumberFormat(
|
||||
"ru",
|
||||
{
|
||||
currency: "RUB",
|
||||
style: "currency",
|
||||
compactDisplay: "short",
|
||||
minimumFractionDigits: 0
|
||||
}
|
||||
);
|
@ -1,4 +1,5 @@
|
||||
import { Discount, DiscountType } from "@root/model/discount";
|
||||
import { Discount } from "@frontend/kitui";
|
||||
import { DiscountType } from "@root/model/discount";
|
||||
|
||||
export function getDiscountTypeFromLayer(layer: Discount["Layer"]): DiscountType {
|
||||
switch (layer) {
|
||||
@ -8,4 +9,4 @@ export function getDiscountTypeFromLayer(layer: Discount["Layer"]): DiscountType
|
||||
case 4: return "purchasesAmount";
|
||||
default: throw new Error("Wrong discount layer");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,22 +1,18 @@
|
||||
import { RealPrivilege } from "@root/model/privilege";
|
||||
import { authStore } from "@root/stores/auth";
|
||||
import { PrivilegeWithAmount, makeRequest } from "@frontend/kitui";
|
||||
import { useEffect } from "react";
|
||||
|
||||
|
||||
const makeRequest = authStore.getState().makeRequest;
|
||||
|
||||
export default function usePrivileges({ onError, onNewPrivileges }: {
|
||||
onNewPrivileges: (response: RealPrivilege[]) => void;
|
||||
onNewPrivileges: (response: PrivilegeWithAmount[]) => void;
|
||||
onError?: (error: any) => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
makeRequest<never, RealPrivilege[]>({
|
||||
makeRequest<never, PrivilegeWithAmount[]>({
|
||||
url: "https://admin.pena.digital/strator/privilege",
|
||||
method: "get",
|
||||
useToken: true,
|
||||
bearer: true,
|
||||
signal: controller.signal,
|
||||
}).then(result => {
|
||||
onNewPrivileges(result);
|
||||
@ -26,4 +22,4 @@ export default function usePrivileges({ onError, onNewPrivileges }: {
|
||||
|
||||
return () => controller.abort();
|
||||
}, [onError, onNewPrivileges]);
|
||||
}
|
||||
}
|
||||
|
5
src/utils/tariffPrice.ts
Normal file
5
src/utils/tariffPrice.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { Tariff } from "@frontend/kitui";
|
||||
|
||||
export function getTariffPrice(tariff: Tariff) {
|
||||
return tariff.price || tariff.privilegies.reduce((sum, privilege) => sum + privilege.amount * privilege.price, 0);
|
||||
}
|
24
yarn.lock
24
yarn.lock
@ -1396,6 +1396,14 @@
|
||||
lodash.isundefined "^3.0.1"
|
||||
lodash.uniq "^4.5.0"
|
||||
|
||||
"@frontend/kitui@^1.0.17":
|
||||
version "1.0.17"
|
||||
resolved "https://penahub.gitlab.yandexcloud.net/api/v4/projects/21/packages/npm/@frontend/kitui/-/@frontend/kitui-1.0.17.tgz#a5bddaaa18b168be0e1814d5cfbd86e4030d15af"
|
||||
integrity sha1-pb3aqhixaL4OGBTVz72G5AMNFa8=
|
||||
dependencies:
|
||||
immer "^10.0.2"
|
||||
reconnecting-eventsource "^1.6.2"
|
||||
|
||||
"@humanwhocodes/config-array@^0.11.8":
|
||||
version "0.11.8"
|
||||
resolved "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.8.tgz"
|
||||
@ -3401,10 +3409,10 @@ axe-core@^4.6.2:
|
||||
resolved "https://registry.npmjs.org/axe-core/-/axe-core-4.6.3.tgz"
|
||||
integrity sha512-/BQzOX780JhsxDnPpH4ZiyrJAzcd8AfzFPkv+89veFSr1rcMjuq2JDCwypKaPeB6ljHp9KjXhPpjgCvQlWYuqg==
|
||||
|
||||
axios@^1.3.4:
|
||||
version "1.3.4"
|
||||
resolved "https://registry.npmjs.org/axios/-/axios-1.3.4.tgz"
|
||||
integrity sha512-toYm+Bsyl6VC5wSkfkbbNB6ROv7KY93PEBBL6xyDczaIHasAiv4wPqQ/c4RjoQzipxRD2W5g21cOqQulZ7rHwQ==
|
||||
axios@^1.4.0:
|
||||
version "1.4.0"
|
||||
resolved "https://registry.yarnpkg.com/axios/-/axios-1.4.0.tgz#38a7bf1224cd308de271146038b551d725f0be1f"
|
||||
integrity sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==
|
||||
dependencies:
|
||||
follow-redirects "^1.15.0"
|
||||
form-data "^4.0.0"
|
||||
@ -12330,9 +12338,9 @@ zip-stream@^4.1.0:
|
||||
compress-commons "^4.1.0"
|
||||
readable-stream "^3.6.0"
|
||||
|
||||
zustand@^4.1.1:
|
||||
version "4.3.3"
|
||||
resolved "https://registry.npmjs.org/zustand/-/zustand-4.3.3.tgz"
|
||||
integrity sha512-x2jXq8S0kfLGNwGh87nhRfEc2eZy37tSatpSoSIN+O6HIaBhgQHSONV/F9VNrNcBcKQu/E80K1DeHDYQC/zCrQ==
|
||||
zustand@^4.3.8:
|
||||
version "4.3.9"
|
||||
resolved "https://registry.yarnpkg.com/zustand/-/zustand-4.3.9.tgz#a7d4332bbd75dfd25c6848180b3df1407217f2ad"
|
||||
integrity sha512-Tat5r8jOMG1Vcsj8uldMyqYKC5IZvQif8zetmLHs9WoZlntTHmIoNM8TpLRY31ExncuUvUOXehd0kvahkuHjDw==
|
||||
dependencies:
|
||||
use-sync-external-store "1.2.0"
|
||||
|
Loading…
Reference in New Issue
Block a user