PSTW_CentralizeSystem/Areas/Inventory/Views/InventoryMaster/ItemRegistration.cshtml
2025-07-31 11:44:56 +08:00

1199 lines
67 KiB
Plaintext

@{
ViewData["Title"] = "Item Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<style>
@@font-face {
font-family: 'OCR-A';
src: url('../assets/fonts/ocraext.ttf');
}
.QrPrintFont {
font-family: 'OCR-A', monospace;
}
.table td img {
display: block !important;
}
</style>
@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml");
<div id="registerItem" class="row">
<div class="row card">
<div class="card-header">
<button id="addItemBtn" class="btn btn-success col-md-3 col-lg-3 m-1 col-12"><i class="fa fa-plus"></i>&nbsp;Add Item</button>
</div>
<div class="card-body">
@* <div v-if="loading">
<div class="spinner-border text-info" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div> *@
<table class="table table-bordered table-hover table-striped no-wrap" id="itemDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
</div>
</div>
<div class="modal fade" id="QrItemModal" tabindex="-1" role="dialog" aria-labelledby="QrItemModalLabel" aria-hidden="true" data-bs-target="#staticBackdrop">
<div class="modal-dialog modal-dialog-centered modal-md" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="QrItemModalLabel"></h5>
<button type="button" class="closeModal btn-close" data-bs-dismiss="modal" aria-label="Close" v-on:click="showItemModal=false"></button>
</div>
<div class="modal-body d-flex justify-content-center align-items-center">
<div class="container" style="font-family: 'OCR A', monospace;">
<div class="row" ref="qrInfo" id="qrInfo">
<div class="col-5 text-center d-flex align-items-center justify-content-center">
<div class="row">
<div class="col-12 text-center">
<div id="QrContainer"></div>
<div class="col-12 text-center">
{{thisQRInfo.uniqueID}}
</div>
</div>
</div>
</div>
<div class="col-7 d-flex align-items-center justify-content-center">
<div class="text-center fs-4 text">
<div class="col-12 my-3">
{{thisQRInfo.departmentName}}
</div>
<div class="col-12 my-3">
{{thisQRInfo.productShortName}}
</div>
<div class="col-12 my-3">
{{thisQRInfo.serialNumber}}
</div>
<div class="col-12 my-3">
{{thisQRInfo.partNumber}}
</div>
</div>
</div>
</div>
<div class="row">
<button v-on:click="printQRInfo">Print QR Info</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="registerItemModal" tabindex="-1" role="dialog" aria-labelledby="addItemModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addItemModalLabel">{{editSection? 'Edit Item' : 'Add Item'}}</h5>
<button type="button" class="closeModal" data-dismiss="modal" aria-label="Close" v-on:click="showItemModal=false">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="container-fluid">
<form v-on:submit.prevent="editSection ? submitEditItem() : addItem()" data-aos="fade-right">
<div class=" register" data-aos="fade-right">
<div class="row" data-aos="fade-right">
@*Right Side*@
<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">
<h3 class="register-heading">{{editSection? 'EDIT ITEM' : 'REGISTRATION ITEM'}}</h3>
<div class="row register-form">
<div class="col-md-6">
<div class="form-group row">
<label class="col-sm-4 col-form-label">Company:</label>
<div class="col-sm-8">
<div class="dropdown">
<select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedCompany" :disabled="currentUserCompanyDept != null" required>
<option class="btn-light" value="" disabled selected>Select Company</option>
<option class="btn-light" v-for="(item, index) in companies" :key="index" :value="item.companyId">{{item.companyName}}</option>
</select>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Department:</label>
<div class="col-sm-8">
<select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedDepartment" :disabled="currentUserCompanyDept != null" required>
<option class="btn-light" value="" disabled selected>Select Department</option>
<option class="btn-light" v-for="(dept, index) in filteredDepartments" :key="index" :value="dept.departmentId">{{ dept.departmentName }}</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Team:</label>
<div class="col-sm-8">
<select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedTeamType" required>
<option class="btn-light" value="" disabled selected>Select Team</option>
<option class="btn-light" v-for="(team, index) in teamTypes" :key="index" :value="team">{{ team }}</option>
</select>
</div>
</div>
@* Product Name Coding *@
<div class="form-group row">
<label class="col-sm-4 col-form-label">Product Name:</label>
<div class="col-sm-8">
<div class="dropdown">
<select class="btn btn-primary dropdown-toggle col-md-10" v-model="selectedProduct" required>
<option class="btn-light" value="" disabled selected>Select Product</option>
<option class="btn-light" v-for="(item, index) in products" :key="index" :value="item.productId">{{ item.productName + ' (' + item.modelNo + ')' }}</option>
</select>
</div>
</div>
</div>
@* Product Image Display *@
<div class="form-group row align-items-center">
<label for="imageProduct" class="col-sm-4 col-form-label">Product Image: </label>
<div class="col-sm-8">
<img v-if="showProduct.imageProduct" :src="showProduct.imageProduct" alt="Product Image" class="img-fluid" data-toggle="modal" data-target="#imageModal" />
<input type="hidden" id="imageProduct" name="imageProduct" v-model="showProduct">
</div>
</div>
<div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="imageModalLabel">Product Image</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<img :src="showProduct.imageProduct" alt="Product Image" class="img-fluid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
@* Product Category Coding *@
<div class="form-group row">
<label class="col-sm-4 col-form-label">Product Category:</label>
<div class="col-sm-8">
<input type="text" id="category" name="category" v-model="showProduct.category" class="form-control" readonly />
</div>
</div>
@* Part Number Coding *@
<div class="form-group row">
<label class="col-sm-4 col-form-label">Part Number:</label>
<div class="col-sm-8">
<input type="text" id="partNumber" name="partNumber" v-model="partNumber" class="form-control" required />
</div>
</div>
@* Serial Number and Quantity Coding *@
<div v-if="showSerialNumber">
<div class="form-group row align-items-center">
<div class="col-sm-4">
<label for="serialNumber">Serial Number: </label>
</div>
<div class="col-sm-8">
<input type="text" id="serialNumber" name="serialNumber" v-if="showSerialNumber" v-model="serialNumber" class="form-control" v-bind:required="showSerialNumber">
</div>
</div>
</div>
<div v-if="!showSerialNumber">
<div class="form-group row align-items-center">
<div class="col-sm-4">
<label for="quantity">Quantity: </label>
</div>
<div class="col-sm-8">
<input type="number" id="quantity" name="quantity" min="1" v-if="!showSerialNumber" v-model="quantity" class="form-control" v-bind:required="!showSerialNumber">
</div>
</div>
</div>
@* Supplier coding *@
<div class="form-group row align-items-center">
<label class="col-sm-4 col-form-label">Supplier: </label>
<div class="col-sm-8">
<div class="dropdown">
<select class="btn btn-primary dropdown-toggle col-md-10" data-toggle="dropdown" aria-expanded="false" v-model="selectedSupplier" required>
<option class="btn-light" value="" disabled selected>Select Supplier</option>
<option class="btn-light" v-for="(item, index) in suppliers" :key="index">{{ item.supplierCompName }}</option>
</select>
</div>
</div>
</div>
@* Purchase Date coding *@
<div class="form-group row align-items-center">
<label for="purchaseDate" class="col-sm-4 col-form-label">Purchase Date: </label>
<div class="col-sm-8">
<input type="date" id="purchaseDate" name="purchaseDate" required v-model="purchaseDate" class="form-control">
</div>
</div>
@* PO coding *@
<div class="form-group row align-items-center">
<label for="PO" class="col-sm-4 col-form-label">Enter PO: </label>
<div class="col-sm-8">
<input type="text" id="PO" name="PO" required v-model="PO" placeholder="PO123456" class="form-control">
</div>
</div>
</div>
<div class="col-md-6">
@* Item Price in RM *@
<div class="form-group row">
<label for="DefaultPrice" class="col-sm-4">Default Item Price:</label>
<div class="col-sm-8">
<input type="number" id="DefaultPrice" name="DefaultPrice" class="form-control" placeholder="RM 00.00" step="0.01" min="0.01" v-on:input="convertCurrency()" required v-model="DefaultPrice">
</div>
</div>
@* Currency Selection *@
<div class="form-group row">
<label for="currency" class="col-sm-4">Select Currency:</label>
<div class="col-sm-8">
<select id="currency" name="currency" class="btn btn-primary form-control col-md-10" v-model="currency" v-on:change="convertCurrency()">
<option class="btn-light" value="" disabled selected>Select a currency</option>
<option class="btn-light" v-for="(name, code) in currencies" :key="code" :value="code">
{{ code }} - {{ name }}
</option>
</select>
</div>
</div>
@* Currency Rate *@
<div class="form-group row">
<label for="currencyRate" class="col-sm-4">Currency Rate(%):</label>
<div class="col-sm-8">
<input type="number" id="currencyRate" name="currencyRate" class="form-control" placeholder="0.01" step="0.01" min="1" v-on:input="convertCurrency()" required v-model="currencyRate">
</div>
</div>
@* Item Convert Price *@
<div class="form-group row">
<label for="convertPrice" class="col-sm-4">{{ currency ? 'Item Price (' + currency + ') : ' : 'Item Price : ' }}</label>
<div class="col-sm-8">
<input type="number" id="convertPrice" name="convertPrice" class="form-control" readonly v-model="convertPrice">
</div>
</div>
@* Delivery Order Number *@
<div class="form-group row">
<label for="DONo" class="col-sm-4">Enter DO Number:</label>
<div class="col-sm-8">
<input type="text" id="DONo" name="DONo" class="form-control" v-model="DONo" placeholder="DO123456" required>
</div>
</div>
@* Delivery Order Date *@
<div class="form-group row">
<label for="DODate" class="col-sm-4">Enter DO Date:</label>
<div class="col-sm-8">
<input type="date" id="DODate" name="DODate" class="form-control" v-on:input="calculateWarrantyEndDate()" v-model="DODate" required>
</div>
</div>
@* Warranty *@
<div class="form-group row">
<label for="warranty" class="col-sm-4">Enter Warranty (Months):</label>
<div class="col-sm-8">
<input type="number" id="warranty" name="warranty" class="form-control" placeholder="0 , 1 , 2 , 3, ..." step="1" min="0" v-on:input="calculateWarrantyEndDate()" v-model="warranty" required>
</div>
</div>
@* Warranty End Date *@
<div class="form-group row">
<label for="EndWDate" class="col-sm-4">Warranty End:</label>
<div class="col-sm-8">
<input type="date" id="EndWDate" name="EndWDate" class="form-control" readonly v-model="EndWDate">
</div>
</div>
@* Invoice Number *@
<div class="form-group row">
<label for="invoiceNo" class="col-sm-4">Invoice Number:</label>
<div class="col-sm-8">
<input type="text" id="invoiceNo" name="invoiceNo" class="form-control" v-model="invoiceNo" placeholder="Invoice123456" required>
</div>
</div>
@* Invoice Date *@
<div class="form-group row">
<label for="invoiceDate" class="col-sm-4">Invoice Date:</label>
<div class="col-sm-8">
<input type="date" id="invoiceDate" name="invoiceDate" class="form-control" v-model="invoiceDate" required>
</div>
</div>
</div>
@* Submit and Reset Buttons *@
<div class="form-group row">
<div class="col-sm-8 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>
</div>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
<script>
$(function () {
app.mount('#registerItem');
// Attach a click event listener to elements with the class 'btn-success'.
$('#addItemBtn').on('click', function () {
// Show the modal with the ID 'addManufacturerModal'.
$('#registerItemModal').modal('show');
this.addSection = true;
this.editSection = false;
});
$('.closeModal').on('click', function () {
// Show the modal with the ID 'addManufacturerModal'.
$('.modal').modal('hide');
});
});
const app = Vue.createApp({
data() {
return {
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: "",
Dept: null,
teamTypes: ["Continuous", "Manual"],
teamType: "",
productName: null,
imageProduct: null,
addSection: false,
editSection: false,
productCategory: null,
itemID: null,
serialNumber: "",
quantity: 1,
supplierName: null,
purchaseDate: null,
PO: null,
currency: "MYR",
DefaultPrice: null,
currencyRate: 1,
convertPrice: 0.01,
DONo: null,
DODate: null,
warranty: null,
EndWDate: null,
invoiceNo: null,
invoiceDate: null,
partNumber: null,
createdDate: null, // Add new data property
modifiedDate: null, // Add new data property
products: [],
depts: [],
suppliers: [
{
supplierId: 1,
supplierName: "Pang",
},
{
supplierId: 2,
supplierName: "Ms Kim",
},
],
isModalOpen: false,
selectedProduct: "",
selectedSupplier: "",
selectedCompany: "",
selectedDepartment: "",
selectedTeamType: "",
currencies: {},
showItemModal: false,
loading: false,
thisQRInfo: {
uniqueID: null,
departmentName: null,
productShortName: null, // Added for print QR
serialNumber: null,
partNumber: null, // Added for print QR
endWDate: null,
},
items: [],
currentUser: null,
currentUserCompanyDept: null,
}
},
mounted() {
this.fetchUser();
this.fetchItem();
this.fetchCurrencyData();
this.fetchCompanies();
this.fetchProducts();
this.fetchSuppliers();
document.getElementById('addItemBtn').addEventListener('click', () => {
this.resetForm();
this.addSection = true;
this.editSection = false;
$('#registerItemModal').modal('show');
});
document.querySelectorAll('.closeModal').forEach(btn => {
btn.addEventListener('click', () => {
$('.modal').modal('hide');
});
});
},
computed: {
filteredDepartments() {
if (!this.selectedCompany) {
return []; // No company selected, return empty list
}
const company = this.companies.find(c => c.companyId === this.selectedCompany);
// this.selectedDepartment = '';
return company ? company.departments : [];
},
showProduct() {
if (!this.selectedProduct) {
return []; // No company selected, return empty listx`
}
const product = this.products.find(c => c.productId === this.selectedProduct);
return product ? product : {};
},
showSerialNumber() {
return this.showProduct.category === 'Asset' || this.showProduct.category === 'Part';
},
},
methods: {
async addItem() {
// List of required fields
const requiredFields = ['DefaultPrice', 'DONo', 'DODate', 'warranty', 'invoiceNo', 'invoiceDate'];
// Loop through required fields and check if any are null or empty
for (let field of requiredFields) {
if (this[field] === null || this[field] === '') {
alert('Item Error', `Please fill in required fields: ${field}.`, 'warning');
return;
}
}
if (this.showProduct.category == "Disposable") {
this.serialNumber = "";
}
const formData = {
CompanyId: this.selectedCompany,
DepartmentId: this.selectedDepartment,
ProductId: this.selectedProduct,
SerialNumber: this.serialNumber,
Quantity: this.quantity,
Supplier: this.selectedSupplier,
PurchaseDate: this.purchaseDate,
PONo: this.PO,
Currency: this.currency,
DefaultPrice: this.DefaultPrice,
CurrencyRate: this.currencyRate,
ConvertPrice: this.convertPrice,
DONo: this.DONo,
DODate: this.DODate,
Warranty: this.warranty,
EndWDate: this.EndWDate,
InvoiceNo: this.invoiceNo,
InvoiceDate: this.invoiceDate,
CreatedByUserId: this.currentUser.id,
TeamType: this.selectedTeamType,
PartNumber: this.partNumber,
// Add these lines for CreatedDate and ModifiedDate
CreatedDate: null, // Send as null, API will set it to DateTime.Now
ModifiedDate: null // Send as null, API will set it to DateTime.Now
};
try {
// Additional specific checks
if (this.showSerialNumber) {
this.quantity = 0;
if (this.serialNumber === null || this.serialNumber === '') {
alert('Serial Number Error', 'Serial Number must be filled when selecting Item or Part.', 'warning');
return;
}
}
else {
this.serialNumber = null;
if (this.quantity === 0 || this.quantity === null || this.quantity === '') {
alert('quantity Error', 'Quantity is required when selecting Disposable.', 'warning');
return;
}
}
// Proceed to send the data to the API
const response = await fetch('/InvMainAPI/AddItem', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'Authorization': `Bearer ${this.token}`
},
body: JSON.stringify(formData)
});
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();
this.items.push(updatedItem);
this.fetchUser();
this.fetchItem();
// Reset the form
this.resetForm();
} else {
throw new Error('Failed to submit form.');
}
} catch (error) {
console.error('Error:', error);
// Displaying error message
alert('Inventory PSTW Error', `An error occurred: ${error.message}`, 'error');
}
},
initiateTable() {
self = this;
this.itemDatatable = $('#itemDatatable').DataTable({
"data": this.items,
"columns": [
{
"title": "Unique Id",
"data": "uniqueID",
"createdCell": function (td, cellData, rowData, row, col) {
// Assign a unique ID to the <td> element
$(td).attr('id', `qr${cellData}`);
},
},
{
"title": "Print",
"data": "uniqueID",
"render": function (data, type, full, meta) {
var printButton = `<button type="button" class="btn btn-success print-btn" data-id="${data}">Print</button>`;
return printButton;
},
"className": "align-middle",
},
{
"title": "Item Short Name",
"data": "productShortName",
},
{
"title": "Serial Number",
"data": "serialNumber",
},
{
"title": "Part Number",
"data": "partNumber",
},
{
"title": "Category",
"data": "category",
},
{
"title": "Quantity",
"data": "quantity",
},
{
"title": "Supplier",
"data": "supplier",
},
{
"title": "Purchase Date",
"data": "purchaseDate",
},
{
"title": "Price(RM)",
"data": (row) => parseFloat(row.convertPrice).toFixed(2),
},
{
"title": "Warranty Until",
"data": "warranty",
"render": function (data, type, full, meta) {
if (data > 0) { return full.endWDate }
else { return data }
}
},
{
"title": "Created Date",
"data": "createdDate", // Map to the new createdDate field
"render": function (data) {
return data ? new Date(data).toLocaleString() : ''; // Format date for display
}
},
{
"title": "Modified Date",
"data": "modifiedDate", // Map to the new modifiedDate field
"render": function (data) {
return data ? new Date(data).toLocaleString() : ''; // Format date for display
}
},
{
"title": "Location",
"data": "currentUser",
"render": function (data, type, full, meta) {
currentUser = data ?? null;
currentStore = full.currentStore ?? 'N/A';
currentStation = full.currentStation ?? 'N/A';
return `User: ${currentUser}<br>
Store: ${currentStore}<br>
Station: ${currentStation}`
}
},
{
"title": "Edit",
"data": "itemID",
"render": function (data) {
var editButton = `<button type="button" class="btn btn-success edit-btn" data-id="${data}">Edit</button>`;
return editButton;
},
"className": "align-middle",
},
{
"title": "Delete",
"data": "itemID",
"render": function (data) {
var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
return deleteButton;
},
"className": "align-middle",
}
],
responsive: true,
drawCallback: function (settings) {
setTimeout(() => {
const api = this.api();
api.rows().every(function () {
const data = this.data();
const containerId = `qr${data.uniqueID}`;
const container = document.getElementById(containerId);
if (!container) {
return;
}
container.innerHTML = "";
container.append(data.uniqueID);
// Ensure qrString is valid before generating QR code
if (!data.qrString) {
return;
}
// Generate QR Code
new QRCode(container, {
text: data.qrString,
width: 100,
height: 100,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.M
});
});
}, 100); // Small delay to ensure elements exist
}
})
// Attach click event listener to the edit buttons
$('#itemDatatable tbody').off('click', '.edit-btn').on('click', '.edit-btn', function () {
const itemId = $(this).data('id');
self.editItem(itemId);
});
// Attach click event listener to the delete buttons
$('#itemDatatable tbody').off('click', '.delete-btn').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;
},
async fetchItem() {
try {
const response = await fetch('/InvMainAPI/ItemList', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
if (!response.ok) {
throw new Error('Failed to fetch item');
}
this.items = await response.json();
if (this.itemDatatable) {
this.itemDatatable.clear().destroy();
}
this.initiateTable();
}
catch (error) {
console.error('Error fetching item:', error);
}
},
async fetchProducts() {
try {
const response = await fetch('/InvMainAPI/ProductList', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
this.products = await response.json();
}
catch (error) {
console.error('Error fetching products:', error);
}
},
async fetchCompanies() {
try {
const response = await fetch('/AdminAPI/GetDepartmentWithCompanyList', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch companies');
}
this.companies = await response.json();
} catch (error) {
console.error('Error fetching products:', error);
}
},
async fetchSuppliers() {
try {
const response = await fetch('/InvMainAPI/SupplierList', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch suppliers');
}
this.suppliers = await response.json();
} catch (error) {
console.error('Error fetching suppliers:', error);
}
},
async fetchCurrencyData() {
try {
const response = await fetch('https://openexchangerates.org/api/currencies.json');
this.currencies = await response.json();
} catch (error) {
console.error('Error fetching currency data:', error);
}
},
calculateWarrantyEndDate() {
if (!this.DODate || isNaN(Date.parse(this.DODate))) {
this.EndWDate = null;
return;
}
const DODates = new Date(this.DODate);
const warrantyMonth = parseInt(this.warranty);
if (!isNaN(warrantyMonth)) {
DODates.setMonth(DODates.getMonth() + warrantyMonth);
this.EndWDate = DODates.toISOString().split('T')[0];
} else {
this.EndWDate = null;
}
},
convertCurrency() {
console.log('Selected currency:', this.currency);
const total = this.DefaultPrice * this.currencyRate;
this.convertPrice = total.toFixed(2);
this.DefaultPrice = this.DefaultPrice
},
resetForm() {
this.company = '';
this.Dept = null;
this.productName = null;
this.imageProduct = null;
this.serialNumber = '';
this.quantity = 1;
this.supplierName = null;
this.purchaseDate = null;
this.PO = null;
this.currency = 'MYR';
this.DefaultPrice = null;
this.currencyRate = 1;
this.convertPrice = 0.01;
this.DODate = null;
this.warranty = null;
this.DONo = null;
this.invoiceNo = null;
this.EndWDate = null;
this.invoiceDate = null;
this.selectedProduct = '';
this.selectedSupplier = '';
this.selectedTeamType = '';
this.partNumber = null;
this.createdDate = null; // Clear createdDate on form reset
this.modifiedDate = null; // Clear modifiedDate on form reset
// Handle currentUserCompanyDept for company and department dropdowns
if (this.currentUserCompanyDept) {
this.selectedCompany = this.currentUserCompanyDept.companyId;
this.selectedDepartment = this.currentUserCompanyDept.departmentId;
} else {
this.selectedCompany = '';
this.selectedDepartment = '';
}
},
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);
this.itemDatatable
.row($(`.delete-btn[data-id="${itemId}"]`).closest('tr'))
.remove()
.draw();
}
}
catch (error) {
console.error("Error deleting item:", error);
alert("An error occurred while deleting the item.");
}
finally {
this.loading = false;
}
},
async editItem(itemID) {
const item = this.items.find(s => s.itemID === itemID);
if (!item) {
alert('Error', 'Item not found!', 'warning');
return;
}
this.itemID = itemID;
this.selectedCompany = item.companyId;
this.selectedDepartment = item.departmentId;
this.selectedProduct = item.productId;
this.serialNumber = item.serialNumber;
this.quantity = item.quantity;
this.selectedSupplier = item.supplier;
this.purchaseDate = item.purchaseDate.split('/').reverse().join('-');
this.PO = item.poNo;
this.currency = item.currency;
this.DefaultPrice = item.defaultPrice;
this.currencyRate = item.currencyRate;
this.convertPrice = item.convertPrice;
this.DONo = item.doNo;
this.DODate = item.doDate ? item.doDate.split('T')[0] : null;
this.warranty = item.warranty;
this.EndWDate = item.endWDate.split('/').reverse().join('-');
this.invoiceNo = item.invoiceNo;
this.invoiceDate = item.invoiceDate.split('/').reverse().join('-');
this.selectedTeamType = item.teamType;
this.partNumber = item.partNumber;
this.createdDate = item.createdDate; // Populate createdDate
this.modifiedDate = item.modifiedDate; // Populate modifiedDate
$('#registerItemModal').modal('show');
this.addSection = false;
this.editSection = true;
},
async submitEditItem() {
// List of required fields
const requiredFields = ['DefaultPrice', 'DONo', 'DODate', 'warranty', 'invoiceNo', 'invoiceDate'];
// Loop through required fields and check if any are null or empty
for (let field of requiredFields) {
if (this[field] === null || this[field] === '') {
alert('Item Error', `Please fill in required fields: ${field}.`, 'warning');
return;
}
}
if (this.showProduct.category == "Disposable") {
this.serialNumber = "";
}
const formData = {
itemId: this.itemID,
CompanyId: this.selectedCompany,
DepartmentId: this.selectedDepartment,
ProductId: this.selectedProduct,
SerialNumber: this.serialNumber,
Quantity: this.quantity,
Supplier: this.selectedSupplier,
PurchaseDate: this.purchaseDate,
PONo: this.PO,
Currency: this.currency,
DefaultPrice: this.DefaultPrice,
CurrencyRate: this.currencyRate,
ConvertPrice: this.convertPrice,
DONo: this.DONo,
DODate: this.DODate,
Warranty: this.warranty,
EndWDate: this.EndWDate,
InvoiceNo: this.invoiceNo,
InvoiceDate: this.invoiceDate,
TeamType: this.selectedTeamType,
PartNumber: this.partNumber,
// ADD THESE TWO LINES:
CreatedDate: this.createdDate, // Include the existing CreatedDate
ModifiedDate: this.modifiedDate // Include the existing ModifiedDate (API will update it)
};
try {
// Additional specific checks
if (this.showSerialNumber) {
this.quantity = 0;
if (this.serialNumber === null || this.serialNumber === '') {
alert('Serial Number Error', 'Serial Number must be filled when selecting Item or Part.', 'warning');
return;
}
}
else {
this.serialNumber = null;
if (this.quantity === 0 || this.quantity === null || this.quantity === '') {
alert('quantity Error', 'Quantity is required when selecting Disposable.', 'warning');
return;
}
}
const response = await fetch('/InvMainAPI/EditItem', {
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;
}
alert('Success!', 'Item form has been successfully submitted.', 'success');
this.fetchItem();
this.resetForm();
this.editSection = false;
this.addSection = false;
$('.modal').modal('hide');
} catch (error) {
console.error('Error editing Item:', error);
this.errorMessage = 'Error: ' + error.message;
}
},
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;
}
const sanitizedImgSrc = encodeURI(imgSrc);
container.innerHTML = `<img src="${sanitizedImgSrc}" alt="QR Code" class="text-center" style="width: 127px; height: 127px"; />`;
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');
}
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/`, {
method: 'POST',
});
if (response.ok) {
const data = await response.json();
this.currentUser = data?.userInfo || null;
const companyDeptData = await this.currentUser.department;
this.currentUserCompanyDept = companyDeptData;
this.selectedCompany = companyDeptData?.companyId || "";
this.selectedDepartment = companyDeptData?.departmentId || "";
}
else {
console.error(`Failed to fetch user: ${response.statusText}`);
}
}
catch (error) {
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;
}
const foundItem = this.items.find(item => String(item.uniqueID).trim() === String(uniqueID).trim());
return foundItem ? JSON.parse(JSON.stringify(foundItem)) : null;
},
printQRInfo() {
const virtualElement = document.createElement('div');
virtualElement.style.width = '360px ';
virtualElement.style.height = '180px';
virtualElement.style.position = 'absolute';
virtualElement.style.left = '-9999px';
virtualElement.innerHTML = `
<div class="container my-3 QrPrintFont" style="font-family: 'OCR A', monospace;">
<div class="row">
<div class="col-5 text-center d-flex align-items-center justify-content-center">
<div class="row">
<div class="col-12">
<div>${this.thisQRInfo.imgContainer}</div>
<div class="col-12 my-1 h4"style="font-family: 'Arial', monospace;"><b>${this.thisQRInfo.uniqueID}</b></div>
</div>
</div>
</div>
<div class="col-7 d-flex align-items-center justify-content-left">
<div class="row-fluid">
<div class="col-12 h3"style="font-family: 'Verdana', monospace;"><b>${this.thisQRInfo.departmentName}</b></div>
<div class="col-12 h4"style="font-family: 'Arial', monospace;"><b>${this.thisQRInfo.productShortName}</b></div>
<div class="col-12 h4"style="font-family: 'Arial', monospace;"><b>${this.thisQRInfo.serialNumber ?? "-"}</b></div>
<div class="col-12 h4"style="font-family: 'Arial', monospace;"><b>${this.thisQRInfo.partNumber}</b></div>
</div>
</div>
</div>
</div>
`;
document.body.appendChild(virtualElement);
document.fonts.load('1em "OCR A"').then(() => {
html2canvas(virtualElement, {
scale: 1,
}).then((canvas) => {
const imgData = canvas.toDataURL('image/png');
printJS({
printable: imgData,
type: 'image',
css: '/../lib/bootstrap/dist/css/bootstrap.css',
style: `
@@media print {
@@page {
margin: 0px 0px 0px 0px;
}
body { margin: 0; }
}
`
});
document.body.removeChild(virtualElement);
}).catch((error) => {
console.error("Error generating image:", error);
document.body.removeChild(virtualElement);
});
}).catch((error) => {
console.error("Error loading font:", error);
document.body.removeChild(virtualElement);
});
},
// New helper method to format dates
formatDate(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
// Check if date is valid
if (isNaN(date.getTime())) {
return '';
}
return date.toLocaleString(); // You can adjust the format as needed
}
},
});
</script>
}