Update Item & Station

This commit is contained in:
ArifHilmi 2025-03-17 10:31:07 +08:00
parent 00a040c0ed
commit f4280b9645
8 changed files with 414 additions and 20 deletions

View File

@ -614,7 +614,7 @@
},
{
"title": "Price(RM)",
"data": "convertPrice",
"data": (row) => parseFloat(row.convertPrice).toFixed(2),
},
{
"title": "Register Date",

View File

@ -65,8 +65,8 @@
<h2 for="sortSelect" class="col-sm-1 col-form-h2" style="min-width:150px;">Sort by:</h2>
<div class="col-sm-4">
<select id="sortSelect" class="form-control" v-model="sortBy" v-on:change="handleSorting">
<option value="tech">Technician</option>
<option value="master">Inventory Master</option>
<option value="tech">Technician -> Inventory Master</option>
<option value="master">Inventory Master -> Inventory Master</option>
</select>
</div>
</div>
@ -407,7 +407,6 @@
</div>
</div>
</div>
</div>
@section Scripts {

View File

@ -99,11 +99,106 @@
</div>
</form>
<div class="row">
<button class="btn btn-danger col-md-3 m-1" v-on:click="addSection = false"><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="addSection = false; resetForm"><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">
<div class="container register" data-aos="fade-right">
<div class="row" data-aos="fade-right">
<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">
<div class="card-header">
<h3 class="register-heading">EDIT PRODUCT</h3>
</div>
<div class="row register-form card-body">
<div class="col-md-6">
@* Product Name *@
<div class="form-group row">
<label for="productName" class="col-sm-3">Product Name:</label>
<div class="col-sm-9">
<input type="text" id="productName" name="productName" class="form-control" required v-model="productName">
</div>
</div>
@* Product Short Name *@
<div class="form-group row">
<label for="productName" class="col-sm-3">Product Short Name:</label>
<div class="col-sm-9">
<input type="text" id="productShortName" name="productShortName" class="form-control" maxlength="13" v-model="productShortName" required>
<p><em><small class="text-danger">* Product short name limited to 13 characters</small></em></p>
</div>
</div>
@* Manufacturer *@
<div class="form-group row">
<label class="col-sm-3">Manufacturer:</label>
<div class="col-sm-9">
<div class="">
<select class="btn btn-primary form-select" v-model="manufacturer" required>
<option class="btn-light" value="" selected disabled>Select Manufacturer</option>
<option class="btn-light" v-for="(item, index) in manufacturers" :key="item.manufacturerId" :value="item.manufacturerId">{{ item.manufacturerName ?? 'Select Manufacturer' }}</option>
</select>
</div>
</div>
</div>
@* Category *@
<div class="form-group row">
<label class="col-sm-3">Category:</label>
<div class="col-sm-9">
<div class="">
<select class="btn btn-primary form-select" v-model="category" required>
<option class="btn-light" value="" selected disabled>Select Category</option>
<option class="btn-light" v-for="(item, index) in categories" :key="item" :value="item">{{ item ?? 'Select Category' }}</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-6">
@* Model No Coding *@
<div class="form-group row">
<label for="modelNo" class="col-sm-3">Model No:</label>
<div class="col-sm-9">
<input type="text" id="modelNo" name="modelNo" class="form-control" required v-model="modelNo">
</div>
</div>
@* Image Product Coding *@
<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>
<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">
<button type="button" v-on:click="resetForm" class="btn btn-secondary mx-1">Reset</button>
<input type="submit" class="btn btn-primary mx-1">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</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>
</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"><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="addSection = true; editSection = false; resetForm"><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>
@ -122,6 +217,8 @@
const app = Vue.createApp({
data() {
return {
editSection: null,
productId: null,
addSection: false,
productName: null,
manufacturer: '',
@ -175,6 +272,14 @@
return image;
},
},
{
"title": "Edit",
"data": "productId",
"render": function (data) {
var editButton = `<button type="button" class="btn btn-success edit-btn" data-id="${data}">Edit</button>`;
return editButton;
},
},
{
"title": "Delete",
"data": "productId",
@ -188,6 +293,13 @@
responsive:true,
})
self = this;
// Attach click event listener to the edit buttons
$('#productDatatable tbody').off('click', '.edit-btn').on('click', '.edit-btn', function () {
const productId = $(this).data('id');
self.editProduct(productId);
});
// Attach click event listener to the delete buttons
$('#productDatatable tbody').on('click', '.delete-btn', function () {
const productId = $(this).data('id'); // Get the manufacturer ID from the button
@ -227,6 +339,75 @@
console.error('Error fetching products:', error);
}
},
async editProduct(productId) {
// Find the selected station data
const product = this.products.find(s => s.productId === productId);
if (!product) {
alert('Error', 'Product not found!', 'warning');
return;
}
// Populate form fields
this.productId = productId;
this.productName = product.productName;
this.stationName = product.stationName;
this.productShortName = product.productShortName;
this.manufacturers = product.manufacturer;
this.category = product.category;
this.modelNo = product.modelNo;
console.log(this.manufactures);
// 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,
ProductShortName: this.productShortName,
ManufacturerId: this.manufacturer,
category: this.category,
ModelNo: this.modelNo,
ImageProduct: this.imageProduct
};
try {
// List of required fields
const requiredFields = ['productName', 'manufacturer', 'category', 'modelNo', 'imageProduct'];
// Loop through required fields and check if any are null or empty
for (let field of requiredFields) {
if (this[field] === null || this[field] === '') {
alert('Product Error', `Please fill in required fields: ${field}.`, 'warning');
return; // Exit early if validation fails
}
}
const response = await fetch('/InvMainAPI/EditProduct', {
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
await this.fetchProducts();
this.resetForm();
this.editSection = false;
} catch (error) {
console.error('Error editing station:', error);
this.errorMessage = 'Error: ' + error.message;
}
},
async addProduct() {
// const existingProduct = this.products.find(p => p.modelNo === this.modelNo);
// if (existingProduct) {

View File

@ -51,6 +51,66 @@
</div>
</div>
<div class="form-group row">
<div class="col-sm-9 offset-sm-3">
<button type="button" v-on:click="resetForm" class="btn btn-secondary m-1">Reset</button>
<button type="submit" class="btn btn-primary m-1">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<form v-on:submit.prevent="submitEditStation" data-aos="fade-right" id="editStationForm" v-if="editStationForm">
<div class="container register" data-aos="fade-right">
<div class="row">
<div class="col-md-9 register-rights" data-aos="fade-right">
<div class="tab-content" id="myTabContent" data-aos="fade-right">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab" data-aos="fade-right">
<h3 class="register-heading">EDIT STATION</h3>
<div class="row register-form">
<div class="col-md-61">
@* Station Name *@
<div class="form-group row">
<label for="stationName" class="col-sm-3">Station Name:</label>
<div class="col-sm-9">
<input type="text" id="stationName" name="stationName" class="form-control" required v-model="stationName">
</div>
</div>
@* User ID *@
<div class="form-group row">
<label class="col-sm-4 col-form-label">Station User PIC</label>
<div class="col-sm-8">
<div class="">
<select class="btn btn-primary form-select" v-model="selectedUserName" :disabled="currentUser != null" required v-on:change="updateDepartment()">
<option class="btn-light" value="" disabled selected>Select User</option>
<option class="btn-light" v-for="(technicianUser, index) in users" :key="index" :value="technicianUser.fullName">
{{ technicianUser.fullName }}
</option>
</select>
</div>
</div>
</div>
@* Department ID *@
<!-- Department Dropdown -->
<div class="form-group row">
<label class="col-sm-4 col-form-label">Department: </label>
<div class="col-sm-8">
<!-- Use a span to keep the same space occupied -->
<span v-if="selectedDepartment">{{ selectedDepartment }}</span>
<span v-else>No department assigned</span>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-9 offset-sm-3">
@ -95,6 +155,7 @@
const app = Vue.createApp({
data() {
return {
stationId: null,
stationName: null,
stationUserPIC: null,
departmentId : null,
@ -104,6 +165,7 @@
currentUser: null,
users : null,
registerStationForm: false,
editStationForm: false,
}
},
mounted() {
@ -235,6 +297,14 @@
"title": "Department",
"data": "departmentName",
},
{
"title": "Edit",
"data": "stationId",
"render": function (data) {
var editButton = `<button type="button" class="btn btn-success edit-btn" data-id="${data}">Edit</button>`;
return editButton;
},
},
{
"title": "Delete",
"data": "stationId",
@ -247,6 +317,11 @@
responsive: true,
})
// Attach click event listener to the edit buttons
$('#stationDatatable tbody').off('click', '.edit-btn').on('click', '.edit-btn', function () {
const stationId = $(this).data('id');
self.editStation(stationId);
});
// Attach click event listener to the delete buttons
$('#stationDatatable tbody').off('click', '.delete-btn').on('click', '.delete-btn', function () {
@ -266,6 +341,70 @@
this.selectedDepartment = selectedUser.department.departmentName; // Set department name
}
},
async editStation(stationId) {
// Find the selected station data
const station = this.stations.find(s => s.stationId === stationId);
if (!station) {
alert('Error', 'Station not found!', 'warning');
return;
}
// Populate form fields
this.stationId = stationId;
this.stationName = station.stationName;
this.selectedUserName = station.fullName;
this.departmentId = station.departmentId;
this.selectedDepartment = station.departmentName;
this.stationUserPIC = station.stationPicID;
// Show the edit form and hide the add form
this.registerStationForm = false;
this.editStationForm = true;
},
async submitEditStation() {
const formData = {
StationId: this.stationId,
StationName: this.stationName,
StationPicID: this.stationUserPIC,
DepartmentId: this.departmentId,
};
try {
// Ensure all required fields are filled
const requiredFields = ['stationName', 'stationUserPIC', 'departmentId'];
for (let field of requiredFields) {
if (!this[field]) {
alert('Error', `Please fill in required fields: ${field}`, 'warning');
return;
}
}
const response = await fetch('/InvMainAPI/EditStation', {
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
await this.fetchStations();
this.resetForm();
this.editStationForm = false;
} catch (error) {
console.error('Error editing station:', error);
this.errorMessage = 'Error: ' + error.message;
}
},
async deleteStation(stationId) {
if (!confirm("Are you sure you want to delete this station?")) {
return;

View File

@ -94,7 +94,7 @@
<h1 class="font-light text-white">
<i class="mdi mdi-checkbox-multiple-blank-circle"></i>
</h1>
<h6 class="text-white">QR Scanner</h6>
<h6 class="text-white">Scan Items</h6>
</div>
</a>
</div>

View File

@ -20,7 +20,7 @@
<h1 class="font-light text-white">
<i class="mdi mdi-checkbox-multiple-blank-circle"></i>
</h1>
<h6 class="text-white">QR Scanner</h6>
<h6 class="text-white">Scan Items</h6>
</div>
</a>
</div>

View File

@ -183,6 +183,50 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
}
}
[HttpPost("EditProduct")]
public async Task<IActionResult> EditProduct([FromBody] ProductModel editedProduct)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var product = await _centralDbContext.Products.FindAsync(editedProduct.ProductId);
if (product == null)
{
return NotFound("Product is null");
}
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))
{
var bytes = Convert.FromBase64String(editedProduct.ImageProduct);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/media/inventory/images", editedProduct.ModelNo + ".jpg");
await System.IO.File.WriteAllBytesAsync(filePath, bytes);
editedProduct.ImageProduct = "/media/inventory/images/" + editedProduct.ModelNo + ".jpg";
}
product.ProductName = editedProduct.ProductName;
product.ProductShortName = editedProduct.ProductShortName;
product.ManufacturerId = editedProduct.ManufacturerId;
product.Category = editedProduct.Category;
product.ModelNo = editedProduct.ModelNo;
product.ImageProduct = editedProduct.ImageProduct;
_centralDbContext.Products.Update(product);
await _centralDbContext.SaveChangesAsync();
var updatedList = await _centralDbContext.Products.Include("Manufacturer").Where(x => x.ManufacturerId == x.ManufacturerId).ToListAsync();
return Json(updatedList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete("DeleteProduct/{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
@ -383,7 +427,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
var product = await _centralDbContext.Products.FirstOrDefaultAsync(p => p.ProductId == item.ProductId) ?? throw new Exception("Product not found");
var inventoryMaster = await _centralDbContext.InventoryMasters.Include("User").FirstOrDefaultAsync(i => i.UserId == item.CreatedByUserId) ?? new InventoryMasterModel{ UserId = item.CreatedByUserId };
var addToProduct = item.Quantity;
product.QuantityProduct += addToProduct;
if (product.Category == "Disposable")
{
@ -391,6 +434,8 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
}
_centralDbContext.Items.Add(item);
product.QuantityProduct += addToProduct;
_centralDbContext.Products.Update(product);
await _centralDbContext.SaveChangesAsync(); // This generates the auto-incremented ItemID
@ -476,6 +521,11 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
return NotFound(new { success = false, message = "Item not found" });
}
var products = _centralDbContext.Products
.FirstOrDefault(i => i.ProductId == item.ProductId);
products.QuantityProduct = products.QuantityProduct - 1;
// Get related item movements
var itemMovements = await _centralDbContext.ItemMovements
.Where(i => i.ItemId == item.ItemID)
@ -488,6 +538,10 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
await _centralDbContext.SaveChangesAsync();
}
//Handle Rules kalau itemMovement dia xde kat store
_centralDbContext.Products.Update(products);
// Remove the item itself
_centralDbContext.Items.Remove(item);
await _centralDbContext.SaveChangesAsync();
@ -1265,6 +1319,27 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
}
}
[HttpPost("EditStation")]
public async Task<IActionResult> EditStation([FromBody] StationModel updatedStation)
{
var station = await _centralDbContext.Stations.FindAsync(updatedStation.StationId);
if (station == null)
{
return NotFound(new { success = false, message = "Station not found" });
}
station.StationId = updatedStation.StationId;
station.StationPicID = updatedStation.StationPicID;
station.StationName = updatedStation.StationName;
station.DepartmentId = updatedStation.DepartmentId;
_centralDbContext.Stations.Update(station);
await _centralDbContext.SaveChangesAsync();
return Ok(new { success = true, message = "Station Updated successfully" });
}
[HttpDelete("DeleteStation/{id}")]
public async Task<IActionResult> DeleteStation(int id)
{

View File

@ -355,7 +355,7 @@
<!-- ============================================================== -->
<!-- User profile and search -->
<!-- ============================================================== -->
<li class="nav-item dropdown">
@* <li class="nav-item dropdown">
<a class="
nav-link
dropdown-toggle
@ -375,14 +375,14 @@
</a>
<ul class="dropdown-menu dropdown-menu-end user-dd animated"
aria-labelledby="navbarDropdown">
@* <a class="dropdown-item" href="javascript:void(0)"><i class="mdi mdi-account me-1 ms-1"></i> My Profile</a>
<a class="dropdown-item" href="javascript:void(0)"><i class="mdi mdi-account me-1 ms-1"></i> My Profile</a>
<a class="dropdown-item" href="javascript:void(0)"><i class="mdi mdi-wallet me-1 ms-1"></i> My Balance</a>
<a class="dropdown-item" href="javascript:void(0)"><i class="mdi mdi-email me-1 ms-1"></i> Inbox</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="javascript:void(0)">
<i class="mdi mdi-settings me-1 ms-1"></i> Account
Setting
</a> *@
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="javascript:void(0)"><i class="fa fa-power-off me-1 ms-1"></i> Logout</a>
<div class="dropdown-divider"></div>
@ -391,7 +391,7 @@
class="btn btn-sm btn-success btn-rounded text-white">View Profile</a>
</div>
</ul>
</li>
</li> *@
<!-- ============================================================== -->
<!-- User profile and search -->
<!-- ============================================================== -->