Skip to content

Commit

Permalink
product delete option change to list and unlist option , it's working…
Browse files Browse the repository at this point in the history
… with ajax
  • Loading branch information
arshadakl committed Nov 4, 2023
1 parent b83fe52 commit e44d1f6
Show file tree
Hide file tree
Showing 9 changed files with 157 additions and 44 deletions.
3 changes: 2 additions & 1 deletion controllers/orderController.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ const placeOrderManage = async (req, res) => {
let addressId = req.body.address;

let paymentType = req.body.payment;
console.log("PYAMENT TYPE: "+paymentType);
const cartDetails = await CartDB.findOne({ user: req.session.user_id });

let userAddrs = await addressDB.findOne({ userId: req.session.user_id });
Expand Down Expand Up @@ -368,7 +369,7 @@ const placeOrderManage = async (req, res) => {
// let analaticResult = await CreateOrderAnalatic();
// console.log(analaticResult);
console.log(placeorder._id);
if (paymentType === "COD") {
if (paymentType == "Cash on Delivery") {
console.log(placeorder._id);
let changeOrderStatus = await OrderDB.updateOne(
{ _id: placeorder._id },
Expand Down
31 changes: 31 additions & 0 deletions controllers/productsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,36 @@ const shopPageSearch = async (req, res) => {
} catch (error) {}
};


// This used to list and unlist user , this function working with Ajax
// ---------------------------------------

const prducutListUnlist = async (req, res) => {
try {
let listStatus = await ProductDB.findOne({ _id: req.body.id });

console.log(listStatus.unlist);
if (listStatus.unlist === 0) {
await ProductDB.updateOne(
{ _id: req.body.id },
{ $set: { unlist: 1 } }
);
} else {
await ProductDB.updateOne(
{ _id: req.body.id },
{ $set: { unlist: 0 } }
);
}

let product = await ProductDB.findOne({_id: req.body.id});
// console.log(product);
res.json({ product: product });
} catch (error) {
console.log(error.message);
}
};


module.exports = {
singleProductLoad,
productPageLoad,
Expand All @@ -311,4 +341,5 @@ module.exports = {
deleteproduct,
shopPageLoad,
shopPageSearch,
prducutListUnlist
};
3 changes: 3 additions & 0 deletions models/productsModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const productSchema = mongoose.Schema({
type:Number,
require:true
},
unlist:{
type:Number
},
images:{
image1:{
type:String,
Expand Down
32 changes: 31 additions & 1 deletion public/admin/js/ajaxScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,34 @@ function formatDate(inputDate) {
const formattedDate = `${day} ${month} ${year}, ${formattedHours}:${formattedMinutes} ${ampm}`;

return formattedDate;
}
}


function productAction(id) {
// Send an AJAX request to update the user's block status
const listBtn = document.getElementById(`BTN${id}`);
$.ajax({
url: '/admin/productlist',
method: "post",
data: { id: id },
success: function (response) {
let targetproduct = response.product;
// let targetproduct = users.find((user) => {
// return user._id === id;
// });

// Update the button class and text based on the user's block status
if (targetproduct.unlist == 0) {
// listBtn.removeClass('btn-inverse-danger').addClass('btn-inverse-success').text('Unlist');
$(`button[data-id="${id}"]`).removeClass('btn-inverse-danger').addClass('btn-inverse-success').text('Unlist');

} else {
// listBtn.removeClass('btn-inverse-success').addClass('btn-inverse-danger').text('List');
$(`button[data-id="${id}"]`).removeClass('btn-inverse-success').addClass('btn-inverse-danger').text('List');
}
},
error: function (error) {
console.error("Error:", error);
}
});
}
94 changes: 64 additions & 30 deletions public/admin/js/formValidations.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ function showFormValidAlert() {
}, 5000);
}

// couponpage validation
// couponpage validation
// ============================
function validateCouponForm() {
// Get form input values
Expand Down Expand Up @@ -41,7 +41,6 @@ function validateCouponForm() {
return false;
}


// Check if validFrom is after or equal to validTo
if (validFrom >= validTo) {
// alert("Valid Date From must be earlier than Valid Date To.");
Expand All @@ -60,8 +59,6 @@ function validateCouponForm() {
}

//check code is valid using ajax with pass code



// If all validation checks pass, allow form submission
return true;
Expand Down Expand Up @@ -103,55 +100,92 @@ function validateProductForm() {
const description = document.getElementsByName("description")[0].value;
const imageInputs = document.querySelectorAll(".imageInput");

if (productName.trim() === "" || isNaN(price) || isNaN(stock) || description.trim() === "") {
// alert("All fields must be filled out.");
ValidErrMess.innerHTML = "All fields must be filled out.";
showFormValidAlert();
return false;
if (
productName.trim() === "" ||
isNaN(price) ||
isNaN(stock) ||
description.trim() === ""
) {
// alert("All fields must be filled out.");
ValidErrMess.innerHTML = "All fields must be filled out.";
showFormValidAlert();
return false;
}

if (price < 0 || stock < 0) {
// alert("Price and Stock cannot have negative values.");
ValidErrMess.innerHTML = "Price and Stock cannot have negative values.";
showFormValidAlert();
return false;
// alert("Price and Stock cannot have negative values.");
ValidErrMess.innerHTML = "Price and Stock cannot have negative values.";
showFormValidAlert();
return false;
}

for (const imageInput of imageInputs) {
if (!imageInput.files || imageInput.files.length === 0) {
// alert("Please select images for all fields.");
ValidErrMess.innerHTML = "Please select images for all fields.";
showFormValidAlert();
return false;
}
if (!imageInput.files || imageInput.files.length === 0) {
// alert("Please select images for all fields.");
ValidErrMess.innerHTML = "Please select images for all fields.";
showFormValidAlert();
return false;
}
}

return true;
}


//edit product form validations
function validateEditProductForm() {
const productName = document.getElementsByName("product_name")[0].value;
const price = parseFloat(document.getElementsByName("price")[0].value);
const stock = parseInt(document.getElementsByName("stock")[0].value);
const description = document.getElementsByName("description")[0].value;

if (productName.trim() === "" || isNaN(price) || isNaN(stock) || description.trim() === "") {
// alert("All fields must be filled out.");
ValidErrMess.innerHTML = "All fields must be filled out.";
showFormValidAlert();
return false;
if (
productName.trim() === "" ||
isNaN(price) ||
isNaN(stock) ||
description.trim() === ""
) {
// alert("All fields must be filled out.");
ValidErrMess.innerHTML = "All fields must be filled out.";
showFormValidAlert();
return false;
}

if (price < 0 || stock < 0) {
// alert("Price and Stock cannot have negative values.");
ValidErrMess.innerHTML = "Price and Stock cannot have negative values.";
// alert("Price and Stock cannot have negative values.");
ValidErrMess.innerHTML = "Price and Stock cannot have negative values.";
showFormValidAlert();
return false;
}

return true;
}

function validUserEditForm() {
const userName = document.getElementById("userName").value;
const fullName = document.getElementById("fullName").value;
const email = document.getElementById("email").value;

if (userName.trim() === "" || fullName.trim() === "") {
// alert("All fields must be filled out.");
ValidErrMess.innerHTML = "All fields must be filled out.";
showFormValidAlert();
return false;
}

if (email.trim() === "") {
// alert('Email cannot be blank. Please enter a valid email address.');
ValidErrMess.innerHTML = "Email fields must be filled out.";
showFormValidAlert();
return false;
} else {
const emailPattern = /^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
if (!emailPattern.test(emailValue)) {
// alert('Invalid email address. Please enter a valid email.');
ValidErrMess.innerHTML = "Invalid email address. Please enter a valid email.";
showFormValidAlert();
return false;
}
}



return true;
return true
}
2 changes: 2 additions & 0 deletions routes/adminRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ router.post('/products/addproduct',auth.isLogin,fileUpload.productImagesUpload,p
router.get('/products/editproduct',auth.isLogin,productController.productEditPageLoad)
router.post('/products/editproduct',auth.isLogin,fileUpload.productImagesUpload,productController.updateProduct)
router.get('/products/deleteproduct',auth.isLogin,productController.deleteproduct)
router.post('/productlist',auth.isLogin,productController.prducutListUnlist)


// category related Routers
router.get('/category',auth.isLogin,categoryController.categoryPageLoad)
Expand Down
2 changes: 1 addition & 1 deletion views/admin/addProduct.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@
<hr>
<span class="row "><i class="fa-sharp fa-light fa-circle-xmark fa-shake" style="color: #ff0505; font-size: 18px;"></i> &nbsp;&nbsp;&nbsp; <p id="ValidErrMess"></p></span>

</div>
</div>
</footer>
<!-- partial -->
</div>
Expand Down
25 changes: 16 additions & 9 deletions views/admin/editUser.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,26 @@
<div class="card">
<div class="card-body">
<h4 class="card-title">Edit user Details</h4>
<form class="forms-sample" action="/admin/edituser?id=<%= user[0]._id %>" method="post">
<form class="forms-sample" action="/admin/edituser?id=<%= user[0]._id %>" onsubmit="return validUserEditForm()" method="post">

<div class="form-group row">
<div class="col-6">

<label for="exampleInputName1">User Name</label>
<input type="text" name="userName" class="form-control text-light" value="<%= user[0].userName %>" id="exampleInputName1">
<label for="userName">User Name <span class="text-danger">*</span></label>
<input type="text" name="userName" class="form-control text-light" value="<%= user[0].userName %>" id="userName">
</div>
<div class="col-6">
<label for="exampleInputName1">Full Name</label>
<input type="text" class="form-control text-light" name="fullName" value="<%= user[0].fullName %>" id="exampleInputName1" placeholder="Name">
<label for="fullName">Full Name <span class="text-danger">*</span></label>
<input type="text" class="form-control text-light" name="fullName" value="<%= user[0].fullName %>" id="fullName" placeholder="Name">
</div>
</div>

<div class="form-group">
<label for="exampleInputEmail3">Email address</label>
<input type="email" name="email" class="form-control text-light" value="<%= user[0].email %>" id="exampleInputEmail3" >
<label for="email">Email address <span class="text-danger">*</span></label>
<input type="email" name="email" class="form-control text-light" value="<%= user[0].email %>" id="email" >
</div>
<div class="form-group">
<label for="exampleInputPassword4">Shipping Address</label>
<label for="exampleInputPassword4">Address</label>
<input type="text" class="form-control text-light" name="shippingAddress" value="<%= user[0].address.shippingAddress %>" id="exampleInputPassword4" >
</div>
<div class="form-group row">
Expand Down Expand Up @@ -57,7 +57,14 @@
<!-- content-wrapper ends -->
<!-- partial:partials/_footer.html -->
<footer class="footer">

<div class="content-wrapper ">
<div id="FormAlert" data-aos="fade-down" class="alert alert-danger col-md-4 col-8 mx-auto fixed-top "
style="display: none; top:30px; border-radius: 7px; opacity: 0.9; " role="alert">
<h6 class="alert-heading text-center">Please provide only valid data.</h6>
<hr>
<span class="row "><i class="fa-sharp fa-light fa-circle-xmark fa-shake" style="color: #ff0505; font-size: 18px;"></i> &nbsp;&nbsp;&nbsp; <p id="ValidErrMess"></p></span>

</div>
</footer>
<!-- partial -->
</div>
Expand Down
9 changes: 7 additions & 2 deletions views/admin/products.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,18 @@
class="btn btn-inverse-info">Edit Product</a>
</td>
<td>
<% if (products[i].unlist == 1) { %>
<button data-id="<%= products[i]._id %>" onclick="productAction('<%= products[i]._id %>')" class="btn btn-inverse-danger">list</button>
<% } else { %>
<button data-id="<%= products[i]._id %>" onclick="productAction('<%= products[i]._id %>')" class="btn btn-inverse-success">Unlist</button>
<% } %>
<!-- <a href="/admin/products/deleteproduct?id=<%= products[i]._id %>" class="btn btn-inverse-danger">Delete Item</a> -->
<!-- Button trigger modal -->
<button type="button" class="btn btn-inverse-danger"
<!-- <button type="button" class="btn btn-inverse-danger"
data-bs-toggle="modal"
data-bs-target="#mod<%= products[i]._id %>">
Delete Item
</button>
</button> -->
<!-- Modal -->
<div class="modal fade" id="mod<%= products[i]._id %>" tabindex="-1"
Expand Down

0 comments on commit e44d1f6

Please sign in to comment.