mirror of
https://github.com/LD-Reborn/Berufsschule_HAM.git
synced 2025-12-20 06:51:55 +00:00
Merge pull request #138 from LD-Reborn/137-feature-qr-scanner-to-inventarize-items
Added qr code reader and general inventory to /Home/Inventory
This commit is contained in:
@@ -102,10 +102,9 @@ public class AssetsController : Controller
|
||||
{
|
||||
attributeSet.Add(new LdapAttribute("name", assetModel.Name));
|
||||
}
|
||||
if (assetModel.Description != null)
|
||||
{
|
||||
assetModel.Description ??= new();
|
||||
assetModel.Description.Inventory = GenerateInventory();
|
||||
attributeSet.Add(new LdapAttribute("description", JsonSerializer.Serialize(assetModel.Description)));
|
||||
}
|
||||
|
||||
await _ldap.CreateAsset(attributeSet);
|
||||
result = new AssetsCreateResponseModel(successful: true, assetId);
|
||||
@@ -145,7 +144,7 @@ public class AssetsController : Controller
|
||||
}
|
||||
|
||||
[HttpPatch("Update")]
|
||||
public async Task<AssetsUpdateResponseModel> Update([FromBody]AssetsModifyRequestModel requestModel)
|
||||
public async Task<AssetsUpdateResponseModel> Update([FromBody] AssetsModifyRequestModel requestModel)
|
||||
{
|
||||
AssetsUpdateResponseModel result;
|
||||
if (requestModel is null)
|
||||
@@ -192,8 +191,7 @@ public class AssetsController : Controller
|
||||
}
|
||||
if (requestModel.UpdateInventory)
|
||||
{
|
||||
string? userName = User.Identity?.Name ?? "Unknown";
|
||||
asset.Description.Inventory = new() { Date = DateTime.Now.ToString("yyyy-MM-dd"), PersonUid = userName };
|
||||
asset.Description.Inventory = GenerateInventory();
|
||||
await _ldap.UpdateAsset(cn, "description", JsonSerializer.Serialize(asset.Description));
|
||||
}
|
||||
|
||||
@@ -206,4 +204,10 @@ public class AssetsController : Controller
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private AssetInventory GenerateInventory()
|
||||
{
|
||||
string? userName = User.Identity?.Name ?? "Unknown";
|
||||
return new() { Date = DateTime.UtcNow.ToString("o"), PersonUid = userName };
|
||||
}
|
||||
}
|
||||
@@ -6,17 +6,606 @@
|
||||
ViewData["Title"] = T["Inventory"];
|
||||
}
|
||||
|
||||
|
||||
<div class="container py-4">
|
||||
<h2 class="mb-3">@T["Inventory"]</h2>
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-md-3 text-center">
|
||||
<input type="text" id="barcodeInput" class="form-control mt-3" placeholder="@T["Scanned code appears here"]" />
|
||||
<button id="enterAssetIdManuallyButton" class="btn btn-secondary mt-3">@T["Enter asset ID manually"]</button>
|
||||
</div>
|
||||
<div class="col-md-6 text-center">
|
||||
<div id="reader" style="display:none" class="mt-3"></div>
|
||||
<button id="scanBarcodeButton" class="btn btn-primary mt-3">@T["Scan barcode"]</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-4 d-flex flex-wrap gap-2">
|
||||
<button class="btn btn-primary">Dummy button</button>
|
||||
<button class="btn btn-secondary">Dummy button</button>
|
||||
<button class="btn btn-danger">Dummy button</button>
|
||||
<!-- Detail view Modal -->
|
||||
<div class="modal fade" id="viewAssetModal" tabindex="-1" aria-labelledby="viewAssetModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-info text-white">
|
||||
<h5 class="modal-title" id="viewAssetModalLabel">@T["Asset Details"]</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<div id="viewAssetContent">
|
||||
<p class="text-center text-muted">@T["Waiting for barcode scan..."]</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Abort"]</button>
|
||||
<button type="button" class="btn btn-warning" data-bs-dismiss="modal">@T["Update information"]</button>
|
||||
<button type="button" class="btn btn-primary" data-bs-dismiss="modal">@T["Information is correct"]</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.asset-row > td:not(:last-child) {
|
||||
cursor: pointer;
|
||||
}
|
||||
.asset-row > td {
|
||||
transition: 0.1s ease;
|
||||
}
|
||||
.asset-row:has(td:not(:last-child):hover) > td {
|
||||
background-color: #17a2b8;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
@section Scripts {
|
||||
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js" defer></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.8/html5-qrcode.min.js"></script>
|
||||
|
||||
<script defer>
|
||||
|
||||
function createToastContainer() {
|
||||
const container = document.createElement('div');
|
||||
container.id = 'toastContainer';
|
||||
container.className = 'toast-container position-fixed bottom-0 end-0 p-3';
|
||||
document.body.appendChild(container);
|
||||
return container;
|
||||
}
|
||||
|
||||
// Simple toast helper
|
||||
function showToast(message, type) {
|
||||
const toastContainer = document.getElementById('toastContainer') || createToastContainer();
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast align-items-center text-white bg-${type} border-0`;
|
||||
toast.role = 'alert';
|
||||
toast.innerHTML = `
|
||||
<div class="d-flex">
|
||||
<div class="toast-body">${message}</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
|
||||
</div>
|
||||
`;
|
||||
toastContainer.appendChild(toast);
|
||||
const bsToast = new bootstrap.Toast(toast, { delay: 3000 });
|
||||
bsToast.show();
|
||||
toast.addEventListener('hidden.bs.toast', () => toast.remove());
|
||||
}
|
||||
|
||||
function downloadBarcode(svgId, filename = "barcode.png") {
|
||||
const svg = document.getElementById(svgId);
|
||||
const serializer = new XMLSerializer();
|
||||
const svgString = serializer.serializeToString(svg);
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
|
||||
// Optionally set canvas size
|
||||
const bbox = svg.getBBox();
|
||||
canvas.width = bbox.width + 20; // padding
|
||||
canvas.height = bbox.height + 20;
|
||||
|
||||
const img = new Image();
|
||||
const svgBlob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
|
||||
const url = URL.createObjectURL(svgBlob);
|
||||
|
||||
img.onload = () => {
|
||||
ctx.drawImage(img, 0, 0);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
const pngUrl = canvas.toDataURL("image/png");
|
||||
const a = document.createElement("a");
|
||||
a.href = pngUrl;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
};
|
||||
|
||||
img.src = url;
|
||||
}
|
||||
|
||||
function printBarcode(svgId) {
|
||||
const svg = document.getElementById(svgId);
|
||||
if (!svg) return;
|
||||
|
||||
// Serialize the SVG
|
||||
const serializer = new XMLSerializer();
|
||||
const svgString = serializer.serializeToString(svg);
|
||||
|
||||
// Open a new window for printing
|
||||
const printWindow = window.open('', '_blank');
|
||||
printWindow.document.write(`
|
||||
<html>
|
||||
<head>
|
||||
<title>Print Barcode</title>
|
||||
<style>
|
||||
body { text-align: center; margin: 0; padding: 20px; }
|
||||
svg { width: 300px; height: auto; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${svgString}
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
printWindow.document.close();
|
||||
printWindow.focus();
|
||||
printWindow.print();
|
||||
printWindow.close();
|
||||
}
|
||||
|
||||
|
||||
function idToEAN13(id) {
|
||||
const padded = id.toString().padStart(12, "0"); // 12 digits
|
||||
return padded;
|
||||
}
|
||||
|
||||
async function onScanSuccess(decodedText, decodedResult) {
|
||||
const rawDecoded = decodedText;
|
||||
decodedText = decodedText.substr(0,11).replace(/^0+/, '');
|
||||
console.log(`Code matched = ${decodedText}`, decodedResult);
|
||||
document.getElementById("barcodeInput").value = decodedText;
|
||||
|
||||
if (decodedResult != null)
|
||||
{
|
||||
html5QrCode.stop().then(() => console.log("Scanner stopped.")).catch(console.error);
|
||||
}
|
||||
|
||||
// Now show the asset modal
|
||||
const viewModal = document.getElementById('viewAssetModal');
|
||||
const viewContent = document.getElementById('viewAssetContent');
|
||||
const modal = new bootstrap.Modal(viewModal);
|
||||
|
||||
viewContent.innerHTML = '<p class="text-center text-muted">@T["Loading..."]</p>';
|
||||
modal.show();
|
||||
|
||||
try {
|
||||
const response = await fetch(`/Assets/Get?cn=${decodedText}`);
|
||||
const json = await response.json();
|
||||
const asset = json.assetsModel;
|
||||
|
||||
if (!asset) {
|
||||
viewContent.innerHTML = `<p class="text-danger text-center">@T["Asset not found."]</p>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const html = `
|
||||
<div class="row g-3">
|
||||
<h6 class="fw-bold">@T["Barcode"]</h6>
|
||||
<div class="col-md-6">
|
||||
<svg id="ean13" class="form-control" name="Barcode" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<button id="downloadBtn" class="form-control my-2 btn btn-primary">@T["Download Barcode"]</button>
|
||||
<button id="printBtn" class="form-control my-2 btn btn-primary">@T["Print Barcode"]</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Name"]</label>
|
||||
<input type="text" class="form-control" name="Name" value="${asset.Name || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Location"]</label>
|
||||
<input type="text" class="form-control" name="Location" value="${asset.Location || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Owner"]</label>
|
||||
<input type="text" class="form-control" name="Owner" value="${asset.Owner || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Serial Number"]</label>
|
||||
<input type="text" class="form-control" name="SerialNumber" value="${asset.SerialNumber || ''}" disabled />
|
||||
</div>
|
||||
</div>
|
||||
<hr class="my-3" />
|
||||
<div class="row g-3">
|
||||
<h6 class="fw-bold">@T["Description"]</h6>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Type"]</label>
|
||||
<input type="text" class="form-control" name="Description.Type" value="${asset.Description?.Type || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Make"]</label>
|
||||
<input type="text" class="form-control" name="Description.Make" value="${asset.Description?.Make || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Model"]</label>
|
||||
<input type="text" class="form-control" name="Description.Model" value="${asset.Description?.Model || ''}" disabled />
|
||||
</div>
|
||||
</div>
|
||||
${asset.Description?.Attributes ? `
|
||||
<hr class="my-3" />
|
||||
<div class="row g-3">
|
||||
<h6 class="fw-bold">@T["Attributes"]</h6>
|
||||
${Object.entries(asset.Description.Attributes)
|
||||
.map(([k,v]) => `
|
||||
<div class="d-flex gap-2 align-items-center attribute-row">
|
||||
<input type="text" class="form-control w-50" placeholder="@T["Attribute name"]" data-attr-name disabled value="${k}" />:
|
||||
<input type="text" class="form-control" placeholder="@T["Attribute value"]" data-attr-value disabled value="${v}" />
|
||||
</div>`)
|
||||
.join('')}
|
||||
</div>` : ''}
|
||||
|
||||
${asset.Description?.Purchase ? `
|
||||
<hr class="my-3" />
|
||||
<div class="row g-3">
|
||||
<h6 class="fw-bold">@T["Purchase Information"]</h6>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchase Date"]</label>
|
||||
<input type="date" class="form-control" name="Description.Purchase.PurchaseDate" value="${asset.Description.Purchase.PurchaseDate || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchase Value"]</label>
|
||||
<input type="text" class="form-control" name="Description.Purchase.PurchaseValue" value="${asset.Description.Purchase.PurchaseValue || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchased At"]</label>
|
||||
<input type="text" class="form-control" name="Description.Purchase.PurchaseAt" value="${asset.Description.Purchase.PurchaseAt || ''}" disabled />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchased By"]</label>
|
||||
<input type="text" class="form-control" name="Description.Purchase.PurchaseBy" value="${asset.Description.Purchase.PurchaseBy || ''}" disabled />
|
||||
</div>
|
||||
</div>` : ''}
|
||||
</div>`;
|
||||
|
||||
viewContent.innerHTML = html;
|
||||
console.log(rawDecoded);
|
||||
JsBarcode("#ean13", idToEAN13(decodedText), {
|
||||
format: "EAN13",
|
||||
lineColor: "#000",
|
||||
width: 2,
|
||||
height: 80,
|
||||
displayValue: true
|
||||
});
|
||||
|
||||
document.getElementById("downloadBtn").addEventListener("click", () => downloadBarcode("ean13", decodedText));
|
||||
document.getElementById("printBtn").addEventListener("click", () => printBarcode("ean13"));
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
viewContent.innerHTML = `<p class="text-danger text-center">@T["Error loading asset details"]</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function onScanError(errorMessage) {
|
||||
console.warn(errorMessage);
|
||||
}
|
||||
|
||||
let html5QrCode;
|
||||
|
||||
const assetIdManuallyButton = document.querySelector('#enterAssetIdManuallyButton');
|
||||
if (assetIdManuallyButton) {
|
||||
assetIdManuallyButton.addEventListener('click', async () => {
|
||||
await onScanSuccess(document.getElementById("barcodeInput").value, null);
|
||||
});
|
||||
}
|
||||
const scanBarcodeButton = document.querySelector('#scanBarcodeButton');
|
||||
if (scanBarcodeButton) {
|
||||
scanBarcodeButton.addEventListener('click', () => {
|
||||
let reader = document.querySelector('#reader');
|
||||
reader.style.display = ""
|
||||
|
||||
html5QrCode = new Html5Qrcode("reader");
|
||||
html5QrCode.start(
|
||||
{ facingMode: "environment" },
|
||||
{ fps: 10, qrbox: { width: 300, height: 150 } },
|
||||
onScanSuccess,
|
||||
onScanError
|
||||
);
|
||||
|
||||
|
||||
document.getElementById('viewAssetModal').addEventListener('hidden.bs.modal', () => {
|
||||
html5QrCode.start(
|
||||
{ facingMode: "environment" },
|
||||
{ fps: 10, qrbox: { width: 300, height: 150 } },
|
||||
onScanSuccess,
|
||||
onScanError
|
||||
).catch(err => console.error("Error restarting scanner:", err));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Handle "Update information" button click in viewAssetModal
|
||||
const updateBtn = document.querySelector('#viewAssetModal .btn.btn-warning');
|
||||
if (updateBtn) {
|
||||
updateBtn.addEventListener('click', () => {
|
||||
const viewModalEl = document.getElementById('viewAssetModal');
|
||||
const viewModal = bootstrap.Modal.getInstance(viewModalEl);
|
||||
|
||||
// Hide current modal
|
||||
viewModal.hide();
|
||||
|
||||
// Wait a bit to ensure fade animation finishes
|
||||
setTimeout(() => {
|
||||
const updateModalEl = document.getElementById('updateAssetModal');
|
||||
const updateModal = new bootstrap.Modal(updateModalEl);
|
||||
|
||||
// If you have the scanned asset ID, pass it as data-asset-id for the next modal
|
||||
const scannedId = document.getElementById("barcodeInput")?.value || "";
|
||||
if (scannedId) {
|
||||
updateModalEl.setAttribute('data-asset-id', scannedId);
|
||||
}
|
||||
|
||||
// Show the update modal
|
||||
updateModal.show();
|
||||
}, 400);
|
||||
});
|
||||
}
|
||||
|
||||
const okBtn = document.querySelector('#viewAssetModal .btn.btn-primary');
|
||||
if (okBtn) {
|
||||
okBtn.addEventListener('click', (e) => {
|
||||
try {
|
||||
let assetId = document.getElementById("barcodeInput").value;
|
||||
const jsonData = {"Cn": assetId};
|
||||
jsonData.UpdateInventory = true;
|
||||
const response = fetch('/Assets/Update', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
||||
body: JSON.stringify(jsonData)
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(result => {
|
||||
if (result.success) {
|
||||
showToast('@T["Asset inventorized successfully"]', 'success');
|
||||
} else {
|
||||
e.preventDefault();
|
||||
showToast(result.reason || '@T["Error updating asset"]', 'danger');
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
showToast('@T["Error contacting server"]', 'danger');
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
}
|
||||
|
||||
|
||||
<div class="modal fade" id="updateAssetModal" tabindex="-1" aria-labelledby="updateAssetModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header bg-warning text-dark">
|
||||
<h5 class="modal-title" id="updateAssetModalLabel">@T["Update Asset"]</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
|
||||
<form id="updateAssetForm">
|
||||
<div class="modal-body">
|
||||
<div class="row g-3">
|
||||
<!-- Same fields as in Create -->
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Name"]</label>
|
||||
<input type="text" class="form-control" name="Name" />
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Location"]</label>
|
||||
<input type="text" class="form-control" name="Location" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Owner"]</label>
|
||||
<input type="text" class="form-control" name="Owner" />
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Serial Number"]</label>
|
||||
<input type="text" class="form-control" name="SerialNumber" />
|
||||
</div>
|
||||
|
||||
<hr class="my-3" />
|
||||
|
||||
<h6 class="fw-bold">@T["Description"]</h6>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Type"]</label>
|
||||
<input type="text" class="form-control" name="Description.Type" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Make"]</label>
|
||||
<input type="text" class="form-control" name="Description.Make" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Model"]</label>
|
||||
<input type="text" class="form-control" name="Description.Model" />
|
||||
</div>
|
||||
|
||||
<div class="col-12 mt-3">
|
||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
<h6 class="fw-bold mb-0">@T["Attributes"]</h6>
|
||||
</div>
|
||||
<div id="updateAttributesContainer" class="d-flex flex-column gap-2"></div>
|
||||
<button type="button" class="btn btn-sm btn-success mt-3" id="updateAddAttributeBtn">
|
||||
@T["Add Attribute"]
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<hr class="my-3" />
|
||||
|
||||
<h6 class="fw-bold">@T["Purchase Information"]</h6>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchase Date"]</label>
|
||||
<input type="date" class="form-control" name="Description.Purchase.PurchaseDate" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchase Value"]</label>
|
||||
<input type="text" class="form-control" name="Description.Purchase.PurchaseValue" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchased At"]</label>
|
||||
<input type="text" class="form-control" name="Description.Purchase.PurchaseAt" />
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">@T["Purchased By"]</label>
|
||||
<input type="text" class="form-control" name="Description.Purchase.PurchaseBy" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Cancel"]</button>
|
||||
<button type="submit" class="btn btn-warning">@T["Save Changes"]</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const updateButtons = document.querySelectorAll('.btn-update');
|
||||
const updateModal = document.getElementById('updateAssetModal');
|
||||
const updateForm = document.getElementById('updateAssetForm');
|
||||
const updateAttributesContainer = document.getElementById('updateAttributesContainer');
|
||||
const addAttrBtn = document.getElementById('updateAddAttributeBtn');
|
||||
let assetId = null;
|
||||
|
||||
addAttrBtn.addEventListener('click', () => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'd-flex gap-2 align-items-center attribute-row';
|
||||
row.innerHTML = `
|
||||
<input type="text" class="form-control" placeholder="@T["Attribute name"]" data-attr-name />
|
||||
<input type="text" class="form-control" placeholder="@T["Attribute value"]" data-attr-value />
|
||||
<button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
|
||||
`;
|
||||
updateAttributesContainer.appendChild(row);
|
||||
});
|
||||
|
||||
updateAttributesContainer.addEventListener('click', e => {
|
||||
if (e.target.classList.contains('btn-remove-attribute')) {
|
||||
e.target.closest('.attribute-row').remove();
|
||||
}
|
||||
});
|
||||
|
||||
updateModal.addEventListener('show.bs.modal', async event => {
|
||||
const modal = event.target;
|
||||
const button = event.relatedTarget;
|
||||
assetId = modal.getAttribute('data-asset-id');
|
||||
|
||||
updateAttributesContainer.innerHTML = '';
|
||||
updateForm.reset();
|
||||
|
||||
try {
|
||||
const response = await fetch(`/Assets/Get?cn=${assetId}`);
|
||||
const responseJson = await response.json();
|
||||
const asset = responseJson.assetsModel;
|
||||
|
||||
for (const [key, value] of Object.entries(asset)) {
|
||||
const input = updateForm.querySelector(`[name="${key}"]`);
|
||||
if (input) input.value = value;
|
||||
}
|
||||
|
||||
// Handle nested description fields
|
||||
if (asset.Description) {
|
||||
for (const [descKey, descVal] of Object.entries(asset.Description)) {
|
||||
const field = updateForm.querySelector(`[name="Description.${descKey}"]`);
|
||||
if (field && typeof descVal === 'string') field.value = descVal;
|
||||
}
|
||||
|
||||
// Attributes
|
||||
if (asset.Description.Attributes) {
|
||||
for (const [attrName, attrValue] of Object.entries(asset.Description.Attributes)) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'd-flex gap-2 align-items-center attribute-row';
|
||||
row.innerHTML = `
|
||||
<input type="text" class="form-control" value="${attrName}" data-attr-name />
|
||||
<input type="text" class="form-control" value="${attrValue}" data-attr-value />
|
||||
<button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
|
||||
`;
|
||||
updateAttributesContainer.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
// Purchase info
|
||||
if (asset.Description.Purchase) {
|
||||
for (const [pKey, pValue] of Object.entries(asset.Description.Purchase)) {
|
||||
const field = updateForm.querySelector(`[name="Description.Purchase.${pKey}"]`);
|
||||
if (field) field.value = pValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
showToast('@T["Error loading asset data"]', 'danger');
|
||||
}
|
||||
});
|
||||
|
||||
updateForm.addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(updateForm);
|
||||
const jsonData = {"Cn": assetId};
|
||||
for (const [key, value] of formData.entries()) {
|
||||
if (!value) continue;
|
||||
const keys = key.split('.');
|
||||
let target = jsonData;
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
target[keys[i]] = target[keys[i]] || {};
|
||||
target = target[keys[i]];
|
||||
}
|
||||
target[keys[keys.length - 1]] = value;
|
||||
}
|
||||
|
||||
const attributes = {};
|
||||
document.querySelectorAll('#updateAttributesContainer .attribute-row').forEach(row => {
|
||||
const name = row.querySelector('[data-attr-name]').value.trim();
|
||||
const value = row.querySelector('[data-attr-value]').value.trim();
|
||||
if (name) attributes[name] = value;
|
||||
});
|
||||
|
||||
if (Object.keys(attributes).length > 0) {
|
||||
jsonData.Description = jsonData.Description || {};
|
||||
jsonData.Description.Attributes = attributes;
|
||||
}
|
||||
jsonData.UpdateInventory = true;
|
||||
|
||||
try {
|
||||
const response = await fetch('/Assets/Update', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
||||
body: JSON.stringify(jsonData)
|
||||
});
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
bootstrap.Modal.getInstance(updateModal).hide();
|
||||
showToast('@T["Asset updated successfully"]', 'success');
|
||||
|
||||
// Optionally refresh the row
|
||||
const row = [...document.querySelectorAll('tr')]
|
||||
.find(r => r.querySelector(`[data-asset-id="${jsonData.Cn}"]`));
|
||||
if (row) {
|
||||
row.children[0].textContent = jsonData.Owner || '';
|
||||
row.children[1].textContent = jsonData.Cn || '';
|
||||
row.children[2].textContent = jsonData.Name || '';
|
||||
row.children[3].textContent = jsonData.Location || '';
|
||||
}
|
||||
} else {
|
||||
showToast(result.reason || '@T["Error updating asset"]', 'danger');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
showToast('@T["Error contacting server"]', 'danger');
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
Reference in New Issue
Block a user