PSTW_CentralizeSystem/Controllers/API/Inventory/InvMainAPI.cs

1080 lines
42 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Mono.TextTemplating;
using Newtonsoft.Json;
using PSTW_CentralSystem.Areas.Inventory.Models;
using PSTW_CentralSystem.DBContext;
using PSTW_CentralSystem.Models;
using System.ComponentModel.Design;
using System.Data;
using System.Diagnostics;
using System.Reflection;
using static System.Collections.Specialized.BitVector32;
namespace PSTW_CentralSystem.Controllers.API.Inventory
{
[ApiController]
[Route("[controller]")]
public class InvMainAPI : Controller
{
private readonly ILogger<InvMainAPI> _logger;
private readonly CentralSystemContext _centralDbContext;
private readonly UserManager<UserModel> _userManager;
public InvMainAPI(ILogger<InvMainAPI> logger, CentralSystemContext centralDbContext, UserManager<UserModel> userManager)
{
_logger = logger;
_centralDbContext = centralDbContext;
_userManager = userManager;
}
public class DepartmentCompany
{
public int DepartmentId { get; set; }
public string? DepartmentName { get; set; }
public int CompanyId { get; set; }
public string? CompanyName { get; set; }
public string? DepartmentCode { get; set; }
}
public async Task<List<DepartmentCompany>> GetDepartmentWithCompanyList()
{
var departmentList = await _centralDbContext.Departments.ToListAsync();
var companyList = await _centralDbContext.Companies.ToListAsync();
// Create a new list to store departments with their company name
var departmentWithCompanyList = departmentList.Select(department => new DepartmentCompany
{
DepartmentId = department.DepartmentId,
DepartmentName = department.DepartmentName,
CompanyId = department.CompanyId,
CompanyName = companyList.FirstOrDefault(company => company.CompanyId == department.CompanyId)?.CompanyName
}).ToList();
// Return the constructed list as JSON
return departmentWithCompanyList;
}
public async Task<DepartmentCompany> GetDepartmentWithCompany(int companyId, int departmentId)
{
var departmentList = await _centralDbContext.Departments.FirstOrDefaultAsync(d => d.DepartmentId == departmentId );
var companyList = await _centralDbContext.Companies.FirstOrDefaultAsync(c => c.CompanyId == companyId);
// Create a new list to store departments with their company name
var departmentWithCompany = new DepartmentCompany
{
DepartmentId = departmentList!.DepartmentId,
DepartmentName = departmentList.DepartmentName,
CompanyId = departmentList.CompanyId,
CompanyName = companyList?.CompanyName,
DepartmentCode = departmentList.DepartmentCode,
};
// Return the constructed list as JSON
return departmentWithCompany;
}
#region Manufacturer
[HttpPost("ManufacturerList")]
public async Task<IActionResult> ManufacturerList()
{
var manifacturerList = await _centralDbContext.Manufacturers.ToListAsync();
return Json(manifacturerList);
}
[HttpPost("AddManufacturer")]
public async Task<IActionResult> AddManufacturer([FromBody] ManufacturerModel manufacturer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
_centralDbContext.Manufacturers.Add(new ManufacturerModel
{
ManufacturerName = manufacturer.ManufacturerName,
});
await _centralDbContext.SaveChangesAsync();
var updatedList = await _centralDbContext.Manufacturers.ToListAsync();
return Json(updatedList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete("DeleteManufacturer/{id}")]
public async Task<IActionResult> DeleteManufacturer(int id)
{
var manufacturer = await _centralDbContext.Manufacturers.FindAsync(id);
if (manufacturer == null)
{
return NotFound(new { success = false, message = "Manufacturer not found" });
}
_centralDbContext.Manufacturers.Remove(manufacturer);
await _centralDbContext.SaveChangesAsync();
return Ok(new { success = true, message = "Manufacturer deleted successfully" });
}
#endregion Manufacturer
#region Product
[HttpPost("ProductList")]
public async Task<IActionResult> ProductList()
{
var productList = await _centralDbContext.Products.Include("Manufacturer").ToListAsync();
return Json(productList);
}
[HttpPost("ProductListWithItem")]
public async Task<IActionResult> ProductListWithItem()
{
var productList = await _centralDbContext.Products
.Include(p => p.Items) // Include related items
.Include(p => p.Manufacturer) // Include related manufacturer
.ToListAsync();
return Json(productList);
}
[HttpPost("AddProduct")]
public async Task<IActionResult> AddProduct([FromBody] ProductModel product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (product == null)
{
return NotFound("Product is null");
}
try
{
product.QuantityProduct = 0;
var productImage = product.ImageProduct; // Save image to wwwroot/media/inventory/images | Images name is product.ModelNo | product.ImageProduct is in base64 string
if (!string.IsNullOrEmpty(product.ImageProduct))
{
var bytes = Convert.FromBase64String(product.ImageProduct);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/media/inventory/images", product.ModelNo + ".jpg");
await System.IO.File.WriteAllBytesAsync(filePath, bytes);
product.ImageProduct = "/media/inventory/images/" + product.ModelNo + ".jpg";
}
_centralDbContext.Products.Add(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)
{
var Product = await _centralDbContext.Products.FindAsync(id);
if (Product == null)
{
return NotFound(new { success = false, message = "Product not found" });
}
_centralDbContext.Products.Remove(Product);
await _centralDbContext.SaveChangesAsync();
return Ok(new { success = true, message = "Product deleted successfully" });
}
#endregion Product
#region Supplier
[HttpPost("SupplierList")]
public async Task<IActionResult> SupplierList()
{
var supplierList = await _centralDbContext.Suppliers.ToListAsync();
return Json(supplierList);
}
[HttpPost("AddSupplier")]
public async Task<IActionResult> AddSupplier([FromBody] SupplierModel supplier)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
_centralDbContext.Suppliers.Add(supplier);
await _centralDbContext.SaveChangesAsync();
var updatedList = await _centralDbContext.Suppliers.ToListAsync();
return Json(updatedList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete("DeleteSupplier/{id}")]
public async Task<IActionResult> DeleteSupplier(int id)
{
var supplier = await _centralDbContext.Suppliers.FindAsync(id);
if (supplier == null)
{
return NotFound(new { success = false, message = "Supplier not found" });
}
_centralDbContext.Suppliers.Remove(supplier);
await _centralDbContext.SaveChangesAsync();
return Ok(new { success = true, message = "Supplier deleted successfully" });
}
#endregion Supplier
#region Item
[HttpPost("ItemList")]
public async Task<IActionResult> ItemList()
{
try
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return BadRequest("User not found");
}
else
{
user.departmentId = user.departmentId != null ? user.departmentId : 0;
}
var userRole = await _userManager.GetRolesAsync(user);
var isAdmin = userRole.Contains("SystemAdmin") || userRole.Contains("SuperAdmin") || userRole.Contains("Finance");
List<ItemModel> itemList = new List<ItemModel>();
// Get the item list
if (isAdmin)
{
itemList = await _centralDbContext.Items
.AsNoTracking()
.Include("CreatedBy")
.Include("Department")
.Include("Product")
.Include(i => i.Movement)
.ThenInclude(m => m!.FromStore)
.Include(i => i.Movement)
.ThenInclude(m => m!.FromStation)
.Include(i => i.Movement)
.ThenInclude(m => m!.FromUser)
.ToListAsync();
}
else
{
itemList = await _centralDbContext.Items
.AsNoTracking()
.Include("CreatedBy")
.Include("Department")
.Include("Product")
.Include(i => i.Movement)
.ThenInclude(m => m!.FromStore)
.Include(i => i.Movement)
.ThenInclude(m => m!.FromStation)
.Include(i => i.Movement)
.ThenInclude(m => m!.FromUser)
.Where(i => i.DepartmentId == user.departmentId)
.ToListAsync();
}
// Get the departments list (DepartmentId references Departments)
var departments = await _centralDbContext.Departments.ToListAsync();
// Now join items with users and departments manually
var itemListWithDetails = itemList.Select(item => new
{
item.ItemID,
item.UniqueID,
item.CompanyId,
item.DepartmentId,
item.ProductId,
item.SerialNumber,
item.Quantity,
item.Supplier,
PurchaseDate = item.PurchaseDate.ToString("dd/MM/yyyy"),
item.PONo,
item.Currency,
item.DefaultPrice,
item.CurrencyRate,
item.ConvertPrice,
item.DODate,
item.Warranty,
item.PartNumber,
EndWDate = item.EndWDate.ToString("dd/MM/yyyy"),
InvoiceDate = item.InvoiceDate?.ToString("dd/MM/yyyy"),
item.Department?.DepartmentName,
CreatedBy=item.CreatedBy!.UserName,
item.Product!.ProductName,
item.Product!.ProductShortName,
item.Product!.Category,
//CurrentUser = item.Movement?.FromUser?.UserName,
CurrentUser = item.Movement?.FromUser?.UserName,
CurrentStore = item.Movement?.FromStore?.StoreName,
CurrentStation = item.Movement?.FromStation?.StationName,
QRString = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/I/{item.UniqueID}" // Generate QR String
}).ToList();
return Json(itemListWithDetails);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("GenerateItemQr/{id}")]
public IActionResult GenerateItemQr(string id)
{
// Retrieve the request's host and scheme
var request = HttpContext.Request;
string domain = $"{request.Scheme}://{request.Host.Value}";
// Append the QR path and item ID
string QRString = $"{domain}/Inventory/ItemInformation/{id}";
return Json(QRString);
}
[HttpPost("AddItem")]
public async Task<IActionResult> AddItem([FromBody] ItemModel item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
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;
product.QuantityProduct += addToProduct;
if (product.Category == "Disposable")
{
item.SerialNumber = null;
}
_centralDbContext.Items.Add(item);
_centralDbContext.Products.Update(product);
await _centralDbContext.SaveChangesAsync(); // This generates the auto-incremented ItemID
ItemMovementModel itemMovement = new ItemMovementModel
{
ItemId = item.ItemID,
ToUser = inventoryMaster.UserId,
ToStore = inventoryMaster.StoreId,
LastStore = inventoryMaster.StoreId,
LastUser = inventoryMaster.UserId,
LatestStatus = "Ready To Deploy",
Quantity = item.Quantity,
Action= "Register",
Date = DateTime.Now,
MovementComplete = true,
};
_centralDbContext.ItemMovements.Add(itemMovement);
await _centralDbContext.SaveChangesAsync();
// Fetch the generated ItemID
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);
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;
savedItem.MovementId = savedMovement?.Id;
_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)
{
var item = await _centralDbContext.Items.FindAsync(id);
if (item == null)
{
return NotFound(new { success = false, message = "Item not found" });
}
_centralDbContext.Items.Remove(item);
await _centralDbContext.SaveChangesAsync();
return Ok(new { success = true, message = "Item deleted successfully" });
}
[HttpPost("GetItem/{id}")] // Endpoint to retrieve an item by its ID
public async Task<IActionResult> GetItem(string id)
{
var item = await _centralDbContext.Items
.Include("CreatedBy")
.Include("Department")
.Include("Product")
.Include("Movement")
.Include(i => i.Movement)
.ThenInclude(m => m!.FromStore)
.Include(i => i.Movement)
.ThenInclude(m => m!.FromStation)
.Include(i => i.Movement)
.ThenInclude(m => m!.FromUser).FirstOrDefaultAsync(i => i.UniqueID == id);
if (item == null){
return NotFound(new { success = false, message = "Item not found" });
}
var singleItem = new
{
item.ItemID,
item.MovementId,
item.UniqueID,
item.CompanyId,
item.DepartmentId,
item.ProductId,
item.SerialNumber,
item.Quantity,
item.Supplier,
PurchaseDate = item.PurchaseDate.ToString("dd/MM/yyyy"),
item.PONo,
item.Currency,
item.DefaultPrice,
item.CurrencyRate,
item.ConvertPrice,
item.DODate,
item.Warranty,
item.PartNumber,
EndWDate = item.EndWDate.ToString("dd/MM/yyyy"),
InvoiceDate = item.InvoiceDate?.ToString("dd/MM/yyyy"),
item.Department?.DepartmentName,
item.CreatedBy!.UserName,
item.Product!.ProductName,
item.Product!.ProductShortName,
item.Product!.ImageProduct,
CurrentUser = item.Movement?.FromUser?.UserName,
CurrentUserId = item.Movement?.FromUser?.Id,
CurrentStore = item.Movement?.FromStore?.StoreName,
CurrentStation = item.Movement?.FromStation?.StationName,
item.Movement?.ToOther,
item.Movement?.LatestStatus,
QRString = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/I/{item.UniqueID}" // Generate QR String
};
return Json(singleItem);
}
#endregion Item
#region ItemMovement
[HttpPost("ItemMovementList")]
public async Task<IActionResult> ItemMovementList()
{
var itemMovementList = await _centralDbContext.ItemMovements.ToListAsync();
//var itemList = await _centralDbContext.Items.ToListAsync();
int itemrow = 0;
var itemMovementListWithQR = itemMovementList.Select(item => new
{
id = itemrow++,
item, // Includes all properties of the original item
QRString = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/I/{item.ItemId}" // Generate QR String
}).ToList();
Console.WriteLine(Json(itemMovementList));
//return Json(itemMovementList);
return Json(itemMovementListWithQR);
//try
//{
// var user = await _userManager.GetUserAsync(User);
// if (user == null)
// {
// return BadRequest("User not found");
// }
// else
// {
// user.departmentId = user.departmentId != null ? user.departmentId : 0;
// }
// var userRole = await _userManager.GetRolesAsync(user);
// var isAdmin = userRole.Contains("SystemAdmin") || userRole.Contains("SuperAdmin") || userRole.Contains("Finance");
// List<ItemModel> itemList = new List<ItemModel>();
// // Get the item list
// if (isAdmin)
// {
// itemList = await _centralDbContext.Items
// .AsNoTracking()
// .Include("CreatedBy")
// .Include("Department")
// .Include("Product")
// .Include(i => i.Movement)
// .ThenInclude(m => m!.FromStore)
// .Include(i => i.Movement)
// .ThenInclude(m => m!.FromStation)
// .Include(i => i.Movement)
// .ThenInclude(m => m!.FromUser)
// .ToListAsync();
// }
// else
// {
// itemList = await _centralDbContext.Items
// .AsNoTracking()
// .Include("CreatedBy")
// .Include("Department")
// .Include("Product")
// .Include(i => i.Movement)
// .ThenInclude(m => m!.FromStore)
// .Include(i => i.Movement)
// .ThenInclude(m => m!.FromStation)
// .Include(i => i.Movement)
// .ThenInclude(m => m!.FromUser)
// .Where(i => i.DepartmentId == user.departmentId)
// .ToListAsync();
// }
// // Get the departments list (DepartmentId references Departments)
// var departments = await _centralDbContext.Departments.ToListAsync();
// // Now join items with users and departments manually
// var itemListWithDetails = itemList.Select(item => new
// {
// item.ItemID,
// item.UniqueID,
// item.CompanyId,
// item.DepartmentId,
// item.ProductId,
// item.SerialNumber,
// item.Quantity,
// item.Supplier,
// PurchaseDate = item.PurchaseDate.ToString("dd/MM/yyyy"),
// item.PONo,
// item.Currency,
// item.DefaultPrice,
// item.CurrencyRate,
// item.ConvertPrice,
// item.DODate,
// item.Warranty,
// item.PartNumber,
// EndWDate = item.EndWDate.ToString("dd/MM/yyyy"),
// InvoiceDate = item.InvoiceDate?.ToString("dd/MM/yyyy"),
// item.Department?.DepartmentName,
// CreatedBy = item.CreatedBy!.UserName,
// item.Product!.ProductName,
// item.Product!.ProductShortName,
// item.Product!.Category,
// //CurrentUser = item.Movement?.FromUser?.UserName,
// CurrentUser = item.Movement?.FromUser?.UserName,
// CurrentStore = item.Movement?.FromStore?.StoreName,
// CurrentStation = item.Movement?.FromStation?.StationName,
// QRString = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/I/{item.UniqueID}" // Generate QR String
// }).ToList();
// return Json(itemListWithDetails);
//}
//catch (Exception ex)
//{
// return BadRequest(ex.Message);
//}
}
[HttpPost("AddItemMovement")]
public async Task<IActionResult> AddItemMovement([FromBody] ItemMovementModel itemmovement)
//public async Task<IActionResult> AddItemMovement()
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
_centralDbContext.ItemMovements.Add(itemmovement);
await _centralDbContext.SaveChangesAsync(); // This generates the auto-incremented ItemID
//ItemMovementModel itemMovement = new ItemMovementModel
//{
// ItemId = item.ItemID,
// ToUser = inventoryMaster.UserId,
// ToStore = inventoryMaster.StoreId,
// LastStore = inventoryMaster.StoreId,
// LastUser = inventoryMaster.UserId,
// LatestStatus = "Ready To Deploy",
// Quantity = item.Quantity,
// Action = "Register",
// Date = DateTime.Now,
// MovementComplete = true,
//};
//_centralDbContext.ItemMovements.Add(itemMovement);
//await _centralDbContext.SaveChangesAsync();
// Fetch the generated ItemID
//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);
//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;
// savedItem.MovementId = savedMovement?.Id;
// _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(itemmovement);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
#endregion ItemMovement
#region ItemRequestUser
[HttpPost("AddRequest")]
public async Task<IActionResult> AddRequest([FromBody] RequestModel request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
_centralDbContext.Requests.Add(request);
await _centralDbContext.SaveChangesAsync();
var updatedList = await _centralDbContext.Requests
.Where(r => r.UserId == request.UserId)
.ToListAsync();
return Json(updatedList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpGet("ItemRequestListEachUser/{userId}")]
public async Task<IActionResult> ItemRequestListEachUser(int userId)
{
var requests = await _centralDbContext.Requests
.Where(r => r.UserId == userId).ToListAsync();
return Ok(requests);
}
[HttpDelete("DeleteRequest/{requestId}")]
public async Task<IActionResult> DeleteRequest(int requestId)
{
var request = await _centralDbContext.Requests.FindAsync(requestId);
if (request == null)
{
return NotFound(new { success = false, message = "Request not found" });
}
_centralDbContext.Requests.Remove(request);
await _centralDbContext.SaveChangesAsync();
return Ok(new { success = true, message = "Request deleted successfully" });
}
#endregion
#region ItemRequestAdmin
[HttpGet("ItemRequestList")]
public async Task<IActionResult> ItemRequestList()
{
var itemRequestList = await _centralDbContext.Requests.ToListAsync();
return Json(itemRequestList);
}
[HttpPost("ApproveRequest/{id}")]
public async Task<IActionResult> ApproveRequest(int id)
{
var Request = await _centralDbContext.Requests.FindAsync(id);
if (Request == null)
{
return NotFound(new { success = false, message = "Request not found" });
}
Request.status = "Approved";
Request.approvalDate = DateTime.UtcNow;
_centralDbContext.SaveChanges();
return Ok(new { success = true, message = "Request Approved Successfully", data = Request });
}
[HttpPost("RejectRequest/{id}")]
public async Task<IActionResult> RejectRequest(int id, [FromBody] RequestModel request)
{
var Request = await _centralDbContext.Requests.FindAsync(id);
if (Request == null)
{
return NotFound(new { success = false, message = "Request not found" });
}
Request.status = "Rejected";
Request.remarkMasterInv = request.remarkMasterInv;
Request.approvalDate = DateTime.UtcNow;
_centralDbContext.SaveChanges();
return Ok(new { success = true, message="Request Rejected Successfully", data=Request });
}
#endregion ItemRequestAdmin
#region ItemReport
[HttpPost("GetInventoryReport/{deptId}")]
public async Task<IActionResult> GetInventoryReport(int deptId)
{
try{
var user = await _userManager.GetUserAsync(User);
var userRole = await _userManager.GetRolesAsync(user ?? new UserModel());
List<ItemModel> items = new List<ItemModel>();
if (userRole.Contains("SuperAdmin") && userRole.Contains("SystemAdmin"))
{
items = await _centralDbContext.Items
.Include("CreatedBy")
.Include("Department")
.Include("Product")
.ToListAsync();
}
else
{
items = await _centralDbContext.Items
.Include("CreatedBy")
.Include("Department")
.Include("Product")
.Where(i => i.DepartmentId == deptId)
.ToListAsync();
}
var itemListWithDetails = items.Where(i => i.Quantity > 0).Select(item => new
{
item.ItemID,
item.UniqueID,
item.CompanyId,
item.DepartmentId,
item.ProductId,
item.SerialNumber,
item.Quantity,
item.Supplier,
PurchaseDate = item.PurchaseDate.ToString("dd/MM/yyyy"),
item.PONo,
item.Currency,
item.DefaultPrice,
item.CurrencyRate,
item.ConvertPrice,
item.DODate,
item.Warranty,
EndWDate = item.EndWDate.ToString("dd/MM/yyyy"),
InvoiceDate = item.InvoiceDate?.ToString("dd/MM/yyyy"),
item.Department?.DepartmentName,
CreatedBy = item.CreatedBy!.UserName,
item.Product!.ProductName,
item.Product!.ProductShortName,
item.Product!.Category,
//CurrentUser = item.Movement?.FromUser?.UserName,
CurrentUser = item.Movement?.FromUser?.UserName,
CurrentStore = item.Movement?.FromStore?.StoreName,
CurrentStation = item.Movement?.FromStation?.StationName,
QRString = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/I/{item.UniqueID}" // Generate QR String
}).ToList();
int itemCountRegistered = items.Count;
int itemCountStillInStock = items.Where(i => i.Quantity > 0).Count();
var itemsMovementsThisMonth = _centralDbContext.ItemMovements
.Where(i => i.Date.Month == DateTime.Now.Month);
int itemCountRegisteredThisMonth = itemsMovementsThisMonth.Count(i => i.Action == "Register");
int itemCountStockOutThisMonth = itemsMovementsThisMonth.Count(i => i.Action == "Stock Out");
var lastMonth = DateTime.Now.AddMonths(-1).Month;
var itemsMovementsLastMonth = _centralDbContext.ItemMovements
.Where(i => i.Date.Month == lastMonth);
int itemCountRegisteredLastMonth = itemsMovementsLastMonth.Count(i => i.Action == "Register");
int itemCountStockOutLastMonth = itemsMovementsLastMonth.Count(i => i.Action == "Stock Out");
var report = new
{
itemListWithDetails,
itemCountRegistered,
itemCountStillInStock,
itemCountRegisteredThisMonth,
itemCountStockOutThisMonth,
itemCountRegisteredLastMonth,
itemCountStockOutLastMonth
};
return Json(report);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
#endregion
#region Station
[HttpPost("StationList")]
public async Task<IActionResult> StationList()
{
var stationList = await _centralDbContext.Stations.ToListAsync();
return Json(stationList);
}
[HttpPost("AddStation")]
public async Task<IActionResult> AddStation([FromBody] StationModel station)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
_centralDbContext.Stations.Add(station);
await _centralDbContext.SaveChangesAsync();
var updatedList = await _centralDbContext.Stations.ToListAsync();
return Json(updatedList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpDelete("DeleteStation/{id}")]
public async Task<IActionResult> DeleteStation(int id)
{
var station = await _centralDbContext.Stations.FindAsync(id);
if (station == null)
{
return NotFound(new { success = false, message = "Station not found" });
}
_centralDbContext.Stations.Remove(station);
await _centralDbContext.SaveChangesAsync();
return Ok(new { success = true, message = "Station deleted successfully" });
}
#endregion Station
#region Store
[HttpPost("StoreList")]
public async Task<IActionResult> StoreList()
{
var storeList = await _centralDbContext.Stores.ToListAsync();
return Json(storeList);
}
#endregion Store
#region AllUser
[HttpPost("UserList")]
public async Task<IActionResult> UserList()
{
var userList = await _centralDbContext.Users.ToListAsync();
return Json(userList);
}
#endregion AllUser
#region ScannerUser
[HttpPost("UpdateItemMovementUser")]
public async Task<IActionResult> UpdateItemMovementUser([FromBody] ItemMovementModel receiveMovement)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var updatedList = await _centralDbContext.ItemMovements.FindAsync(receiveMovement.Id);
if (updatedList == null)
{
return NotFound("Item movement record not found.");
}
updatedList.LastStation = receiveMovement.LastStation;
updatedList.LatestStatus = receiveMovement.LatestStatus;
updatedList.receiveDate = receiveMovement.receiveDate;
updatedList.MovementComplete = receiveMovement.MovementComplete;
_centralDbContext.ItemMovements.Update(updatedList);
await _centralDbContext.SaveChangesAsync();
return Json(updatedList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPost("ReturnItemMovementUser")]
public async Task<IActionResult> ReturnItemMovementUser([FromBody] ItemMovementModel returnMovement)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var updatedList = await _centralDbContext.ItemMovements
.Where(r => r.Id == returnMovement.Id)
.FirstAsync();
updatedList.ItemId = updatedList.ItemId;
updatedList.ToStation = updatedList.ToStation;
updatedList.ToStore = updatedList.ToStore;
updatedList.ToUser = updatedList.ToUser;
updatedList.ToOther = updatedList.ToOther;
updatedList.sendDate = updatedList.sendDate;
updatedList.ToStation = updatedList.ToStation;
updatedList.Action = updatedList.Action;
updatedList.Quantity = updatedList.Quantity;
updatedList.Remark = updatedList.Remark;
updatedList.ConsignmentNote = updatedList.ConsignmentNote;
updatedList.Date = updatedList.Date;
updatedList.LastUser = updatedList.LastUser;
updatedList.LastStore = updatedList.ToStore;
updatedList.LastStation = returnMovement.LastStation;
updatedList.LatestStatus = returnMovement.LatestStatus;
updatedList.receiveDate = returnMovement.receiveDate;
updatedList.MovementComplete = returnMovement.MovementComplete;
await _centralDbContext.SaveChangesAsync();
return Json(updatedList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
#endregion
}
}