Product & Item Button Update

This commit is contained in:
ArifHilmi 2025-03-19 08:29:30 +08:00
parent bad7c62bbb
commit 4de1a6633c
4 changed files with 403 additions and 138 deletions

View File

@ -80,14 +80,14 @@
<div class="modal-dialog modal-dialog-centered modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addItemModalLabel">Add Item</h5>
<h5 class="modal-title" id="addItemModalLabel">{{editSection? 'Edit Item' : 'Add Item'}}</h5>
<button type="button" class="closeModal" data-dismiss="modal" aria-label="Close" v-on:click="showItemModal=false">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="container-fluid">
<form v-on:submit.prevent="addItem" data-aos="fade-right">
<form v-on:submit.prevent="editSection ? submitEditItem() : addItem()" data-aos="fade-right">
<div class=" register" data-aos="fade-right">
<div class="row" data-aos="fade-right">
@ -95,7 +95,7 @@
<div class="col-md-12">
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<h3 class="register-heading">REGISTRATION ITEM</h3>
<h3 class="register-heading">{{editSection? 'EDIT ITEM' : 'REGISTRATION ITEM'}}</h3>
<div class="row register-form">
<div class="col-md-6">
@ -367,6 +367,8 @@
$('#addItemBtn').on('click', function () {
// Show the modal with the ID 'addManufacturerModal'.
$('#registerItemModal').modal('show');
this.addSection = true;
this.editSection = false;
});
$('.closeModal').on('click', function () {
// Show the modal with the ID 'addManufacturerModal'.
@ -394,7 +396,10 @@
teamType: "",
productName: null,
imageProduct: null,
addSection: false,
editSection: false,
productCategory: null,
itemID: null,
serialNumber: "",
quantity: 1,
supplierName: null,
@ -450,6 +455,19 @@
this.fetchCompanies();
this.fetchProducts();
this.fetchSuppliers();
document.getElementById('addItemBtn').addEventListener('click', () => {
this.resetForm();
this.addSection = true;
this.editSection = false;
$('#registerItemModal').modal('show');
});
document.querySelectorAll('.closeModal').forEach(btn => {
btn.addEventListener('click', () => {
$('.modal').modal('hide');
});
});
},
computed: {
filteredDepartments() {
@ -640,6 +658,15 @@
Station: ${currentStation}`
}
},
{
"title": "Edit",
"data": "itemID",
"render": function (data) {
var editButton = `<button type="button" class="btn btn-success edit-btn" data-id="${data}">Edit</button>`;
return editButton;
},
"className": "align-middle",
},
{
"title": "Delete",
"data": "itemID",
@ -685,6 +712,12 @@
}
})
// Attach click event listener to the edit buttons
$('#itemDatatable tbody').off('click', '.edit-btn').on('click', '.edit-btn', function () {
const itemId = $(this).data('id');
self.editItem(itemId);
});
// Attach click event listener to the delete buttons
$('#itemDatatable tbody').off('click', '.delete-btn').on('click', '.delete-btn', function () {
const itemId = $(this).data('id');
@ -854,24 +887,7 @@
// .replace(/^(\d*\.\d{0,2})\d*$/, '$1'); // Limit to two decimal places
},
calculateWarrantyEndDate() {
// Check if DODate and warranty are valid
if (!this.DODate || isNaN(Date.parse(this.DODate))) {
this.EndWDate = null;
return;
}
const DODates = new Date(this.DODate);
const warrantyMonth = parseInt(this.warranty);
// Ensure warranty is a valid number
if (!isNaN(warrantyMonth)) {
DODates.setMonth(DODates.getMonth() + warrantyMonth);
this.EndWDate = DODates.toISOString().split('T')[0];
} else {
this.EndWDate = null;
}
},
async deleteItem(itemId) {
if (!confirm("Are you sure you want to delete this item?")) {
return;
@ -902,6 +918,127 @@
this.loading = false;
}
},
async editItem(itemID) {
// Cari data item yang dipilih
const item = this.items.find(s => s.itemID === itemID);
if (!item) {
alert('Error', 'Item not found!', 'warning');
return;
}
// Populate form fields
this.itemID = itemID;
this.selectedCompany = item.companyId;
this.selectedDepartment = item.departmentId;
this.selectedProduct = item.productId;
this.serialNumber = item.serialNumber;
this.quantity = item.quantity;
this.selectedSupplier = item.supplier;
this.purchaseDate = item.purchaseDate.split('/').reverse().join('-');
this.PO = item.poNo;
this.currency = item.currency;
this.DefaultPrice = item.defaultPrice;
this.currencyRate = item.currencyRate;
this.convertPrice = item.convertPrice;
this.DONo = item.doNo;
this.DODate = item.doDate ? item.doDate.split('T')[0] : null;
this.warranty = item.warranty;
this.EndWDate = item.endWDate.split('/').reverse().join('-');
this.invoiceNo = item.invoiceNo;
this.invoiceDate = item.invoiceDate.split('/').reverse().join('-');
this.selectedTeamType = item.teamType;
this.partNumber = item.partNumber;
// Tunjukkan modal edit
$('#registerItemModal').modal('show');
this.addSection = false;
this.editSection = true;
},
async submitEditItem() {
// List of required fields
const requiredFields = ['DefaultPrice', 'DONo', 'DODate', 'warranty', 'invoiceNo', 'invoiceDate'];
// Loop through required fields and check if any are null or empty
for (let field of requiredFields) {
if (this[field] === null || this[field] === '') {
alert('Item Error', `Please fill in required fields: ${field}.`, 'warning');
return;
}
}
if (this.showProduct.category == "Disposable") {
this.serialNumber = "";
}
const formData = {
itemId : this.itemID,
CompanyId: this.selectedCompany,
DepartmentId: this.selectedDepartment,
ProductId: this.selectedProduct,
SerialNumber: this.serialNumber,
Quantity: this.quantity,
Supplier: this.selectedSupplier,
PurchaseDate: this.purchaseDate,
PONo: this.PO,
Currency: this.currency,
DefaultPrice: this.DefaultPrice,
CurrencyRate: this.currencyRate,
ConvertPrice: this.convertPrice,
DONo: this.DONo,
DODate: this.DODate,
Warranty: this.warranty,
EndWDate: this.EndWDate,
InvoiceNo: this.invoiceNo,
InvoiceDate: this.invoiceDate,
TeamType: this.selectedTeamType,
PartNumber: this.partNumber,
};
try {
// Additional specific checks
if (this.showSerialNumber) {
this.quantity = 0;
if (this.serialNumber === null || this.serialNumber === '') {
alert('Serial Number Error', 'Serial Number must be filled when selecting Item or Part.', 'warning');
return;
}
}
else {
this.serialNumber = null;
if (this.quantity === 0 || this.quantity === null || this.quantity === '') {
alert('quantity Error', 'Quantity is required when selecting Disposable.', 'warning');
return;
}
}
const response = await fetch('/InvMainAPI/EditItem', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
if (!response.ok) {
const errorData = await response.json();
console.error('Error response:', errorData);
this.errorMessage = 'Error: ' + (errorData.message || 'Unknown error');
return;
}
// Refresh station list and reset form
alert('Success!', 'Item form has been successfully submitted.', 'success');
this.fetchItem();
this.resetForm();
this.editSection = false;
this.addSection = false;
$('.modal').modal('hide');
} catch (error) {
console.error('Error editing Item:', error);
this.errorMessage = 'Error: ' + error.message;
}
},
async printItem(itemId, imgSrc) {
try {
this.thisQRInfo.uniqueID = itemId;

View File

@ -99,11 +99,11 @@
</div>
</form>
<div class="row">
<button class="btn btn-danger col-md-3 m-1" v-on:click="addSection = false; resetForm"><i class="fa fa-minus"></i>&nbsp;Hide Add Product Section</button>
<button class="btn btn-danger col-md-3 m-1" v-on:click=" resetForm(); addSection = false;"><i class="fa fa-minus"></i>&nbsp;Hide Add Product Section</button>
</div>
</div>
<div class="row" v-if="editSection == true">
<form v-on:submit.prevent="editProduct" data-aos="fade-right">
<form v-on:submit.prevent="submitEditProduct" data-aos="fade-right">
<div class="container register" data-aos="fade-right">
<div class="row" data-aos="fade-right">
<div class="col-md-12">
@ -173,12 +173,14 @@
<div class="form-group row">
<label for="imageProduct" class="col-sm-3">Image:</label>
<div class="col-sm-9">
<input type="file" id="imageProduct" name="imageProduct" class="form-control" v-on:change="previewImage" accept="image/*" required>
<input type="file" id="imageProduct" name="imageProduct" class="form-control" v-on:change="previewImage" accept="image/*" ref="fileInput">
<small v-if="existingFileName">{{ existingFileName }}</small>
<br>
<img v-if="imageSrc" :src="imageSrc" alt="Image Preview" class="img-thumbnail" style="width: 200px; margin-top: 10px;" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-9 offset-sm-3">
@ -194,11 +196,11 @@
</div>
</form>
<div class="row">
<button class="btn btn-danger col-md-3 m-1" v-on:click="editSection = false; addSection = false; resetForm"><i class="fa fa-minus"></i>&nbsp;Hide Edit Product Section</button>
<button class="btn btn-danger col-md-3 m-1" v-on:click=" resetForm(); editSection = false; addSection = false;"><i class="fa fa-minus"></i>&nbsp;Hide Edit Product Section</button>
</div>
</div>
<div class="row">
<button id="addProductBtn" class="btn btn-success col-md-3 m-1" v-show="addSection == false" v-on:click="addSection = true; editSection = false; resetForm"><i class="fa fa-plus"></i>&nbsp;Show Add Product Section</button>
<button id="addProductBtn" class="btn btn-success col-md-3 m-1" v-show="addSection == false" v-on:click="resetForm(); addSection = true; editSection = false;"><i class="fa fa-plus"></i>&nbsp;Show Add Product Section</button>
</div>
<div class="row table-responsive">
<table class="table table-bordered table-hover table-striped no-wrap" id="productDatatable" style="width:100%;border-style: solid; border-width: 1px"></table>
@ -233,37 +235,48 @@
products: null,
productDatatable: null,
productShortName: null,
existingFileName: null,
}
},
mounted() {
// Fetch companies, depts, and products from the API
this.fetchManufactures();
this.fetchProducts();
},
computed() {
},
methods: {
initiateTable() {
this.productDatatable = $('#productDatatable').DataTable({
"data": this.products,
"columns": [
{ "title": "Product Name",
{
"title": "Product Name",
"data": "productName",
},
{ "title": "Product Short Name",
{
"title": "Product Short Name",
"data": "productShortName",
},
{ "title": "Model Number",
{
"title": "Model Number",
"data": "modelNo",
},
{ "title": "Manufacturer",
{
"title": "Manufacturer",
"data": "manufacturer.manufacturerName",
},
{ "title": "Product Category",
{
"title": "Product Category",
"data": "category",
},
{ "title": "Product Stock",
{
"title": "Product Stock",
"data": "quantityProduct",
},
{ "title": "Image",
{
"title": "Image",
"data": "imageProduct",
"render": function (data, type, full, meta) {
var image = `<a href="${data}" target="_blank" data-lightbox="image-1">
@ -290,7 +303,7 @@
}
],
responsive:true,
responsive: true,
})
self = this;
@ -301,7 +314,7 @@
});
// Attach click event listener to the delete buttons
$('#productDatatable tbody').on('click', '.delete-btn', function () {
$('#productDatatable tbody').off('click', '.delete-btn').on('click', '.delete-btn', function () {
const productId = $(this).data('id'); // Get the manufacturer ID from the button
self.deleteProduct(productId); // Call the Vue method
});
@ -314,8 +327,7 @@
})
.then(response => response.json())
.then(data => {
if (data != null && data.length > 0)
{
if (data != null && data.length > 0) {
this.manufacturers = data;
}
})
@ -325,13 +337,16 @@
},
async fetchProducts() {
try {
const response = await fetch('/InvMainAPI/ProductList',{
const response = await fetch('/InvMainAPI/ProductList', {
method: 'POST'
}); // Call the API
if (!response.ok) {
throw new Error('Failed to fetch products');
}
this.products = await response.json(); // Store the fetched products
if (this.productDatatable) {
this.productDatatable.clear().destroy();
}
this.$nextTick(() => {
this.initiateTable()
})
@ -352,19 +367,22 @@
this.productName = product.productName;
this.stationName = product.stationName;
this.productShortName = product.productShortName;
this.manufacturers = product.manufacturer;
this.manufacturer = product.manufacturer.manufacturerId;
this.category = product.category;
this.modelNo = product.modelNo;
console.log(this.manufactures);
this.imageProduct = product.imageProduct;
this.previewImage(this.imageProduct);
// Show the edit form and hide the add form
this.addSection = false;
this.editSection = true;
},
async submitEditProduct() {
const formData = {
ProductId: this.productId,
productName: this.stationName,
productName: this.productName,
ProductShortName: this.productShortName,
ManufacturerId: this.manufacturer,
category: this.category,
@ -399,11 +417,12 @@
}
// Refresh station list and reset form
await this.fetchProducts();
alert('Success!', 'Product form has been successfully submitted.', 'success');
this.fetchProducts();
this.resetForm();
this.editSection = false;
} catch (error) {
console.error('Error editing station:', error);
console.error('Error editing Product:', error);
this.errorMessage = 'Error: ' + error.message;
}
},
@ -466,6 +485,7 @@
resetForm() {
this.productName = null;
this.manufacturer = '';
this.productShortName = '';
this.category = '';
this.modelNo = null;
this.imageProduct = null;
@ -494,18 +514,25 @@
// User Inserting an Image
previewImage(event) {
const file = event.target.files[0];
if (typeof event === "string") {
this.imageSrc = event;
this.existingFileName = event.split('/').pop(); // Ambil nama fail daripada URL
return;
}
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
this.imageSrc = e.target.result; // Show the image preview
this.imageProduct = e.target.result.split(',')[1]; // Get Base64 string (remove metadata)
this.imageSrc = e.target.result;
this.imageProduct = e.target.result.split(',')[1];
this.existingFileName = file.name; // Simpan nama fail
};
reader.readAsDataURL(file);
} else {
this.imageSrc = '';
this.imageProduct = null;
this.existingFileName = null;
}
},
async deleteProduct(productId) {

View File

@ -199,7 +199,7 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
try
{
var productImage = editedProduct.ImageProduct; // Save image to wwwroot/media/inventory/images | Images name is product.ModelNo | product.ImageProduct is in base64 string
if (!string.IsNullOrEmpty(editedProduct.ImageProduct))
if (product.ImageProduct != editedProduct.ImageProduct)
{
var bytes = Convert.FromBase64String(editedProduct.ImageProduct);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/media/inventory/images", editedProduct.ModelNo + ".jpg");
@ -368,7 +368,10 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
item.Supplier,
PurchaseDate = item.PurchaseDate.ToString("dd/MM/yyyy"),
item.PONo,
item.DONo,
item.Currency,
item.InvoiceNo,
item.TeamType,
item.DefaultPrice,
item.CurrencyRate,
item.ConvertPrice,
@ -512,6 +515,104 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
}
}
[HttpPost("EditItem")]
public async Task<IActionResult> EditItem([FromBody] ItemModel item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var savedItem = await _centralDbContext.Items.FirstOrDefaultAsync(i => i.ItemID == item.ItemID);
if (savedItem == null)
{
return NotFound(new { success = false, message = "Item not found" });
}
var product = await _centralDbContext.Products.FirstOrDefaultAsync(p => p.ProductId == item.ProductId) ?? throw new Exception("Product not found");
if (product.Category == "Disposable")
{
item.SerialNumber = null;
}
savedItem.ItemID = item.ItemID;
savedItem.DefaultPrice = item.DefaultPrice;
savedItem.CompanyId = item.CompanyId;
savedItem.DepartmentId = item.DepartmentId;
savedItem.ProductId = item.ProductId;
savedItem.SerialNumber = item.SerialNumber;
savedItem.TeamType = item.TeamType;
savedItem.Quantity = item.Quantity;
savedItem.Supplier = item.Supplier;
savedItem.PurchaseDate = item.PurchaseDate;
savedItem.PONo = item.PONo;
savedItem.Currency = item.Currency;
savedItem.CurrencyRate = item.CurrencyRate;
savedItem.ConvertPrice = item.ConvertPrice;
savedItem.DONo = item.DONo;
savedItem.DODate = item.DODate;
savedItem.Warranty = item.Warranty;
savedItem.EndWDate = item.EndWDate;
savedItem.InvoiceNo = item.InvoiceNo;
savedItem.InvoiceDate = item.InvoiceDate;
savedItem.PartNumber = item.PartNumber;
savedItem.UniqueID = item.PartNumber;
_centralDbContext.Items.Update(savedItem);
await _centralDbContext.SaveChangesAsync(); // This generates the auto-incremented ItemID
if (savedItem != null)
{
var companyDepartment = await GetDepartmentWithCompany(item.CompanyId, item.DepartmentId);
var itemProduct = _centralDbContext.Products.Where(p => p.ProductId == item.ProductId).FirstOrDefault();
string? companyInitial = companyDepartment!.CompanyName?.ToString().Substring(0, 1).ToUpper();
string? departmentInitial = companyDepartment!.DepartmentName?.ToString().Substring(0, 1).ToUpper();
string? deptCode = companyDepartment!.DepartmentCode?.ToString();
char? initialCategory = itemProduct!.Category.ToString().Substring(0, 1).ToUpper().FirstOrDefault();
string? productId = itemProduct!.ProductId.ToString("D3");
string? itemId = item.ItemID.ToString("D5");
var uniqueId = $"{deptCode}{initialCategory}{productId}{itemId}".ToUpper();
savedItem.UniqueID = uniqueId;
_centralDbContext.Items.Update(savedItem);
await _centralDbContext.SaveChangesAsync();
}
var updatedItem = new
{
savedItem!.ItemID,
savedItem.UniqueID,
savedItem.CompanyId,
savedItem.DepartmentId,
savedItem.ProductId,
savedItem.SerialNumber,
savedItem.Quantity,
savedItem.Supplier,
savedItem.PurchaseDate,
savedItem.PONo,
savedItem.Currency,
savedItem.DefaultPrice,
savedItem.CurrencyRate,
savedItem.ConvertPrice,
savedItem.DODate,
savedItem.Warranty,
savedItem.EndWDate,
savedItem.InvoiceDate,
savedItem.PartNumber,
};
return Json(updatedItem);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete("DeleteItem/{id}")]
public async Task<IActionResult> DeleteItem(int id)
{

View File

@ -3,7 +3,7 @@
//"DefaultConnection": "Server=localhost;uid=root;Password='';Database=web_interface;"
//"DefaultConnection": "server=175.136.244.102;user id=root;password=tw_mysql_root;port=3306;database=web_interface"
//"CentralConnnection": "Server=192.168.12.12;Port=3306;uid=installer;password='pstw_mysql_installer';database=pstw_cs;", //DB_dev Local connection
"CentralConnnection": "Server=219.92.7.60;Port=3307;uid=installer;password='pstw_mysql_installer';database=pstw_cs;" //DB_dev Public connection
"CentralConnnection": "Server=219.92.7.60;Port=3307;uid=installer;password='pstw_mysql_installer';database=pstw_cs_prod;" //DB_dev Public connection
//"InventoryConnection": "Server=219.92.7.60;Port=3307;uid=installer;password='pstw_mysql_installer';database=pstw_cs_inventory;" //DB_dev connection
//"DefaultConnection": "Server=219.92.7.60;Port=3307;uid=intern;password='intern_mysql_acct';database=web_interface;"//DB_dev connection
},