diff --git a/src/api/promocode/requests.ts b/src/api/promocode/requests.ts index 1e7e114..d5da8d1 100644 --- a/src/api/promocode/requests.ts +++ b/src/api/promocode/requests.ts @@ -25,6 +25,33 @@ const getPromocodeList = async (body: GetPromocodeListBody) => { } }; +export const getAllPromocodes = async () => { + try { + const promocodes: Promocode[] = []; + + let page = 0; + while (true) { + const promocodeList = await getPromocodeList({ + limit: 2, + filter: { + active: true, + }, + page, + }); + + if (promocodeList.items.length === 0) break; + + promocodes.push(...promocodeList.items); + page++; + } + + return promocodes; + } catch (nativeError) { + const [error] = parseAxiosError(nativeError); + throw new Error(`Ошибка при получении списка промокодов. ${error}`); + } +}; + const createPromocode = async (body: CreatePromocodeBody) => { try { const createPromocodeResponse = await makeRequest< @@ -42,7 +69,7 @@ const createPromocode = async (body: CreatePromocodeBody) => { if (isAxiosError(nativeError) && nativeError.response?.data.error === "Duplicate Codeword") { throw new Error(`Промокод уже существует`); } - + const [error] = parseAxiosError(nativeError); throw new Error(`Ошибка создания промокода. ${error}`); } @@ -65,4 +92,5 @@ export const promocodeApi = { getPromocodeList, createPromocode, deletePromocode, + getAllPromocodes, }; diff --git a/src/api/promocode/swr.ts b/src/api/promocode/swr.ts index 064d41a..afa0d4e 100644 --- a/src/api/promocode/swr.ts +++ b/src/api/promocode/swr.ts @@ -78,4 +78,17 @@ export function usePromocodes(page: number, pageSize: number) { deletePromocode, promocodesCount: promocodesCountRef.current, }; -} +} + +export function useAllPromocodes() { + const swrResponse = useSwr("allPromocodes", promocodeApi.getAllPromocodes, { + keepPreviousData: true, + suspense: true, + onError(err) { + console.log("Error fetching all promocodes", err); + enqueueSnackbar(err.message, { variant: "error" }); + }, + }); + + return swrResponse.data; +} diff --git a/src/kitUI/Cart/Cart.tsx b/src/kitUI/Cart/Cart.tsx index aa2a0ff..35f1faf 100644 --- a/src/kitUI/Cart/Cart.tsx +++ b/src/kitUI/Cart/Cart.tsx @@ -16,20 +16,23 @@ import { useMediaQuery, useTheme } from "@mui/material"; +import { useDiscounts } from "@root/api/discounts"; +import { useAllPromocodes } from "@root/api/promocode/swr"; import { requestDiscounts } from "@root/services/discounts.service"; import { requestPrivileges } from "@root/services/privilegies.service"; import { setCartData, useCartStore } from "@root/stores/cart"; import { useTariffStore } from "@root/stores/tariffs"; +import { createDiscountFromPromocode } from "@root/utils/createDiscountFromPromocode"; import { currencyFormatter } from "@root/utils/currencyFormatter"; import { useState } from "react"; import CartItemRow from "./CartItemRow"; -import { useDiscounts } from "@root/api/discounts"; export default function Cart() { const theme = useTheme(); const mobile = useMediaQuery(theme.breakpoints.down(400)); const discounts = useDiscounts(); + const promocodes = useAllPromocodes(); const cartData = useCartStore((store) => store.cartData); const tariffs = useTariffStore(state => state.tariffs); const [couponField, setCouponField] = useState(""); @@ -48,8 +51,21 @@ export default function Cart() { if (!isFinite(loyaltyValue)) loyaltyValue = 0; + const promocode = promocodes.find(promocode => { + if (promocode.dueTo < (Date.now() / 1000)) return false; + + return promocode.codeword === couponField; + }); + + const userId = crypto.randomUUID(); + + const discountsWithPromocodeDiscount = promocode ? [ + ...discounts, + createDiscountFromPromocode(promocode, userId), + ] : discounts; + try { - const cartData = calcCart(cartTariffs, discounts, loyaltyValue, couponField); + const cartData = calcCart(cartTariffs, discountsWithPromocodeDiscount, loyaltyValue, userId); setErrorMessage(null); setCartData(cartData); diff --git a/src/model/cart.ts b/src/model/cart.ts deleted file mode 100644 index e5263b3..0000000 --- a/src/model/cart.ts +++ /dev/null @@ -1,8 +0,0 @@ -export interface Promocode { - id: string; - name: string; - endless: boolean; - from: string; - dueTo: string; - privileges: string[]; -} diff --git a/src/utils/createDiscountFromPromocode.ts b/src/utils/createDiscountFromPromocode.ts new file mode 100644 index 0000000..392b9e4 --- /dev/null +++ b/src/utils/createDiscountFromPromocode.ts @@ -0,0 +1,42 @@ +import { Promocode } from "@root/model/promocodes"; + + +export function createDiscountFromPromocode(promocode: Promocode, userId: string) { + return { + "ID": crypto.randomUUID(), + "Name": promocode.codeword, + "Layer": promocode.bonus.discount.layer, + "Description": "", + "Condition": { + "User": userId, + "UserType": "", + "Coupon": promocode.codeword, + "PurchasesAmount": "0", + "CartPurchasesAmount": "0", + "Product": promocode.bonus.discount.target, + "Term": "0", + "Usage": "0", + "PriceFrom": "0", + "Group": promocode.bonus.discount.target + }, + "Target": { + "Products": promocode.bonus.discount.layer === 1 ? [ + { + "ID": promocode.bonus.discount.target, + "Factor": promocode.bonus.discount.factor, + "Overhelm": false + } + ] : [], + "Factor": promocode.bonus.discount.layer === 2 ? promocode.bonus.discount.factor : 0, + "TargetScope": "Sum", + "TargetGroup": promocode.bonus.discount.target, + "Overhelm": true + }, + "Audit": { + "UpdatedAt": "", + "CreatedAt": "", + "Deleted": false + }, + "Deprecated": false + }; +}