import { faAngleRight, faArrowLeft } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { useNavigation, useRoute } from "@react-navigation/native"; import React, { useEffect, useState } from "react"; import { View, Text, StyleSheet, TouchableOpacity, TextInput, Image, // Modal, Dimensions, ActivityIndicator, } from "react-native"; import { ScrollView } from "react-native-gesture-handler"; // import { user } from "../../constants/user"; import { update_order } from "../../services/api/controllers/order"; import Auth from "../../services/obananapay/Auth"; import { create_payment } from "../../services/obananapayGatewayApi/controllers/payment_api"; const deviceWidth = Dimensions.get("window").width; import Modal from "react-native-modal"; import { useToast } from "react-native-toast-notifications"; const CheckOutMultiple = () => { //NOTE !!!! must pass the update product details to the shipping option and payment method page!!!! to prevent error const [message, setmessage] = useState(""); const [paymessage, setpaymessage] = useState(""); const [pay_refno, setpay_refno] = useState(""); const [successCOD, setsuccessCOD] = useState(false); const toast = useToast(); const [billingAdd, setbillingAdd] = useState(""); const [orderIdC, setorderIdC] = useState(""); const [descrip, setdescrip] = useState(""); const [codLoad, setcodLoad] = useState(false); const [token, settoken] = useState(""); const [amount, setamount] = useState(0); const [totalShipFee, settotalShipFee] = useState(0); const [modalVisible, setModalVisible] = useState(false); const [shippingMethod, setshippingMethod] = useState( "select shipping method" ); const [paymentMethod, setpaymentMethod] = useState("select shipping method"); const [recipientDetails, setrecipientDetails] = useState([]); const [user, setuser] = useState([]); useEffect(() => { /* ---------------Check for the user saved email--------------- */ AsyncStorage.getItem("AccessToken") .then((pass) => { if (pass) { settoken(pass); } }) .catch((error) => { console.log(error + "weeewwww"); }); AsyncStorage.getItem("userData") .then((pass) => { const userDataArray = JSON.parse(pass); setuser(userDataArray); const ship = userDataArray[0]?.address.find( (address) => address?.shipping === true ); if (ship) { setrecipientDetails(ship); } const bill = userDataArray[0]?.address?.find( (address) => address.billing === true ); setbillingAdd(bill); console.log(pass); }) .catch((error) => { console.log(error + "weeewwww"); }); }, []); // console.log(shippingAddress) const navigation = useNavigation(); const route = useRoute(); const { product, shipMethod, payMethod, address, orderId } = route.params; console.log(orderId); useEffect(() => { setshippingMethod(shipMethod ?? "select shipping method"); }, [shipMethod]); useEffect(() => { setpaymentMethod(payMethod ?? "select payment method"); }, [payMethod]); useEffect(() => { setrecipientDetails(address ?? null); }, [address]); useEffect(() => { const descr = product?.reduce((desc, d) => { const dTotal = d.cartItems.reduce( (subTotal, item) => item.items[0].product.name + ` (${item.items[0].quantity} qty)`, 0 ); const descrips = desc !== 0 ? desc : ""; return descrips !== "" ? descrips + ", " + dTotal : dTotal; }, 0); setdescrip(descr); console.log("description: " + descr); }, []); console.log("descriptionsss: " + descrip); useEffect(() => {}, []); console.log(billingAdd); const checkOutClicked = () => { const amount = product.reduce((total, order) => { const orderTotal = order.cartItems.reduce( (subTotal, item) => subTotal + parseFloat(item.total_amount) + parseFloat(item.shipping_fee ?? 50), 0 ); return total + orderTotal; }, 0); // product.reduce((totalAmount, order) => { // const itemPrice = parseFloat(order.items[0].product.price) * parseFloat(order.items[0].quantity); // return totalAmount + itemPrice; // }, 0) * 100; console.log("amount: " + amount); // const descriptions = // product.map((order) => order.items[0].product.name).join(", ") + // ", ordered from obanana e-commerce"; // console.log(descr); if (recipientDetails) { if (paymentMethod === "Obananapay") { create_payment({ body: { amount: amount * 100, description: descrip + " , ordered from Obanana e-commerce mobile app", }, }) .then((result) => { if (result.status === 200) { const currentDate = new Date(); const iso8601String = currentDate.toISOString(); setpay_refno(result.data.attributes.reference_number); console.log("I am here"); // Create an array to hold promises for updating orders const updatePromises = []; product.forEach((order) => { // Loop through the items in each order's 'cartItems' order.cartItems.forEach((cartItem) => { // Construct the 'body' object for updating the order console.log( "I am here and the order cart items is " + order.cartItems ); const orderId = cartItem._id; // const orderName = cartItem.items[0].name; const shipFee = cartItem.shipping_fee ?? 50; const updatePromise = update_order({ token: token, id: orderId, body: { payment_method: paymentMethod, billing_address: { billing_first_name: billingAdd?.first_name, billing_last_name: billingAdd?.last_name, billing_company: billingAdd?.company, billing_email: billingAdd?.email, billing_phone: billingAdd?.phone, billing_address_1: billingAdd?.address_1, billing_address_2: billingAdd?.address_2, billing_city: billingAdd?.city, billing_barangay: billingAdd?.barangay, billing_state: billingAdd?.province, billing_country: billingAdd?.country, }, shipping_address: { shipping_first_name: recipientDetails?.first_name, shipping_last_name: recipientDetails?.last_name, shipping_company: recipientDetails?.company, shipping_email: recipientDetails?.email, shipping_phone: recipientDetails?.phone, shipping_address_1: recipientDetails?.address_1, shipping_address_2: recipientDetails?.address_2, shipping_city: recipientDetails?.city, shipping_barangay: recipientDetails?.barangay, shipping_state: recipientDetails?.province, shipping_country: recipientDetails?.country, }, order_date: iso8601String, payment: { status: "UNPAID", reference_number: result.data.attributes.reference_number, }, total_amount: parseFloat(cartItem.total_amount) + parseFloat(shipFee), }, }); updatePromises.push(updatePromise); }); }); Promise.all(updatePromises) .then((results) => { // Handle results of updating orders results.forEach((updateResult, index) => { if (updateResult.status === 200) { console.log(); const shipFee = updateResult.data.shipping_fee ? updateResult.data.shipping_fee * 100 : 500; setamount(result.data.attributes.amount); setpaymessage(result.data.attributes.description); setModalVisible(!modalVisible); } else { // console.log("Update order failed for order with ID:", product[index].cartItems[0]._id); // ("failed"); } }); }) .catch((err) => { console.error(err); }); } else { console.log("Create payment link failed"); } }) .catch((err) => { console.error(err); }); } else if (paymentMethod === "Cash On Delivery") { setModalVisible(!modalVisible); } else { toast.show("Please select payment method!", { type: "danger", placement: "top", duration: 3000, offset: 30, animationType: "slide-in", }); } } else { toast.show("Please select delivery address first!", { type: "danger", placement: "top", duration: 3000, offset: 30, animationType: "slide-in", }); } }; const CODpay = () => { // if (result.status === 200) { setcodLoad(true); const currentDate = new Date(); const iso8601String = currentDate.toISOString(); // setpay_refno(result.data.attributes.reference_number); const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let refno = ""; for (let i = 0; i < 8; i++) { const randomIndex = Math.floor(Math.random() * characters.length); refno += characters.charAt(randomIndex); } console.log("I am here"); // Create an array to hold promises for updating orders const updatePromises = []; product.forEach((order) => { // Loop through the items in each order's 'cartItems' order.cartItems.forEach((cartItem) => { // Construct the 'body' object for updating the order console.log("I am here and the order cart items is " + order.cartItems); const orderId = cartItem._id; // const orderName = cartItem.items[0].name; const shipFee = cartItem.shipping_fee ?? 50; const updatePromise = update_order({ token: token, token: token, id: orderId, body: { payment_method: paymentMethod, billing_address: { billing_first_name: billingAdd?.first_name, billing_last_name: billingAdd?.last_name, billing_company: billingAdd?.company, billing_email: billingAdd?.email, billing_phone: billingAdd?.phone, billing_address_1: billingAdd?.address_1, billing_address_2: billingAdd?.address_2, billing_city: billingAdd?.city, billing_barangay: billingAdd?.barangay, billing_state: billingAdd?.province, billing_country: billingAdd?.country, }, shipping_address: { shipping_first_name: recipientDetails?.first_name, shipping_last_name: recipientDetails?.last_name, shipping_company: recipientDetails?.company, shipping_email: recipientDetails?.email, shipping_phone: recipientDetails?.phone, shipping_address_1: recipientDetails?.address_1, shipping_address_2: recipientDetails?.address_2, shipping_city: recipientDetails?.city, shipping_barangay: recipientDetails?.barangay, shipping_state: recipientDetails?.province, shipping_country: recipientDetails?.country, }, order_date: iso8601String, payment: { status: "UNPAID", reference_number: refno, }, status: "TO PAY", // total_amount: result.data.attributes.amount / 100, total_amount: parseFloat(cartItem.total_amount) + parseFloat(shipFee), }, }); updatePromises.push(updatePromise); }); }); Promise.all(updatePromises) .then((results) => { // Handle results of updating orders results.forEach((updateResult, index) => { if (updateResult.status === 200) { console.log( // `Order update id: ${updateResult.data} orderName: ${product[index].cartItems[0].items[0].name} orderId: ${product[index].cartItems[0]._id} amount: ${result.data.attributes.amount}` "updated" ); // setamount(result.data.attributes.amount); // setpaymessage(result.data.attributes.description); // setModalVisible(!modalVisible); setsuccessCOD(true); } else { // console.log("Update order failed for order with ID:", product[index].cartItems[0]._id); // ("failed"); setsuccessCOD("error"); } }); }) .catch((err) => { console.error(err); }); // } }; const calculateTotalPricePerShop = (cart) => { let totalPrice = 0; cart.forEach((order) => { order.items.forEach((item) => { const price = parseFloat(item.price); const quantity = parseInt(item.quantity); const shipFee = parseFloat(item.shipping_fee ?? 50); const itemPrice = price * quantity; totalPrice += itemPrice + shipFee; console.log("item price: " + price * quantity); }); }); console.log(cart[0].items); return parseFloat(totalPrice).toLocaleString("en-US"); }; useEffect(() => { let total = 0; let shipTotal = 0; // Iterate through the cartSort to calculate the total price product.forEach((shop) => { let shopHasSelectedProducts = false; // Flag to check if the shop has selected products shop.cartItems.forEach((product1) => { if (product1.selected) { // Calculate the total price for the selected product let productTotal = 0; const shipFee = parseFloat(product1.shipping_fee ?? 50); // Otherwise, calculate total without promo discount productTotal = parseFloat(product1.items[0].price) * parseInt(product1.items[0].quantity, 10); // Add the product total to the overall total // const shipFee = parseFloat(item.shipping_fee??50); total += parseFloat(productTotal) + shipFee; shipTotal += shipFee; // Set the flag to true if at least one product is selected in the shop shopHasSelectedProducts = true; } }); // if (shopHasSelectedProducts) { // // Add the shipping fee for the shop if it has selected products // total += shop.shippingFee; // } }); settotalShipFee(shipTotal); }, []); const calculateTotalPrice = () => { let total = 0; let shipTotal = 0; // Iterate through the cartSort to calculate the total price product.forEach((shop) => { let shopHasSelectedProducts = false; // Flag to check if the shop has selected products shop.cartItems.forEach((product1) => { if (product1.selected) { // Calculate the total price for the selected product let productTotal = 0; const shipFee = parseFloat(product1.shipping_fee ?? 50); // Otherwise, calculate total without promo discount productTotal = parseFloat(product1.items[0].price) * parseInt(product1.items[0].quantity, 10); // Add the product total to the overall total // const shipFee = parseFloat(item.shipping_fee??50); total += parseFloat(productTotal) + shipFee; shipTotal += parseFloat(product1.items[0].quantity); // Set the flag to true if at least one product is selected in the shop shopHasSelectedProducts = true; } }); // if (shopHasSelectedProducts) { // // Add the shipping fee for the shop if it has selected products // total += shop.shippingFee; // } }); console.log(total); return total?.toFixed(2); }; const calculateTotalPriceW = () => { let total = 0; let shipTotal = 0; // Iterate through the cartSort to calculate the total price product.forEach((shop) => { let shopHasSelectedProducts = false; // Flag to check if the shop has selected products shop.cartItems.forEach((product1) => { if (product1.selected) { // Calculate the total price for the selected product let productTotal = 0; const shipFee = parseFloat(product1.shipping_fee ?? 50); // Otherwise, calculate total without promo discount productTotal = parseFloat(product1.items[0].price) * parseInt(product1.items[0].quantity, 10); // Add the product total to the overall total // const shipFee = parseFloat(item.shipping_fee??50); total += parseFloat(productTotal); shipTotal += parseFloat(product1.items[0].quantity); // Set the flag to true if at least one product is selected in the shop shopHasSelectedProducts = true; } }); // if (shopHasSelectedProducts) { // // Add the shipping fee for the shop if it has selected products // total += shop.shippingFee; // } }); console.log(total); return total?.toFixed(2); }; return ( navigation.navigate("Home")} style={styles.backIcon} > Checkout navigation.navigate("AddressSelectionMulti", { product, shipMethod: shippingMethod, payMethod: paymentMethod, address: recipientDetails, orderId: orderId, address: user[0]?.address, }) } > DELIVERY ADDRESS {recipientDetails !== null ? `${recipientDetails?.first_name} ${ recipientDetails?.last_name }, ${recipientDetails?.phone} ${ recipientDetails?.address_1 + " " + recipientDetails?.address_2 + ", " + recipientDetails?.city + " " + recipientDetails?.province + " " }${ recipientDetails?.country === "PH" ? "Philippines" : recipientDetails?.country }` : "select address"} {product?.map((prod, i) => ( {prod.shopname} {/* {product.shopId} */} {prod?.cartItems?.map((prodSub, i) => ( <> {prodSub.items[0].product.name} {prodSub.items[0].price ? ( <> ₱ {parseFloat( prodSub?.items[0]?.price )?.toLocaleString("en-US")} {/* {prodSub.items[0].sale_price ? ( */} {/* {" "} {product.price - product.price * 0.3}{" "} (-{product.sale_price}%) */} {/* {parseFloat(product?.items[0]?.sale_price)?.toLocaleString('en-US')} */} {/* ) : null} */} ) : ( No price )} {prodSub.items[0].quantity} qty{" "} Shipping Fee {/* ₱{calculateTotalPricePerShop(prodSub?.items[0].sale_price)} */} ₱{prodSub?.shipping_fee ?? 50.0} ))} ORDER TOTAL {/* ₱{calculateTotalPricePerShop(prodSub?.items[0].sale_price)} */} ₱{calculateTotalPricePerShop(prod?.cartItems)} {/* navigation.navigate("ShippingOptionMulti", { product:product, shipMethod: shippingMethod, payMethod: paymentMethod, address: recipientDetails, orderId: orderId, }) } > SHIPPING OPTION {shippingMethod} */} ))} {/* MESSAGE setmessage()} value={message} numberOfLines={2} placeholder="write a message" /> */} navigation.navigate("PaymentoptionMulti", { product: product ? product : [], shipMethod: shippingMethod, payMethod: paymentMethod, address: recipientDetails, orderId: orderId ? orderId : null, }) } > PAYMENT OPTION {paymentMethod} PAYMENT DETAILS Merchandise Sub Total: ₱{calculateTotalPriceW()} Shipping: {/*{parseFloat(prodSub.shipping_fee ?? 50.0)} */}₱ {totalShipFee} Total: ₱{calculateTotalPrice()} {successCOD === true ? ( <> Completed Transaction ) : ( checkOutClicked()} > Order Now )} setModalVisible(!modalVisible)} swipeDirection={["down"]} swipeThreshold="100" backdropOpacity={0.2} style={{ margin: 0 }} propagateSwipe={true} deviceWidth={deviceWidth} onRequestClose={() => { setModalVisible(!modalVisible); }} > {paymentMethod === "Cash On Delivery" ? ( {successCOD === true ? ( <> Successful Order! navigation.navigate("Home")} > Exit ) : successCOD === "error" ? ( <> Failed Order! Please try again later navigation.navigate("Home")} > Exit ) : ( <> Checkout order using Cash On Delivery payment method? CODpay()} disabled={codLoad} > {codLoad ? ( ) : ( "Continue" )} )} ) : ( )} ); }; const styles = StyleSheet.create({ container: { backgroundColor: "#fff", height: "100%", }, header: { alignItems: "center", width: "100%", top: 0, paddingLeft: 15, flexDirection: "row", borderColor: "#ddd", paddingBottom: 15, borderBottomWidth: 1, }, headerText: { fontSize: 16, fontWeight: "600", marginLeft: 25, }, shopNameText: { fontSize: 14, fontWeight: "600", marginLeft: 5, color: "#202020", }, ordercard: { marginVertical: 10, width: "100%", justifyContent: "center", alignItems: "center", paddingHorizontal: 5, backgroundColor: "#ffffff", }, add: { width: "50%", }, input: { width: "60%", }, wallet: { // width: '50%' }, footer: { position: "absolute", bottom: 0, width: "100%", justifyContent: "center", alignItems: "center", paddingVertical: 10, }, footerBtn: { backgroundColor: "#ff5e00", width: "90%", paddingVertical: 10, justifyContent: "center", borderRadius: 20, alignItems: "center", }, footerBtnText: { color: "#fff", fontSize: 16, }, footerBtnText2: { color: "#353535", fontSize: 16, }, wrapper: { // height: "85%", backgroundColor: "#f3f3f3", width: "100%", height: "100%", }, wrapper1: { // height: "85%", backgroundColor: "#ffffff", width: "100%", height: "100%", }, content: { width: "100%", justifyContent: "center", alignItems: "center", }, subContent: { width: "98%", justifyContent: "space-between", flexDirection: "row", alignItems: "center", padding: 10, // height: 60, borderColor: "#f0f0f0dd", borderWidth: 1, backgroundColor: "#ffffff", }, subContent1: { width: "98%", justifyContent: "center", // flexDirection: "row", // alignItems: "center", padding: 15, // height: 60, borderColor: "#f0f0f0dd", borderWidth: 1, backgroundColor: "#ffffff", }, subContent2: { width: "98%", justifyContent: "space-between", flexDirection: "row", // alignItems: "center", padding: 10, // height: 60, borderColor: "#f0f0f0dd", // borderWidth: 1, backgroundColor: "#ffffff", }, subContent3: { width: "98%", justifyContent: "space-between", flexDirection: "row", alignItems: "center", padding: 10, // height: 60, borderColor: "#f0f0f0dd", borderWidth: 1, marginTop: 20, backgroundColor: "#ffffff", }, subContent4: { width: "98%", justifyContent: "space-between", flexDirection: "row", alignItems: "center", padding: 10, // height: 60, borderColor: "#f8f8f8dd", borderWidth: 1, // marginTop: 20, backgroundColor: "#ffffff", }, subContentText: { fontWeight: "600", color: "#494949", }, subContentText2: { width: "90%", flexDirection: "row", justifyContent: "space-between", // backgroundColor: "#b8141433", }, subContentTexthead: { fontWeight: "600", color: "#000000", }, addText: { color: "#5f5f5f", textAlign: "left", }, imgWrap: { padding: 10, }, card: { height: 80, flexDirection: "row", // justifyContent: "center", alignItems: "center", borderColor: "#f0f0f0dd", borderWidth: 1, padding: 10, marginTop: 10, backgroundColor: "#ffffff", }, payCon: { width: "80%", marginBottom: 70, }, priceCon: { flexDirection: "row", paddingVertical: 10, }, rateCon: { width: "75%", flexDirection: "row", justifyContent: "space-between", alignItems: "center", }, qty: { fontSize: 14, color: "#5f5f5f", }, textPrice: { fontSize: 14, fontWeight: "600", textTransform: "capitalize", color: "#ffaa00", }, textPricePromo: { fontSize: 14, fontWeight: "600", textTransform: "capitalize", textDecorationLine: "line-through", color: "#ffaa00", }, details: { // width: "50%", }, text: { fontSize: 14, fontWeight: "500", width: "75%", }, CodWrap: { backgroundColor: "#fff", marginTop: 20, height: "50%", bottom: 0, borderWidth: 2, borderColor: "#eeeeee", // borderTopRightRadius: 25, borderRadius: 25, borderTopLeftRadius: 25, padding: 10, justifyContent: "center", alignItems: "center", }, }); export default CheckOutMultiple;