Skip to content
This repository has been archived by the owner on Dec 31, 2023. It is now read-only.

Commit

Permalink
add new product
Browse files Browse the repository at this point in the history
  • Loading branch information
yuhtnguyen committed Dec 7, 2023
1 parent 81559b2 commit cbd36d0
Show file tree
Hide file tree
Showing 5 changed files with 127 additions and 262 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(name = "CategoryManagement", urlPatterns = {"/categorymanagement"})
@MultipartConfig
public class CategoryManagement extends HttpServlet {

@Override
Expand All @@ -25,6 +27,9 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.json.simple.JSONObject;

@WebServlet(name = "ProductManagement", urlPatterns = {"/productmanagement"})
public class ProductManagement extends HttpServlet {
Expand All @@ -21,6 +22,29 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle form submission here
}

@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
int ID = Integer.parseInt(request.getParameter("id"));

Singleton.productDAO.delete(ID);

JSONObject jsonResponse = new JSONObject();
jsonResponse.put("status", "success");
jsonResponse.put("message", "User canceled successfully");

response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());

response.setStatus(HttpServletResponse.SC_OK);

} catch (NumberFormatException ex) {
System.err.println(ex.getMessage());
}
}

}
160 changes: 30 additions & 130 deletions src/main/webapp/assets/js/admin/add-product.js
Original file line number Diff line number Diff line change
@@ -1,136 +1,36 @@
// add-product.js

var currentId = 1;

function openEditModal() {
$('#editProductModal').modal('show');
selectedRowIndex = $(this).closest('tr').index();
}

function populateEditModalFields(row) {
var productName = row.cells[1].textContent.trim();
var category = row.cells[2].textContent.trim();
var price = row.cells[3].textContent.trim();
var amount = row.cells[4].textContent.trim();

document.getElementById('editProductName').value = productName;
document.getElementById('editCategory').value = category;
document.getElementById('editPrice').value = price;
document.getElementById('editAmount').value = amount;
}

function saveChanges() {
var editedProductName = document.getElementById('editProductName').value;
var editedCategory = document.getElementById('editCategory').value;
var editedPrice = document.getElementById('editPrice').value;
var editedAmount = document.getElementById('editAmount').value;

console.log("Edited Product Name:", editedProductName); // ....

var rowToUpdate = $('#datatablesSimple tbody tr').eq(selectedRowIndex);

if (rowToUpdate.length > 0) {
rowToUpdate.find('td:eq(1)').text(editedProductName);
rowToUpdate.find('td:eq(2)').text(editedCategory);
rowToUpdate.find('td:eq(3)').text(editedPrice);
rowToUpdate.find('td:eq(4)').text(editedAmount);

closeAddModal();
} else {
console.error("Row to update not found!");
}
}

function closeAddModal() {
$('#editProductModal').modal('hide');
}

// Function to open the Add Product Modal
function openAddModal() {
$('#addProductName').val('');

$('#addProductModal').modal('show');
}

function closeAddModal() {
$('#addProductModal').modal('hide');
}

function addNewProduct() {
var productName = $('#addProductName').val();
var category = $('#addCategory').val();
var price = $('#addPrice').val();
var amount = $('#addAmount').val();
var currentDateTime = getCurrentDateTime(); // Lấy giá trị ngày hiện tại

console.log("Product Name:", ProductName);
console.log("Current Date/Time:", currentDateTime); // ....
// Còn cột thumnail là upload ảnh lên, GPT nhé

currentId++;

// Tạo dòng mới bằng cách sử dụng template string
var newRow = `
<tr>
<td>${currentId}</td>
<td>${productName}</td>
<td>${category}</td>
<td>${price}</td>
<td>${amount}</td>
<td>NULL</td>
<td>${currentDateTime}</td>
<td>NULL</td>
<td>NULL</td>
<td>
<a href="#" class="btn btn-info btn-tiny" title="Edit"><i class="fa fa-pencil"></i></a>
<button class="btn btn-danger btn-tiny" title="Delete" disabled><i class="fa fa-trash"></i></button>
</td>
</tr>`;

// Thêm dòng vào bảng
$('#datatablesSimple tbody').append(newRow);

closeAddModal();
}


