сохранение кэша в рублях, копейках и строкой

This commit is contained in:
Tamara 2024-04-07 19:19:49 +03:00
parent e77e83d5d4
commit 843877c570
5 changed files with 93 additions and 53 deletions

@ -204,23 +204,22 @@ export const Answers: FC<AnswersProps> = ({ data }) => {
const theme = useTheme(); const theme = useTheme();
const answers = useMemo( const answers = useMemo(
() => () =>
data === null ? data === null
[] ? []
: : Object.keys(data ?? {})
Object.keys(data ?? {}) .map((key) =>
.map((key) => Object.entries(data[key]).map(([title, percent]) => ({
Object.entries(data[key]).map(([title, percent]) => ({ title,
title, percent,
percent, key,
key, })),
})), )
) .flat(),
.flat(),
[data], [data],
); );
console.log(answers) console.log(answers);
console.log(page) console.log(page);
if (!data) { if (!data) {
return ( return (
<Typography textAlign="center" m="10px 0"> <Typography textAlign="center" m="10px 0">
@ -274,7 +273,13 @@ console.log(page)
}, },
}} }}
> >
Заголовок вопроса. {answers.slice(ANSWERS_PER_PAGE * (page - 1), ANSWERS_PER_PAGE * page)[0]?.key} Заголовок вопроса.{" "}
{
answers.slice(
ANSWERS_PER_PAGE * (page - 1),
ANSWERS_PER_PAGE * page,
)[0]?.key
}
</Typography> </Typography>
<ButtonBase> <ButtonBase>
<DoubleCheckIcon /> <DoubleCheckIcon />

