From 46995fef7b14a687626e9de6488fd1329a751739 Mon Sep 17 00:00:00 2001 From: jouls Date: Thu, 25 Apr 2024 15:16:37 +0800 Subject: [PATCH 01/19] removed forgot pass in register user --- register.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/register.php b/register.php index 8bf48de..282135a 100644 --- a/register.php +++ b/register.php @@ -112,9 +112,6 @@ $_SESSION["isVendor"] = false;

I accept this Terms & Conditions and Privacy Policy

- - - From 35a6c3b6938ec3021f4887983d1f487b411f4599 Mon Sep 17 00:00:00 2001 From: jouls Date: Thu, 25 Apr 2024 15:34:57 +0800 Subject: [PATCH 02/19] added functions for getAllCustomers and getAllVendors --- functions.php | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/functions.php b/functions.php index d8bd171..9ff8b31 100644 --- a/functions.php +++ b/functions.php @@ -2010,3 +2010,48 @@ function updatePayout($token, $payoutId) return $response; } +function getAllCustomers () +{ + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => "https://" . $_SESSION["data_endpoint"] . "/api/v1/customers", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'GET', + CURLOPT_HTTPHEADER => array( + 'X-Api-Key: {{apiKey}}' + ), + )); + $response = curl_exec($curl); + curl_close($curl); + $json = json_decode($response, true); + + return $json; +} + +function getAllVendors () +{ + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => "https://" . $_SESSION["data_endpoint"] . "/api/v1/vendors", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => '', + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 0, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => 'GET', + CURLOPT_HTTPHEADER => array( + 'X-Api-Key: {{apiKey}}' + ), + )); + $response = curl_exec($curl); + curl_close($curl); + $json = json_decode($response, true); + + return $json; +} \ No newline at end of file From 793afa339fd83c168a47b0a9822d6687d819b280 Mon Sep 17 00:00:00 2001 From: jouls Date: Thu, 25 Apr 2024 15:35:16 +0800 Subject: [PATCH 03/19] Added Daily Signup Counter --- admin/index.php | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/admin/index.php b/admin/index.php index 1da4c50..97e83f9 100644 --- a/admin/index.php +++ b/admin/index.php @@ -14,8 +14,15 @@ if($_SESSION["user_type"]!="admin"){ header("location: login.php?alert=Only admins allowed here!"); } -$all_orders = getAllOrder(); date_default_timezone_set('Asia/Manila'); +$currentDate = date('m-d-Y'); + +$all_orders = getAllOrder(); +$all_customers = getAllCustomers(); +$all_vendors = getAllVendors(); + +$allSignups = array_merge($all_customers, $all_vendors); + ?> @@ -707,8 +714,19 @@ date_default_timezone_set('Asia/Manila');
-

1,503

-

Daily Signups

+ +

+ +

Today's Signups

@@ -726,7 +744,7 @@ date_default_timezone_set('Asia/Manila');
-

Sales Report

From 8858763cd66a997bf23714370cbd8d9b8b77227c Mon Sep 17 00:00:00 2001 From: jouls Date: Thu, 25 Apr 2024 17:18:36 +0800 Subject: [PATCH 04/19] Added New Customers Table --- admin/index.php | 158 +++++++++++------------------------------------- 1 file changed, 35 insertions(+), 123 deletions(-) diff --git a/admin/index.php b/admin/index.php index 97e83f9..1aea4b9 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1088,10 +1088,10 @@ $allSignups = array_merge($all_customers, $all_vendors); = 8) { - break; - } + $iterationCount++; + if ($iterationCount >= 8) { + break; + } } } ?> @@ -1107,8 +1107,13 @@ $allSignups = array_merge($all_customers, $all_vendors);
+

New Customers

-
+
From to
+
+ $val) { + $formattedSignupDate = date('m-d-Y', strtotime($val['createdAt'])); + $imageUrl = $val['file_path_image']; + $fullName = $val['first_name'] . ' ' . $val['last_name']; + $email = $val['user_email']; + if ($formattedSignupDate >= $weekAgoDate && $formattedSignupDate <= $currentDate) { + ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - + + = 15) { + break; + } + } + } + ?>
- customer image + customer image
- -
Selena - Wagner
-
- @selena.oi +
+
2 Orders$150
-
-
- customer image -
-
- -
Walter - Reuter
-
- @walter.me -
-
-
5 Orders$200
-
-
- customer image -
-
- -
Larissa - Gebhardt
-
- @larissa.gb -
-
-
1 Order$50
-
-
- customer image -
-
- -
Albrecht - Straub
-
- @albrech.as -
-
-
2 Orders$100
-
-
- customer image -
-
- -
Leopold - Ebert
-
- @leopold.et -
-
-
1 Order$60
-
-
- customer image -
-
- -
Larissa - Gebhardt
-
- @larissa.gb -
-
-
1 Order$50
@@ -1350,7 +1262,7 @@ $allSignups = array_merge($all_customers, $all_vendors);

Copyright © Ekka Admin Dashboard. All Rights Reserved. -

+

From 0dfa648b19c54200539d98101a63e746a45db550 Mon Sep 17 00:00:00 2001 From: jouls Date: Thu, 25 Apr 2024 18:21:15 +0800 Subject: [PATCH 05/19] Added total users and new vendors table, improvements on recent orders table --- admin/index.php | 180 ++++++++++++++++++++++++++---------------------- 1 file changed, 99 insertions(+), 81 deletions(-) diff --git a/admin/index.php b/admin/index.php index 1aea4b9..b4fbff9 100644 --- a/admin/index.php +++ b/admin/index.php @@ -734,9 +734,17 @@ $allSignups = array_merge($all_customers, $all_vendors);
-

79,503

-

Daily Visitors

- + +

+ +

Total Users

+
@@ -763,7 +771,7 @@ $allSignups = array_merge($all_customers, $all_vendors); $finalDailyRevenue = number_format($dailyRevenue, 2, '.', ','); ?>

-

Today's Order

+

Today's Orders