$(document).on('click', '.btn-info.btn-tiny', function() {
openEditModal();
populateEditModalFields($(this).closest('tr')[0]);
});

$(document).on('click', '#addProductBtn', function() {
openAddModal();
});

$(document).on('click', '#cancelAddBtn', function() {
closeAddModal();
});

$(document).on('click', '#saveChangesBtn', function() {
saveChanges();
// Function to handle form submission
$(document).ready(function () {
$('#addProductForm').submit(function (e) {
e.preventDefault();

// Serialize form data
var formData = $(this).serialize();

// AJAX request to send form data to the server for processing
$.ajax({
type: 'POST',
url: 'productmanagement', // Update with the actual URL
data: formData,
success: function (response) {
// Handle success response
console.log(response);

// Close the modal after successful submission
$('#addProductModal').modal('hide');

// Optionally, you can update the product list or perform other actions
},
error: function (error) {
// Handle error response
console.error(error.responseText);
}
});
});
});

$(document).on('click', '#cancelChangesBtn', function() {
closeEditModal();
});



function getCurrentDateTime() {
var currentDate = new Date();

var year = currentDate.getFullYear();
var month = ('0' + (currentDate.getMonth() + 1)).slice(-2); // Thêm '0' và cắt chỉ lấy hai số cuối cùng
var day = ('0' + currentDate.getDate()).slice(-2);
var hours = ('0' + currentDate.getHours()).slice(-2);
var minutes = ('0' + currentDate.getMinutes()).slice(-2);
var seconds = ('0' + currentDate.getSeconds()).slice(-2);

// Định dạng theo yêu cầu "YYYY-MM-DD HH:mm:ss"
var formattedDateTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;

return formattedDateTime;
}

// Sử dụng hàm để cập nhật giá trị ngày hiện tại
var currentDateTime = getCurrentDateTime();
console.log(currentDateTime);
76 changes: 47 additions & 29 deletions src/main/webapp/assets/js/admin/delete-product.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,48 @@
var selectedProductRowIndex;
function deleteProduct(id) {
Swal.fire({
title: "Delete product?",
text: "You really want to delete this product?",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Delete!",
cancelButtonText: "No!"
}).then((result) => {
if (result.isConfirmed) {
const url = "productmanagement?id=" + id;

function openDeleteModal() {
$('#deleteProductModal').modal('show');
// Lưu index của hàng được chọn
selectedProductRowIndex = $(this).closest('tr').index();
}

function closeDeleteModal() {
$('#deleteProductModal').modal('hide');
}

function deleteProduct() {
console.log("Deleting product...");

// Thực hiện các bước cần thiết để xóa user
// ...

// Xóa hàng trong bảng
var rowToDelete = $('#datatablesSimple tbody tr').eq(selectedProductRowIndex);
rowToDelete.remove();

// Đóng modal
closeDeleteModal();
}

// Event delegation to handle dynamically added elements
$(document).on('click', '.btn-danger', function() {
openDeleteModal();
});
$.ajax({
url: url,
type: "DELETE",
dataType: "json",
success: function (data) {
if (data.status === "success") {
Swal.fire({
title: "Success!",
text: "You delete product success!",
icon: "success"
}).then((result) => {
if (result.isConfirmed) {
window.location.reload();
}
});
} else {
Swal.fire({
title: "Oops...",
text: "Something was wrong!",
icon: "error"
});
}
},
error: function () {
Swal.fire({
title: "Oops...",
text: "Something was wrong when send the request!",
icon: "error"
});
}
});
}
});
}
Loading

0 comments on commit cbd36d0

Please sign in to comment.