bonsai-web/plugins/bottomSheet/BottomSheetDiscount.jsx

75 lines
2.4 KiB
JavaScript

"use client";
import AppContext from "@ctx/AppContext";
import Chapar from "plugins/Chapar";
import { useContext, useState } from "react";
import { BottomSheet } from "react-spring-bottom-sheet";
import { toast } from "react-toastify";
const BottomSheetDiscount = ({ orderId }) => {
// const [item, setItem] = useState();
const CTX = useContext(AppContext);
const [discountCode, setDiscountCode] = useState(null);
const body = { orderId, discountCode };
// Function to handle discount operation asynchronously
const handleDiscount = async () => {
// Retrieve token from localStorage asynchronously
const token = localStorage.getItem("token");
try {
// Send a POST request to the API endpoint to apply discount
const data = await Chapar.post(
`${process.env.NEXT_PUBLIC_API_URL}/order/bag/discount/${orderId}?discountCode=${discountCode}`,
{
// Include the token in the Authorization header
headers: {
Authorization: token,
},
}
);
// Update the checkout data with the response
CTX.setCheckOutData(data);
// Close the bottom sheet for discount
CTX.setBottomSheetDiscountOpen(false);
} catch ({ error, status }) {
// If there's an error, display an error message using toast
toast.error(`${error?.response?.data?.message}`, {
position: "bottom-right",
closeOnClick: true,
});
}
};
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="کد را وارد کنید"
onChange={(e) => setDiscountCode(e.target.value)}
/>
</div>
<div className="w-full p-3 ">
<button
className="btn btn-primary text-sm w-full py-3 rounded-3xl"
onClick={() => handleDiscount()}
>
برسی کد تخفیف{" "}
</button>
</div>
</BottomSheet>
);
};
export default BottomSheetDiscount;