import { message } from "antd"; import { clearCart, selectCart, selectCartTotal, selectDiscountTotal, selectGrandTotal, selectHighestPricedLoyaltyItem, } from "features/order/orderSlice"; import { OrderType } from "pages/checkout/hooks/types.ts"; import { useCallback } from "react"; import { useTranslation } from "react-i18next"; import { useNavigate, useParams } from "react-router-dom"; import { useCreateOrderMutation } from "redux/api/others"; import { useAppDispatch, useAppSelector } from "redux/hooks"; import { PAYMENT_CONFIRMATION_URL } from "utils/constants"; import { Customer } from "../../otp/types"; import { Variant } from "utils/types/appTypes"; export default function useOrder() { const dispatch = useAppDispatch(); const navigate = useNavigate(); const { t } = useTranslation(); const { subdomain } = useParams(); const restaurantID = localStorage.getItem("restaurantID"); const { mobilenumber, user_uuid } = JSON.parse( localStorage.getItem("customer") || "{}", ) as Customer; const { items, coupon, tip, table, specialRequest, phone, estimateTime, orderType, location, discount, plateCar, pickupTime, pickupDate, pickupType, giftDetails, order, restaurant, } = useAppSelector(selectCart); const highestLoyaltyItem = useAppSelector(selectHighestPricedLoyaltyItem); const { useLoyaltyPoints } = useAppSelector(selectCart); const orderPrice = useAppSelector(selectGrandTotal); const subtotal = useAppSelector(selectCartTotal); const discountAmount = useAppSelector(selectDiscountTotal); const [createOrder] = useCreateOrderMutation(); console.log(order); const getDeliveryMethod = useCallback(() => { if (orderType === OrderType.Delivery) return 1; if (orderType === OrderType.Pickup) return 2; if (orderType === OrderType.DineIn) return 3; if (orderType === OrderType.Gift) return 10; if (orderType === OrderType.ScheduledOrder) return 9; if (orderType === OrderType.ToRoom) return 5; if (orderType === OrderType.ToOffice) return 4; return undefined; }, [orderType]); const handleCreateOrder = useCallback(() => { const loadingMessageKey = "create-order-loader"; message.loading({ content: t("order.creatingOrder", { defaultValue: "Creating order...", }), key: loadingMessageKey, duration: 0, }); createOrder({ phone: mobilenumber || phone || giftDetails?.senderPhone, comment: specialRequest, delivery_method: getDeliveryMethod(), timeslot: "", table_id: table, deliveryType: orderType, type: "table-pickup", // user_id: id, restorant_id: restaurantID, items: items.map((i) => ({ ...i, qty: i.quantity, extras: i.extras?.map((e) => e.id) || [], extrasgroup: i.extrasgroup || [], order_item_comment: i.comment || "", variant: (i.variant as Variant)?.id || "", })), office_no: order?.officeNumber, room_no: order?.roomNumber, ...(discount.isDiscount ? { couponID: coupon } : {}), ...(discount.isGift ? { discountGiftCode: coupon } : {}), discountAmount: discountAmount || 0, paymentType: "cod", uuid: user_uuid, pickup_comments: "", pickup_time: pickupTime, pickup_date: pickupDate, car_plate: plateCar, pickupTimeType: pickupType, delivery_pickup_interval: "", orderPrice: orderPrice, use_loylaty: useLoyaltyPoints && highestLoyaltyItem ? 1 : 0, useWallet: 0, tip, userCoordinates: location?.lat && location?.lng ? `${location?.lat},${location?.lng}` : "", delivery_address: location?.address, vatvalue: ((restaurant?.vat || 0) / 100) * (subtotal - discountAmount), taxes: restaurant?.taxes ?.filter((t) => t.is_active === 1) .map((t) => ({ tax_id: t.id, percentage: t.percentage, amount: ((Number(t.percentage) || 0) / 100) * (subtotal - discountAmount), })) || [], ...(orderType === OrderType.Gift ? { receiverName: giftDetails?.receiverName, receiverPhone: giftDetails?.receiverPhone, specialMessage: giftDetails?.message, keepNameSecret: giftDetails?.isSecret, senderEmail: giftDetails?.senderEmail, senderPhone: giftDetails?.senderPhone, senderName: giftDetails?.senderName, dineType: orderType, } : {}), }) .then((res: unknown) => { message.destroy(loadingMessageKey); const mutationResult = res as { data?: { result?: { orderID?: string } }; error?: { data?: { message?: string } }; }; if (mutationResult.error) message.error( mutationResult.error.data?.message || t("order.createOrderFailed"), ); else { const redirectMessageKey = "order-redirect-loader"; if ( orderType === OrderType.Gift && mutationResult.data?.result?.orderID ) { message.loading({ content: t("order.redirectingToPayment", { defaultValue: "Redirecting to payment...", }), key: redirectMessageKey, duration: 0, }); window.location.href = `${PAYMENT_CONFIRMATION_URL}/${mutationResult.data.result.orderID}`; } else { message.destroy(redirectMessageKey); if (mutationResult.data?.result?.orderID) { navigate( `/${subdomain}/order/${mutationResult.data.result.orderID}`, ); } } dispatch(clearCart()); } }) .catch((error: unknown) => { message.destroy(loadingMessageKey); console.error("Create Order failed:", error); message.error(t("order.createOrderFailed")); }); }, [ createOrder, mobilenumber, phone, specialRequest, getDeliveryMethod, table, orderType, restaurantID, items, giftDetails, discount.isDiscount, discount.isGift, discount.value, coupon, user_uuid, estimateTime, orderPrice, useLoyaltyPoints, highestLoyaltyItem, tip, location?.lat, location?.lng, location?.address, t, navigate, subdomain, dispatch, ]); return { handleCreateOrder }; }