update inventory

This commit is contained in:
Naz 2025-07-22 10:09:06 +08:00
parent d671db342a
commit 1922f78cef
9 changed files with 869 additions and 583 deletions

View File

@ -47,4 +47,12 @@ namespace PSTW_CentralSystem.Areas.Inventory.Models
public virtual ItemMovementModel? Movement { get; set; }
}
public class ItemQuantityUpdateModel
{
public int ItemId { get; set; }
public int Quantity { get; set; }
public int MovementId { get; set; }
}
}

View File

@ -45,4 +45,10 @@ namespace PSTW_CentralSystem.Areas.Inventory.Models
[ForeignKey("LastUser")]
public virtual UserModel? FromUser { get; set; }
}
public class ItemStatusUpdateModel
{
public int ItemId { get; set; }
public int Status { get; set; }
}
}

File diff suppressed because it is too large Load Diff

View File

@ -497,22 +497,28 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
try
{
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;
var inventoryMaster = await _centralDbContext.InventoryMasters.Include("User").FirstOrDefaultAsync(i => i.UserId == item.CreatedByUserId) ?? new InventoryMasterModel { UserId = item.CreatedByUserId };
if (product.Category == "Disposable")
{
item.SerialNumber = null;
// For disposable items, the quantity product is increased by the item's quantity
product.QuantityProduct += item.Quantity;
item.SerialNumber = null; // Ensure serial number is null for disposables
}
else if (product.Category == "Asset" || product.Category == "Part")
{
// For assets or parts, each added item counts as 1 to the product quantity
// and the item's quantity should be set to 1 if it's not already, or based on specific logic.
// Assuming for Assets/Parts, each 'AddItem' call registers one unit of that product.
product.QuantityProduct = (product.QuantityProduct ?? 0) + 1; // Increment by 1 for Asset/Part
item.Quantity = 1; // Force quantity to 1 for Assets/Parts if it's not already
}
_centralDbContext.Items.Add(item);
product.QuantityProduct += addToProduct;
_centralDbContext.Products.Update(product);
_centralDbContext.Products.Update(product); // Update the product quantity
await _centralDbContext.SaveChangesAsync(); // This generates the auto-incremented ItemID
ItemMovementModel itemMovement = new ItemMovementModel
{
ItemId = item.ItemID,
@ -521,8 +527,8 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
LastStore = inventoryMaster.StoreId,
LastUser = inventoryMaster.UserId,
LatestStatus = "Ready To Deploy",
Quantity = item.Quantity,
Action= "Register",
Quantity = item.Quantity, // Use the item's quantity for movement record
Action = "Register",
Date = DateTime.Now,
MovementComplete = true,
};
@ -530,10 +536,9 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
_centralDbContext.ItemMovements.Add(itemMovement);
await _centralDbContext.SaveChangesAsync();
// Fetch the generated ItemID
// Fetch the generated ItemID and MovementId for the response
var savedItem = await _centralDbContext.Items.FirstOrDefaultAsync(i => i.ItemID == item.ItemID);
// Fetch the generated itemMovement
var savedMovement = await _centralDbContext.ItemMovements.FirstOrDefaultAsync(i => i.Id == itemMovement.Id);
var savedMovement = await _centralDbContext.ItemMovements.FirstOrDefaultAsync(im => im.Id == itemMovement.Id);
if (savedItem != null)
{
@ -545,8 +550,8 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
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();
string? itemIdString = item.ItemID.ToString("D5");
var uniqueId = $"{deptCode}{initialCategory}{productId}{itemIdString}".ToUpper();
savedItem.UniqueID = uniqueId;
savedItem.MovementId = savedMovement?.Id;
@ -584,6 +589,7 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
}
}
[HttpPost("EditItem")]
public async Task<IActionResult> EditItem([FromBody] ItemModel item)
{
@ -594,20 +600,76 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
try
{
var savedItem = await _centralDbContext.Items.FirstOrDefaultAsync(i => i.ItemID == item.ItemID);
var savedItem = await _centralDbContext.Items
.Include(i => i.Product) // Include product to get the original category
.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");
var originalProduct = savedItem.Product; // Get the original product associated with the item
// Calculate quantity changes for Disposable category
if (originalProduct?.Category == "Disposable" && product.Category == "Disposable")
{
int quantityDifference = item.Quantity - savedItem.Quantity;
product.QuantityProduct += quantityDifference;
}
else if (originalProduct?.Category != "Disposable" && product.Category == "Disposable")
{
// Category changed from Asset/Part to Disposable: add new quantity
product.QuantityProduct += item.Quantity;
// Optionally, if the old item was counted as 1 in QuantityProduct (for Asset/Part), decrement it.
if (originalProduct?.QuantityProduct > 0) // Ensure it doesn't go below zero
{
var oldProduct = await _centralDbContext.Products.FirstOrDefaultAsync(p => p.ProductId == originalProduct.ProductId);
if (oldProduct != null)
{
oldProduct.QuantityProduct = (oldProduct.QuantityProduct ?? 0) - 1;
_centralDbContext.Products.Update(oldProduct);
}
}
}
else if (originalProduct?.Category == "Disposable" && product.Category != "Disposable")
{
// Category changed from Disposable to Asset/Part: subtract old quantity
product.QuantityProduct -= savedItem.Quantity;
// Add 1 to the new product's quantity if it's now an Asset/Part
product.QuantityProduct = (product.QuantityProduct ?? 0) + 1;
}
// If both are Asset/Part, no quantity change needed for ProductModel based on ItemModel quantity
// If ProductId changes for Asset/Part, you need to decrement old product and increment new product by 1
else if ((originalProduct?.Category == "Asset" || originalProduct?.Category == "Part") && (product.Category == "Asset" || product.Category == "Part"))
{
if (savedItem.ProductId != item.ProductId) // Product changed for Asset/Part
{
// Decrement old product quantity
var oldProduct = await _centralDbContext.Products.FirstOrDefaultAsync(p => p.ProductId == savedItem.ProductId);
if (oldProduct != null)
{
oldProduct.QuantityProduct = (oldProduct.QuantityProduct ?? 0) - 1;
_centralDbContext.Products.Update(oldProduct);
}
// Increment new product quantity
product.QuantityProduct = (product.QuantityProduct ?? 0) + 1;
}
}
// Handle serial number for Disposable
if (product.Category == "Disposable")
{
item.SerialNumber = null;
}
else if (product.Category == "Asset" || product.Category == "Part")
{
item.Quantity = 1; // Enforce quantity to 1 for Assets/Parts
}
savedItem.ItemID = item.ItemID;
// Update savedItem properties from item model
savedItem.DefaultPrice = item.DefaultPrice;
savedItem.CompanyId = item.CompanyId;
savedItem.DepartmentId = item.DepartmentId;
@ -628,30 +690,30 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
savedItem.InvoiceNo = item.InvoiceNo;
savedItem.InvoiceDate = item.InvoiceDate;
savedItem.PartNumber = item.PartNumber;
savedItem.UniqueID = item.PartNumber;
savedItem.UniqueID = item.PartNumber; // This might need to be re-evaluated for UniqueID generation if PartNumber can change
_centralDbContext.Products.Update(product); // Update the product with the new quantity
_centralDbContext.Items.Update(savedItem); // Update the item
await _centralDbContext.SaveChangesAsync();
// Regenerate UniqueID if necessary (e.g., if PartNumber is part of it and changed)
// Note: The UniqueID generation logic seems to re-use PartNumber in your code,
// which might be fine, but if UniqueID should be truly unique and immutable
// after creation, you might reconsider updating it on edit.
var companyDepartment = await GetDepartmentWithCompany(savedItem.CompanyId, savedItem.DepartmentId);
var itemProduct = _centralDbContext.Products.Where(p => p.ProductId == savedItem.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? itemIdString = savedItem.ItemID.ToString("D5");
savedItem.UniqueID = $"{deptCode}{initialCategory}{productId}{itemIdString}".ToUpper(); // Re-generate UniqueID based on updated fields
_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();
}
await _centralDbContext.SaveChangesAsync();
var updatedItem = new
{
@ -682,6 +744,7 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
return BadRequest(ex.Message);
}
}
[HttpDelete("DeleteItem/{id}")]
public async Task<IActionResult> DeleteItem(int id)
{
@ -694,7 +757,7 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
var products = _centralDbContext.Products
.FirstOrDefault(i => i.ProductId == item.ProductId);
products.QuantityProduct = products.QuantityProduct - 1;
products.QuantityProduct = products.QuantityProduct - item.Quantity;
// Get related item movements
var itemMovements = await _centralDbContext.ItemMovements
@ -771,6 +834,7 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
item.Product!.ProductName,
item.Product!.ProductShortName,
item.Product!.ImageProduct,
Category = item.Product!.Category,
CurrentUser = item.Movement?.FromUser?.UserName,
CurrentUserFullName = item.Movement?.FromUser?.FullName,
CurrentUserId = item.Movement?.FromUser?.Id,
@ -866,7 +930,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
[HttpPost("AddItemMovement")]
public async Task<IActionResult> AddItemMovement([FromBody] ItemMovementModel itemmovement)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
@ -874,11 +937,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
try
{
//if (itemmovement.ToUser == null)
//{
// throw new Exception("itemmovement.ToUser is null");
//}
var inventoryMaster = await _centralDbContext.InventoryMasters.Include("User").FirstOrDefaultAsync(i => i.UserId == itemmovement.ToUser);
if (inventoryMaster != null)
{
@ -931,9 +989,19 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
{
updateItem.ItemStatus = 8;
}
// Handle quantity update for disposable items here
// This is crucial: if it's a disposable item, decrement the Item's Quantity
// You'll need to fetch the Product to know if it's Disposable
var product = await _centralDbContext.Products.FindAsync(updateItem.ProductId);
if (product != null && product.Category == "Disposable" && itemmovement.Quantity.HasValue)
{
updateItem.Quantity -= itemmovement.Quantity.Value;
if (updateItem.Quantity < 0)
{
updateItem.Quantity = 0; // Prevent negative quantity
}
}
//Console.WriteLine("updateItem.MovementId" + updateItem.MovementId);
//Console.WriteLine("itemmovement.Id" + itemmovement.Id);
updateItem.MovementId = itemmovement.Id;
_centralDbContext.Items.Update(updateItem);
@ -963,10 +1031,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
itemmovement.MovementComplete
});
//return Json(itemmovement);
}
catch (Exception ex)
{
@ -1016,6 +1080,70 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory
}
}
[HttpPost("UpdateItemQuantity")]
public async Task<IActionResult> UpdateItemQuantity([FromBody] ItemQuantityUpdateModel model)
{
try
{
// Find the item
var item = await _centralDbContext.Items
.Include(i => i.Product) // Include product for category check
.FirstOrDefaultAsync(i => i.ItemID == model.ItemId);
if (item == null)
{
return NotFound("Item not found.");
}
// Only process if it's a disposable item
if (item.Product?.Category == "Disposable")
{
// Get the original movement to find the exact quantity that was assigned
var originalMovement = await _centralDbContext.ItemMovements
.FirstOrDefaultAsync(m => m.Id == model.MovementId);
if (originalMovement == null)
{
return BadRequest("Original movement record not found.");
}
// The quantity to return is the original movement's quantity
var quantityToReturn = originalMovement.Quantity ?? 1;
// Update the item quantity by adding back the assigned amount
item.Quantity += quantityToReturn;
// Ensure quantity doesn't go negative (just in case)
if (item.Quantity < 0)
{
item.Quantity = 0;
}
_centralDbContext.Items.Update(item);
await _centralDbContext.SaveChangesAsync();
return Ok(new
{
item.ItemID,
OriginalQuantity = originalMovement.Quantity,
NewQuantity = item.Quantity,
Message = $"Successfully returned {quantityToReturn} to item quantity"
});
}
// For non-disposable items, just return success without changing quantity
return Ok(new
{
item.ItemID,
Message = "No quantity change - item is not disposable"
});
}
catch (Exception ex)
{
return BadRequest($"Error updating item quantity: {ex.Message}");
}
}
#endregion ItemMovement
#region ItemMovementUser

Binary file not shown.

After

Width:  |  Height:  |  Size: 980 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB