Merge pull request 'mark_4' (#80) from mark_4 into main

Reviewed-on: #80
This commit is contained in:
MarkHipe 2024-05-03 18:46:44 +08:00
commit fd8016afd0
11 changed files with 259 additions and 105 deletions

View File

@ -1,6 +1,6 @@
<?php
$_SESSION["is_test"]=true;
$_SESSION["test_email_rcpt"]="junjihadbarroga@gmail.com";
$_SESSION["test_email_rcpt"]="kramblooda@gmail.com";
$_SESSION["sales_email"]="sales@obanana.com";
$_SESSION["data_endpoint"]="api.obanana.shop";
$_SESSION["transfer_fee"]=0.02;

View File

@ -506,9 +506,34 @@ function popupAddToCart(
} catch (error) {
console.error("Error parsing customer JSON: ", error);
}
let vendorData = decodeURIComponent(productVendor);
var vendorObj = JSON.parse(vendorData);
let vendorData = null;
console.log(productVendor);
if (
productVendor === undefined ||
productVendor === null ||
productVendor === "undefined"
) {
console.log("here i am");
var vendorCheckXhr = new XMLHttpRequest();
vendorCheckXhr.open(
"GET",
"https://api.obanana.shop/api/v1/vendors/" + productData.vendor_api_id,
true
);
vendorCheckXhr.onreadystatechange = function () {
if (vendorCheckXhr.readyState === 4) {
if (vendorCheckXhr.status === 200) {
var vendorObj = JSON.parse(vendorCheckXhr.responseText);
console.log(vendorObj);
}
}
};
vendorCheckXhr.send();
} else {
vendorData = decodeURIComponent(productVendor);
console.log("vendorData");
var vendorObj = JSON.parse(vendorData);
}
var sessionToken = token;
var productImage = productObj.images;
@ -541,52 +566,57 @@ function popupAddToCart(
console.log("Customer Names: " + customerName);
login(email, password, function (token) {
var priceMatrix = productObj.price_matrix !=="" ? productObj.price_matrix : "[]";
// var quantityValue = productData.quantity;
var minimumOrder = productObj.minimum_order;
var priceMatrix =
productObj.price_matrix !== "" ? productObj.price_matrix : "[]";
// var quantityValue = productData.quantity;
var minimumOrder = productObj.minimum_order;
var quantityValue = productObj.minimum_order =="" ? productQuantity : '1';
var quantityValue = productObj.minimum_order == "" ? productQuantity : "1";
// var minimumOrder = productObj.minimum_order !=="" ? productObj.minimum_order : '1';
// var quantityValue = minimumOrder ;
// var minimumOrder = productObj.minimum_order !=="" ? productObj.minimum_order : '1';
// var quantityValue = minimumOrder ;
if (parseInt(quantityValue) < minimumOrder) {
quantityValue = minimumOrder;
alert("The minimum order quantity is " + minimumOrder);
}
if (parseInt(quantityValue) < minimumOrder) {
quantityValue = minimumOrder;
alert("The minimum order quantity is " + minimumOrder);
}
//Apply Matrix
var productPrice;
var foundPrice = false;
//Apply Matrix
var productPrice;
var foundPrice = false;
if (priceMatrix.length > 0) {
for (var i = 0; i < priceMatrix.length; i++) {
for (var j = 0; j < priceMatrix[i].length; j++) {
var currentQuantity = parseFloat(priceMatrix[i][j].quantity);
var nextQuantity = (j < priceMatrix[i].length - 1) ? parseFloat(priceMatrix[i][j + 1].quantity) : Infinity;
if (quantityValue >= currentQuantity && quantityValue < nextQuantity) {
productPrice = parseFloat(priceMatrix[i][j].price);
foundPrice = true;
break;
}
}
if (foundPrice) {
break;
}
if (priceMatrix.length > 0) {
for (var i = 0; i < priceMatrix.length; i++) {
for (var j = 0; j < priceMatrix[i].length; j++) {
var currentQuantity = parseFloat(priceMatrix[i][j].quantity);
var nextQuantity =
j < priceMatrix[i].length - 1
? parseFloat(priceMatrix[i][j + 1].quantity)
: Infinity;
if (
quantityValue >= currentQuantity &&
quantityValue < nextQuantity
) {
productPrice = parseFloat(priceMatrix[i][j].price);
foundPrice = true;
break;
}
}
if (foundPrice) {
break;
}
}
}
if (!foundPrice) {
productPrice = productObj.sale_price ? productObj.sale_price : productObj.regular_price;
// productPrice = parseFloat(document.getElementById("productNewPrice") ? document.getElementById("productNewPrice").innerText : document.getElementById("productPrice"));
// productPrice = parseFloat(document.getElementById("productNewPrice") ? document.getElementById("productNewPrice").innerText : document.getElementById("productPrice"));
// productPrice;
}
if (!foundPrice) {
productPrice = productObj.sale_price
? productObj.sale_price
: productObj.regular_price;
// productPrice = parseFloat(document.getElementById("productNewPrice") ? document.getElementById("productNewPrice").innerText : document.getElementById("productPrice"));
// productPrice = parseFloat(document.getElementById("productNewPrice") ? document.getElementById("productNewPrice").innerText : document.getElementById("productPrice"));
// productPrice;
}
var productData = {
product: {
@ -696,7 +726,7 @@ function popupAddToCart(
: "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png";
console.log(response);
newOrder.innerHTML = `
newOrder.innerHTML = `
<input type="checkbox" class="rowcartCheckbox" name="cart-item[]" value="${response._id}"/>
<a href="product-left-sidebar.php?id=${response.items[0]._id}" class="sidekka_pro_img">
<img src="${imageUrl}" alt="product" />
@ -736,7 +766,7 @@ function popupAddToCart(
}
function getLatestOrders() {
var customerId = '<?php echo $customer_data[0][\'_id\'] ?>'
var customerId = "<?php echo $customer_data[0]['_id'] ?>";
// Fetch the order data
fetch(`https://api.obanana.shop/api/v1/orders/customer/${customerId}`)
.then((response) => response.json())
@ -831,32 +861,38 @@ function popupAddToCart(
var updatedQuantity = existingQuantity + newQuantity;
// Check if the updated quantity exceeds the previous price matrix
var newProductPrice = productPrice;
var foundNewPrice = false;
if (priceMatrix.length > 0) {
for (var i = 0; i < priceMatrix.length; i++) {
for (var j = 0; j < priceMatrix[i].length; j++) {
var currentQuantity = parseFloat(priceMatrix[i][j].quantity);
var nextQuantity = (j < priceMatrix[i].length - 1) ? parseFloat(priceMatrix[i][j + 1].quantity) : Infinity;
if (updatedQuantity >= currentQuantity && updatedQuantity < nextQuantity) {
newProductPrice = parseFloat(priceMatrix[i][j].price);
foundNewPrice = true;
break;
}
}
if (foundNewPrice) {
break;
}
}
var newProductPrice = productPrice;
var foundNewPrice = false;
if (priceMatrix.length > 0) {
for (var i = 0; i < priceMatrix.length; i++) {
for (var j = 0; j < priceMatrix[i].length; j++) {
var currentQuantity = parseFloat(priceMatrix[i][j].quantity);
var nextQuantity =
j < priceMatrix[i].length - 1
? parseFloat(priceMatrix[i][j + 1].quantity)
: Infinity;
if (
updatedQuantity >= currentQuantity &&
updatedQuantity < nextQuantity
) {
newProductPrice = parseFloat(priceMatrix[i][j].price);
foundNewPrice = true;
break;
}
}
if (foundNewPrice) {
productPrice = newProductPrice;
break;
}
}
}
if (foundNewPrice) {
productPrice = newProductPrice;
}
var updateData = {
quantity: updatedQuantity,
price: productPrice
price: productPrice,
};
updateOrderXhr.send(JSON.stringify(updateData));

View File

@ -191,11 +191,26 @@ if ($_SESSION["userId"] <> "") {
<div class="ec-cart-content">
<div class="ec-cart-inner">
<div class="row">
<style>
.rowcart{
display:flex;
justify-content:center;
align-self: center;
flex-direction:row;
}
.rowcartCheckbox{
height:15px;
width:15px;
margin-right:5px;
}
</style>
<form action="#">
<div class="table-content cart-table-content">
<table>
<thead>
<tr>
<th></th>
<th>Product</th>
<th>Price</th>
<th style="text-align: center;">Quantity</th>
@ -229,6 +244,10 @@ if ($_SESSION["userId"] <> "") {
?>
<tr id="cart_order_<?php echo $order['_id'] ?>">
<td>
<input type="checkbox" class="rowcartCheckbox" name="cart-item1[]" value="<?php echo $order['_id']?>"/>
</td>
<td data-label="Product" class="ec-cart-pro-name"><a href="product-left-sidebar.php?id=<?php echo $order['items'][0]['product']['product_id']; ?>">
<img loading="lazy" class="ec-cart-pro-img mr-4" src="<?php echo $order['items'][0]['product']['product_image']; ?>" alt="" />
<?php echo $order['items'][0]['product']['name']; ?></a>
@ -270,6 +289,34 @@ if ($_SESSION["userId"] <> "") {
?>
<script>
// let myLatestOrders = [];
var checkboxes = document.querySelectorAll('input[name="cart-item1[]"]');
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
getCheckedCheckboxes();
getLatestOrdersCart();
// update_Total()
});
});
function getCheckedCheckboxes() {
var checkboxes = document.querySelectorAll('input[name="cart-item1[]"]');
var checkedValues = [];
var uncheckedValues = [];
checkboxes.forEach(function(checkbox) {
if (checkbox.checked) {
checkedValues.push(checkbox.value.toLowerCase().trim());
} else {
uncheckedValues.push(checkbox.value.toLowerCase().trim());
}
});
if (checkedValues.length === 0) {
return uncheckedValues;
} else {
console.log(checkedValues);
return checkedValues;
}
}
function handleQtyInputCart(input, orderId, itemId, prodId) {
var newQuantity = parseInt(input.value);
@ -564,7 +611,18 @@ if ($_SESSION["userId"] <> "") {
if (orderData && orderData !== "") {
console.log(orderData)
const filteredOrders = orderData.filter(order => order.status.toUpperCase() === 'CART');
const totalAmountSum = filteredOrders.reduce((sum, order) => {
var checkedCategories = getCheckedCheckboxes();
let orderInitial= null;
if (filteredOrders && filteredOrders !== "") {
// Calculate the new total amount based on the updated quantities
if(checkedCategories?.length>0){
orderInitial = filteredOrders?.filter(order => checkedCategories?.includes(order._id));
}else{
orderInitial = filteredOrders
}
}
const totalAmountSum = orderInitial.reduce((sum, order) => {
const totalAmount = parseFloat(order.total_amount);
return sum + totalAmount;
}, 0);
@ -602,6 +660,16 @@ if ($_SESSION["userId"] <> "") {
})
.catch(error => console.error('Error:', error));
}
function handleCheckoutButton(event) {
event.preventDefault();
var checkedCategories = getCheckedCheckboxes();
const selectedIdString = checkedCategories.join('-');
login(email, password, function(token) {
window.location.href = `checkouttest.php?selected=${selectedIdString}`;
});
}
</script>
<!-- <tr>
<td data-label="Product" class="ec-cart-pro-name"><a
@ -670,7 +738,7 @@ if ($_SESSION["userId"] <> "") {
<div class="col-lg-12">
<div class="ec-cart-update-bottom">
<a href="index.php">Continue Shopping</a>
<a style="text-decoration:none; color:white" href="checkout.php" class="btn btn-primary">Check Out</a>
<a style="text-decoration:none; color:white"onclick="handleCheckoutButton(event)" class="btn btn-primary">Check Out</a>
</div>
</div>
</div>

View File

@ -28,7 +28,7 @@ if ($_SESSION["userId"] <> "") {
$cartencode = json_encode($filteredCartItems);
}else{
$cartItems = $filteredCartItems;
// $cartItems = $filteredCartItems;
$cartencode = json_encode($cartItems);
}

View File

@ -24,7 +24,7 @@ $_SESSION["email"] = $_POST["name"];
// Check if the customer exists in the database
$result = customerExists($_SESSION["email"]);
if ($result > 0) {
if ($result) {
$forgot = forgot_password($_SESSION["email"]);
if($forgot){
header("location: forget_otp.php");

View File

@ -565,13 +565,24 @@ if ($_SESSION["userId"] <> "") {
});
});
function getCheckedCheckboxes() {
var checkboxes = document.querySelectorAll('input[name="cart-item[]"]:checked');
var values = [];
var checkboxes = document.querySelectorAll('input[name="cart-item[]"]');
var checkedValues = [];
var uncheckedValues = [];
checkboxes.forEach(function(checkbox) {
values.push(checkbox.value.toLowerCase().trim());
if (checkbox.checked) {
checkedValues.push(checkbox.value.toLowerCase().trim());
} else {
uncheckedValues.push(checkbox.value.toLowerCase().trim());
}
});
console.log(values);
return values;
if (checkedValues.length === 0) {
return uncheckedValues;
} else {
console.log(checkedValues);
return checkedValues;
}
}
function update_Total(){

View File

@ -304,7 +304,7 @@ function updateWishItemCount() {
var filteredProducts = [];
// Filter by category
if (checkedCategories.length > 0) {
let filteredProduct= products?.results?.filter((product) => {
let filteredProduct= products?.filter((product) => {
let categoryF = product?.product?.product_category?.toLowerCase();
// console.log('Category (lowercase):', categoryF);
let result =checkedCategories.includes(categoryF)
@ -316,7 +316,7 @@ console.log(filteredProducts);
} else {
// If no categories are selected, keep all products
filteredProducts = products?.results;
filteredProducts = products;
}
// If minPrice or maxPrice is not provided, set them to default values
@ -349,7 +349,7 @@ console.log({results:filteredProducts});
// Final filtered products
// console.log({results:filteredProducts});
let final = {results:filteredProducts}
let final = filteredProducts
return final;
}
function loadVendors(page,isFilter) {
@ -479,8 +479,9 @@ function loadProducts(page,isFilter) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Parse JSON response
let products = JSON.parse(xhr.responseText);
let products1 = JSON.parse(xhr.responseText);
let products = products1.results.filter(product => product.product.product_type !== 'variation');
console.log(products);
// if(isFilter===true){
var checkedCategories = getCheckedCheckboxes();
var prices = getMinMaxPrices();
@ -494,8 +495,8 @@ function loadProducts(page,isFilter) {
let startIndex = (page - 1) * productsPerPage;
let endIndex = startIndex + productsPerPage - 1;
// Filter products for current page
if(products.results.length>0){
let productsForPage = products.results.slice(startIndex, endIndex + 1);
if(products.length>0){
let productsForPage = products.slice(startIndex, endIndex + 1);
productsForPage.forEach(function(prod) {
@ -574,7 +575,7 @@ function loadProducts(page,isFilter) {
</div>
</div>`;
productContainer.appendChild(card);
updatePaginationUI(page, products.results.length);
updatePaginationUI(page, products.length);
});
gridList()
}else{

View File

@ -628,8 +628,8 @@ if ($_SESSION["isVendor"] == true) {
<?php
$jsonorder = json_encode($order);
?>
<tr class="tableView" style="cursor:pointer;" onmouseover="this.style.backgroundColor='#e5e5e5'" onmouseout="this.style.backgroundColor='#ffffff'">
<td data-value=' <?php echo $jsonorder; ?>' data-bs-toggle="modal" data-bs-target="#productDetails">
<tr class="tableView" style="cursor:pointer;" onmouseover="this.style.backgroundColor='#e5e5e5'" onmouseout="this.style.backgroundColor='#ffffff'" id="to-receive-<?php echo $order['_id']?>" data-value=' <?php echo $jsonorder; ?>'>
<td data-bs-toggle="modal" data-bs-target="#productDetails">
<?php
if(!empty($order['items'][0]['product']['product_image']))
{
@ -1069,20 +1069,20 @@ if ($_SESSION["isVendor"] == true) {
// const token = '<?php echo $_SESSION["token"] ?>';
const orderResponse = await fetch(`https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/orders/${orderId}`);
const orderData = await orderResponse.json();
const updatedDetails = orderData.payment.details.map(detail => ({
...detail,
attributes: {
...detail.attributes,
data: {
...detail.attributes.data,
attributes: {
...detail.attributes.data.attributes,
status: 'paid'
}
}
},
status: 'paid'
}));
// const updatedDetails = orderData.payment.details.map(detail => ({
// ...detail,
// attributes: {
// ...detail.attributes,
// data: {
// ...detail.attributes.data,
// attributes: {
// ...detail.attributes.data.attributes,
// status: 'paid'
// }
// }
// },
// status: 'paid'
// }));
fetch(`https://<?php echo $_SESSION["data_endpoint"]; ?>/api/v1/orders/${orderId}`, {
method: 'PATCH',
headers: {
@ -1091,11 +1091,11 @@ if ($_SESSION["isVendor"] == true) {
},
body: JSON.stringify({
status: 'COMPLETED',
payment: {
status: 'PAID',
reference_number: orderData.payment.reference_number,
details: updatedDetails,
}
// payment: {
// status: 'PAID',
// reference_number: orderData.payment.reference_number,
// // details: updatedDetails,
// }
}),
})
.then(response => response.json())
@ -1105,6 +1105,39 @@ if ($_SESSION["isVendor"] == true) {
// Update the status in the table without reloading the page
// document.querySelector(`[data-order-id="${orderId}"] .order-status`).innerText = 'COMPLETED';
// location.reload();
var rowToMove = document.querySelector(`#to-receive-${orderId}`);
if (rowToMove) {
// Get the values of the order
var image = rowToMove.querySelector('td:nth-child(1)').innerHTML;
var name = rowToMove.querySelector('td:nth-child(2)').innerHTML;
var quantity = rowToMove.querySelector('td:nth-child(3)').innerHTML;
var unitPrice = rowToMove.querySelector('td:nth-child(4)').innerHTML;
var price = rowToMove.querySelector('td:nth-child(5)').innerHTML;
var status = rowToMove.querySelector('td:nth-child(6)').innerHTML;
var date = rowToMove.querySelector('td:nth-child(7)').innerHTML;
// Construct the HTML for the new row in the "Completed" table
var newRowHTML = '<tr>' +
'<td>' + image + '</td>' +
'<td>' + name + '</td>' +
'<td>' + quantity + '</td>' +
'<td>' + unitPrice + '</td>' +
'<td>' + price + '</td>' +
'<td><span> COMPLETED </span></td>' +
'<td>' + date + '</td>' +
'<td>' +
'</td>' +
'</tr>';
// var newRowHTML = 'HERE!!!!!!!!!!!!!!!!!'
// Remove the row from the "To Receive" table
rowToMove.parentNode.removeChild(rowToMove);
// Append the HTML for the new row to the "Completed" table
document.querySelector('#completed tbody').innerHTML += newRowHTML;
}
// rowToMove.parentNode.removeChild(rowToMove);
} else {
alert('Failed to update order status');

View File

@ -111,6 +111,10 @@ $products = productList();
<!-- ekka Cart End -->
<!-- Category Sidebar start -->
<?php include "category-slider.php" ?>
<!-- Ec breadcrumb start -->
<div class="sticky-header-next-sec ec-breadcrumb section-space-mb">
<div class="container">

View File

@ -254,7 +254,7 @@ if ($_SESSION["isCustomer"] == true) {
$order = $vendorOrders[$i];
$orderArray = json_encode($order, true);
$orderItems = json_decode($orderArray, true);
if ($orderItems['status'] !== 'TO CHECKOUT' ) {
foreach ($orderItems['items'] as $item) {
?>
<tr>
@ -333,6 +333,7 @@ $style = "display: flex; height: 15px;font-weight:400; width:90px; margin-top:10
<?php
}
}
}
?>
</tbody>
</table>

View File

@ -265,7 +265,7 @@ if ($_SESSION["isCustomer"] == true) {
<h5 class="name"><?php echo $vendorData['user_login'] ?></h5>
</div>
<!-- <div class="ec-vendor-block-items">
<!-- <ul>
<ul>
<li><a href="vendor-dashboard.php">Dashboard</a></li>
<li><a href="vendor-uploads.php">Upload Product</a></li>
<li><a href="vendor-settings.php">Settings (Edit)</a></li>
@ -1085,7 +1085,7 @@ if ($_SESSION["isCustomer"] == true) {
if (jsonObject.return_order.status === 'To Approve') {
modal.innerHTML = `
<div class="modal-header" style="height:5px;">
<div class="modal-header" style="height:5px; padding:10px;">
<h5 class="modal-title fs-5 font-weight-bold">${jsonObject.items[0].product.name}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>