From 6c2923ca1a952a1e9b513e0d828dcf88d3657cf2 Mon Sep 17 00:00:00 2001 From: ameerulrasyid Date: Mon, 10 Mar 2025 09:30:17 +0800 Subject: [PATCH] maintain code readability --- .../Views/InventoryMaster/ItemMovement.cshtml | 235 +----------------- .../Views/InventoryMaster/QrMaster.cshtml | 224 +++-------------- Controllers/API/Inventory/InvMainAPI.cs | 19 +- 3 files changed, 44 insertions(+), 434 deletions(-) diff --git a/Areas/Inventory/Views/InventoryMaster/ItemMovement.cshtml b/Areas/Inventory/Views/InventoryMaster/ItemMovement.cshtml index d38ff16..ce43c42 100644 --- a/Areas/Inventory/Views/InventoryMaster/ItemMovement.cshtml +++ b/Areas/Inventory/Views/InventoryMaster/ItemMovement.cshtml @@ -893,35 +893,6 @@ }, }) - // Attach click event listener to the delete buttons - $('#itemDatatable tbody').on('click', '.delete-btn', function () { - const itemId = $(this).data('id'); - self.deleteItem(itemId); - }); - - // $('#itemDatatable tbody').on('click', '.print-btn', function () { - // const $button = $(this); The clicked button - // const $row = $button.closest('tr'); The parent row of the button - // const itemId = $button.data('id'); Get the item ID from the button's data attribute - - // let imageSrc; - - // Check if the table is collapsed - // if ($row.hasClass('child')) { - // For collapsed view: Look for the closest `.dtr-data` that contains the img - // imageSrc = $row.prev('tr').find('td:nth-child(1) img').attr('src'); - // } else { - // For expanded view: Find the img in the first column of the current row - // imageSrc = $row.find('td:nth-child(1) img').attr('src'); - // } - - // if (imageSrc) { - // self.printItem(itemId, imageSrc); Call the print function with the itemId and imageSrc - // } else { - // console.error("Image source not found."); - // } - // }); - this.loading = false; }, @@ -948,28 +919,21 @@ this.initAllTables(); } else { - const data = await response.json(); + const data = await response.json(); this.items = data.filter(item => - item.toUser === this.currentUser.id || - item.lastUser === this.currentUser.id || - item.toStore === this.currentUser.store || - item.lastStore === this.currentUser.store + item.toUser === this.currentUser.id || + item.lastUser === this.currentUser.id || + item.toStore === this.currentUser.store || + item.lastStore === this.currentUser.store ); - this.initAllTables(); + this.initAllTables(); // console.log(this.items); } - // const allowedKeys = ["toUser", "lastUser"]; - // this.items = (await response.json()).filter(item => allowedKeys.some(key => item[key] === this.currentUser.id)); - // this.items = (await response.json()).filter(item => item.lastUser === this.currentUser); - // const allowedKeys = ["toUser", "lastUser"]; - // this.items = (await response.json()).filter(item => - // allowedKeys.some(key => item[key] === this.currentuser.id) - // ); if (this.itemDatatable) { this.itemDatatable.clear().destroy(); @@ -982,101 +946,6 @@ this.loading = false; }, - - // FRONT END FUNCTIONS - //----------------------// - //Calculate Total Price - convertCurrency() { - const total = this.DefaultPrice * this.currencyRate; - this.convertPrice = total.toFixed(2); - this.DefaultPrice = this.DefaultPrice - // .replace(/[^0-9.]/g, '') // Remove non-numeric characters except decimal points - // .replace(/(\..*)\..*/g, '$1') // Allow only one decimal point - // .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; - } - try { - const response = await fetch(`/InvMainAPI/DeleteItem/${itemId}`, { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - }, - }); - const result = await response.json(); - - if (result.success) { - alert(result.message); - // Remove the row from DataTables - this.itemDatatable - .row($(`.delete-btn[data-id="${itemId}"]`).closest('tr')) - .remove() - .draw(); - } else { - alert(result.message); - } - } - catch (error) { - console.error("Error deleting item:", error); - alert("An error occurred while deleting the item."); - } - finally { - this.loading = false; - } - }, - async printItem(itemId, imgSrc) { - try { - this.thisQRInfo.uniqueID = itemId; - const uniqueQR = itemId; - const container = document.getElementById("QrContainer"); - - if (!container) { - console.error("Container not found."); - return; - } - - // Safely set image content - const sanitizedImgSrc = encodeURI(imgSrc); // Sanitize the URL - container.innerHTML = `QR Code`; - - // Fetch QR information - const qrInfo = this.getPrintedQR(uniqueQR); - if (!qrInfo) { - console.error("QR Info not found."); - return; - } - - this.thisQRInfo = qrInfo; - this.thisQRInfo.imgSrc = sanitizedImgSrc - this.thisQRInfo.imgContainer = container.innerHTML - $(`#QrItemModal`).modal('show'); // Show modal - } - catch (error) { - console.error("Error generating QR code:", error); - alert("An error occurred while generating the QR code."); - } - }, async fetchUser() { try { const response = await fetch(`/IdentityAPI/GetUserInformation/`, { @@ -1109,89 +978,6 @@ console.error('There was a problem with the fetch operation:', error); } }, - // getPrintedQR(uniqueID) { - // if (!this.items || !Array.isArray(this.items)) { - // console.error("Items list is not available or is not an array."); - // return null; - // } - // return this.items.find(item => item.uniqueID === uniqueID); - // }, - // printQRInfo() { - // Create a virtual DOM element - // const virtualElement = document.createElement('div'); - // virtualElement.style.width = '330px '; Match label size for 2 inches at 203 DPI - // virtualElement.style.height = '160px'; - // virtualElement.style.position = 'absolute'; - // virtualElement.style.left = '-9999px'; Position offscreen to avoid rendering on the main UI - // virtualElement.style.border = '1px solid #000'; Optional: Add a border for debugging dimensions - - // Populate the virtual DOM with content - // virtualElement.innerHTML = ` - //
- //
- //
- //
- //
- //
${this.thisQRInfo.imgContainer}
- //
${this.thisQRInfo.uniqueID}
- //
- //
- //
- //
- //
- //
${this.thisQRInfo.departmentName}
- //
${this.thisQRInfo.productShortName}
- //
${this.thisQRInfo.serialNumber??"-"}
- //
${this.thisQRInfo.partNumber}
- //
- //
- //
- //
- // `; - - // Append the virtual DOM to the body (temporarily) - // document.body.appendChild(virtualElement); - - // Wait for the font to be loaded (important for custom fonts like OCR-A) - // document.fonts.load('1em "OCR A"').then(() => { - // Use html2canvas to convert the virtual DOM to an image - // html2canvas(virtualElement, { - // scale: 1, Increase scale for sharper images - // }).then((canvas) => { - // Convert the canvas to an image - // const imgData = canvas.toDataURL('image/png'); - // Open the image in a new tab for preview (optional) - // const newWindow = window.open(); - // newWindow.location.href = imgData; - // console.log(imgData) - // Use printJS to print the image - // printJS({ - // printable: imgData, - // type: 'image', - // css: '/../lib/bootstrap/dist/css/bootstrap.css', - // style: ` - // @@media print { - // @@page { - // margin: 5px 5px 0px 5px; - // } - // body { margin: 0; } - // } - // ` - // }); - - // Remove the virtual DOM from the body after use - // document.body.removeChild(virtualElement); - // }).catch((error) => { - // console.error("Error generating image:", error); - // Remove the virtual DOM if an error occurs - // document.body.removeChild(virtualElement); - // }); - // }).catch((error) => { - // console.error("Error loading font:", error); - // Remove the virtual DOM if font loading fails - // document.body.removeChild(virtualElement); - // }); - // }, handleSorting() { this.renderTables(); }, @@ -1226,11 +1012,9 @@ { title: "Last User", data: "lastUserName" }, { title: "From Station", data: "toStationName" }, { title: "From Store", data: "toStoreName" }, - // { title: "Action", data: "action" }, { title: "Start Status", data: "toOther" }, { title: "Product Category", data: "productCategory" }, { title: "Qty", data: "quantity" }, - // { title: "Send Date", data: "sendDate" }, { title: "Note", data: "consignmentNote", @@ -1280,13 +1064,10 @@ { title: "Last Station", data: "lastStationName" }, { title: "From Store", data: "toStoreName" }, { title: "Last Store", data: "lastStoreName" }, - // { title: "Action", data: "action" }, { title: "Start Status", data: "toOther" }, { title: "Latest Status", data: "latestStatus" }, - { title: "Product Category", data: "productCategory" }, + { title: "Product Category", data: "productCategory" }, { title: "Qty", data: "quantity" }, - // { title: "Send Date", data: "sendDate" }, - // { title: "Receive Date", data: "receiveDate" }, { title: "Note", data: "consignmentNote", render: function (data, type, full, meta) { @@ -1374,7 +1155,7 @@ toggleHistory(itemId) { this.historyVisible[itemId] = !this.historyVisible[itemId]; - // this.historyVisible = {}; + // this.historyVisible = {}; }, diff --git a/Areas/Inventory/Views/InventoryMaster/QrMaster.cshtml b/Areas/Inventory/Views/InventoryMaster/QrMaster.cshtml index 6ef6ac4..1b0258f 100644 --- a/Areas/Inventory/Views/InventoryMaster/QrMaster.cshtml +++ b/Areas/Inventory/Views/InventoryMaster/QrMaster.cshtml @@ -585,7 +585,6 @@ return { thisItem: null, qrCodeResult: null, - debounceTimeout: null, userlist: null, stationlist: null, @@ -601,19 +600,6 @@ selectedOther: "", remark: "", document: null, - // companies: [ - // { - // companyId: 1, - // companyName: "PSTW", - // departments: [{ departmentId: 1, departmentName: "Air" }, { departmentId: 2, departmentName: "Marine" }, { departmentId: 3, departmentName: "River" }] - // }, - // { - // companyId: 2, - // companyName: "TES", - // departments: [{ departmentId: 1, departmentName: "Air" }], - // }, - // ], - // company: "", currentUser: null, currentUserCompanyDept: null, itemlateststatus: "", @@ -682,59 +668,6 @@ }, }, methods: { - sharpenFrame(videoCanvas) { - const ctx = videoCanvas.getContext("2d"); - if (!ctx) return; - - const { width, height } = videoCanvas; - const imageData = ctx.getImageData(0, 0, width, height); - const data = imageData.data; - - // Sharpening kernel (edge enhancement) - const kernel = [0, -1, 0, -1, 5, -1, 0, -1, 0]; - - // Apply convolution - const newData = new Uint8ClampedArray(data); - const w = width * 4; // Each pixel has 4 values (RGBA) - - for (let y = 1; y < height - 1; y++) { - for (let x = 1; x < width - 1; x++) { - const i = (y * width + x) * 4; - - let r = 0, g = 0, b = 0; - for (let ky = -1; ky <= 1; ky++) { - for (let kx = -1; kx <= 1; kx++) { - const j = i + (ky * w) + (kx * 4); - const weight = kernel[(ky + 1) * 3 + (kx + 1)]; - r += data[j] * weight; - g += data[j + 1] * weight; - b += data[j + 2] * weight; - } - } - - // Apply sharpening - newData[i] = Math.min(255, Math.max(0, r)); - newData[i + 1] = Math.min(255, Math.max(0, g)); - newData[i + 2] = Math.min(255, Math.max(0, b)); - } - } - - // Update canvas with the sharpened frame - ctx.putImageData(new ImageData(newData, width, height)); - }, - processFrame(videoElement) { - console.log(videoElement); - console.log("Type:", typeof videoElement); - console.log(videoElement.constructor.name); - console.log(Array.isArray(videoElement)); // Check if it's an array - console.log(Object.keys(videoElement)); - - for (const key in videoElement) { - if (videoElement[key] instanceof HTMLVideoElement) { - console.log("Found HTMLVideoElement at:", key, videoElement[key]); - } - } - }, // Split Url dapatkan unique ID Je onDecode(detectedCodes) { // const endTime = performance.now(); @@ -766,126 +699,48 @@ async onCameraReady(videoElement) { const video = document.querySelector("video"); -console.log("📸 Found Video Element:", video); -console.log("🎬 Video.srcObject:", video?.srcObject); + // console.log("📸 Found Video Element:", video); + // console.log("🎬 Video.srcObject:", video?.srcObject); - const track = video.srcObject.getVideoTracks()[0]; - console.log("🎞 Video Track:", track); + const track = video.srcObject.getVideoTracks()[0]; + // console.log("🎞 Video Track:", track); - if (track && track.getCapabilities) { - const capabilities = track.getCapabilities(); // Get camera capabilities - console.log("🎛 Camera Capabilities:", capabilities); + if (track && track.getCapabilities) { + const capabilities = track.getCapabilities(); // Get camera capabilities + // console.log("🎛 Camera Capabilities:", capabilities); - if (capabilities.sharpness) { - // track.applyConstraints({ - // advanced: [ { sharpness: 100 }, Max sharpness - // { contrast: 50 }, Boost contrast - // { brightness: 60 }, Increase brightness - // { frameRate: 30 }, Try max FPS - // { exposureTime: 100 }, Lower for less motion blur - // { focusMode: "continuous" }, Ensure auto-focus - // { width: 1280, height: 720 } - //] - // }) Max resolution] Max sharpness + if (capabilities.sharpness) { + + // Step 1: Apply resolution constraints first + track.applyConstraints({ + advanced: [{ width: 1280, height: 720 }] + }).then(() => { + // console.log("✅ Resolution applied", track.getSettings().width, "x", track.getSettings().height); + + // Step 2: Apply sharpness separately + return track.applyConstraints({ advanced: [{ sharpness: 100 }] }); + }).then(() => { + // console.log("✅ Sharpness applied") + + return track.applyConstraints({ advanced: [{ exposureMode: 'continuous' }] }); + }).then(() => { + // console.log("✅ exposureMode applied"); - // track.applyConstraints ({ - // advanced: [ - // {sharpness: 80}, - // { width: 1280, height: 720 } - // ] - // }) - // .then(() => {console.log("✅ Sharpness applied"); console.log("📷 Applied Constraintsss:", track.getSettings()); }) - // .catch(err => console.error("❌ Failed to apply sharpness:", err)); + }) + .then(() => { console.log("📷 Applied Constraintsss:", track.getSettings()); + }).catch(err => + // console.error("❌ Failed to apply constraints:", err) + ); - // Step 1: Apply resolution constraints first - track.applyConstraints({ - advanced: [{ width: 1280, height: 720 }] - }).then(() => { - console.log("✅ Resolution applied", track.getSettings().width, "x", track.getSettings().height); - - // Step 2: Apply sharpness separately - return track.applyConstraints({ advanced: [{ sharpness: 100 }] }); - }).then(() => {console.log("✅ Sharpness applied") - - // Step 2: Apply sharpness separately - // return track.applyConstraints({ advanced: [{ whiteBalanceMode: 'manual' }] }); - // }).then(() => {console.log("✅ whitebalancemode continous applied"); - - return track.applyConstraints({ advanced: [{ exposureMode: 'continuous' }] }); - }).then(() => {console.log("✅ exposureMode applied"); - - // return track.applyConstraints({ advanced: [{ exposureTime: 100 }] }); - // }).then(() => {console.log("✅ exposure time improvement applied"); - - - - - }) - .then(() => { console.log("📷 Applied Constraintsss:", track.getSettings()); - }).catch(err => console.error("❌ Failed to apply constraints:", err)); - - } else { - console.warn("⚠️ Sharpness not supported on this camera"); - } - } - - console.log("📷 Applied Constraintsss:", track.getSettings()); - console.log("📷 Applied Capabilities:",track.getCapabilities()); - - // console.log("Is it a video element?", videoElement instanceof HTMLVideoElement); - // console.log("Camera Ready! Video element:", videoElement); - // this.videoElement = videoElement; Store for later use - // this.scanStartTime = performance.now(); Start timing - // this.scanTime = null; Reset previous scan time - // if (!videoElement || !videoElement.srcObject) { - // console.error("❌ No video source found."); - // return; - // } - - // const track = videoElement.srcObject.getVideoTracks()[0]; - - // if (!videoElement) { - // console.error("❌ No video element provided."); - // return; - // } else { - // console.log(" video element provided."); - - // } - - // Wait a bit to ensure the video stream is attached - // await new Promise(resolve => setTimeout(resolve, 1000)); - - // if (!videoElement.srcObject) { - // console.error("❌ No video source (srcObject is missing)."); - // return; - // } - - // const track = videoElement.srcObject.getVideoTracks()[0]; - - // if (!track) { - // console.error("❌ No video track found."); - // return; - // } - // const capabilities = track.getCapabilities(); - - // console.log("📸 Camera Capabilities:", capabilities); Debugging - - // if ("sharpness" in capabilities) { - // try { - // await track.applyConstraints({ - // advanced: [{ sharpness: 100 }] Max sharpness - // }); - - // console.log("✅ Sharpness applied:", track.getSettings().sharpness); - // } catch (error) { - // console.error("❌ Failed to apply sharpness:", error); - // } - // } else { - // console.warn("⚠️ Sharpness not supported on this camera."); - // }; + } else { + console.warn("⚠️ Some settings are not supported on this camera"); + } + } + // console.log("📷 Applied Constraintsss:", track.getSettings()); + // console.log("📷 Applied Capabilities:",track.getCapabilities()); try { const devices = await navigator.mediaDevices.enumerateDevices(); @@ -1039,7 +894,7 @@ console.log("🎬 Video.srcObject:", video?.srcObject); if (response.ok) { // If the form submission was successful, display a success message // alert('Success!', 'Item form has been successfully submitted.', 'success'); - const updatedItem = await response.json(); + //const updatedItem = await response.json(); // this.items.push(updatedItem); // console.log(updatedItem); @@ -1071,15 +926,6 @@ console.log("🎬 Video.srcObject:", video?.srcObject); this.itemlateststatus = this.thisItem.latestStatus ? this.thisItem.latestStatus : this.thisItem.toOther; this.itemassignedtouser = this.thisItem.toUser == this.currentUser.id || this.thisItem.lastUser == this.currentUser.id ? true : false; // console.log(this.thisItem); - - - // if ((this.thisItem.toOther === "Repair" || this.thisItem.toOther === "Calibration" || this.thisItem.toOther === "Return" ) && this.thisItem.lastUser === this.currentUser.id && this.thisItem.movementComplete === false) { - // this.selectedAction = "receive"; - // } - - // if ((this.itemlateststatus === "Repair" || this.itemlateststatus === "Calibration" || this.itemlateststatus === "Return" ) && this.thisItem.lastUser === this.currentUser.id && this.thisItem.movementComplete === false) { - // this.selectedAction = "receive"; - // } } else { console.error('Failed to fetch item information'); diff --git a/Controllers/API/Inventory/InvMainAPI.cs b/Controllers/API/Inventory/InvMainAPI.cs index a91cf37..4afb06a 100644 --- a/Controllers/API/Inventory/InvMainAPI.cs +++ b/Controllers/API/Inventory/InvMainAPI.cs @@ -553,8 +553,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory public async Task ItemMovementList() { - //var itemMovementList = await _centralDbContext.ItemMovements.Include(i => i.NextUser).Include(i => i.Item).ThenInclude(i => i.Product).ToListAsync(); - var itemMovementList = await _centralDbContext.ItemMovements .Include(i => i.Item) .ThenInclude(i => i.Product) @@ -566,7 +564,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory .Include(i => i.NextUser) .Include(i => i.NextUser) .ToListAsync(); - //var itemList = await _centralDbContext.Items.ToListAsync(); int itemrow = 0; var itemMovementListWithQR = itemMovementList.Select(item => new @@ -578,12 +575,9 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory toUserName = item.NextUser?.FullName, lastUserName = item.FromUser?.FullName }).ToList(); - //Console.WriteLine(Json(itemMovementList)); + //Console.WriteLine(Json(itemMovementListWithQR)); - //return Json(itemMovementList); - //return Json(itemMovementListWithQR); - return Json(itemMovementList.Select(i => new { i.Id, @@ -614,16 +608,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory i.receiveDate, i.MovementComplete })); - - //return Json(itemMovementList.Select(item => new - //{ - // id = itemrow++, - // item, - // QRString = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.Value}/I/{item.ItemId}", // Generate QR String - // ProductName = item.Item?.Product?.ProductName, - // toUserName = item.NextUser?.FullName, - // lastUserName = item.FromUser?.FullName - //})); } [HttpPost("AddItemMovement")] @@ -642,7 +626,6 @@ namespace PSTW_CentralSystem.Controllers.API.Inventory // throw new Exception("itemmovement.ToUser is null"); //} - //var inventoryMaster = await _centralDbContext.InventoryMasters.Include("User").FirstOrDefaultAsync(i => i.UserId == itemmovement.ToUser) ?? new InventoryMasterModel { UserId = itemmovement.ToUser }; var inventoryMaster = await _centralDbContext.InventoryMasters.Include("User").FirstOrDefaultAsync(i => i.UserId == itemmovement.ToUser); if (inventoryMaster != null) {