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",
|
"@date-io/dayjs": "^2.15.0",
|
||||||
"@emotion/react": "^11.10.4",
|
"@emotion/react": "^11.10.4",
|
||||||
"@emotion/styled": "^11.10.4",
|
"@emotion/styled": "^11.10.4",
|
||||||
|
"@frontend/kitui": "^1.0.17",
|
||||||
"@material-ui/pickers": "^3.3.10",
|
"@material-ui/pickers": "^3.3.10",
|
||||||
"@mui/icons-material": "^5.10.3",
|
"@mui/icons-material": "^5.10.3",
|
||||||
"@mui/material": "^5.10.5",
|
"@mui/material": "^5.10.5",
|
||||||
@ -22,7 +23,7 @@
|
|||||||
"@types/react": "^18.0.18",
|
"@types/react": "^18.0.18",
|
||||||
"@types/react-dom": "^18.0.6",
|
"@types/react-dom": "^18.0.6",
|
||||||
"@types/react-router-dom": "^5.3.3",
|
"@types/react-router-dom": "^5.3.3",
|
||||||
"axios": "^1.3.4",
|
"axios": "^1.4.0",
|
||||||
"craco": "^0.0.3",
|
"craco": "^0.0.3",
|
||||||
"dayjs": "^1.11.5",
|
"dayjs": "^1.11.5",
|
||||||
"formik": "^2.2.9",
|
"formik": "^2.2.9",
|
||||||
@ -40,7 +41,7 @@
|
|||||||
"styled-components": "^5.3.5",
|
"styled-components": "^5.3.5",
|
||||||
"typescript": "^4.8.2",
|
"typescript": "^4.8.2",
|
||||||
"web-vitals": "^2.1.4",
|
"web-vitals": "^2.1.4",
|
||||||
"zustand": "^4.1.1"
|
"zustand": "^4.3.8"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "craco start",
|
"start": "craco start",
|
||||||
|
@ -1,12 +1,9 @@
|
|||||||
import { CreateDiscountBody, Discount, DiscountType } from "@root/model/discount";
|
import { Discount, makeRequest } from "@frontend/kitui";
|
||||||
import { ServiceType } from "@root/model/tariff";
|
import { CreateDiscountBody, DiscountType } from "@root/model/discount";
|
||||||
import { authStore } from "@root/stores/auth";
|
|
||||||
|
|
||||||
|
|
||||||
const baseUrl = process.env.NODE_ENV === "production" ? "/price" : "https://admin.pena.digital/price";
|
const baseUrl = process.env.NODE_ENV === "production" ? "/price" : "https://admin.pena.digital/price";
|
||||||
|
|
||||||
const makeRequest = authStore.getState().makeRequest;
|
|
||||||
|
|
||||||
export function createDiscount(discountParams: CreateDiscountParams) {
|
export function createDiscount(discountParams: CreateDiscountParams) {
|
||||||
const discount = createDiscountObject(discountParams);
|
const discount = createDiscountObject(discountParams);
|
||||||
|
|
||||||
@ -14,7 +11,6 @@ export function createDiscount(discountParams: CreateDiscountParams) {
|
|||||||
url: baseUrl + "/discount",
|
url: baseUrl + "/discount",
|
||||||
method: "post",
|
method: "post",
|
||||||
useToken: true,
|
useToken: true,
|
||||||
bearer: true,
|
|
||||||
body: discount,
|
body: discount,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@ -24,7 +20,6 @@ export function deleteDiscount(discountId: string) {
|
|||||||
url: baseUrl + "/discount/" + discountId,
|
url: baseUrl + "/discount/" + discountId,
|
||||||
method: "delete",
|
method: "delete",
|
||||||
useToken: true,
|
useToken: true,
|
||||||
bearer: true,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -35,7 +30,6 @@ export function patchDiscount(discountId: string, discountParams: CreateDiscount
|
|||||||
url: baseUrl + "/discount/" + discountId,
|
url: baseUrl + "/discount/" + discountId,
|
||||||
method: "patch",
|
method: "patch",
|
||||||
useToken: true,
|
useToken: true,
|
||||||
bearer: true,
|
|
||||||
body: discount,
|
body: discount,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -51,7 +45,7 @@ interface CreateDiscountParams {
|
|||||||
startDate: string;
|
startDate: string;
|
||||||
/** ISO string */
|
/** ISO string */
|
||||||
endDate: string;
|
endDate: string;
|
||||||
serviceType: ServiceType;
|
serviceType: string;
|
||||||
discountType: DiscountType;
|
discountType: DiscountType;
|
||||||
privilegeId: string;
|
privilegeId: string;
|
||||||
}
|
}
|
||||||
@ -134,12 +128,11 @@ export function createDiscountObject({
|
|||||||
return discount;
|
return discount;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function changeDiscount (discountId:string, discount:Discount) {
|
export function changeDiscount(discountId: string, discount: Discount) {
|
||||||
return makeRequest<Discount>({
|
return makeRequest<Discount>({
|
||||||
url: baseUrl + "/discount/" + discountId,
|
url: baseUrl + "/discount/" + discountId,
|
||||||
method: "patch",
|
method: "patch",
|
||||||
useToken: true,
|
useToken: true,
|
||||||
bearer: true,
|
|
||||||
body: discount,
|
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 {
|
import { makeRequest } from "@frontend/kitui";
|
||||||
GetMessagesRequest,
|
import { SendTicketMessageRequest } from "@root/model/ticket";
|
||||||
GetMessagesResponse,
|
|
||||||
GetTicketsRequest,
|
|
||||||
GetTicketsResponse,
|
|
||||||
SendTicketMessageRequest,
|
|
||||||
} from "@root/model/ticket";
|
|
||||||
import { authStore } from "@root/stores/auth";
|
|
||||||
import ReconnectingEventSource from "reconnecting-eventsource";
|
|
||||||
|
|
||||||
|
|
||||||
const supportApiUrl = "https://admin.pena.digital/heruvym";
|
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; }) {
|
export async function sendTicketMessage({ body }: { body: SendTicketMessageRequest; }) {
|
||||||
return makeRequest({
|
return makeRequest({
|
||||||
url: `${supportApiUrl}/send`,
|
url: `${supportApiUrl}/send`,
|
||||||
@ -91,14 +12,3 @@ export async function sendTicketMessage({ body }: { body: SendTicketMessageReque
|
|||||||
body,
|
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 {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Paper,
|
Paper,
|
||||||
Box,
|
Box,
|
||||||
Typography,
|
Typography,
|
||||||
TableHead,
|
TableHead,
|
||||||
TableRow,
|
TableRow,
|
||||||
TableCell,
|
TableCell,
|
||||||
TableBody,
|
TableBody,
|
||||||
Table,
|
Table,
|
||||||
Tooltip,
|
Alert,
|
||||||
Alert,
|
Checkbox,
|
||||||
Checkbox,
|
FormControlLabel,
|
||||||
FormControlLabel,
|
useTheme
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import Input from "@kitUI/input";
|
import Input from "@kitUI/input";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { setCartData, useCartStore } from "@root/stores/cart";
|
||||||
|
import { useTariffStore } from "@root/stores/tariffs";
|
||||||
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 { useDiscountStore } from "@root/stores/discounts";
|
import { useDiscountStore } from "@root/stores/discounts";
|
||||||
import { requestPrivilegies } from "@root/services/privilegies.service";
|
import { requestPrivilegies } from "@root/services/privilegies.service";
|
||||||
import { requestDiscounts } from "@root/services/discounts.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 {
|
export default function Cart() {
|
||||||
_id: string;
|
const theme = useTheme();
|
||||||
id: string;
|
let discounts = useDiscountStore(state => state.discounts);
|
||||||
name: string;
|
const cartData = useCartStore((store) => store.cartData);
|
||||||
privilegeId: string;
|
const tariffs = useTariffStore(state => state.tariffs);
|
||||||
serviceName: string;
|
const [couponField, setCouponField] = useState<string>("");
|
||||||
price: number;
|
const [loyaltyField, setLoyaltyField] = useState<string>("");
|
||||||
isCustom: boolean;
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
createdAt: string;
|
const [isNonCommercial, setIsNonCommercial] = useState<boolean>(false);
|
||||||
isDeleted: boolean;
|
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
||||||
amount: number;
|
|
||||||
customPricePerUnit?: number;
|
|
||||||
privilegies: Privilege[];
|
|
||||||
isFront: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Cart({ selectedTariffs }: Props) {
|
const cartDiscounts = [cartData?.appliedCartPurchasesDiscount, cartData?.appliedLoyaltyDiscount].filter((d): d is Discount => !!d);
|
||||||
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 cartRows = cartTotal?.items.map((cartItemTotal) => {
|
const cartDiscountsResultFactor = findDiscountFactor(cartData?.appliedCartPurchasesDiscount) * findDiscountFactor(cartData?.appliedLoyaltyDiscount);
|
||||||
const privilege = findPrivilegeById(cartItemTotal.tariff.privilegeId);
|
|
||||||
|
|
||||||
const service = privilege?.serviceKey;
|
async function handleCalcCartClick() {
|
||||||
const serviceDiscount = service
|
await requestPrivilegies();
|
||||||
? cartTotal.discountsByService[privilege?.serviceKey]
|
try {
|
||||||
: null;
|
discounts = await requestDiscounts();
|
||||||
|
} catch { }
|
||||||
|
|
||||||
console.log(cartTotal.discountsByService);
|
const cartTariffs = tariffs.filter(tariff => selectedTariffIds.includes(tariff._id));
|
||||||
console.log(serviceDiscount);
|
|
||||||
console.log(cartItemTotal);
|
|
||||||
|
|
||||||
const envolvedDiscountsElement = (
|
let loyaltyValue = parseInt(loyaltyField);
|
||||||
<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>
|
|
||||||
);
|
|
||||||
|
|
||||||
const totalIncludingServiceDiscount =
|
if (!isFinite(loyaltyValue)) loyaltyValue = 0;
|
||||||
cartItemTotal.totalPrice * (serviceDiscount?.Target.Factor || 1);
|
|
||||||
console.log(cartItemTotal.totalPrice);
|
|
||||||
console.log(serviceDiscount?.Target.Factor);
|
|
||||||
console.log(serviceDiscount);
|
|
||||||
|
|
||||||
return {
|
try {
|
||||||
id: cartItemTotal.tariff.id,
|
const cartData = calcCart(cartTariffs, discounts, loyaltyValue, couponField);
|
||||||
tariffName: cartItemTotal.tariff.name,
|
|
||||||
privilegeDesc: privilege?.description ?? "Привилегия не найдена",
|
|
||||||
envolvedDiscounts: envolvedDiscountsElement,
|
|
||||||
price: totalIncludingServiceDiscount,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const cartDiscounts = cartTotal?.envolvedCartDiscounts;
|
setErrorMessage(null);
|
||||||
const cartDiscountsResultFactor =
|
setCartData(cartData);
|
||||||
cartDiscounts &&
|
} catch (error: any) {
|
||||||
cartDiscounts?.length > 1 &&
|
setErrorMessage(error.message);
|
||||||
cartDiscounts.reduce(
|
setCartData(null);
|
||||||
(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);
|
return (
|
||||||
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,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
component="section"
|
||||||
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
|
|
||||||
sx={{
|
sx={{
|
||||||
width: "90%",
|
border: "1px solid white",
|
||||||
margin: "5px",
|
display: "flex",
|
||||||
border: "2px solid",
|
flexDirection: "column",
|
||||||
borderColor: theme.palette.secondary.main,
|
alignItems: "center",
|
||||||
|
width: "100%",
|
||||||
|
pb: "20px",
|
||||||
|
borderRadius: "4px",
|
||||||
}}
|
}}
|
||||||
aria-label="simple table"
|
>
|
||||||
>
|
<Typography variant="caption">корзина</Typography>
|
||||||
<TableHead>
|
<Paper
|
||||||
<TableRow
|
variant="bar"
|
||||||
sx={{
|
sx={{
|
||||||
borderBottom: "2px solid",
|
display: "flex",
|
||||||
borderColor: theme.palette.grayLight.main,
|
alignItems: "center",
|
||||||
height: "100px",
|
justifyContent: "space-between",
|
||||||
|
gap: "20px",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<TableCell>
|
<FormControlLabel
|
||||||
<Typography
|
checked={isNonCommercial}
|
||||||
variant="h4"
|
onChange={(e, checked) => setIsNonCommercial(checked)}
|
||||||
sx={{ color: theme.palette.secondary.main }}
|
control={
|
||||||
>
|
<Checkbox
|
||||||
Имя
|
sx={{
|
||||||
</Typography>
|
color: theme.palette.secondary.main,
|
||||||
</TableCell>
|
"&.Mui-checked": {
|
||||||
<TableCell>
|
color: theme.palette.secondary.main,
|
||||||
<Typography
|
},
|
||||||
variant="h4"
|
}}
|
||||||
sx={{ color: theme.palette.secondary.main }}
|
/>
|
||||||
>
|
}
|
||||||
Описание
|
label="НКО"
|
||||||
</Typography>
|
sx={{
|
||||||
</TableCell>
|
color: theme.palette.secondary.main,
|
||||||
<TableCell>
|
}}
|
||||||
<Typography
|
/>
|
||||||
variant="h4"
|
<Box
|
||||||
sx={{ color: theme.palette.secondary.main }}
|
sx={{
|
||||||
>
|
border: "1px solid white",
|
||||||
Скидки
|
padding: "3px",
|
||||||
</Typography>
|
display: "flex",
|
||||||
</TableCell>
|
flexDirection: "column",
|
||||||
<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,
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<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={{
|
sx={{
|
||||||
color: theme.palette.secondary.main,
|
border: "1px solid white",
|
||||||
|
padding: "3px",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
ml: "auto",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{row.tariffName}
|
<Input
|
||||||
</TableCell>
|
label="лояльность"
|
||||||
<TableCell
|
size="small"
|
||||||
sx={{
|
type="number"
|
||||||
color: theme.palette.secondary.main,
|
value={loyaltyField}
|
||||||
}}
|
onChange={(e) => setLoyaltyField(e.target.value)}
|
||||||
>
|
InputProps={{
|
||||||
{row.privilegeDesc}
|
style: {
|
||||||
</TableCell>
|
backgroundColor: theme.palette.content.main,
|
||||||
<TableCell
|
color: theme.palette.secondary.main,
|
||||||
sx={{
|
},
|
||||||
color: theme.palette.secondary.main,
|
}}
|
||||||
}}
|
InputLabelProps={{
|
||||||
>
|
style: {
|
||||||
{row.envolvedDiscounts}
|
color: theme.palette.secondary.main,
|
||||||
</TableCell>
|
},
|
||||||
<TableCell
|
}}
|
||||||
sx={{
|
/>
|
||||||
color: theme.palette.secondary.main,
|
</Box>
|
||||||
}}
|
<Button onClick={handleCalcCartClick}>рассчитать</Button>
|
||||||
>
|
</Paper>
|
||||||
{(row.price / 100).toFixed(2)} ₽
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
))}
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
|
||||||
|
|
||||||
<Typography
|
{cartData?.services.length && (
|
||||||
id="transition-modal-title"
|
<>
|
||||||
variant="h6"
|
<Table
|
||||||
sx={{
|
sx={{
|
||||||
fontWeight: "normal",
|
width: "90%",
|
||||||
textAlign: "center",
|
margin: "5px",
|
||||||
marginTop: "15px",
|
border: "2px solid",
|
||||||
fontSize: "16px",
|
borderColor: theme.palette.secondary.main,
|
||||||
}}
|
}}
|
||||||
>
|
aria-label="simple table"
|
||||||
Скидки корзины: {envolvedCartDiscountsElement}
|
>
|
||||||
</Typography>
|
<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
|
<Typography
|
||||||
id="transition-modal-title"
|
id="transition-modal-title"
|
||||||
variant="h6"
|
variant="h6"
|
||||||
sx={{
|
sx={{
|
||||||
fontWeight: "normal",
|
fontWeight: "normal",
|
||||||
textAlign: "center",
|
textAlign: "center",
|
||||||
marginTop: "10px",
|
marginTop: "15px",
|
||||||
}}
|
fontSize: "16px",
|
||||||
>
|
}}
|
||||||
ИТОГО: <span>{(cartTotal?.totalPrice / 100).toFixed(2)} ₽</span>
|
>
|
||||||
</Typography>
|
Скидки корзины:
|
||||||
</>
|
{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 && (
|
<Typography
|
||||||
<Alert variant="filled" severity="error" sx={{ mt: "20px" }}>
|
id="transition-modal-title"
|
||||||
{errorMessage}
|
variant="h6"
|
||||||
</Alert>
|
sx={{
|
||||||
)}
|
fontWeight: "normal",
|
||||||
</Box>
|
textAlign: "center",
|
||||||
);
|
marginTop: "10px",
|
||||||
}
|
}}
|
||||||
|
>
|
||||||
function DiscountTooltip({
|
ИТОГО: <span>{currencyFormatter.format(cartData.priceAfterDiscounts / 100)}</span>
|
||||||
discount,
|
</Typography>
|
||||||
cartItemTotal,
|
</>
|
||||||
}: {
|
)}
|
||||||
discount: Discount;
|
|
||||||
cartItemTotal?: CartItemTotal;
|
{errorMessage !== null && (
|
||||||
}) {
|
<Alert variant="filled" severity="error" sx={{ mt: "20px" }}>
|
||||||
const discountText = formatDiscountFactor(findDiscountFactor(discount));
|
{errorMessage}
|
||||||
|
</Alert>
|
||||||
return discountText ? (
|
)}
|
||||||
<Tooltip
|
</Box>
|
||||||
title={
|
);
|
||||||
<>
|
|
||||||
<Typography>Скидка: {discount?.Name}</Typography>
|
|
||||||
<Typography>{discount?.Description}</Typography>
|
|
||||||
</>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<span>{discountText}</span>
|
|
||||||
</Tooltip>
|
|
||||||
) : (
|
|
||||||
<span>Ошибка поиска значения скидки</span>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
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 { DataGrid } from "@mui/x-data-grid";
|
||||||
import { styled } from "@mui/material/styles";
|
import { styled } from "@mui/material/styles";
|
||||||
|
|
||||||
|
|
||||||
export default styled(DataGrid)(({ theme }) => ({
|
export default styled(DataGrid)(({ theme }) => ({
|
||||||
width: "100%",
|
width: "100%",
|
||||||
minHeight: "400px",
|
minHeight: "400px",
|
||||||
@ -23,4 +25,4 @@ export default styled(DataGrid)(({ theme }) => ({
|
|||||||
"& .MuiButton-text": {
|
"& .MuiButton-text": {
|
||||||
color: theme.palette.secondary.main
|
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 * as React from "react";
|
||||||
import { useLocation, Navigate } from "react-router-dom";
|
import { useLocation, Navigate } from "react-router-dom";
|
||||||
|
|
||||||
export default ({ children }: any) => {
|
export default ({ children }: any) => {
|
||||||
const { token } = authStore();
|
const token = useToken();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
|
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
|
||||||
if (token) {
|
if (token) {
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
import { useLocation, Navigate } from "react-router-dom";
|
import { useLocation, Navigate } from "react-router-dom";
|
||||||
|
|
||||||
import { authStore } from "@root/stores/auth";
|
import { useToken } from "@frontend/kitui";
|
||||||
|
|
||||||
const PublicRoute = ({ children }: any) => {
|
const PublicRoute = ({ children }: any) => {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const { token } = authStore();
|
const token = useToken();
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
return <Navigate to="/users" state={{ from: location }} />;
|
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 {
|
export interface Promocode {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
endless: boolean;
|
endless: boolean;
|
||||||
from: string;
|
from: string;
|
||||||
dueTo: string;
|
dueTo: string;
|
||||||
privileges: Privilege[];
|
privileges: string[];
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
@ -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 = {
|
export type GetDiscountResponse = {
|
||||||
Discounts: Discount[];
|
Discounts: Discount[];
|
||||||
};
|
};
|
||||||
@ -75,13 +34,13 @@ export type CreateDiscountBody = {
|
|||||||
Term: number;
|
Term: number;
|
||||||
Usage: number;
|
Usage: number;
|
||||||
PriceFrom: number;
|
PriceFrom: number;
|
||||||
Group: ServiceType | "";
|
Group: string;
|
||||||
};
|
};
|
||||||
Target: {
|
Target: {
|
||||||
Factor: number;
|
Factor: number;
|
||||||
TargetScope: "Sum" | "Group" | "Each";
|
TargetScope: "Sum" | "Group" | "Each";
|
||||||
Overhelm: boolean;
|
Overhelm: boolean;
|
||||||
TargetGroup: ServiceType | "";
|
TargetGroup: string;
|
||||||
Products: [{
|
Products: [{
|
||||||
ID: string;
|
ID: string;
|
||||||
Factor: number;
|
Factor: number;
|
||||||
|
@ -12,38 +12,5 @@ export const SERVICE_LIST = [
|
|||||||
displayName: "Аналитика сокращателя",
|
displayName: "Аналитика сокращателя",
|
||||||
},
|
},
|
||||||
] as const;
|
] 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 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 = [
|
export const SERVICE_LIST = [
|
||||||
{
|
{
|
||||||
serviceKey: "templategen",
|
serviceKey: "templategen",
|
||||||
@ -17,58 +19,9 @@ export type ServiceType = (typeof SERVICE_LIST)[number]["serviceKey"];
|
|||||||
|
|
||||||
export type PrivilegeType = "unlim" | "gencount" | "activequiz" | "abcount" | "extended";
|
export type PrivilegeType = "unlim" | "gencount" | "activequiz" | "abcount" | "extended";
|
||||||
|
|
||||||
export interface Privilege_BACKEND {
|
export type EditTariffRequestBody = {
|
||||||
name: string;
|
name: string;
|
||||||
privilegeId: string;
|
|
||||||
serviceKey: "templategen" | "squiz" | "dwarfener";
|
|
||||||
amount: number;
|
|
||||||
description: string;
|
|
||||||
price: number;
|
price: number;
|
||||||
type: "count" | "day" | "mb";
|
isCustom: boolean;
|
||||||
value: string;
|
privilegies: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
||||||
updatedAt: string;
|
|
||||||
_id: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type Tariff_FRONTEND = {
|
|
||||||
id: string,
|
|
||||||
name: string,
|
|
||||||
amount: number,
|
|
||||||
privilegeId: string,
|
|
||||||
customPricePerUnit?: number;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @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[];
|
files: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TicketStatus = "open"; // TODO
|
export type TicketStatus = "open";
|
||||||
|
|
||||||
export interface GetTicketsRequest {
|
|
||||||
amt: number;
|
|
||||||
/** Пагинация начинается с индекса 0 */
|
|
||||||
page: number;
|
|
||||||
srch?: string;
|
|
||||||
status?: TicketStatus;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface GetTicketsResponse {
|
|
||||||
count: number;
|
|
||||||
data: Ticket[] | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface Ticket {
|
export interface Ticket {
|
||||||
id: string;
|
id: string;
|
||||||
@ -55,12 +42,3 @@ export interface TicketMessage {
|
|||||||
request_screenshot: string,
|
request_screenshot: string,
|
||||||
created_at: 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 EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
||||||
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
||||||
import OutlinedInput from "@kitUI/outlinedInput";
|
import OutlinedInput from "@kitUI/outlinedInput";
|
||||||
import { authStore } from "@root/stores/auth";
|
|
||||||
|
|
||||||
export default () => {
|
export default () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [restore, setRestore] = React.useState(true);
|
const [restore, setRestore] = React.useState(true);
|
||||||
const [isReady, setIsReady] = React.useState(true);
|
const [isReady, setIsReady] = React.useState(true);
|
||||||
const { makeRequest } = authStore();
|
|
||||||
if (restore) {
|
if (restore) {
|
||||||
return (
|
return (
|
||||||
<Formik
|
<Formik
|
||||||
|
@ -8,7 +8,7 @@ import Logo from "@pages/Logo";
|
|||||||
import OutlinedInput from "@kitUI/outlinedInput";
|
import OutlinedInput from "@kitUI/outlinedInput";
|
||||||
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
||||||
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
interface Values {
|
interface Values {
|
||||||
email: string;
|
email: string;
|
||||||
@ -37,8 +37,6 @@ const SigninForm = () => {
|
|||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const { makeRequest } = authStore();
|
|
||||||
|
|
||||||
const initialValues: Values = {
|
const initialValues: Values = {
|
||||||
email: "",
|
email: "",
|
||||||
password: "",
|
password: "",
|
||||||
|
@ -9,7 +9,8 @@ import OutlinedInput from "@kitUI/outlinedInput";
|
|||||||
import Logo from "@pages/Logo/index";
|
import Logo from "@pages/Logo/index";
|
||||||
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
import EmailOutlinedIcon from "@mui/icons-material/EmailOutlined";
|
||||||
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
interface Values {
|
interface Values {
|
||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
@ -33,7 +34,6 @@ function validate(values: Values) {
|
|||||||
const SignUp = () => {
|
const SignUp = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const { makeRequest } = authStore();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Formik
|
<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 { enqueueSnackbar } from "notistack";
|
||||||
import { Box, IconButton, TextField, Tooltip, Typography } from "@mui/material";
|
import { Box, IconButton, TextField, Tooltip, Typography } from "@mui/material";
|
||||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
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 {
|
interface CardPrivilegie {
|
||||||
name: string;
|
privilege: PrivilegeWithAmount;
|
||||||
type: "count" | "day" | "mb";
|
|
||||||
price: string | number;
|
|
||||||
description: string;
|
|
||||||
value?: string;
|
|
||||||
privilegeId: string;
|
|
||||||
serviceKey: "templategen" | "squiz" | "dwarfener";
|
|
||||||
amount: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const baseUrl =
|
const baseUrl =
|
||||||
process.env.NODE_ENV === "production"
|
process.env.NODE_ENV === "production"
|
||||||
? "/strator"
|
? "/strator"
|
||||||
: "https://admin.pena.digital/strator";
|
: "https://admin.pena.digital/strator";
|
||||||
|
|
||||||
export const СardPrivilegie = ({
|
export const СardPrivilegie = ({ privilege }: CardPrivilegie) => {
|
||||||
name,
|
const [inputOpen, setInputOpen] = useState<boolean>(false);
|
||||||
type,
|
const [inputValue, setInputValue] = useState<string>("");
|
||||||
price,
|
const priceRef = useRef<any>(null);
|
||||||
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();
|
|
||||||
|
|
||||||
const translationType = {
|
const translationType = {
|
||||||
count: "за единицу",
|
count: "за единицу",
|
||||||
day: "за день",
|
day: "за день",
|
||||||
mb: "за МБ",
|
mb: "за МБ",
|
||||||
};
|
};
|
||||||
|
|
||||||
const PutPrivilegies = () => {
|
const PutPrivilegies = () => {
|
||||||
makeRequest<Omit<Privilege_BACKEND, "_id" | "updatedAt">>({
|
makeRequest<Omit<PrivilegeWithAmount, "_id" | "updatedAt">>({
|
||||||
url: baseUrl + "/privilege/",
|
url: baseUrl + "/privilege/",
|
||||||
method: "put",
|
method: "put",
|
||||||
body: {
|
body: {
|
||||||
name: name,
|
name: privilege.name,
|
||||||
privilegeId: privilegeId,
|
privilegeId: privilege.privilegeId,
|
||||||
serviceKey: serviceKey,
|
serviceKey: privilege.serviceKey,
|
||||||
description: description,
|
description: privilege.description,
|
||||||
amount: 1,
|
amount: 1,
|
||||||
type: type,
|
type: privilege.type,
|
||||||
value: value,
|
value: privilege.value,
|
||||||
price: Number(inputValue),
|
price: Number(inputValue),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
priceRef.current.innerText = "price: " + inputValue;
|
priceRef.current.innerText = "price: " + inputValue;
|
||||||
setInputValue("");
|
setInputValue("");
|
||||||
setInputOpen(false);
|
setInputOpen(false);
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
enqueueSnackbar(error.message);
|
enqueueSnackbar(error.message);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const requestOnclickEnter = (event: any) => {
|
const requestOnclickEnter = (event: any) => {
|
||||||
if (event.key === "Enter" && inputValue !== "") {
|
if (event.key === "Enter" && inputValue !== "") {
|
||||||
PutPrivilegies();
|
PutPrivilegies();
|
||||||
setInputOpen(false);
|
setInputOpen(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const onCloseInput = (event: any) => {
|
const onCloseInput = (event: any) => {
|
||||||
if (event.key === "Escape") {
|
if (event.key === "Escape") {
|
||||||
setInputOpen(false);
|
setInputOpen(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
key={type}
|
key={privilege.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"
|
|
||||||
sx={{
|
sx={{
|
||||||
color: "#fe9903",
|
px: "20px",
|
||||||
overflowWrap: "break-word",
|
|
||||||
overflow: "hidden",
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
border: "1px solid gray",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{name}
|
<Box sx={{ display: "flex", borderRight: "1px solid gray" }}>
|
||||||
</Typography>
|
<Box sx={{ width: "200px", py: "25px" }}>
|
||||||
<Tooltip
|
<Typography
|
||||||
sx={{
|
variant="h6"
|
||||||
span: {
|
sx={{
|
||||||
fontSize: "1rem",
|
color: "#fe9903",
|
||||||
},
|
overflowWrap: "break-word",
|
||||||
}}
|
overflow: "hidden",
|
||||||
placement="top"
|
}}
|
||||||
title={
|
>
|
||||||
<Typography sx={{ fontSize: "16px" }}>{description}</Typography>
|
{privilege.name}
|
||||||
}
|
</Typography>
|
||||||
>
|
<Tooltip
|
||||||
<IconButton disableRipple>
|
sx={{
|
||||||
<svg
|
span: {
|
||||||
width="40"
|
fontSize: "1rem",
|
||||||
height="40"
|
},
|
||||||
viewBox="0 0 20 20"
|
}}
|
||||||
fill="none"
|
placement="top"
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
title={
|
||||||
>
|
<Typography sx={{ fontSize: "16px" }}>{privilege.description}</Typography>
|
||||||
<path
|
}
|
||||||
d="M9.25 9.25H10V14.5H10.75"
|
>
|
||||||
stroke="#7E2AEA"
|
<IconButton disableRipple>
|
||||||
strokeWidth="1.5"
|
<svg
|
||||||
strokeLinecap="round"
|
width="40"
|
||||||
strokeLinejoin="round"
|
height="40"
|
||||||
/>
|
viewBox="0 0 20 20"
|
||||||
<path
|
fill="none"
|
||||||
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"
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
fill="#7E2AEA"
|
>
|
||||||
/>
|
<path
|
||||||
</svg>
|
d="M9.25 9.25H10V14.5H10.75"
|
||||||
</IconButton>
|
stroke="#7E2AEA"
|
||||||
</Tooltip>
|
strokeWidth="1.5"
|
||||||
<IconButton onClick={() => setInputOpen(!inputOpen)}>
|
strokeLinecap="round"
|
||||||
<ModeEditOutlineOutlinedIcon sx={{ color: "gray" }} />
|
strokeLinejoin="round"
|
||||||
</IconButton>
|
/>
|
||||||
|
<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>
|
);
|
||||||
<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,
|
TextField,
|
||||||
} from "@mui/material";
|
} from "@mui/material";
|
||||||
import { MOCK_DATA_USERS } from "@root/api/roles";
|
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_HEIGHT = 48;
|
||||||
const ITEM_PADDING_TOP = 8;
|
const ITEM_PADDING_TOP = 8;
|
||||||
@ -28,7 +28,6 @@ const baseUrl =
|
|||||||
export default function DeleteForm() {
|
export default function DeleteForm() {
|
||||||
const [personName, setPersonName] = useState<string[]>([]);
|
const [personName, setPersonName] = useState<string[]>([]);
|
||||||
const [roleId, setRoleId] = useState<string>();
|
const [roleId, setRoleId] = useState<string>();
|
||||||
const { makeRequest } = authStore.getState();
|
|
||||||
|
|
||||||
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
|
const handleChange = (event: SelectChangeEvent<typeof personName>) => {
|
||||||
const {
|
const {
|
||||||
|
@ -6,39 +6,21 @@ import { requestPrivilegies } from "@root/services/privilegies.service";
|
|||||||
import { СardPrivilegie } from "./CardPrivilegie";
|
import { СardPrivilegie } from "./CardPrivilegie";
|
||||||
|
|
||||||
export default function ListPrivilegie() {
|
export default function ListPrivilegie() {
|
||||||
const privileges = usePrivilegeStore((state) => state.privileges);
|
const privileges = usePrivilegeStore((state) => state.privileges);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
requestPrivilegies();
|
requestPrivilegies();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{privileges.map(
|
{privileges.map(privilege => (
|
||||||
({
|
<СardPrivilegie
|
||||||
name,
|
key={privilege._id}
|
||||||
type,
|
privilege={privilege}
|
||||||
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}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,6 @@ import {
|
|||||||
GridRowsProp,
|
GridRowsProp,
|
||||||
GridToolbar,
|
GridToolbar,
|
||||||
} from "@mui/x-data-grid";
|
} from "@mui/x-data-grid";
|
||||||
import { formatDiscountFactor } from "@root/kitUI/Cart/calc";
|
|
||||||
import {
|
import {
|
||||||
openEditDiscountDialog,
|
openEditDiscountDialog,
|
||||||
setSelectedDiscountIds,
|
setSelectedDiscountIds,
|
||||||
@ -19,6 +18,7 @@ import { deleteDiscount } from "@root/api/discounts";
|
|||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
import { requestDiscounts } from "@root/services/discounts.service";
|
import { requestDiscounts } from "@root/services/discounts.service";
|
||||||
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||||
|
import { formatDiscountFactor } from "@root/utils/calcCart";
|
||||||
|
|
||||||
const columns: GridColDef[] = [
|
const columns: GridColDef[] = [
|
||||||
// {
|
// {
|
||||||
@ -118,7 +118,6 @@ export default function DiscountDataGrid({ selectedRowsHC }: Props) {
|
|||||||
(state) => state.selectedDiscountIds
|
(state) => state.selectedDiscountIds
|
||||||
);
|
);
|
||||||
const realDiscounts = useDiscountStore((state) => state.discounts);
|
const realDiscounts = useDiscountStore((state) => state.discounts);
|
||||||
const editDiscountId = useDiscountStore((state) => state.editDiscountId);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
requestDiscounts();
|
requestDiscounts();
|
||||||
|
@ -16,7 +16,7 @@ export default function EditDiscountDialog() {
|
|||||||
const editDiscountId = useDiscountStore(state => state.editDiscountId);
|
const editDiscountId = useDiscountStore(state => state.editDiscountId);
|
||||||
const discounts = useDiscountStore(state => state.discounts);
|
const discounts = useDiscountStore(state => state.discounts);
|
||||||
const privileges = usePrivilegeStore(state => state.privileges);
|
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 [discountType, setDiscountType] = useState<DiscountType>("purchasesAmount");
|
||||||
const [discountNameField, setDiscountNameField] = useState<string>("");
|
const [discountNameField, setDiscountNameField] = useState<string>("");
|
||||||
const [discountDescriptionField, setDiscountDescriptionField] = useState<string>("");
|
const [discountDescriptionField, setDiscountDescriptionField] = useState<string>("");
|
||||||
@ -322,4 +322,4 @@ export default function EditDiscountDialog() {
|
|||||||
</Box>
|
</Box>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,20 @@
|
|||||||
import { Box, IconButton, InputAdornment, TextField, Typography, useMediaQuery, useTheme } from "@mui/material";
|
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 Message from "./Message";
|
||||||
import SendIcon from "@mui/icons-material/Send";
|
import SendIcon from "@mui/icons-material/Send";
|
||||||
import AttachFileIcon from "@mui/icons-material/AttachFile";
|
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 { useParams } from "react-router-dom";
|
||||||
import { GetMessagesRequest, TicketMessage } from "@root/model/ticket";
|
import { TicketMessage } from "@root/model/ticket";
|
||||||
import { getTicketMessages, sendTicketMessage, subscribeToTicketMessages } from "@root/api/tickets";
|
import { sendTicketMessage } from "@root/api/tickets";
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import { useTicketStore } from "@root/stores/tickets";
|
import { useTicketStore } from "@root/stores/tickets";
|
||||||
import { throttle } from "@root/utils/throttle";
|
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() {
|
export default function Chat() {
|
||||||
const token = authStore(state => state.token);
|
const token = useToken();
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||||
const tickets = useTicketStore(state => state.tickets);
|
const tickets = useTicketStore(state => state.tickets);
|
||||||
@ -24,95 +24,53 @@ export default function Chat() {
|
|||||||
const chatBoxRef = useRef<HTMLDivElement>(null);
|
const chatBoxRef = useRef<HTMLDivElement>(null);
|
||||||
const messageApiPage = useMessageStore(state => state.apiPage);
|
const messageApiPage = useMessageStore(state => state.apiPage);
|
||||||
const messagesPerPage = useMessageStore(state => state.messagesPerPage);
|
const messagesPerPage = useMessageStore(state => state.messagesPerPage);
|
||||||
const messagesFetchStateRef = useRef(useMessageStore.getState().fetchState);
|
|
||||||
const isPreventAutoscroll = useMessageStore(state => state.isPreventAutoscroll);
|
const isPreventAutoscroll = useMessageStore(state => state.isPreventAutoscroll);
|
||||||
const lastMessageId = useMessageStore(state => state.lastMessageId);
|
const lastMessageId = useMessageStore(state => state.lastMessageId);
|
||||||
|
|
||||||
const ticket = tickets.find(ticket => ticket.id === ticketId);
|
const ticket = tickets.find(ticket => ticket.id === ticketId);
|
||||||
|
|
||||||
useEffect(function fetchTicketMessages() {
|
const fetchState = useTicketMessages({
|
||||||
if (!ticketId) return;
|
url: "https://admin.pena.digital/heruvym/getMessages",
|
||||||
|
|
||||||
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({
|
|
||||||
ticketId,
|
ticketId,
|
||||||
accessToken: token,
|
messagesPerPage,
|
||||||
onMessage(event) {
|
messageApiPage,
|
||||||
try {
|
onNewMessages: messages => {
|
||||||
const newMessage = JSON.parse(event.data) as TicketMessage;
|
if (chatBoxRef.current && chatBoxRef.current.scrollTop < 1) chatBoxRef.current.scrollTop = 1;
|
||||||
console.log("SSE: parsed newMessage:", newMessage);
|
addOrUpdateMessages(messages);
|
||||||
addOrUpdateMessages([newMessage]);
|
|
||||||
} catch (error) {
|
|
||||||
console.log("SSE: couldn't parse:", event.data);
|
|
||||||
console.log("Error parsing message SSE", error);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onError(event) {
|
onError: (error: Error) => {
|
||||||
console.log("SSE Error:", event);
|
const message = getMessageFromFetchError(error);
|
||||||
|
if (message) enqueueSnackbar(message);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => {
|
useSSESubscription<TicketMessage>({
|
||||||
unsubscribe();
|
enabled: Boolean(token) && Boolean(ticketId),
|
||||||
|
url: `https://admin.pena.digital/heruvym/ticket?ticket=${ticketId}&Authorization=${token}`,
|
||||||
|
onNewData: addOrUpdateMessages,
|
||||||
|
onDisconnect: () => {
|
||||||
clearMessageState();
|
clearMessageState();
|
||||||
setIsPreventAutoscroll(false);
|
setIsPreventAutoscroll(false);
|
||||||
};
|
},
|
||||||
}, [ticketId, token]);
|
marker: "ticket message"
|
||||||
|
});
|
||||||
useEffect(function attachScrollHandler() {
|
|
||||||
if (!chatBoxRef.current) return;
|
|
||||||
|
|
||||||
|
const throttledScrollHandler = useMemo(() => throttle(() => {
|
||||||
const chatBox = chatBoxRef.current;
|
const chatBox = chatBoxRef.current;
|
||||||
const scrollHandler = () => {
|
if (!chatBox) return;
|
||||||
const scrollBottom = chatBox.scrollHeight - chatBox.scrollTop - chatBox.clientHeight;
|
|
||||||
const isPreventAutoscroll = scrollBottom > chatBox.clientHeight;
|
|
||||||
setIsPreventAutoscroll(isPreventAutoscroll);
|
|
||||||
|
|
||||||
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) {
|
if (fetchState !== "idle") return;
|
||||||
incrementMessageApiPage();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const throttledScrollHandler = throttle(scrollHandler, 200);
|
if (chatBox.scrollTop < chatBox.clientHeight) {
|
||||||
chatBox.addEventListener("scroll", throttledScrollHandler);
|
incrementMessageApiPage();
|
||||||
|
}
|
||||||
|
}, 200), [fetchState]);
|
||||||
|
|
||||||
return () => {
|
useEventListener("scroll", throttledScrollHandler, chatBoxRef);
|
||||||
chatBox.removeEventListener("scroll", throttledScrollHandler);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(function scrollOnNewMessage() {
|
useEffect(function scrollOnNewMessage() {
|
||||||
if (!chatBoxRef.current) return;
|
if (!chatBoxRef.current) return;
|
||||||
@ -125,8 +83,6 @@ export default function Chat() {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [lastMessageId]);
|
}, [lastMessageId]);
|
||||||
|
|
||||||
useEffect(() => useMessageStore.subscribe(state => (messagesFetchStateRef.current = state.fetchState)), []);
|
|
||||||
|
|
||||||
function scrollToBottom(behavior?: ScrollBehavior) {
|
function scrollToBottom(behavior?: ScrollBehavior) {
|
||||||
if (!chatBoxRef.current) return;
|
if (!chatBoxRef.current) return;
|
||||||
|
|
||||||
|
@ -1,99 +1,60 @@
|
|||||||
import { Box, useMediaQuery, useTheme } from "@mui/material";
|
import { Box, useMediaQuery, useTheme } from "@mui/material";
|
||||||
import { useEffect } from "react";
|
|
||||||
import Chat from "./Chat/Chat";
|
import Chat from "./Chat/Chat";
|
||||||
import Collapse from "./Collapse";
|
import Collapse from "./Collapse";
|
||||||
import TicketList from "./TicketList/TicketList";
|
import TicketList from "./TicketList/TicketList";
|
||||||
import { getTickets, subscribeToAllTickets } from "@root/api/tickets";
|
import { Ticket } from "@root/model/ticket";
|
||||||
import { GetTicketsRequest, Ticket } from "@root/model/ticket";
|
import { clearTickets, updateTickets, useTicketStore } from "@root/stores/tickets";
|
||||||
import { clearTickets, setTicketsFetchState, updateTickets, useTicketStore } from "@root/stores/tickets";
|
|
||||||
import { enqueueSnackbar } from "notistack";
|
import { enqueueSnackbar } from "notistack";
|
||||||
import { clearMessageState } from "@root/stores/messages";
|
import { clearMessageState } from "@root/stores/messages";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { getMessageFromFetchError, useSSESubscription, useTickets, useToken } from "@frontend/kitui";
|
||||||
|
|
||||||
export default function Support() {
|
export default function Support() {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||||
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
|
const ticketsPerPage = useTicketStore((state) => state.ticketsPerPage);
|
||||||
const ticketApiPage = useTicketStore((state) => state.apiPage);
|
const ticketApiPage = useTicketStore((state) => state.apiPage);
|
||||||
const token = authStore((state) => state.token);
|
const token = useToken();
|
||||||
|
|
||||||
useEffect(
|
const ticketsFetchState = useTickets({
|
||||||
function fetchTickets() {
|
url: "https://admin.pena.digital/heruvym/getTickets",
|
||||||
const getTicketsBody: GetTicketsRequest = {
|
ticketsPerPage,
|
||||||
amt: ticketsPerPage,
|
ticketApiPage,
|
||||||
page: ticketApiPage,
|
onNewTickets: result => {
|
||||||
status: "open",
|
if (result.data) updateTickets(result.data);
|
||||||
};
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onError(event) {
|
onError: (error: Error) => {
|
||||||
console.log("SSE Error:", event);
|
const message = getMessageFromFetchError(error);
|
||||||
|
if (message) enqueueSnackbar(message);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return () => {
|
useSSESubscription<Ticket>({
|
||||||
unsubscribe();
|
enabled: Boolean(token),
|
||||||
clearMessageState();
|
url: `https://admin.pena.digital/heruvym/subscribe?Authorization=${token}`,
|
||||||
clearTickets();
|
onNewData: updateTickets,
|
||||||
};
|
onDisconnect: () => {
|
||||||
},
|
clearMessageState();
|
||||||
[token]
|
clearTickets();
|
||||||
);
|
},
|
||||||
|
marker: "ticket"
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
display: "flex",
|
display: "flex",
|
||||||
width: "100%",
|
width: "100%",
|
||||||
flexDirection: upMd ? "row" : "column",
|
flexDirection: upMd ? "row" : "column",
|
||||||
gap: "12px",
|
gap: "12px",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{!upMd && (
|
{!upMd && (
|
||||||
<Collapse headerText="Тикеты">
|
<Collapse headerText="Тикеты">
|
||||||
<TicketList />
|
<TicketList ticketsFetchState={ticketsFetchState} />
|
||||||
</Collapse>
|
</Collapse>
|
||||||
)}
|
)}
|
||||||
<Chat />
|
<Chat />
|
||||||
{upMd && <TicketList />}
|
{upMd && <TicketList ticketsFetchState={ticketsFetchState} />}
|
||||||
</Box>
|
</Box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -6,13 +6,17 @@ import { incrementTicketsApiPage, useTicketStore } from "@root/stores/tickets";
|
|||||||
import { throttle } from '@root/utils/throttle';
|
import { throttle } from '@root/utils/throttle';
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
import TicketItem from "./TicketItem";
|
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 theme = useTheme();
|
||||||
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
const upMd = useMediaQuery(theme.breakpoints.up("md"));
|
||||||
const tickets = useTicketStore(state => state.tickets);
|
const tickets = useTicketStore(state => state.tickets);
|
||||||
const ticketsFetchStateRef = useRef(useTicketStore.getState().fetchState);
|
|
||||||
const ticketsBoxRef = useRef<HTMLDivElement>(null);
|
const ticketsBoxRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
useEffect(function updateCurrentPageOnScroll() {
|
useEffect(function updateCurrentPageOnScroll() {
|
||||||
@ -23,7 +27,7 @@ export default function TicketList() {
|
|||||||
const scrollBottom = ticketsBox.scrollHeight - ticketsBox.scrollTop - ticketsBox.clientHeight;
|
const scrollBottom = ticketsBox.scrollHeight - ticketsBox.scrollTop - ticketsBox.clientHeight;
|
||||||
if (
|
if (
|
||||||
scrollBottom < ticketsBox.clientHeight &&
|
scrollBottom < ticketsBox.clientHeight &&
|
||||||
ticketsFetchStateRef.current === "idle"
|
ticketsFetchState === "idle"
|
||||||
) incrementTicketsApiPage();
|
) incrementTicketsApiPage();
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -33,9 +37,7 @@ export default function TicketList() {
|
|||||||
return () => {
|
return () => {
|
||||||
ticketsBox.removeEventListener("scroll", throttledScrollHandler);
|
ticketsBox.removeEventListener("scroll", throttledScrollHandler);
|
||||||
};
|
};
|
||||||
}, []);
|
}, [ticketsFetchState]);
|
||||||
|
|
||||||
useEffect(() => useTicketStore.subscribe(state => (ticketsFetchStateRef.current = state.fetchState)), []);
|
|
||||||
|
|
||||||
const sortedTickets = tickets.sort(sortTicketsByUpdateTime).sort(sortTicketsByUnread);
|
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 isUnread1 = ticket1.user === ticket1.top_message.user_id;
|
||||||
const isUnread2 = ticket2.user === ticket2.top_message.user_id;
|
const isUnread2 = ticket2.user === ticket2.top_message.user_id;
|
||||||
return Number(isUnread2) - Number(isUnread1);
|
return Number(isUnread2) - Number(isUnread1);
|
||||||
}
|
}
|
||||||
|
@ -15,19 +15,18 @@ import { enqueueSnackbar } from "notistack";
|
|||||||
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
import { CustomTextField } from "@root/kitUI/CustomTextField";
|
||||||
import { requestTariffs } from "@root/services/tariffs.service";
|
import { requestTariffs } from "@root/services/tariffs.service";
|
||||||
|
|
||||||
import { authStore } from "@root/stores/auth";
|
|
||||||
import {
|
import {
|
||||||
findPrivilegeById,
|
findPrivilegeById,
|
||||||
usePrivilegeStore,
|
usePrivilegeStore,
|
||||||
} from "@root/stores/privilegesStore";
|
} from "@root/stores/privilegesStore";
|
||||||
|
import { PrivilegeWithAmount, makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
import type { Privilege_BACKEND } from "@root/model/tariff";
|
|
||||||
|
|
||||||
type CreateTariffBackendRequest = {
|
type CreateTariffBackendRequest = {
|
||||||
name: string;
|
name: string;
|
||||||
price: number;
|
price: number;
|
||||||
isCustom: boolean;
|
isCustom: boolean;
|
||||||
privilegies: Omit<Privilege_BACKEND, "_id" | "updatedAt">[];
|
privilegies: Omit<PrivilegeWithAmount, "_id" | "updatedAt">[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseUrl =
|
const baseUrl =
|
||||||
@ -36,7 +35,6 @@ const baseUrl =
|
|||||||
: "https://admin.pena.digital/strator";
|
: "https://admin.pena.digital/strator";
|
||||||
|
|
||||||
export default function CreateTariff() {
|
export default function CreateTariff() {
|
||||||
const { makeRequest } = authStore();
|
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
|
|
||||||
const privileges = usePrivilegeStore((store) => store.privileges);
|
const privileges = usePrivilegeStore((store) => store.privileges);
|
||||||
@ -73,7 +71,6 @@ export default function CreateTariff() {
|
|||||||
makeRequest<CreateTariffBackendRequest>({
|
makeRequest<CreateTariffBackendRequest>({
|
||||||
url: baseUrl + "/tariff/",
|
url: baseUrl + "/tariff/",
|
||||||
method: "post",
|
method: "post",
|
||||||
bearer: true,
|
|
||||||
body: {
|
body: {
|
||||||
name: nameField,
|
name: nameField,
|
||||||
price: Number(customPriceField) * 100,
|
price: Number(customPriceField) * 100,
|
||||||
@ -81,7 +78,7 @@ export default function CreateTariff() {
|
|||||||
privilegies: [
|
privilegies: [
|
||||||
{
|
{
|
||||||
name: privilege.name,
|
name: privilege.name,
|
||||||
privilegeId: privilege.id ?? "",
|
privilegeId: privilege.privilegeId ?? "",
|
||||||
serviceKey: privilege.serviceKey,
|
serviceKey: privilege.serviceKey,
|
||||||
description: privilege.description,
|
description: privilege.description,
|
||||||
type: privilege.type,
|
type: privilege.type,
|
||||||
@ -170,7 +167,7 @@ export default function CreateTariff() {
|
|||||||
inputProps={{ sx: { pt: "12px" } }}
|
inputProps={{ sx: { pt: "12px" } }}
|
||||||
>
|
>
|
||||||
{privileges.map((privilege) => (
|
{privileges.map((privilege) => (
|
||||||
<MenuItem key={privilege.description} value={privilege.id}>
|
<MenuItem key={privilege.description} value={privilege._id}>
|
||||||
{privilege.description}
|
{privilege.description}
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
|
@ -1,117 +1,74 @@
|
|||||||
import * as React from "react";
|
|
||||||
import Box from "@mui/material/Box";
|
import Box from "@mui/material/Box";
|
||||||
import Button from "@mui/material/Button";
|
import Button from "@mui/material/Button";
|
||||||
import Typography from "@mui/material/Typography";
|
import Typography from "@mui/material/Typography";
|
||||||
import Modal from "@mui/material/Modal";
|
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 { requestTariffs } from "@root/services/tariffs.service";
|
||||||
import { enqueueSnackbar } from "notistack";
|
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 = {
|
export default function DeleteModal() {
|
||||||
id: string;
|
const deleteTariffIds = useTariffStore(state => state.deleteTariffIds);
|
||||||
};
|
|
||||||
|
|
||||||
const baseUrl =
|
async function handleTariffDeleteClick() {
|
||||||
process.env.NODE_ENV === "production"
|
if (!deleteTariffIds?.length) return;
|
||||||
? "/strator"
|
|
||||||
: "https://admin.pena.digital/strator";
|
|
||||||
|
|
||||||
export default function DeleteModal({
|
const results = await deleteManyTariffs(deleteTariffIds);
|
||||||
open,
|
|
||||||
handleClose,
|
|
||||||
selectedTariffs,
|
|
||||||
}: DeleteModalProps) {
|
|
||||||
const { makeRequest } = authStore();
|
|
||||||
const tariffs = useTariffStore((state) => state.tariffs);
|
|
||||||
|
|
||||||
const deleteTariff = async (id: string): Promise<void> => {
|
enqueueSnackbar(`Тарифов удалено: ${results.deletedCount}, ошибок: ${results.errorCount}`);
|
||||||
const currentTariff = tariffs[id];
|
if (results.errors.length) devlog("Errors deleting tariffs", results.errors);
|
||||||
|
closeDeleteTariffDialog();
|
||||||
|
|
||||||
if (!currentTariff) {
|
requestTariffs();
|
||||||
enqueueSnackbar("Тариф не найден");
|
};
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
return (
|
||||||
await makeRequest<DeleteTariffRequest>({
|
<Modal
|
||||||
url: baseUrl + "/tariff/",
|
open={Boolean(deleteTariffIds?.length)}
|
||||||
method: "delete",
|
onClose={closeDeleteTariffDialog}
|
||||||
bearer: true,
|
aria-labelledby="modal-modal-title"
|
||||||
body: { id },
|
aria-describedby="modal-modal-description"
|
||||||
});
|
|
||||||
} 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,
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Typography id="modal-modal-title" variant="h6" component="h2">
|
<Box
|
||||||
Вы уверены, что хотите удалить{" "}
|
sx={{
|
||||||
{typeof open === "string" ? "тариф" : "тарифы"} ?
|
position: "absolute",
|
||||||
</Typography>
|
top: "50%",
|
||||||
<Box
|
left: "50%",
|
||||||
sx={{
|
transform: "translate(-50%, -50%)",
|
||||||
mt: "20px",
|
width: 400,
|
||||||
display: "flex",
|
bgcolor: "background.paper",
|
||||||
width: "332px",
|
border: "2px solid gray",
|
||||||
justifyContent: "space-between",
|
borderRadius: "6px",
|
||||||
alignItems: "center",
|
boxShadow: 24,
|
||||||
}}
|
p: 4,
|
||||||
>
|
}}
|
||||||
<Button
|
|
||||||
onClick={() => onClickTariffDelete()}
|
|
||||||
sx={{ width: "40px", height: "25px" }}
|
|
||||||
>
|
>
|
||||||
Да
|
<Typography id="modal-modal-title" variant="h6" component="h2">
|
||||||
</Button>
|
Вы уверены, что хотите удалить тариф(ы)?
|
||||||
{/* <Typography>Тариф:</Typography>
|
</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) => (
|
{tariffName.map((name, index) => (
|
||||||
<Typography key={index}>{name};</Typography>
|
<Typography key={index}>{name};</Typography>
|
||||||
))} */}
|
))} */}
|
||||||
</Box>
|
</Box>
|
||||||
</Box>
|
</Box>
|
||||||
</Modal>
|
</Modal>
|
||||||
</div>
|
);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
@ -1,182 +1,113 @@
|
|||||||
// @ts-nocheck
|
import { useEffect, useState } from "react";
|
||||||
import React, { useEffect, useState } from "react";
|
|
||||||
import Box from "@mui/material/Box";
|
import Box from "@mui/material/Box";
|
||||||
import Button from "@mui/material/Button";
|
import Button from "@mui/material/Button";
|
||||||
import Typography from "@mui/material/Typography";
|
import Typography from "@mui/material/Typography";
|
||||||
import Modal from "@mui/material/Modal";
|
import Modal from "@mui/material/Modal";
|
||||||
import TextField from "@mui/material/TextField";
|
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 { 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 = {
|
export default function EditModal() {
|
||||||
name: string;
|
const [nameField, setNameField] = useState("");
|
||||||
price: number;
|
const [priceField, setPriceField] = useState("");
|
||||||
isCustom: boolean;
|
const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
privilegies: Omit<Privilege_BACKEND, "_id" | "updatedAt">[];
|
const editTariffId = useTariffStore(state => state.editTariffId);
|
||||||
};
|
|
||||||
|
|
||||||
const baseUrl =
|
const tariff = tariffs.find(tariff => tariff._id === editTariffId);
|
||||||
process.env.NODE_ENV === "production"
|
|
||||||
? "/strator"
|
|
||||||
: "https://admin.pena.digital/strator";
|
|
||||||
|
|
||||||
const editTariff = ({
|
useEffect(function setCurrentTariffFields() {
|
||||||
tarifIid,
|
if (!tariff) return;
|
||||||
tariffName,
|
|
||||||
tariffPrice,
|
|
||||||
privilege,
|
|
||||||
}: EditProps): Promise<unknown> => {
|
|
||||||
const { makeRequest } = authStore.getState();
|
|
||||||
|
|
||||||
return makeRequest<EditTariffBackendRequest>({
|
setNameField(tariff.name);
|
||||||
method: "put",
|
setPriceField((tariff.price || 0).toString());
|
||||||
url: baseUrl + `/tariff/${tarifIid}`,
|
}, [tariff]);
|
||||||
bearer: true,
|
|
||||||
body: {
|
|
||||||
name: tariffName,
|
|
||||||
price: tariffPrice,
|
|
||||||
isCustom: false,
|
|
||||||
privilegies: [privilege],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
interface Props {
|
|
||||||
tariff: Tariff;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function EditModal({ tariff = undefined }: Props) {
|
async function handleEditClick() {
|
||||||
const [open, setOpen] = useState(false);
|
if (!tariff) return enqueueSnackbar(`Тариф ${editTariffId} не найден`);
|
||||||
const [name, setName] = useState("");
|
|
||||||
const [price, setPrice] = useState("");
|
|
||||||
const tariffs = useTariffStore((state) => state.tariffs);
|
|
||||||
const currentTariff = tariff ? tariffs[tariff.id] : undefined;
|
|
||||||
|
|
||||||
useEffect(() => {
|
const price = parseFloat(priceField);
|
||||||
setOpen(tariff !== undefined);
|
|
||||||
}, [tariff]);
|
|
||||||
|
|
||||||
return (
|
if (!isFinite(price)) return enqueueSnackbar("Поле \"Цена за единицу\" не число");
|
||||||
<Modal
|
if (!nameField) return enqueueSnackbar("Поле \"Имя\" пустое");
|
||||||
open={open}
|
|
||||||
onClose={() => setOpen(false)}
|
const updatedTariff = structuredClone(tariff);
|
||||||
aria-labelledby="modal-modal-title"
|
updatedTariff.name = nameField;
|
||||||
aria-describedby="modal-modal-description"
|
updatedTariff.price = price;
|
||||||
>
|
try {
|
||||||
<Box
|
await putTariff(updatedTariff);
|
||||||
sx={{
|
closeEditTariffDialog();
|
||||||
position: "absolute",
|
|
||||||
top: "50%",
|
requestTariffs();
|
||||||
left: "50%",
|
} catch (error) {
|
||||||
transform: "translate(-50%, -50%)",
|
devlog("Error updating tariff", error);
|
||||||
width: 400,
|
const message = getMessageFromFetchError(error);
|
||||||
bgcolor: "background.paper",
|
if (message) enqueueSnackbar(message);
|
||||||
border: "2px solid gray",
|
}
|
||||||
borderRadius: "6px",
|
}
|
||||||
boxShadow: 24,
|
|
||||||
p: 4,
|
return (
|
||||||
}}
|
<Modal
|
||||||
>
|
open={editTariffId !== null}
|
||||||
<Typography
|
onClose={closeEditTariffDialog}
|
||||||
id="modal-modal-title"
|
aria-labelledby="modal-modal-title"
|
||||||
variant="h6"
|
aria-describedby="modal-modal-description"
|
||||||
component="h2"
|
|
||||||
sx={{ whiteSpace: "nowrap" }}
|
|
||||||
>
|
>
|
||||||
Редактирование тариффа
|
<Box
|
||||||
</Typography>
|
sx={{
|
||||||
|
position: "absolute",
|
||||||
{currentTariff !== undefined && (
|
top: "50%",
|
||||||
<Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
|
left: "50%",
|
||||||
<Typography>Название Тарифа: {currentTariff.name}</Typography>
|
transform: "translate(-50%, -50%)",
|
||||||
<TextField
|
width: 400,
|
||||||
onChange={(event) => setName(event.target.value)}
|
bgcolor: "background.paper",
|
||||||
label="Имя"
|
border: "2px solid gray",
|
||||||
name="name"
|
borderRadius: "6px",
|
||||||
value={name}
|
boxShadow: 24,
|
||||||
sx={{ marginBottom: "10px" }}
|
p: 4,
|
||||||
/>
|
}}
|
||||||
<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("не нашел такой тариф в сторе");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
Редактировать
|
<Typography
|
||||||
</Button>
|
id="modal-modal-title"
|
||||||
</Box>
|
variant="h6"
|
||||||
)}
|
component="h2"
|
||||||
</Box>
|
sx={{ whiteSpace: "nowrap" }}
|
||||||
</Modal>
|
>
|
||||||
);
|
Редактирование тариффа
|
||||||
|
</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 { Typography } from "@mui/material";
|
||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
|
||||||
|
|
||||||
import Cart from "@root/kitUI/Cart/Cart";
|
import Cart from "@root/kitUI/Cart/Cart";
|
||||||
import TariffsDG from "./tariffsDG";
|
import TariffsDG from "./tariffsDG";
|
||||||
|
|
||||||
|
|
||||||
export default function TariffsInfo() {
|
export default function TariffsInfo() {
|
||||||
const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>(
|
|
||||||
[]
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Typography variant="h6" mt="20px">
|
<Typography variant="h6" mt="20px">
|
||||||
Список тарифов
|
Список тарифов
|
||||||
</Typography>
|
</Typography>
|
||||||
<TariffsDG
|
<TariffsDG />
|
||||||
selectedTariffs={selectedTariffs}
|
<Cart />
|
||||||
handleSelectionChange={setSelectedTariffs}
|
</>
|
||||||
/>
|
);
|
||||||
|
|
||||||
<Cart selectedTariffs={selectedTariffs} />
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
@ -1,164 +1,96 @@
|
|||||||
// @ts-nocheck
|
import { GridColDef, GridToolbar } from "@mui/x-data-grid";
|
||||||
import React, { useEffect } from "react";
|
|
||||||
import { useState } from "react";
|
|
||||||
import { GridColDef, GridSelectionModel, GridToolbar } from "@mui/x-data-grid";
|
|
||||||
import { Box, Button, IconButton, Tooltip } from "@mui/material";
|
import { Box, Button, IconButton, Tooltip } from "@mui/material";
|
||||||
import BackspaceIcon from "@mui/icons-material/Backspace";
|
import BackspaceIcon from "@mui/icons-material/Backspace";
|
||||||
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
|
||||||
|
|
||||||
import DataGrid from "@kitUI/datagrid";
|
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 DeleteModal from "@root/pages/dashboard/Content/Tariffs/DeleteModal";
|
||||||
import EditModal from "./EditModal";
|
import EditModal from "./EditModal";
|
||||||
import { Tariff } from "@root/model/tariff";
|
|
||||||
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
import AutorenewIcon from "@mui/icons-material/Autorenew";
|
||||||
import { requestTariffs } from "@root/services/tariffs.service";
|
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({
|
const columns: GridColDef<Tariff, string | number>[] = [
|
||||||
selectedTariffs,
|
{ field: "_id", headerName: "ID", width: 100, valueGetter: ({ row }) => row._id },
|
||||||
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 },
|
|
||||||
{
|
{
|
||||||
field: "edit",
|
field: "edit",
|
||||||
headerName: "Изменение",
|
headerName: "Изменение",
|
||||||
width: 60,
|
width: 60,
|
||||||
renderCell: ({ row }) => {
|
renderCell: ({ row }) => {
|
||||||
return (
|
return (
|
||||||
<IconButton onClick={() => setChangingTariff(row)}>
|
<IconButton onClick={() => openEditTariffDialog(row._id)}>
|
||||||
<ModeEditOutlineOutlinedIcon />
|
<ModeEditOutlineOutlinedIcon />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ field: "name", headerName: "Название тарифа", width: 150 },
|
{ field: "name", headerName: "Название тарифа", width: 150, valueGetter: ({ row }) => row.name },
|
||||||
{ field: "amount", headerName: "Количество", width: 110 },
|
{ field: "amount", headerName: "Количество", width: 110, valueGetter: ({ row }) => row.privilegies[0].amount },
|
||||||
{ field: "serviceName", headerName: "Сервис", width: 150 }, //инфо из гитлаба.
|
{ field: "serviceName", headerName: "Сервис", width: 150, valueGetter: ({ row }) => row.privilegies[0].serviceKey },
|
||||||
{ field: "privilegeName", headerName: "Привилегия", width: 150 },
|
{ field: "privilegeName", headerName: "Привилегия", width: 150, valueGetter: ({ row }) => row.privilegies[0].name },
|
||||||
{ field: "type", headerName: "Единица", width: 100 },
|
{ field: "type", headerName: "Единица", width: 100, valueGetter: ({ row }) => row.privilegies[0].type },
|
||||||
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100 },
|
{ field: "pricePerUnit", headerName: "Цена за ед.", width: 100, valueGetter: ({ row }) => row.privilegies[0].price },
|
||||||
{ field: "customPricePerUnit", headerName: "Кастомная цена", width: 130 },
|
{ field: "customPricePerUnit", headerName: "Кастомная цена", width: 130, valueGetter: ({ row }) => row.isCustom ? "Да" : "Нет" },
|
||||||
{ field: "total", headerName: "Сумма", width: 60 },
|
{ field: "total", headerName: "Сумма", width: 60, valueGetter: ({ row }) => getTariffPrice(row) },
|
||||||
{
|
{
|
||||||
field: "delete",
|
field: "delete",
|
||||||
headerName: "Удаление",
|
headerName: "Удаление",
|
||||||
width: 60,
|
width: 60,
|
||||||
renderCell: ({ row }) => {
|
renderCell: ({ row }) => {
|
||||||
return (
|
return (
|
||||||
<IconButton
|
<IconButton onClick={() => openDeleteTariffDialog([row._id])}>
|
||||||
onClick={() => {
|
<BackspaceIcon />
|
||||||
setOpenDeleteModal(row.id);
|
</IconButton>
|
||||||
}}
|
);
|
||||||
>
|
},
|
||||||
<BackspaceIcon />
|
|
||||||
</IconButton>
|
|
||||||
);
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
// console.log(gridData)
|
export default function TariffsDG() {
|
||||||
|
const tariffs = useTariffStore((state) => state.tariffs);
|
||||||
|
const selectedTariffIds = useTariffStore(state => state.selectedTariffIds);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Tooltip title="обновить список тарифов">
|
<Tooltip title="обновить список тарифов">
|
||||||
<IconButton onClick={() => requestTariffs()}>
|
<IconButton onClick={() => requestTariffs()}>
|
||||||
<AutorenewIcon sx={{ color: "white" }} />
|
<AutorenewIcon sx={{ color: "white" }} />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<DataGrid
|
<DataGrid
|
||||||
disableSelectionOnClick={true}
|
disableSelectionOnClick={true}
|
||||||
checkboxSelection={true}
|
checkboxSelection={true}
|
||||||
rows={gridData}
|
rows={tariffs}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
getRowId={(row) => row.id}
|
getRowId={(row) => row._id}
|
||||||
components={{ Toolbar: GridToolbar }}
|
components={{ Toolbar: GridToolbar }}
|
||||||
onSelectionModelChange={handleSelectionChange}
|
onSelectionModelChange={setSelectedTariffIds}
|
||||||
/>
|
sx={{
|
||||||
{selectedTariffs.length ? (
|
minHeight: "600px",
|
||||||
<Box
|
}}
|
||||||
component="section"
|
/>
|
||||||
sx={{
|
{selectedTariffIds.length ? (
|
||||||
width: "100%",
|
<Box
|
||||||
display: "flex",
|
component="section"
|
||||||
justifyContent: "start",
|
sx={{
|
||||||
mb: "30px",
|
width: "100%",
|
||||||
}}
|
display: "flex",
|
||||||
>
|
justifyContent: "start",
|
||||||
<Button
|
mb: "30px",
|
||||||
onClick={() => setOpenDeleteModal(true)}
|
}}
|
||||||
sx={{ mr: "20px", zIndex: "10000" }}
|
>
|
||||||
>
|
<Button
|
||||||
Удаление
|
onClick={() => openDeleteTariffDialog(selectedTariffIds.map(s => s.toString()))}
|
||||||
</Button>
|
sx={{ mr: "20px", zIndex: "10000" }}
|
||||||
</Box>
|
>
|
||||||
) : (
|
Удалить выделенные
|
||||||
<React.Fragment />
|
</Button>
|
||||||
)}
|
</Box>
|
||||||
<DeleteModal
|
) : null}
|
||||||
open={openDeleteModal}
|
<DeleteModal />
|
||||||
handleClose={() => {
|
<EditModal />
|
||||||
closeDeleteModal();
|
</>
|
||||||
}}
|
);
|
||||||
selectedTariffs={selectedTariffs}
|
|
||||||
/>
|
|
||||||
<EditModal tariff={changingTariff} />
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
@ -24,19 +24,17 @@ import ClearIcon from "@mui/icons-material/Clear";
|
|||||||
import ConditionalRender from "@root/pages/Setting/ConditionalRender";
|
import ConditionalRender from "@root/pages/Setting/ConditionalRender";
|
||||||
import ServiceUsersDG from "./ServiceUsersDG";
|
import ServiceUsersDG from "./ServiceUsersDG";
|
||||||
|
|
||||||
import { authStore } from "@stores/auth";
|
|
||||||
|
|
||||||
import { getRoles_mock, TMockData } from "../../../api/roles";
|
import { getRoles_mock, TMockData } from "../../../api/roles";
|
||||||
|
|
||||||
import theme from "../../../theme";
|
import theme from "../../../theme";
|
||||||
|
|
||||||
import type { UsersType } from "../../../api/roles";
|
import type { UsersType } from "../../../api/roles";
|
||||||
|
import { makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
const baseUrl =
|
const baseUrl =
|
||||||
process.env.NODE_ENV === "production" ? "" : "https://admin.pena.digital";
|
process.env.NODE_ENV === "production" ? "" : "https://admin.pena.digital";
|
||||||
|
|
||||||
const Users: React.FC = () => {
|
const Users: React.FC = () => {
|
||||||
const { makeRequest } = authStore();
|
|
||||||
// makeRequest({
|
// makeRequest({
|
||||||
// url: "https://admin.pena.digital/strator/account",
|
// url: "https://admin.pena.digital/strator/account",
|
||||||
// method: "get",
|
// method: "get",
|
||||||
|
@ -3,11 +3,11 @@ import { Box, IconButton, Typography } from "@mui/material";
|
|||||||
import theme from "../../../theme";
|
import theme from "../../../theme";
|
||||||
import ExitToAppOutlinedIcon from "@mui/icons-material/ExitToAppOutlined";
|
import ExitToAppOutlinedIcon from "@mui/icons-material/ExitToAppOutlined";
|
||||||
import Logo from "../../Logo";
|
import Logo from "../../Logo";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { clearAuthToken, makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
const Header: React.FC = () => {
|
const Header: React.FC = () => {
|
||||||
const { makeRequest, clearToken } = authStore();
|
|
||||||
return (
|
return (
|
||||||
<React.Fragment>
|
<React.Fragment>
|
||||||
<Box
|
<Box
|
||||||
sx={{
|
sx={{
|
||||||
@ -55,7 +55,7 @@ const Header: React.FC = () => {
|
|||||||
makeRequest({
|
makeRequest({
|
||||||
url: "https://admin.pena.digital/auth/logout",
|
url: "https://admin.pena.digital/auth/logout",
|
||||||
contentType: true,
|
contentType: true,
|
||||||
}).then(() => clearToken());
|
}).then(() => clearAuthToken());
|
||||||
}}
|
}}
|
||||||
sx={{
|
sx={{
|
||||||
display: "flex",
|
display: "flex",
|
||||||
|
@ -1,31 +1,30 @@
|
|||||||
import { setDiscounts } from "@root/stores/discounts";
|
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 =
|
const baseUrl =
|
||||||
process.env.NODE_ENV === "production"
|
process.env.NODE_ENV === "production"
|
||||||
? "/price"
|
? "/price"
|
||||||
: "https://admin.pena.digital/price";
|
: "https://admin.pena.digital/price";
|
||||||
|
|
||||||
const { makeRequest } = authStore.getState();
|
|
||||||
|
|
||||||
const filterDiscounts = (discounts: Discount[]) => {
|
const filterDiscounts = (discounts: Discount[]) => {
|
||||||
const activeDiscounts = discounts.filter((discount) => !discount.Deprecated);
|
const activeDiscounts = discounts.filter((discount) => !discount.Deprecated);
|
||||||
|
|
||||||
setDiscounts(activeDiscounts);
|
setDiscounts(activeDiscounts);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const requestDiscounts = async (): Promise<void> => {
|
export const requestDiscounts = async (): Promise<Discount[]> => {
|
||||||
try {
|
try {
|
||||||
const { Discounts } = await makeRequest<never, GetDiscountResponse>({
|
const { Discounts } = await makeRequest<never, GetDiscountResponse>({
|
||||||
url: baseUrl + "/discounts",
|
url: baseUrl + "/discounts",
|
||||||
method: "get",
|
method: "get",
|
||||||
useToken: true,
|
useToken: true,
|
||||||
bearer: true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
filterDiscounts(Discounts);
|
filterDiscounts(Discounts);
|
||||||
|
|
||||||
|
return Discounts
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error("Ошибка при получении скидок");
|
throw new Error("Ошибка при получении скидок");
|
||||||
}
|
}
|
||||||
|
@ -1,26 +1,10 @@
|
|||||||
import { authStore } from "@root/stores/auth";
|
|
||||||
|
|
||||||
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
import { resetPrivilegeArray } from "@root/stores/privilegesStore";
|
||||||
import { exampleCartValues } from "@stores/mocks/exampleCartValues";
|
import { exampleCartValues } from "@stores/mocks/exampleCartValues";
|
||||||
|
|
||||||
import type { RealPrivilege } from "@root/model/privilege";
|
import { PrivilegeWithAmount, makeRequest } from "@frontend/kitui";
|
||||||
|
|
||||||
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;
|
|
||||||
};
|
|
||||||
|
|
||||||
type SeverPrivilegiesResponse = {
|
type SeverPrivilegiesResponse = {
|
||||||
templategen: RealPrivilege[];
|
templategen: PrivilegeWithAmount[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseUrl =
|
const baseUrl =
|
||||||
@ -28,10 +12,8 @@ const baseUrl =
|
|||||||
? "/strator"
|
? "/strator"
|
||||||
: "https://admin.pena.digital/strator";
|
: "https://admin.pena.digital/strator";
|
||||||
|
|
||||||
const { makeRequest } = authStore.getState();
|
const mutatePrivilegies = (privilegies: PrivilegeWithAmount[]) => {
|
||||||
|
let extracted: PrivilegeWithAmount[] = [];
|
||||||
const mutatePrivilegies = (privilegies: RealPrivilege[]) => {
|
|
||||||
let extracted: RealPrivilege[] = [];
|
|
||||||
for (let serviceKey in privilegies) {
|
for (let serviceKey in privilegies) {
|
||||||
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
//Приходит объект. В его значениях массивы привилегий для разных сервисов. Высыпаем в общую кучу и обновляем стор
|
||||||
extracted = extracted.concat(privilegies[serviceKey]);
|
extracted = extracted.concat(privilegies[serviceKey]);
|
||||||
@ -45,7 +27,7 @@ const mutatePrivilegies = (privilegies: RealPrivilege[]) => {
|
|||||||
type: privilege.type,
|
type: privilege.type,
|
||||||
price: privilege.price,
|
price: privilege.price,
|
||||||
value: privilege.value,
|
value: privilege.value,
|
||||||
id: privilege._id,
|
_id: privilege._id,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
resetPrivilegeArray([...readyArray, ...exampleCartValues.privileges]);
|
resetPrivilegeArray([...readyArray, ...exampleCartValues.privileges]);
|
||||||
|
@ -1,62 +1,43 @@
|
|||||||
import { resetTariffsStore } from "@root/stores/tariffsStore";
|
import { Tariff, makeRequest } from "@frontend/kitui";
|
||||||
import { authStore } from "@root/stores/auth";
|
import { updateTariffs } from "@root/stores/tariffs";
|
||||||
|
|
||||||
import type { Tariff, Tariff_BACKEND } from "@root/model/tariff";
|
|
||||||
|
|
||||||
type GetTariffsResponse = {
|
type GetTariffsResponse = {
|
||||||
totalPages: number;
|
totalPages: number;
|
||||||
tariffs: Tariff_BACKEND[];
|
tariffs: Tariff[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const baseUrl =
|
const baseUrl =
|
||||||
process.env.NODE_ENV === "production"
|
process.env.NODE_ENV === "production"
|
||||||
? "/strator"
|
? "/strator"
|
||||||
: "https://admin.pena.digital/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[]) => {
|
updateTariffs(nonDeletedTariffs);
|
||||||
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);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const requestTariffs = async (
|
export const requestTariffs = async (
|
||||||
page: number = 1,
|
page: number = 1,
|
||||||
existingTariffs: Tariff_BACKEND[] = []
|
existingTariffs: Tariff[] = []
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const { tariffs, totalPages } = await makeRequest<
|
const { tariffs, totalPages } = await makeRequest<
|
||||||
never,
|
never,
|
||||||
GetTariffsResponse
|
GetTariffsResponse
|
||||||
>({
|
>({
|
||||||
url: baseUrl + `/tariff/?page=${page}&limit=${100}`,
|
url: baseUrl + `/tariff/?page=${page}&limit=${100}`,
|
||||||
method: "get",
|
method: "get",
|
||||||
bearer: true,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
if (page < totalPages) {
|
if (page < totalPages) {
|
||||||
return requestTariffs(page + 1, [...existingTariffs, ...tariffs]);
|
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 { create } from "zustand";
|
||||||
import { devtools, persist } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
import { CartTotal } from "@root/model/cart";
|
import { CartData } from "@frontend/kitui";
|
||||||
|
|
||||||
|
|
||||||
interface CartStore {
|
interface CartStore {
|
||||||
cartTotal: CartTotal | null;
|
cartData: CartData | null;
|
||||||
setCartTotal: (newCartTotal: CartTotal | null) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const initialState: CartStore = {
|
||||||
|
cartData: null,
|
||||||
|
};
|
||||||
|
|
||||||
export const useCartStore = create<CartStore>()(
|
export const useCartStore = create<CartStore>()(
|
||||||
devtools(
|
devtools(
|
||||||
// persist(
|
(set, get) => initialState,
|
||||||
(set, get) => ({
|
{
|
||||||
cartTotal: null,
|
name: "Cart",
|
||||||
setCartTotal: (newCartTotal) => set({ cartTotal: newCartTotal }),
|
enabled: process.env.NODE_ENV === "development",
|
||||||
}),
|
}
|
||||||
// {
|
)
|
||||||
// name: "cart",
|
|
||||||
// getStorage: () => localStorage,
|
|
||||||
// }
|
|
||||||
// ),
|
|
||||||
{
|
|
||||||
name: "Cart store",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const setCartData = (cartData: CartStore["cartData"]) => useCartStore.setState({ cartData });
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import { GridSelectionModel } from "@mui/x-data-grid";
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { devtools } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
import { Discount } from "@root/model/discount";
|
|
||||||
import { produce } from "immer";
|
import { produce } from "immer";
|
||||||
|
import { Discount } from "@frontend/kitui";
|
||||||
|
|
||||||
|
|
||||||
interface DiscountStore {
|
interface DiscountStore {
|
||||||
@ -19,15 +19,15 @@ export const useDiscountStore = create<DiscountStore>()(
|
|||||||
editDiscountId: null,
|
editDiscountId: null,
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
name: "Real discount store",
|
name: "Discount",
|
||||||
enabled: process.env.NODE_ENV === "development"
|
enabled: process.env.NODE_ENV === "development",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
export const setDiscounts = (discounts: DiscountStore["discounts"]) => useDiscountStore.setState({ discounts });
|
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(
|
export const addDiscount = (discount: DiscountStore["discounts"][number]) => useDiscountStore.setState(
|
||||||
state => ({ discounts: [...state.discounts, discount] })
|
state => ({ discounts: [...state.discounts, discount] })
|
||||||
|
@ -24,7 +24,8 @@ export const useMessageStore = create<MessageStore>()(
|
|||||||
isPreventAutoscroll: false,
|
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 date1 = new Date(ticket1.created_at).getTime();
|
||||||
const date2 = new Date(ticket2.created_at).getTime();
|
const date2 = new Date(ticket2.created_at).getTime();
|
||||||
return date1 - date2;
|
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 { create } from "zustand";
|
||||||
import { devtools } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
import { exampleCartValues } from "./mocks/exampleCartValues";
|
import { PrivilegeWithAmount } from "@frontend/kitui";
|
||||||
import { mergedBackFrontPrivilege } from "@root/model/privilege";
|
|
||||||
|
|
||||||
interface PrivilegeStore {
|
interface PrivilegeStore {
|
||||||
privileges: mergedBackFrontPrivilege[];
|
privileges: PrivilegeWithAmount[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export const usePrivilegeStore = create<PrivilegeStore>()(
|
export const usePrivilegeStore = create<PrivilegeStore>()(
|
||||||
@ -14,14 +13,14 @@ export const usePrivilegeStore = create<PrivilegeStore>()(
|
|||||||
privileges: [],
|
privileges: [],
|
||||||
}),
|
}),
|
||||||
{
|
{
|
||||||
name: "Privilege store",
|
name: "Privileges",
|
||||||
|
enabled: process.env.NODE_ENV === "development",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
export const resetPrivilegeArray = (privileges: PrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges });
|
export const resetPrivilegeArray = (privileges: PrivilegeStore["privileges"]) => usePrivilegeStore.setState({ privileges });
|
||||||
|
|
||||||
|
|
||||||
export const findPrivilegeById = (privilegeId: string) => {
|
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 { create } from "zustand";
|
||||||
import { persist } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
import { Tariff_BACKEND, Tariff_FRONTEND } from "@root/model/tariff";
|
import { Tariff } from "@frontend/kitui";
|
||||||
|
import { GridSelectionModel } from "@mui/x-data-grid";
|
||||||
|
|
||||||
|
|
||||||
interface TariffStore {
|
interface TariffStore {
|
||||||
tariffs: Tariff_FRONTEND[]
|
tariffs: Tariff[];
|
||||||
|
editTariffId: string | null;
|
||||||
|
deleteTariffIds: string[] | null;
|
||||||
|
selectedTariffIds: GridSelectionModel;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useTariffStore = create<TariffStore>()(
|
export const useTariffStore = create<TariffStore>()(
|
||||||
persist(
|
devtools(
|
||||||
(set, get) => ({
|
(set, get) => ({
|
||||||
tariffs: [],
|
tariffs: [],
|
||||||
// tariffs: exampleTariffs,
|
editTariffId: null,
|
||||||
}),
|
deleteTariffIds: null,
|
||||||
{
|
selectedTariffIds: [],
|
||||||
name: "Tariff store",
|
}),
|
||||||
}
|
{
|
||||||
)
|
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) => {
|
const sortedTariffs = Object.values(tariffMap).sort(sortTariffsByCreatedAt);
|
||||||
let stateTariffs = useTariffStore.getState().tariffs
|
|
||||||
let index
|
return { tariffs: sortedTariffs };
|
||||||
stateTariffs.forEach((e,i) => { //ищем такой тариф для замены на новый
|
},
|
||||||
if (e.id == tariff.id) index = i
|
false,
|
||||||
})
|
{
|
||||||
if (index === undefined) {// не нашли. Добавляем
|
type: "updateTariffs",
|
||||||
addTariffs([tariff])
|
tariffsLength: tariffs.length,
|
||||||
} else { //нашли. Заменяем
|
|
||||||
stateTariffs[index] = tariff
|
|
||||||
useTariffStore.setState(() => ({tariffs: stateTariffs}))
|
|
||||||
}
|
}
|
||||||
}
|
);
|
||||||
|
|
||||||
|
export const openEditTariffDialog = (editTariffId: TariffStore["editTariffId"]) => useTariffStore.setState({ editTariffId });
|
||||||
|
|
||||||
export const addTariffs = (newTariffs: Tariff_FRONTEND[]) => {
|
export const closeEditTariffDialog = () => useTariffStore.setState({ editTariffId: null });
|
||||||
let stateTariffs = useTariffStore.getState().tariffs
|
|
||||||
let newArrayTariffs = [...stateTariffs, ...newTariffs]
|
export const openDeleteTariffDialog = (deleteTariffId: TariffStore["deleteTariffIds"]) => useTariffStore.setState({ deleteTariffIds: deleteTariffId });
|
||||||
newArrayTariffs.forEach((tariff) => {
|
|
||||||
updateTariff(tariff)
|
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 {
|
interface TicketStore {
|
||||||
tickets: Ticket[];
|
tickets: Ticket[];
|
||||||
fetchState: "idle" | "fetching" | "all fetched";
|
|
||||||
apiPage: number;
|
apiPage: number;
|
||||||
ticketsPerPage: number;
|
ticketsPerPage: number;
|
||||||
}
|
}
|
||||||
@ -14,21 +13,18 @@ export const useTicketStore = create<TicketStore>()(
|
|||||||
devtools(
|
devtools(
|
||||||
(set, get) => ({
|
(set, get) => ({
|
||||||
tickets: [],
|
tickets: [],
|
||||||
fetchState: "idle",
|
|
||||||
apiPage: 0,
|
apiPage: 0,
|
||||||
ticketsPerPage: 20,
|
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 = () => {
|
export const incrementTicketsApiPage = () => {
|
||||||
const state = useTicketStore.getState();
|
const state = useTicketStore.getState();
|
||||||
if (state.fetchState !== "idle") return;
|
|
||||||
|
|
||||||
useTicketStore.setState({ apiPage: state.apiPage + 1 });
|
useTicketStore.setState({ apiPage: state.apiPage + 1 });
|
||||||
};
|
};
|
||||||
@ -42,4 +38,4 @@ export const updateTickets = (receivedTickets: Ticket[]) => {
|
|||||||
useTicketStore.setState({ tickets: Object.values(ticketIdToTicketMap) });
|
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 {
|
export function getDiscountTypeFromLayer(layer: Discount["Layer"]): DiscountType {
|
||||||
switch (layer) {
|
switch (layer) {
|
||||||
@ -8,4 +9,4 @@ export function getDiscountTypeFromLayer(layer: Discount["Layer"]): DiscountType
|
|||||||
case 4: return "purchasesAmount";
|
case 4: return "purchasesAmount";
|
||||||
default: throw new Error("Wrong discount layer");
|
default: throw new Error("Wrong discount layer");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,18 @@
|
|||||||
import { RealPrivilege } from "@root/model/privilege";
|
import { PrivilegeWithAmount, makeRequest } from "@frontend/kitui";
|
||||||
import { authStore } from "@root/stores/auth";
|
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
|
||||||
const makeRequest = authStore.getState().makeRequest;
|
|
||||||
|
|
||||||
export default function usePrivileges({ onError, onNewPrivileges }: {
|
export default function usePrivileges({ onError, onNewPrivileges }: {
|
||||||
onNewPrivileges: (response: RealPrivilege[]) => void;
|
onNewPrivileges: (response: PrivilegeWithAmount[]) => void;
|
||||||
onError?: (error: any) => void;
|
onError?: (error: any) => void;
|
||||||
}) {
|
}) {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
|
|
||||||
makeRequest<never, RealPrivilege[]>({
|
makeRequest<never, PrivilegeWithAmount[]>({
|
||||||
url: "https://admin.pena.digital/strator/privilege",
|
url: "https://admin.pena.digital/strator/privilege",
|
||||||
method: "get",
|
method: "get",
|
||||||
useToken: true,
|
useToken: true,
|
||||||
bearer: true,
|
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
}).then(result => {
|
}).then(result => {
|
||||||
onNewPrivileges(result);
|
onNewPrivileges(result);
|
||||||
@ -26,4 +22,4 @@ export default function usePrivileges({ onError, onNewPrivileges }: {
|
|||||||
|
|
||||||
return () => controller.abort();
|
return () => controller.abort();
|
||||||
}, [onError, onNewPrivileges]);
|
}, [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.isundefined "^3.0.1"
|
||||||
lodash.uniq "^4.5.0"
|
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":
|
"@humanwhocodes/config-array@^0.11.8":
|
||||||
version "0.11.8"
|
version "0.11.8"
|
||||||
resolved "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.8.tgz"
|
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"
|
resolved "https://registry.npmjs.org/axe-core/-/axe-core-4.6.3.tgz"
|
||||||
integrity sha512-/BQzOX780JhsxDnPpH4ZiyrJAzcd8AfzFPkv+89veFSr1rcMjuq2JDCwypKaPeB6ljHp9KjXhPpjgCvQlWYuqg==
|
integrity sha512-/BQzOX780JhsxDnPpH4ZiyrJAzcd8AfzFPkv+89veFSr1rcMjuq2JDCwypKaPeB6ljHp9KjXhPpjgCvQlWYuqg==
|
||||||
|
|
||||||
axios@^1.3.4:
|
axios@^1.4.0:
|
||||||
version "1.3.4"
|
version "1.4.0"
|
||||||
resolved "https://registry.npmjs.org/axios/-/axios-1.3.4.tgz"
|
resolved "https://registry.yarnpkg.com/axios/-/axios-1.4.0.tgz#38a7bf1224cd308de271146038b551d725f0be1f"
|
||||||
integrity sha512-toYm+Bsyl6VC5wSkfkbbNB6ROv7KY93PEBBL6xyDczaIHasAiv4wPqQ/c4RjoQzipxRD2W5g21cOqQulZ7rHwQ==
|
integrity sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==
|
||||||
dependencies:
|
dependencies:
|
||||||
follow-redirects "^1.15.0"
|
follow-redirects "^1.15.0"
|
||||||
form-data "^4.0.0"
|
form-data "^4.0.0"
|
||||||
@ -12330,9 +12338,9 @@ zip-stream@^4.1.0:
|
|||||||
compress-commons "^4.1.0"
|
compress-commons "^4.1.0"
|
||||||
readable-stream "^3.6.0"
|
readable-stream "^3.6.0"
|
||||||
|
|
||||||
zustand@^4.1.1:
|
zustand@^4.3.8:
|
||||||
version "4.3.3"
|
version "4.3.9"
|
||||||
resolved "https://registry.npmjs.org/zustand/-/zustand-4.3.3.tgz"
|
resolved "https://registry.yarnpkg.com/zustand/-/zustand-4.3.9.tgz#a7d4332bbd75dfd25c6848180b3df1407217f2ad"
|
||||||
integrity sha512-x2jXq8S0kfLGNwGh87nhRfEc2eZy37tSatpSoSIN+O6HIaBhgQHSONV/F9VNrNcBcKQu/E80K1DeHDYQC/zCrQ==
|
integrity sha512-Tat5r8jOMG1Vcsj8uldMyqYKC5IZvQif8zetmLHs9WoZlntTHmIoNM8TpLRY31ExncuUvUOXehd0kvahkuHjDw==
|
||||||
dependencies:
|
dependencies:
|
||||||
use-sync-external-store "1.2.0"
|
use-sync-external-store "1.2.0"
|
||||||
|
Loading…
Reference in New Issue
Block a user