web/plugins/bottomSheet/BottomSheetDiscount.jsx

75 lines
2.4 KiB
React
Raw Normal View History

2024-02-11 17:24:30 +03:30
"use client";
import AppContext from "@ctx/AppContext";
2024-02-16 18:23:02 +03:30
import Chapar from "plugins/Chapar";
2024-02-16 19:36:30 +03:30
import { useContext, useState } from "react";
2024-02-11 17:24:30 +03:30
import { BottomSheet } from "react-spring-bottom-sheet";
import { toast } from "react-toastify";
2024-02-16 18:23:02 +03:30
const BottomSheetDiscount = ({ orderId }) => {
2024-04-16 02:04:28 +03:30
// const [item, setItem] = useState();
2024-02-11 17:24:30 +03:30
const CTX = useContext(AppContext);
2024-02-16 18:23:02 +03:30
const [discountCode, setDiscountCode] = useState(null);
const body = { orderId, discountCode };
2024-04-16 02:04:28 +03:30
// Function to handle discount operation asynchronously
2024-02-16 18:23:02 +03:30
const handleDiscount = async () => {
2024-04-16 02:04:28 +03:30
// Retrieve token from localStorage asynchronously
const token = localStorage.getItem("token");
2024-02-16 18:23:02 +03:30
try {
2024-04-16 02:04:28 +03:30
// Send a POST request to the API endpoint to apply discount
2024-02-16 18:23:02 +03:30
const data = await Chapar.post(
`${process.env.NEXT_PUBLIC_API_URL}/order/bag/discount/${orderId}?discountCode=${discountCode}`,
{
2024-04-16 02:04:28 +03:30
// Include the token in the Authorization header
2024-02-16 18:23:02 +03:30
headers: {
2024-04-16 02:04:28 +03:30
Authorization: token,
2024-02-16 18:23:02 +03:30
},
}
);
2024-04-16 02:04:28 +03:30
// Update the checkout data with the response
2024-02-16 18:23:02 +03:30
CTX.setCheckOutData(data);
2024-04-16 02:04:28 +03:30
// Close the bottom sheet for discount
2024-02-16 18:23:02 +03:30
CTX.setBottomSheetDiscountOpen(false);
} catch ({ error, status }) {
2024-04-16 02:04:28 +03:30
// If there's an error, display an error message using toast
2024-02-16 18:23:02 +03:30
toast.error(`${error?.response?.data?.message}`, {
position: "bottom-right",
closeOnClick: true,
});
}
};
2024-02-11 17:24:30 +03:30
return (
<BottomSheet
open={CTX.state.bottomSheetDiscountOpen}
onDismiss={() => CTX.setBottomSheetDiscountOpen(false)}
className={"z-50 relative"}
>
<div className="text-center p-3">
<p className="mb-0 text-sm pb-3">افزودن کد تخفیف </p>
</div>
<div className="p-3">
<input
type="text"
className="form-control bg-white !border-[1px] focus:!border-[1px] border-gray-400 focus:!border-gray-300 rounded-lg text-right !text-sm tr03 "
placeholder="کد را وارد کنید"
2024-02-16 18:23:02 +03:30
onChange={(e) => setDiscountCode(e.target.value)}
2024-02-11 17:24:30 +03:30
/>
</div>
<div className="w-full p-3 ">
2024-02-16 18:23:02 +03:30
<button
className="btn btn-primary text-sm w-full py-3 rounded-3xl"
onClick={() => handleDiscount()}
>
2024-02-11 17:24:30 +03:30
برسی کد تخفیف{" "}
</button>
</div>
</BottomSheet>
);
};
export default BottomSheetDiscount;