@@ -1040,7 +1048,7 @@ $allSignups = array_merge($all_customers, $all_vendors); style="width:100%"> - Order ID + Payment Method Customer Name Vendor Name Total Amount @@ -1055,11 +1063,12 @@ $allSignups = array_merge($all_customers, $all_vendors); foreach (array_reverse($all_orders) as $x => $val) { $paymentStatus = strtolower($val['payment']['status']); $formattedOrderDate = date('m-d-Y', strtotime($val['order_date'])); - $orderId = $val['_id']; + $paymentMethod = $val['payment_method']; $customerName = $val['customer'][0]['name']; $vendorName = $val['items'][0]['vendor_name']; $totalAmount = $val['total_amount']; $orderStatus = strtoupper($val['status']); + $statusClass = ''; if ($orderStatus === 'UNPAID' || $orderStatus === 'RETURNED') { @@ -1079,10 +1088,10 @@ $allSignups = array_merge($all_customers, $all_vendors); $displayDate = date('m-d-Y, g:i A', strtotime($val['order_date'])); ?> - + - + ₱ @@ -1103,12 +1112,11 @@ $allSignups = array_merge($all_customers, $all_vendors);
-
+

New Customers

@@ -1134,12 +1142,17 @@ $allSignups = array_merge($all_customers, $all_vendors); $val) { $formattedSignupDate = date('m-d-Y', strtotime($val['createdAt'])); - $imageUrl = $val['file_path_image']; + $imageUrl = $val['customer_image']; $fullName = $val['first_name'] . ' ' . $val['last_name']; $email = $val['user_email']; if ($formattedSignupDate >= $weekAgoDate && $formattedSignupDate <= $currentDate) { + $customersDisplayed = true; + ?> = 15) { + if ($iterationCount >= 8) { break; } } } + if (!$customersDisplayed) { + ?> + + + +
@@ -1160,11 +1173,18 @@ $allSignups = array_merge($all_customers, $all_vendors);
No new vendors in the past week
@@ -1172,83 +1192,81 @@ $allSignups = array_merge($all_customers, $all_vendors);
-
- -
-
-

Top Products

-
- +
+ +
+
+ +

New Vendors

+
From to
+
-
-
-
- customer image -
-
- -
Baby cotton shoes
-
-

58Sales

-

Statement belting with double-turnlock hardware - adds “swagger” to a simple.

-

- $520 - $580 -

-
-
-
-
- customer image -
-
- -
Hoodies for men
-
-

20Sales

-

Statement belting with double-turnlock hardware - adds “swagger” to a simple.

-

- $250 - $300 -

-
-
-
-
- customer image -
-
- -
Long slive t-shirt
-
-

10Sales

-

Statement belting with double-turnlock hardware - adds “swagger” to a simple.

-

- $480 - $654 -

-
-
+
+ + + $val) { + $formattedSignupDate = date('m-d-Y', strtotime($val['createdAt'])); + $imageUrl = $val['vendor_image']; + $fullName = $val['first_name'] . ' ' . $val['last_name']; + $email = $val['user_email']; + if ($formattedSignupDate >= $weekAgoDate && $formattedSignupDate <= $currentDate) { + $vendorsDisplayed = true; + ?> + + + + + = 8) { + break; + } + } + } + + if (!$vendorsDisplayed) { + ?> + + + + + +
+
+
+ customer image +
+
+
+ +
+
+
No new vendors in the past week
From e30cbcebd725add84c495dbf9dc01de03565a17b Mon Sep 17 00:00:00 2001 From: jouls Date: Fri, 26 Apr 2024 13:01:28 +0800 Subject: [PATCH 06/19] improvements on admin dashboard and order history --- admin/index.php | 18 +++++++++++++++--- admin/order-history.php | 10 ++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/admin/index.php b/admin/index.php index b4fbff9..efbe96a 100644 --- a/admin/index.php +++ b/admin/index.php @@ -114,7 +114,7 @@ $allSignups = array_merge($all_customers, $all_vendors);
  • - + My Profile
  • @@ -1060,6 +1060,8 @@ $allSignups = array_merge($all_customers, $all_vendors); $val) { $paymentStatus = strtolower($val['payment']['status']); $formattedOrderDate = date('m-d-Y', strtotime($val['order_date'])); @@ -1085,6 +1087,8 @@ $allSignups = array_merge($all_customers, $all_vendors); } if ($formattedOrderDate == $currentDate) { + $ordersDisplayed = true; + $displayDate = date('m-d-Y, g:i A', strtotime($val['order_date'])); ?> @@ -1103,6 +1107,14 @@ $allSignups = array_merge($all_customers, $all_vendors); } } } + + if (!$ordersDisplayed) { + ?> + + No Recent Orders Yet. + + @@ -1181,7 +1193,7 @@ $allSignups = array_merge($all_customers, $all_vendors); if (!$customersDisplayed) { ?> - No new vendors in the past week + No new customers in the past week - No new vendors in the past week + No new vendors in the past week @@ -24,9 +24,9 @@ $allorders = json_encode($orders, true); - + - Ekka - Admin Dashboard HTML Template. + oBanana B2B - Admin Dashboard @@ -82,7 +82,8 @@ $allorders = json_encode($orders, true); - + + @@ -102,6 +103,7 @@ $allorders = json_encode($orders, true); ?> + From 88ae2713bbd3877e547cc566635eb91007b1c5da Mon Sep 17 00:00:00 2001 From: jouls Date: Fri, 26 Apr 2024 14:26:32 +0800 Subject: [PATCH 07/19] improvements on new vendors table --- admin/index.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/admin/index.php b/admin/index.php index efbe96a..e83eaed 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1239,6 +1239,7 @@ $allSignups = array_merge($all_customers, $all_vendors); foreach (array_reverse($all_vendors) as $x => $val) { $formattedSignupDate = date('m-d-Y', strtotime($val['createdAt'])); $imageUrl = $val['vendor_image']; + $shopName = $val['user_login']; $fullName = $val['first_name'] . ' ' . $val['last_name']; $email = $val['user_email']; if ($formattedSignupDate >= $weekAgoDate && $formattedSignupDate <= $currentDate) { @@ -1254,7 +1255,8 @@ $allSignups = array_merge($all_customers, $all_vendors); alt="customer image">
    -
    +
    + ||
    From 0dd203aba2f02b7575b1f5061b0f0ade4040e861 Mon Sep 17 00:00:00 2001 From: jouls Date: Fri, 26 Apr 2024 15:47:05 +0800 Subject: [PATCH 08/19] added error handling for routes on vendor pages --- vendor-all-product-list.php | 5 +++++ vendor-dashboard-orders-edit.php | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/vendor-all-product-list.php b/vendor-all-product-list.php index 889b1d4..147174b 100644 --- a/vendor-all-product-list.php +++ b/vendor-all-product-list.php @@ -19,6 +19,11 @@ if ($_SESSION["userId"] <> "") { $_SESSION["isLoggedIn"] = false; header("location: login.php"); } + +if ($_SESSION["isCustomer"] == true) { + header("location: user-profile.php"); +} + $products = productList(); ?> '; + echo ''; } else { echo ''; } From b4b69ba2234d7758c262f71ae0449f17f57b4782 Mon Sep 17 00:00:00 2001 From: jouls Date: Tue, 30 Apr 2024 09:26:24 +0800 Subject: [PATCH 14/19] added dynamic bank information on upcoming payouts based on the default bank payout set by the user --- vendor-payouts.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/vendor-payouts.php b/vendor-payouts.php index ebed651..6cf41e5 100644 --- a/vendor-payouts.php +++ b/vendor-payouts.php @@ -211,7 +211,13 @@ $vendorPayoutData = json_decode($response, true); $vendorResponse = getVendorbyId($vendorId); $vendorInformation = json_decode($vendorResponse, true); $bankAccountNumber = $vendorInformation['bank_acount_details'][0]['bank_account_number']; - $bankName = $vendorInformation['bank_acount_details'][0]['bank_name']; + $bankDetails = $vendorInformation['bank_acount_details']; + foreach ($bankDetails as $details) { + if ($details['bank_payout'] === true) { + $bankName = $details['bank_name']; + $bankAccountNumber = $details['bank_account_number']; + } + } $bankNumEnding = substr($bankAccountNumber, -3); ?> Receipient: Account ending in From 7d847cd44764bc61eabc79763da03b3acc2390f2 Mon Sep 17 00:00:00 2001 From: Stacy Date: Tue, 30 Apr 2024 13:44:23 +0800 Subject: [PATCH 15/19] removed some reload and modified console --- user-profile.php | 12 ++++++------ vendor-settings.php | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/user-profile.php b/user-profile.php index 8e2c482..39c1704 100644 --- a/user-profile.php +++ b/user-profile.php @@ -532,11 +532,11 @@ if ($_SESSION["isVendor"] == true) { }) .then(response => { if (response.ok) { - console.log('Email update successful'); + console.log('Profile updated Successful'); location.reload(); // Handle any other actions after the successful email update } else { - console.error('Email update failed'); + console.error('Profile Failed to Upload'); // Handle errors or display a message to the user } }) @@ -1253,10 +1253,10 @@ if ($_SESSION["isVendor"] == true) { }) .then(secondResponse => { if (secondResponse.ok) { - console.log('Second request successful'); - location.reload(); + console.log('Image Uploaded Successful'); + // location.reload(); } else { - console.error('Second request failed'); + console.error('Image Failed to Upload'); } }) .catch(error => { @@ -1294,7 +1294,7 @@ if ($_SESSION["isVendor"] == true) { aria-label="Close">Close --> - + diff --git a/vendor-settings.php b/vendor-settings.php index 9e1800c..e987313 100644 --- a/vendor-settings.php +++ b/vendor-settings.php @@ -640,11 +640,11 @@ if ($_SESSION["isCustomer"] == true) { }) .then(response => { if (response.ok) { - console.log('Email update successful'); + console.log('Profile updated successful'); location.reload(); // Handle any other actions after the successful email update } else { - console.error('Email update failed'); + console.error('Profile failed to update'); // Handle errors or display a message to the user } }) @@ -1492,10 +1492,10 @@ if ($_SESSION["isCustomer"] == true) { }) .then(secondResponse => { if (secondResponse.ok) { - console.log('Second request successful'); - location.reload(); + console.log('Profile Image Uploaded Successful'); + // location.reload(); } else { - console.error('Second request failed'); + console.error('Profile Image Failed to Upload'); } }) .catch(error => { @@ -1585,10 +1585,10 @@ if ($_SESSION["isCustomer"] == true) { }) .then(secondResponse => { if (secondResponse.ok) { - console.log('Second request successful'); - location.reload(); + console.log('Profile Banner Uploaded Successful'); + // location.reload(); } else { - console.error('Second request failed'); + console.error('Profile Banner Failed to Upload'); } }) .catch(error => { From 3f334715f34cd7c3d37be542bb46ccb8ef2c1c04 Mon Sep 17 00:00:00 2001 From: Stacy Date: Tue, 30 Apr 2024 13:45:35 +0800 Subject: [PATCH 16/19] updated quantity UI --- cart.php | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/cart.php b/cart.php index 63c70e8..3e49ae4 100644 --- a/cart.php +++ b/cart.php @@ -229,19 +229,35 @@ if ($_SESSION["userId"] <> "") { ?>
    - + Date: Tue, 30 Apr 2024 13:46:28 +0800 Subject: [PATCH 17/19] created back button --- vendor-dashboard-orders-edit.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/vendor-dashboard-orders-edit.php b/vendor-dashboard-orders-edit.php index 88c11e3..4174cb5 100644 --- a/vendor-dashboard-orders-edit.php +++ b/vendor-dashboard-orders-edit.php @@ -252,11 +252,19 @@ $array = json_decode($result, true); To Ship'; + echo ''; } elseif ($array['status'] === 'TO SHIP' || $array['status'] === 'To Ship') { echo ''; + echo ''; } elseif ($array['status'] === 'TO RECEIVE' || $array['status'] === 'To Receive') { echo ''; + echo ''; + } elseif ($array['status'] === 'COMPLETED' || $array['status'] === 'Completed') { + echo ''; + } elseif ($array['status'] === 'RETURNED' || $array['status'] === 'Returned') { + echo ''; } + ?> From 3fdab759556734f520dadb332346bf39ff4769af Mon Sep 17 00:00:00 2001 From: Stacy Date: Tue, 30 Apr 2024 13:47:33 +0800 Subject: [PATCH 18/19] applied price matrix on hover addtocart buttons --- assets/js/tester11.js | 1071 ++++++++++++++++++++++------------------- 1 file changed, 579 insertions(+), 492 deletions(-) diff --git a/assets/js/tester11.js b/assets/js/tester11.js index ece88cf..883c291 100644 --- a/assets/js/tester11.js +++ b/assets/js/tester11.js @@ -403,505 +403,592 @@ // .catch(error => console.error('Error:', error)); // } function login(username, password, callback) { - fetch("https://api.obanana.shop/api/v1/login", { - method: "POST", - headers: { - "Content-Type": "application/json", - "X-Api-Key": "{{apiKey}}", - }, - body: JSON.stringify({ - username: username, - password: password, - }), + fetch("https://api.obanana.shop/api/v1/login", { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Api-Key": "{{apiKey}}", + }, + body: JSON.stringify({ + username: username, + password: password, + }), + }) + .then((response) => { + if (response.ok) { + return response.json(); + } else { + throw new Error("Unable to login"); + } }) - .then((response) => { - if (response.ok) { - return response.json(); - } else { - throw new Error("Unable to login"); - } + .then((data) => { + fetch("update-token-session.php", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + token: data.token, + }), }) - .then((data) => { - fetch("update-token-session.php", { - method: "POST", + .then((response) => response.json()) + .then((result) => { + if (result.status === "success") { + sessionToken = data.token; + console.log("New Token:", sessionToken); + callback(sessionToken); + } else { + throw new Error("Unable to update session token"); + } + }); + }) + .catch((error) => { + console.error("Error:", error.message); + }); +} + +function popupAddToCart( + product, + productVendor, + token, + email, + password, + customer +) { + // var productObj = JSON.parse(product); + let productData = decodeURIComponent(product); + console.log(productData); + var cleanedProduct = productData.replace(/[\r\n]+/gm, ""); + var productObj; + + try { + // Attempt to parse 'cleanedProduct' as JSON + productObj = JSON.parse(cleanedProduct); + + // Log the parsed object for debugging + console.log("Parsed Product Object:", productObj); + } catch (error) { + // Log the error and return, or handle it accordingly + console.error("Error parsing product JSON: ", error); + return; + } + + // Now 'productObj' contains the parsed product or the original object/array + + try { + let customerData = decodeURIComponent(customer); + var cleanedCustomer = new Array(customerData); + + try { + function parseJSONSafely(jsonString) { + try { + // First attempt to parse the JSON + var parsedJSON = JSON.parse(jsonString); + + // Second attempt to parse the JSON + var parsedJSONAgain = JSON.parse(parsedJSON); + + // If the second parse succeeds, return its result + return parsedJSONAgain; + } catch (error) { + // If an error occurs during the second parse, return the result of the first parse + return parsedJSON; + } + } + + // Example usage: + var customerObj = parseJSONSafely(cleanedCustomer); + + console.log(); + } catch (error) { + console.error("Error parsing customer JSON:", error); + } + } catch (error) { + console.error("Error parsing customer JSON: ", error); + } + let vendorData = decodeURIComponent(productVendor); + + var vendorObj = JSON.parse(vendorData); + + var sessionToken = token; + var productImage = productObj.images; + var productId = productObj._id; + var productName = productObj.product_name; + // var productPrice = productObj.sale_price + // ? productObj.sale_price + // : productObj.regular_price; + var shippingFee = + productObj.shipping_fee && productObj.shipping_fee !== "" + ? productObj.shipping_fee + : "50"; + var productVendorId = vendorObj._id; + var vendorName = vendorObj.user_login; + var productQuantity = 1; + var customerId = customerObj[0]._id; + var customerName = customerObj[0].first_name + " " + customerObj[0].last_name; + + console.log("Product email: " + email); + console.log("Product password: " + password); + console.log("Product Token: " + sessionToken); + console.log("Product Image: " + productImage); + console.log("Product ID: " + productId); + console.log("Product Name: " + productName); + // console.log("Product Price: " + productPrice); + console.log("Product Vendor ID: " + productVendorId); + console.log("Product Vendor Name: " + vendorName); + console.log("Product Quantity: " + productQuantity); + console.log("Customer ID: " + customerId); + 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 quantityValue = productObj.minimum_order =="" ? productQuantity : '1'; + + + + // 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); + } + + + + //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 (!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: { + product_image: productImage, + product_id: productId, + name: productName, + }, + price: productPrice, + quantity: quantityValue, + vendor_id: productVendorId, + vendor_name: vendorName, + }; + + //Apply Matrix + console.log("Product dataa:", productData); + + var totalAmount = productData.price * productData.quantity; + + var customerData = { + customer_id: customerId, + name: customerName, + }; + + console.log("Customer data:", customerData); + // console.log("Price Matrix: " + priceMatrix); + + // Check if the product is already in the order API + var existingOrder; + var orderCheckXhr = new XMLHttpRequest(); + orderCheckXhr.open( + "GET", + "https://api.obanana.shop/api/v1/orders/customer/" + + customerData.customer_id, + true + ); + orderCheckXhr.onreadystatechange = function () { + if (orderCheckXhr.readyState === 4) { + if (orderCheckXhr.status === 200) { + var orders = JSON.parse(orderCheckXhr.responseText); + var existingItemId; + var ordersFiltered = orders.filter( + (e) => e.status === "CART" || e.status === "Cart" + ); + console.log(); + existingOrder = ordersFiltered.find((order) => + order.items.some( + (item) => + item.product.product_id === productData.product.product_id + ) + ); + console.log("exist? " + existingOrder); + if (existingOrder) { + var existingItemId = existingOrder.items[0]._id; + + // If the product is found in an existing CART order, update the order + updateOrder(existingOrder._id, existingItemId); + } else { + // If the product is not found or the order is not a CART, create a new order + console.log("No Order Yet!"); + createNewOrder(); + } + } else if (orderCheckXhr.status === 404) { + // If the customer has no orders, create a new order + console.log("No Order Yet!"); + createNewOrder(); + } else { + // Handle error response from the server when checking orders + console.log("Error checking orders:", orderCheckXhr.responseText); + } + } + }; + + orderCheckXhr.send(); + + function createNewOrder() { + var xhr = new XMLHttpRequest(); + + // Declare requestData before sending the request + var requestData = { + items: [productData], + customer: [customerData], + status: "CART", + total_amount: totalAmount, + shipping_fee: shippingFee, + }; + + console.log("Request data:", requestData); // Debugging statement + // const token = ''; + xhr.open("POST", "https://api.obanana.shop/api/v1/orders", true); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("Authorization", "Bearer " + token); + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + if (xhr.status === 201) { + var response = JSON.parse(xhr.responseText); + + console.log("Response:", response); // Debugging statement + + // Update the cart dynamically + var cartList = document.querySelector(".eccart-pro-items"); + + var newOrder = document.createElement("li"); + newOrder.id = `order_${response._id}`; + var imageUrl = response.items[0].product.product_image + ? response.items[0].product.product_image.split(",")[0].trim() + : "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; + console.log(response); + + newOrder.innerHTML = ` + + product + +
    + ${response.items[0].product.name} + Unit Price11: ${response.items[0].price} +
    + Subtotal: ${totalAmount} +
    + +
    +
    -
    + +
    +
    + + +
    + +
    + `; + getLatestOrders(); + updateCartItemCount(); + cartList.appendChild(newOrder); + } else { + // Handle error response from the server + console.log("Error response from the server"); + console.log(xhr.responseText); // Log the server's response + } + } + }; + + xhr.send(JSON.stringify(requestData)); + } + + function getLatestOrders() { + var customerId = '' + // Fetch the order data + fetch(`https://api.obanana.shop/api/v1/orders/customer/${customerId}`) + .then((response) => response.json()) + .then((orderData) => { + if (orderData && orderData !== "") { + console.log(orderData); + const filteredOrders = orderData.filter( + (order) => order.status.toUpperCase() === "CART" + ); + const totalAmountSum = filteredOrders.reduce((sum, order) => { + const totalAmount = parseFloat(order.total_amount); + return sum + totalAmount; + }, 0); + + console.log("Total Amount Sum:", totalAmountSum); + document.getElementById(`floatCartTotalAmount`).innerText = + totalAmountSum; + } else { + alert("Error fetching order data"); + } + }) + .catch((error) => console.error("Error:", error)); + } + + function updateOrder(orderId, existingItemId) { + var updateOrderXhr = new XMLHttpRequest(); + // const token = ''; + updateOrderXhr.open( + "PUT", + `https://api.obanana.shop/api/v1/orders/${orderId}/items/${existingItemId}`, + true + ); + updateOrderXhr.setRequestHeader("Content-Type", "application/json"); + updateOrderXhr.setRequestHeader("Authorization", "Bearer " + token); + updateOrderXhr.onreadystatechange = function () { + if (updateOrderXhr.readyState === 4) { + if (updateOrderXhr.status === 200) { + var response = JSON.parse(updateOrderXhr.responseText); + console.log("Order updated:", response); + + var cartItem = document.getElementById(`order_${response._id}`); + + if (cartItem) { + var updatedQuantity = response.items[0].quantity; // Use the correct quantity from the updated order + var totalAmount = response.items[0].price * updatedQuantity; + var imageUrl = response.items[0].product.product_image + ? response.items[0].product.product_image.split(",")[0].trim() + : "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; + + // If the cart item already exists, update its content using innerHTML + cartItem.innerHTML = ` + + product + +
    + ${response.items[0].product.name} + Unit Price: ${response.items[0].price} +
    + Subtotal: ${totalAmount} +
    +
    +
    -
    + +
    +
    + + +
    +
    + `; + document.getElementById( + `qty-input-${response.items[0]._id}` + ).value = updatedQuantity; + } else { + // If the cart item doesn't exist, create a new one + console.log("Error updating order:", updateOrderXhr.responseText); + } + + getLatestOrders(); + updateCartItemCount(); + } else { + // Handle error response from the server + console.log("Error response from the server"); + console.log(xhr.responseText); // Log the server's response + } + } + }; + var existingQuantity = parseInt(existingOrder.items[0].quantity, 10); + var newQuantity = parseInt(quantityValue, 10); + 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; + } + } + } + + if (foundNewPrice) { + productPrice = newProductPrice; + } + + var updateData = { + quantity: updatedQuantity, + price: productPrice + }; + + updateOrderXhr.send(JSON.stringify(updateData)); + + var patchTotalAmountXhr = new XMLHttpRequest(); + patchTotalAmountXhr.open( + "PATCH", + `https://api.obanana.shop/api/v1/orders/${orderId}`, + true + ); + patchTotalAmountXhr.setRequestHeader("Content-Type", "application/json"); + patchTotalAmountXhr.setRequestHeader("Authorization", "Bearer " + token); + + // var originalPrice = productPrice; + var totalAmount = productPrice * updatedQuantity; + // console.log(originalPrice); + // console.log(totalAmount); + var patchData = { + total_amount: totalAmount, + }; + + patchTotalAmountXhr.send(JSON.stringify(patchData)); + } + }); +} + +function popupWishlist(wishproduct, wishCustomer) { + // var productObject = JSON.parse(wishproduct); + let productData = decodeURIComponent(wishproduct); + console.log(productData); + var cleanedProduct = productData.replace(/[\r\n]+/gm, ""); + var productObject; + + try { + // Attempt to parse 'cleanedProduct' as JSON + productObject = JSON.parse(cleanedProduct); + + // Log the parsed object for debugging + console.log("Parsed Product Object:", productObject); + } catch (error) { + // Log the error and return, or handle it accordingly + console.error("Error parsing product JSON: ", error); + return; + } + // var customerObject = JSON.parse(wishCustomer); + try { + let customerData = decodeURIComponent(wishCustomer); + var cleanedCustomer = new Array(customerData); + + try { + function parseJSONSafely(jsonString) { + try { + // First attempt to parse the JSON + var parsedJSON = JSON.parse(jsonString); + + // Second attempt to parse the JSON + var parsedJSONAgain = JSON.parse(parsedJSON); + + // If the second parse succeeds, return its result + return parsedJSONAgain; + } catch (error) { + // If an error occurs during the second parse, return the result of the first parse + return parsedJSON; + } + } + + // Example usage: + var customerObject = parseJSONSafely(cleanedCustomer); + + console.log(); + } catch (error) { + console.error("Error parsing customer JSON:", error); + } + } catch (error) { + console.error("Error parsing customer JSON: ", error); + } + var prodId = productObject._id; + var custId = customerObject[0]._id; + fetch("https://api.obanana.shop/api/v1/customers/" + custId) + .then((response) => response.json()) + .then((data) => { + const existingWishlist = data.favorites ?? { + products: [], + vendors: [], + }; + + // Check if the product already exists in the wishlist + const isAlreadyAdded = existingWishlist.products.some( + (product) => product._id === prodId + ); + + if (!isAlreadyAdded) { + const newFavorites = { + products: [ + { + ...productObject, // Use the spread operator to include all properties from product_details + }, + ], + }; + + existingWishlist.products.push(newFavorites.products[0]); + + return fetch("https://api.obanana.shop/api/v1/customers/" + custId, { + method: "PATCH", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ - token: data.token, + favorites: existingWishlist, }), - }) - .then((response) => response.json()) - .then((result) => { - if (result.status === "success") { - sessionToken = data.token; - console.log("New Token:", sessionToken); - callback(sessionToken); - } else { - throw new Error("Unable to update session token"); - } - }); - }) - .catch((error) => { - console.error("Error:", error.message); - }); - } - - function popupAddToCart( - product, - productVendor, - token, - email, - password, - customer - ) { - // var productObj = JSON.parse(product); - let productData = decodeURIComponent(product); - console.log(productData); - var cleanedProduct = productData.replace(/[\r\n]+/gm, ""); - var productObj; - - try { - // Attempt to parse 'cleanedProduct' as JSON - productObj = JSON.parse(cleanedProduct); - - // Log the parsed object for debugging - console.log("Parsed Product Object:", productObj); - } catch (error) { - // Log the error and return, or handle it accordingly - console.error("Error parsing product JSON: ", error); - return; - } - - // Now 'productObj' contains the parsed product or the original object/array - - try { - let customerData = decodeURIComponent(customer); - var cleanedCustomer = new Array(customerData); - - try { - function parseJSONSafely(jsonString) { - try { - // First attempt to parse the JSON - var parsedJSON = JSON.parse(jsonString); - - // Second attempt to parse the JSON - var parsedJSONAgain = JSON.parse(parsedJSON); - - // If the second parse succeeds, return its result - return parsedJSONAgain; - } catch (error) { - // If an error occurs during the second parse, return the result of the first parse - return parsedJSON; - } - } - - // Example usage: - var customerObj = parseJSONSafely(cleanedCustomer); - - console.log(); - } catch (error) { - console.error("Error parsing customer JSON:", error); + }); + } else { + console.log("Product already exists in favorites"); + // Optionally, you can notify the user that the product is already in their favorites + // alert("Product already exists in favorites"); + return Promise.resolve(); // Resolve the promise to continue the chain } - } catch (error) { - console.error("Error parsing customer JSON: ", error); - } - let vendorData = decodeURIComponent(productVendor); - - var vendorObj = JSON.parse(vendorData); - - var sessionToken = token; - var productImage = productObj.images; - var productId = productObj._id; - var productName = productObj.product_name; - var productPrice = productObj.sale_price - ? productObj.sale_price - : productObj.regular_price; - var shippingFee = - productObj.shipping_fee && productObj.shipping_fee !== "" - ? productObj.shipping_fee - : "50"; - var productVendorId = vendorObj._id; - var vendorName = vendorObj.user_login; - var productQuantity = 1; - var customerId = customerObj[0]._id; - var customerName = customerObj[0].first_name + " " + customerObj[0].last_name; - - console.log("Product email: " + email); - console.log("Product password: " + password); - console.log("Product Token: " + sessionToken); - console.log("Product Image: " + productImage); - console.log("Product ID: " + productId); - console.log("Product Name: " + productName); - console.log("Product Price: " + productPrice); - console.log("Product Vendor ID: " + productVendorId); - console.log("Product Vendor Name: " + vendorName); - console.log("Product Quantity: " + productQuantity); - console.log("Customer ID: " + customerId); - console.log("Customer Names: " + customerName); - - login(email, password, function (token) { - var productData = { - product: { - product_image: productImage, - product_id: productId, - name: productName, - }, - price: productPrice, - quantity: productQuantity, - vendor_id: productVendorId, - vendor_name: vendorName, - }; - - var totalAmount = productData.price * productData.quantity; - - var customerData = { - customer_id: customerId, - name: customerName, - }; - - var existingOrder; - var orderCheckXhr = new XMLHttpRequest(); - orderCheckXhr.open( - "GET", - "https://api.obanana.shop/api/v1/orders/customer/" + - customerData.customer_id, - true - ); - orderCheckXhr.onreadystatechange = function () { - if (orderCheckXhr.readyState === 4) { - if (orderCheckXhr.status === 200) { - var orders = JSON.parse(orderCheckXhr.responseText); - var existingItemId; - var ordersFiltered = orders.filter( - (e) => e.status === "CART" || e.status === "Cart" - ); - console.log(); - existingOrder = ordersFiltered.find((order) => - order.items.some( - (item) => - item.product.product_id === productData.product.product_id - ) - ); - console.log("exist? " + existingOrder); - if (existingOrder) { - var existingItemId = existingOrder.items[0]._id; - - // If the product is found in an existing CART order, update the order - updateOrder(existingOrder._id, existingItemId); - } else { - // If the product is not found or the order is not a CART, create a new order - console.log("No Order Yet!"); - createNewOrder(); - } - } else if (orderCheckXhr.status === 404) { - // If the customer has no orders, create a new order - console.log("No Order Yet!"); - createNewOrder(); - } else { - // Handle error response from the server when checking orders - console.log("Error checking orders:", orderCheckXhr.responseText); - } - } - }; - - orderCheckXhr.send(); - - function createNewOrder() { - var xhr = new XMLHttpRequest(); - - // Declare requestData before sending the request - var requestData = { - items: [productData], - customer: [customerData], - status: "CART", - total_amount: totalAmount, - shipping_fee: shippingFee, - }; - - console.log("Request data:", requestData); // Debugging statement - // const token = ''; - xhr.open("POST", "https://api.obanana.shop/api/v1/orders", true); - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Authorization", "Bearer " + token); - xhr.onreadystatechange = function () { - if (xhr.readyState === 4) { - if (xhr.status === 201) { - var response = JSON.parse(xhr.responseText); - - console.log("Response:", response); // Debugging statement - - // Update the cart dynamically - var cartList = document.querySelector(".eccart-pro-items"); - - var newOrder = document.createElement("li"); - newOrder.id = `order_${response._id}`; - var imageUrl = response.items[0].product.product_image - ? response.items[0].product.product_image.split(",")[0].trim() - : "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; - console.log(response); - - newOrder.innerHTML = ` - - product - -
    - ${response.items[0].product.name} - - Unit Price: ${response.items[0].price} - - Subtotal: ${totalAmount} - -
    -
    -
    - -
    +
    - -
    - -
    - `; - getLatestOrders(); - updateCartItemCount(); - cartList.appendChild(newOrder); - } else { - // Handle error response from the server - console.log("Error response from the server"); - console.log(xhr.responseText); // Log the server's response - } - } - }; - - xhr.send(JSON.stringify(requestData)); - } - - function getLatestOrders() { - // var customerId = '' - // Fetch the order data - fetch(`https://api.obanana.shop/api/v1/orders/customer/${customerId}`) - .then((response) => response.json()) - .then((orderData) => { - if (orderData && orderData !== "") { - console.log(orderData); - const filteredOrders = orderData.filter( - (order) => order.status.toUpperCase() === "CART" - ); - const totalAmountSum = filteredOrders.reduce((sum, order) => { - const totalAmount = parseFloat(order.total_amount); - return sum + totalAmount; - }, 0); - - console.log("Total Amount Sum:", totalAmountSum); - document.getElementById(`floatCartTotalAmount`).innerText = - totalAmountSum; - } else { - alert("Error fetching order data"); - } - }) - .catch((error) => console.error("Error:", error)); - } - - function updateOrder(orderId, existingItemId) { - var updateOrderXhr = new XMLHttpRequest(); - // const token = ''; - updateOrderXhr.open( - "PUT", - `https://api.obanana.shop/api/v1/orders/${orderId}/items/${existingItemId}`, - true - ); - updateOrderXhr.setRequestHeader("Content-Type", "application/json"); - updateOrderXhr.setRequestHeader("Authorization", "Bearer " + token); - updateOrderXhr.onreadystatechange = function () { - if (updateOrderXhr.readyState === 4) { - if (updateOrderXhr.status === 200) { - var response = JSON.parse(updateOrderXhr.responseText); - console.log("Order updated:", response); - - var cartItem = document.getElementById(`order_${response._id}`); - - if (cartItem) { - var updatedQuantity = response.items[0].quantity; // Use the correct quantity from the updated order - var totalAmount = response.items[0].price * updatedQuantity; - var imageUrl = response.items[0].product.product_image - ? response.items[0].product.product_image.split(",")[0].trim() - : "https://api.obanana.com/images/storage/web_images/1709002636671-viber_image_2024-02-22_15-54-42-498.png"; - - // If the cart item already exists, update its content using innerHTML - cartItem.innerHTML = ` - - product - -
    - ${response.items[0].product.name} - - Unit Price: ${response.items[0].price} - - Subtotal: ${totalAmount} -
    -
    -
    - -
    +
    - -
    - `; - document.getElementById( - `qty-input-${response.items[0]._id}` - ).value = updatedQuantity; - } else { - // If the cart item doesn't exist, create a new one - console.log("Error updating order:", updateOrderXhr.responseText); - } - - getLatestOrders(); - updateCartItemCount(); - } else { - // Handle error response from the server - console.log("Error response from the server"); - console.log(xhr.responseText); // Log the server's response - } - } - }; - var existingQuantity = parseInt(existingOrder.items[0].quantity, 10); - var newQuantity = parseInt(productQuantity, 10); - var updatedQuantity = existingQuantity + newQuantity; - - var updateData = { - quantity: updatedQuantity, - }; - - updateOrderXhr.send(JSON.stringify(updateData)); - - var patchTotalAmountXhr = new XMLHttpRequest(); - patchTotalAmountXhr.open( - "PATCH", - `https://api.obanana.shop/api/v1/orders/${orderId}`, - true - ); - patchTotalAmountXhr.setRequestHeader("Content-Type", "application/json"); - patchTotalAmountXhr.setRequestHeader("Authorization", "Bearer " + token); - - var originalPrice = productPrice; - var totalAmount = originalPrice * updatedQuantity; - console.log(originalPrice); - console.log(totalAmount); - var patchData = { - total_amount: totalAmount, - }; - - patchTotalAmountXhr.send(JSON.stringify(patchData)); + }) + + .then((response) => { + if (response && response.ok) { + // Handle success (e.g., show a success message) + console.log("Added to favorites"); + updateWishItemCount(); + // location.reload(); + } else if (response) { + // Handle error + console.error("Failed to submit data"); + alert("Failed to submit data"); } + }) + .catch((error) => { + // Handle network or other errors + console.error("Error:", error); + alert("Error submitting data"); }); - } - - function popupWishlist(wishproduct, wishCustomer) { - // var productObject = JSON.parse(wishproduct); - let productData = decodeURIComponent(wishproduct); - console.log(productData); - var cleanedProduct = productData.replace(/[\r\n]+/gm, ""); - var productObject; - - try { - // Attempt to parse 'cleanedProduct' as JSON - productObject = JSON.parse(cleanedProduct); - - // Log the parsed object for debugging - console.log("Parsed Product Object:", productObject); - } catch (error) { - // Log the error and return, or handle it accordingly - console.error("Error parsing product JSON: ", error); - return; - } - // var customerObject = JSON.parse(wishCustomer); - try { - let customerData = decodeURIComponent(wishCustomer); - var cleanedCustomer = new Array(customerData); - - try { - function parseJSONSafely(jsonString) { - try { - // First attempt to parse the JSON - var parsedJSON = JSON.parse(jsonString); - - // Second attempt to parse the JSON - var parsedJSONAgain = JSON.parse(parsedJSON); - - // If the second parse succeeds, return its result - return parsedJSONAgain; - } catch (error) { - // If an error occurs during the second parse, return the result of the first parse - return parsedJSON; - } - } - - // Example usage: - var customerObject = parseJSONSafely(cleanedCustomer); - - console.log(); - } catch (error) { - console.error("Error parsing customer JSON:", error); - } - } catch (error) { - console.error("Error parsing customer JSON: ", error); - } - var prodId = productObject._id; - var custId = customerObject[0]._id; - fetch("https://api.obanana.shop/api/v1/customers/" + custId) - .then((response) => response.json()) - .then((data) => { - const existingWishlist = data.favorites ?? { - products: [], - vendors: [], - }; - - // Check if the product already exists in the wishlist - const isAlreadyAdded = existingWishlist.products.some( - (product) => product._id === prodId - ); - - if (!isAlreadyAdded) { - const newFavorites = { - products: [ - { - ...productObject, // Use the spread operator to include all properties from product_details - }, - ], - }; - - existingWishlist.products.push(newFavorites.products[0]); - - return fetch("https://api.obanana.shop/api/v1/customers/" + custId, { - method: "PATCH", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ - favorites: existingWishlist, - }), - }); - } else { - console.log("Product already exists in favorites"); - // Optionally, you can notify the user that the product is already in their favorites - // alert("Product already exists in favorites"); - return Promise.resolve(); // Resolve the promise to continue the chain - } - }) - - .then((response) => { - if (response && response.ok) { - // Handle success (e.g., show a success message) - console.log("Added to favorites"); - updateWishItemCount(); - // location.reload(); - } else if (response) { - // Handle error - console.error("Failed to submit data"); - alert("Failed to submit data"); - } - }) - .catch((error) => { - // Handle network or other errors - console.error("Error:", error); - alert("Error submitting data"); - }); - } - \ No newline at end of file +} From f278bb854d0033d9ed82589834b94fc78115f6eb Mon Sep 17 00:00:00 2001 From: gelonspr Date: Tue, 30 Apr 2024 14:09:53 +0800 Subject: [PATCH 19/19] fixed admin dashboard download csv and initialized dynamic dataset for sales report --- admin/assets/js/dashboard-chart.js | 366 +++++++++++++++++++++++------ admin/index.php | 6 +- 2 files changed, 296 insertions(+), 76 deletions(-) diff --git a/admin/assets/js/dashboard-chart.js b/admin/assets/js/dashboard-chart.js index 8a66047..793d5f5 100644 --- a/admin/assets/js/dashboard-chart.js +++ b/admin/assets/js/dashboard-chart.js @@ -11,7 +11,7 @@ $(document).ready(function() { const completedOrdersCount = countCompletedOrders(responseData); const toPayOrdersCount = countToPayOrders(responseData); const toShipOrdersCount = countToShipOrders(responseData); - const returnedOrdersCount = countReturnedpOrders(responseData); + const returnedOrdersCount = countReturnedOrders(responseData); initializeChart(completedOrdersCount, toPayOrdersCount, toShipOrdersCount, returnedOrdersCount); }) .catch(function (error) { @@ -24,50 +24,65 @@ $(document).ready(function() { } - function countCompletedOrders(data) { - let completedOrdersCount = 0; - data.forEach(function(order) { + function getCurrentMonthData(data) { + const now = new Date(); + const currentMonth = now.getMonth(); + const currentYear = now.getFullYear(); + + return data.filter(order => { + const orderDate = new Date(order.order_date); + return orderDate.getMonth() === currentMonth && orderDate.getFullYear() === currentYear; + }); + } + + function countCompletedOrders(data) { + const filteredData = getCurrentMonthData(data); + let completedOrdersCount = 0; + filteredData.forEach(function(order) { if (order.status === 'COMPLETED') { - completedOrdersCount++; + completedOrdersCount++; } - }); - console.log(completedOrdersCount) - return completedOrdersCount; - } - - - function countToPayOrders(data) { - let toPayOrdersCount = 0; - data.forEach(function(order) { + }); + console.log(completedOrdersCount); + return completedOrdersCount; + } + + function countToPayOrders(data) { + const filteredData = getCurrentMonthData(data); + let toPayOrdersCount = 0; + filteredData.forEach(function(order) { if (order.status === 'TO PAY') { - toPayOrdersCount++; + toPayOrdersCount++; } - }); - console.log(toPayOrdersCount) - return toPayOrdersCount; - } - - - function countToShipOrders(data) { - let toShipOrdersCount = 0; - data.forEach(function(order) { + }); + console.log(toPayOrdersCount); + return toPayOrdersCount; + } + + function countToShipOrders(data) { + const filteredData = getCurrentMonthData(data); + let toShipOrdersCount = 0; + filteredData.forEach(function(order) { if (order.status === 'TO SHIP') { - toShipOrdersCount++; + toShipOrdersCount++; } - }); - console.log(toShipOrdersCount) - return toShipOrdersCount; - } - function countReturnedpOrders(data) { - let returnedOrdersCount = 0; - data.forEach(function(order) { + }); + console.log(toShipOrdersCount); + return toShipOrdersCount; + } + + function countReturnedOrders(data) { + const filteredData = getCurrentMonthData(data); + let returnedOrdersCount = 0; + filteredData.forEach(function(order) { if (order.status === 'RETURNED') { - returnedOrdersCount++; + returnedOrdersCount++; } - }); - console.log(returnedOrdersCount) - return returnedOrdersCount; - } + }); + console.log(returnedOrdersCount); + return returnedOrdersCount; + } + function initializeChart(completedOrdersCount , toPayOrdersCount, toShipOrdersCount, returnedOrdersCount) { var doughnut = document.getElementById("doughnut-chart"); @@ -115,43 +130,248 @@ $(document).ready(function() { } } + + + var acquisition = document.getElementById("salesChart"); + if (acquisition !== null) { + function updateDailyLabels() { + var labelsDaily = []; + for (let i = 6; i >= 0; i--) { + var date = new Date(); + date.setDate(date.getDate() - i); + labelsDaily.push(formatDate(date)); + } + return labelsDaily; + } + + function formatDate(date) { + const options = { day: 'numeric', month: 'short' }; // E.g., 26 Apr + return date.toLocaleDateString('en-US', options); + } + + // Updating labelsDaily dynamically + var labelsDaily = updateDailyLabels(); + var labelsMonthly = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + var labelsYearly = ["2021", "2022", "2023", "2024", "2025"]; + var acqData = [ + { //daily data + first: [91, 180, 44, 75, 150, 66, 70], //COD + second: [300, 44, 177, 76, 23, 189, 12], //ObPay + third: [44, 167, 102, 123, 183, 88, 134] //Paymongo + }, + { //monthly data + first: [144, 44, 110, 5, 123, 89, 12], //COD + second: [22, 123, 45, 130, 112, 54, 181], //ObPay + third: [55, 44, 144, 75, 155, 166, 70] //Paymongo + }, + { //yearly data + first: [134, 80, 123, 65, 171, 33, 22], //COD + second: [44, 144, 77, 76, 123, 89, 112], //ObPay + third: [156, 23, 165, 88, 112, 54, 181] //Paymongo + } + ]; + + var configAcq = { + // The type of chart we want to create + type: "line", + + // The data for our dataset + data: { + // labels: [ + // "4 Jan", + // "5 Jan", + // "6 Jan", + // "7 Jan", + // "8 Jan", + // "9 Jan", + // "10 Jan" + // ], + datasets: [ + { + label: "Cash on Delivery", + backgroundColor: "rgba(52, 116, 212, .2)", + borderColor: "rgba(52, 116, 212, .7)", + data: acqData[0].first, + lineTension: 0.3, + pointBackgroundColor: "rgba(52, 116, 212,0)", + pointHoverBackgroundColor: "rgba(52, 116, 212,1)", + pointHoverRadius: 3, + pointHitRadius: 30, + pointBorderWidth: 2, + pointStyle: "rectRounded" + }, + { + label: "ObananaPay", + backgroundColor: "rgba(255, 192, 203, .3)", + borderColor: "rgba(255, 192, 203, .7)", + data: acqData[0].second, + lineTension: 0.3, + pointBackgroundColor: "rgba(255, 192, 203, 0)", + pointHoverBackgroundColor: "rgba(255, 192, 203, 1)", + pointHoverRadius: 3, + pointHitRadius: 30, + pointBorderWidth: 2, + pointStyle: "rectRounded" + }, + { + label: "Paymongo", + backgroundColor: "rgb(178, 251, 212, .3)", + borderColor: "rgba(178, 251, 212, .7)", + data: acqData[0].third, + lineTension: 0.3, + pointBackgroundColor: "rgba(178, 251, 212, 0)", + pointHoverBackgroundColor: "rgba(178, 251, 212, 1)", + pointHoverRadius: 3, + pointHitRadius: 30, + pointBorderWidth: 2, + pointStyle: "rectRounded" + } + ] + }, + + // Configuration options go here + options: { + responsive: true, + maintainAspectRatio: false, + legend: { + display: false + }, + scales: { + xAxes: [ + { + gridLines: { + display: false + } + } + ], + yAxes: [ + { + gridLines: { + display: true, + color: "#eee", + zeroLineColor: "#eee" + }, + ticks: { + beginAtZero: true, + stepSize: 100, + max: 1000 + } + } + ] + }, + tooltips: { + mode: "index", + titleFontColor: "#888", + bodyFontColor: "#555", + titleFontSize: 12, + bodyFontSize: 15, + backgroundColor: "rgba(256,256,256,0.95)", + displayColors: true, + xPadding: 20, + yPadding: 10, + borderColor: "rgba(220, 220, 220, 0.9)", + borderWidth: 2, + caretSize: 10, + caretPadding: 15 + } + } + }; + + var ctx = document.getElementById("salesChart").getContext("2d"); + var lineAcq = new Chart(ctx, configAcq); + document.getElementById("acqLegend").innerHTML = lineAcq.generateLegend(); + + var items = document.querySelectorAll( + "#user-acquisition .nav-tabs .nav-item" + ); + items.forEach(function (item, index) { + item.addEventListener("click", function() { + // Determine which tab was clicked + var selectedTab = this.textContent.trim(); + + // Choose data and labels based on the selected tab + switch (selectedTab) { + case "Daily": + configAcq.data.labels = labelsDaily; + configAcq.data.datasets[0].data = acqData[0].first; + configAcq.data.datasets[1].data = acqData[0].second; + configAcq.data.datasets[2].data = acqData[0].third; + break; + case "Monthly": + configAcq.data.labels = labelsMonthly; + configAcq.data.datasets[0].data = acqData[1].first; + configAcq.data.datasets[1].data = acqData[1].second; + configAcq.data.datasets[2].data = acqData[1].third; + break; + case "Yearly": + configAcq.data.labels = labelsYearly; + configAcq.data.datasets[0].data = acqData[2].first; + configAcq.data.datasets[1].data = acqData[2].second; + configAcq.data.datasets[2].data = acqData[2].third; + break; + } + + lineAcq.update(); + }); +}); + items[0].click(); + } + function convertToCSV(data) { - const columnTitles = ['ORDER ID', 'STATUS', 'BUYER NAME', 'TOTAL AMOUNT', 'ORDER DATE', - 'ORDER TIME', 'PRODUCT NAME','PRICE', 'QUANTITY', - 'VENDOR ID', 'VENDOR NAME',]; - const header = columnTitles.join(',') + '\n'; - const body = data.map(order => { - const orderDate = new Date(order.order_date).toLocaleDateString('en-US'); - const orderTime = new Date(order.order_date).toLocaleTimeString('en-US'); - const productName = order.items.length > 0 ? `"${order.items[0].product.name}"` : ''; - return [ - order._id, - order.status, - order.customer[0]?.name, - order.total_amount, - orderDate, - orderTime, - productName, - order.items[0]?.price, - order.items[0]?.quantity, - order.items[0]?.vendor_id, - order.items[0]?.vendor_name - ].join(','); - }).join('\n'); - return header + body; - } - function downloadCSV(filename) { - const csv = convertToCSV(responseData); - const blob = new Blob([csv], { type: 'text/csv' }); - const url = window.URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - window.URL.revokeObjectURL(url); - } + const now = new Date(); + const currentMonth = now.getMonth(); // Months are 0-indexed (0 for January, 11 for December) + const currentYear = now.getFullYear(); + + const filteredData = data.filter(order => { + const orderDate = new Date(order.order_date); + return orderDate.getMonth() === currentMonth && orderDate.getFullYear() === currentYear; + }); + + const columnTitles = [ + 'ORDER ID', 'STATUS', 'BUYER NAME', 'TOTAL AMOUNT', 'METHOD', 'ORDER DATE', + 'ORDER TIME', 'PRODUCT NAME', 'PRICE', 'QUANTITY', 'VENDOR ID', 'VENDOR NAME' + ]; + const header = columnTitles.join(',') + '\n'; + const body = filteredData.map(order => { + const orderDate = new Date(order.order_date).toLocaleDateString('en-US'); + const orderTime = new Date(order.order_date).toLocaleTimeString('en-US'); + const productName = order.items.length > 0 ? `"${order.items[0].product.name}"` : ''; + return [ + order._id, + order.status, + order.customer[0]?.name, + order.total_amount, + order.payment_method, + orderDate, + orderTime, + productName, + order.items[0]?.price, + order.items[0]?.quantity, + order.items[0]?.vendor_id, + order.items[0]?.vendor_name + ].join(','); + }).join('\n'); + return header + body; + } + + function downloadCSV() { + const now = new Date(); + const months = ["January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December"]; + const currentMonthName = months[now.getMonth()]; + const filename = `${currentMonthName}_orders_overview.csv`; + + const csv = convertToCSV(responseData); // Ensure responseData is up to date + const blob = new Blob([csv], { type: 'text/csv' }); + const url = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + window.URL.revokeObjectURL(url); + } $('#download-btn').on('click', function(event) { event.preventDefault(); diff --git a/admin/index.php b/admin/index.php index 9944da9..4811983 100644 --- a/admin/index.php +++ b/admin/index.php @@ -800,7 +800,7 @@ $allSignups = array_merge($all_customers, $all_vendors); role="tablist">
    Download overall report + class="mdi mdi-download mr-2"> Download Current Month's Overall Report
    DateUpdated DateOrder Date Customer Vendor Product
    + + + -
    -
    -
    - -
    +
    + +
    +
    - +
    + +
    +
    - + + + + +