@ -44,15 +44,18 @@ const GeneralItem = ({
const numberValue = const numberValue =
numberType === "sum" numberType === "sum"
? Object.values(general).reduce((total, item) => total + item, 0) ? Object.values(general).reduce((total, item) => total + item, 0)
: 0 : 0;
Object.entries(general).reduce( Object.entries(general).reduce(
(total, [key, value]) => total + (value / Number(key)) * 100, (total, [key, value]) => total + (value / Number(key)) * 100,
0, 0,
) / Object.keys(general).length || Number(0); ) / Object.keys(general).length || Number(0);
console.log("general" , general) console.log("general", general);
console.log(Object.keys(general).length === 0) console.log(Object.keys(general).length === 0);
if (Object.keys(general).length === 0) return <Typography textAlign="center">{`${title} - нет данных`}</Typography> if (Object.keys(general).length === 0)
return (
<Typography textAlign="center">{`${title} - нет данных`}</Typography>
);
return ( return (
<Paper <Paper
sx={{ sx={{
@ -66,7 +69,6 @@ const GeneralItem = ({
{numberType === "sum" ? numberValue : `${numberValue.toFixed()}%`} {numberType === "sum" ? numberValue : `${numberValue.toFixed()}%`}
</Typography> </Typography>
<LineChart <LineChart
xAxis={[ xAxis={[
{ {
data: Object.keys(general), data: Object.keys(general),
@ -126,25 +128,41 @@ export const General: FC<GeneralProps> = ({ data }) => {
<GeneralItem <GeneralItem
title="Открыли квиз" title="Открыли квиз"
numberType="sum" numberType="sum"
general={ Object.entries(data.Open).filter(([, v]) => v > 0).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }} general={
Object.entries(data.Open)
.filter(([, v]) => v > 0)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }
}
color={COLORS[0]} color={COLORS[0]}
/> />
<GeneralItem <GeneralItem
title="Получено заявок" title="Получено заявок"
numberType="sum" numberType="sum"
general={ Object.entries(data.Result).filter(([, v]) => v > 0).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }} general={
Object.entries(data.Result)
.filter(([, v]) => v > 0)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }
}
color={COLORS[1]} color={COLORS[1]}
/> />
<GeneralItem <GeneralItem
title="Конверсия" title="Конверсия"
numberType="percent" numberType="percent"
general={ Object.entries(data.Conversion).filter(([, v]) => v > 0).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }} general={
Object.entries(data.Conversion)
.filter(([, v]) => v > 0)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }
}
color={COLORS[2]} color={COLORS[2]}
/> />
<GeneralItem <GeneralItem
title="Среднее время прохождения квиза" title="Среднее время прохождения квиза"
numberType="time" numberType="time"
general={Object.entries(data.AvTime).filter(([, v]) => v > 0).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }} general={
Object.entries(data.AvTime)
.filter(([, v]) => v > 0)
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}) || { 0: 0 }
}
color={COLORS[3]} color={COLORS[3]}
/> />
</Box> </Box>

@ -48,7 +48,7 @@ function TariffPage() {
const [user, setUser] = useState(); const [user, setUser] = useState();
const [discounts, setDiscounts] = useState(); const [discounts, setDiscounts] = useState();
const [openModal, setOpenModal] = useState({}); const [openModal, setOpenModal] = useState({});
const {cash} = useWallet() const { cashString, cashCop, cashRub } = useWallet();
const [selectedItem, setSelectedItem] = useState<"count" | "day" | "dop">( const [selectedItem, setSelectedItem] = useState<"count" | "day" | "dop">(
"day", "day",
); );
@ -95,8 +95,10 @@ function TariffPage() {
setUser(user); setUser(user);
setTariffs(tariffsList); setTariffs(tariffsList);
setDiscounts(discounts.Discounts); setDiscounts(discounts.Discounts);
let c = currencyFormatter.format(Number(user.wallet.cash) / 100); let cs = currencyFormatter.format(Number(user.wallet.cash) / 100);
setCash(c); let cc = Number(user.wallet.cash);
let cr = Number(user.wallet.cash) / 100;
setCash(cs, cc, cr);
}; };
get(); get();
}, []); }, []);
@ -105,8 +107,8 @@ function TariffPage() {
const openModalHC = (tariffInfo: any) => setOpenModal(tariffInfo); const openModalHC = (tariffInfo: any) => setOpenModal(tariffInfo);
const tryBuy = async ({ id, price }: { id: string; price: number }) => { const tryBuy = async ({ id, price }: { id: string; price: number }) => {
console.log("цена", price) console.log("цена", price);
console.log("мои деньги", (user.wallet.cash / 100)) // console.log("мои деньги", (user.wallet.cash / 100))
openModalHC({}); openModalHC({});
//Если в корзине что-то было - выкладываем содержимое и запоминаем чо там лежало //Если в корзине что-то было - выкладываем содержимое и запоминаем чо там лежало
if (user.cart.length > 0) { if (user.cart.length > 0) {
@ -118,14 +120,18 @@ function TariffPage() {
url: process.env.REACT_APP_DOMAIN + `/customer/cart?id=${id}`, url: process.env.REACT_APP_DOMAIN + `/customer/cart?id=${id}`,
}); });
//Если нам хватает денежек - покупаем тариф //Если нам хватает денежек - покупаем тариф
if ((price * 100) <= user.wallet.cash) { if (price * 100 <= cashCop) {
try { try {
const data = await makeRequest({ const data = await makeRequest({
method: "POST", method: "POST",
url: process.env.REACT_APP_DOMAIN + "/customer/cart/pay", url: process.env.REACT_APP_DOMAIN + "/customer/cart/pay",
}); });
console.log(data) console.log(data);
setCash(currencyFormatter.format(Number(data.wallet.cash) / 100)); setCash(
currencyFormatter.format(Number(data.wallet.cash) / 100),
Number(data.wallet.cash),
Number(data.wallet.cash) / 100,
);
enqueueSnackbar("Тариф успешно приобретён"); enqueueSnackbar("Тариф успешно приобретён");
} catch (e) { } catch (e) {
enqueueSnackbar("Произошла ошибка. Попробуйте позже"); enqueueSnackbar("Произошла ошибка. Попробуйте позже");
@ -137,9 +143,9 @@ function TariffPage() {
// history.pushState({}, null, "https://hub.pena.digital/wallet?action=squizpay"); // history.pushState({}, null, "https://hub.pena.digital/wallet?action=squizpay");
var link = document.createElement("a"); var link = document.createElement("a");
link.href = `https://${isTestServer ? "s" : ""}hub.pena.digital/quizpayment?action=squizpay&dif=${ link.href = `https://${isTestServer ? "s" : ""}hub.pena.digital/quizpayment?action=squizpay&dif=${Math.floor(
Math.floor((price * 100) - Math.floor(Number(user.wallet.cash))) price * 100 - cashCop,
}&data=${token}&userid=${userId}`; )}&data=${token}&userid=${userId}`;
document.body.appendChild(link); document.body.appendChild(link);
link.click(); link.click();
} }
@ -192,6 +198,7 @@ function TariffPage() {
enqueueSnackbar(error.message); enqueueSnackbar(error.message);
}); });
} }
console.log("nfhbas", filteredTariffs);
return ( return (
<> <>
@ -231,9 +238,11 @@ function TariffPage() {
<Typography <Typography
variant="body2" variant="body2"
color={"#7e2aea"} color={"#7e2aea"}
fontSize={isMobile ? (cash.length > 9 ? "13px" : "16px") : "16px"} fontSize={
isMobile ? (cashString.length > 9 ? "13px" : "16px") : "16px"
}
> >
{cash} {cashString}
</Typography> </Typography>
</Box> </Box>
<LogoutButton <LogoutButton
@ -338,7 +347,8 @@ function TariffPage() {
component="h2" component="h2"
mb="20px" mb="20px"
> >
Вы подтверждаете платёж в сумму {openModal.price ? openModal.price.toFixed(2) : 0} Вы подтверждаете платёж в сумму{" "}
{openModal.price ? openModal.price.toFixed(2) : 0}
</Typography> </Typography>
<Button variant="contained" onClick={() => tryBuy(openModal)}> <Button variant="contained" onClick={() => tryBuy(openModal)}>
купить купить

@ -1,14 +1,16 @@
import { create } from "zustand"; import { create } from "zustand";
import { devtools } from "zustand/middleware"; import { devtools } from "zustand/middleware";
type Wallet = { cash: number } type Wallet = { cashString: string; cashCop: number; cashRub: number };
export const useWallet = create<Wallet>()( export const useWallet = create<Wallet>()(
devtools(() => ( devtools(() => ({ cashString: "", cashCop: 0, cashRub: 0 })),
{ cash: 0 }
))
); );
export const setCash = (cash: number) => { export const setCash = (
console.log("я получил ", cash) cashString: string,
useWallet.setState({ cash }) cashCop: number,
}; cashRub: number,
) => {
console.log("я получил ", cashString);
useWallet.setState({ cashString, cashCop, cashRub });
};

@ -2,13 +2,13 @@ import { useNavigate } from "react-router-dom";
import { useWallet, setCash } from "@root/cash"; import { useWallet, setCash } from "@root/cash";
import { payCart } from "@api/cart"; import { payCart } from "@api/cart";
import { currencyFormatter } from "../../pages/Tariffs/tariffsUtils/currencyFormatter"; import { currencyFormatter } from "../../pages/Tariffs/tariffsUtils/currencyFormatter";
const MINUTE = 1000 * 60; const MINUTE = 1000 * 60;
export const useAfterpay = () => { export const useAfterpay = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const { cash } = useWallet() // const { cash } = useWallet()
const checkPayment = () => { const checkPayment = () => {
const redirectUrl = new URL(window.location.href); const redirectUrl = new URL(window.location.href);
@ -31,7 +31,12 @@ export const useAfterpay = () => {
tryCount += 1; tryCount += 1;
const [data, payCartError] = await payCart(); const [data, payCartError] = await payCart();
if (data !== null) setCash(currencyFormatter.format(Number(data.wallet.cash) / 100)); if (data !== null)
setCash(
currencyFormatter.format(Number(data.wallet.cash) / 100),
Number(data.wallet.cash),
Number(data.wallet.cash) / 100,
);
if (!payCartError || Date.now() > deadline) { if (!payCartError || Date.now() > deadline) {
localStorage.removeItem("payCartPendingRequestDeadline"); localStorage.removeItem("payCartPendingRequestDeadline");