PSTW_CentralizeSystem/Areas/Inventory/Views/Item/ProductRegistration.cshtml
2024-11-26 12:48:14 +08:00

265 lines
12 KiB
Plaintext

@{
ViewData["Title"] = "Product Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartial.cshtml");
<div id="registerProduct" class="card m-1">
<form v-on:submit.prevent="addProduct" data-aos="fade-right">
<div class="container register" data-aos="fade-right">
<div class="row" data-aos="fade-right">
<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">
<div class="card-header">
<h3 class="register-heading">REGISTRATION PRODUCT</h3>
</div>
<div class="row register-form card-body">
<div class="col-md-6">
@* Product Name *@
<div class="form-group row">
<label for="productName" class="col-sm-3">Product Name:</label>
<div class="col-sm-9">
<input type="text" id="productName" name="productName" class="form-control" required v-model="productName">
</div>
</div>
@* Manufacturer *@
<div class="form-group row">
<label class="col-sm-3">Manufacturer:</label>
<div class="col-sm-9">
<div class="">
<select class="btn btn-primary form-select" v-model="manufacturer" required>
<option class="btn-light" value="" selected disabled>Select Manufacturer</option>
<option class="btn-light" v-for="(item, index) in manufacturers" :key="item.manufacturerId" :value="item.manufacturerId">{{ item.manufacturerName ?? 'Select Manufacturer' }}</option>
</select>
</div>
</div>
</div>
@* Category *@
<div class="form-group row">
<label class="col-sm-3">Category:</label>
<div class="col-sm-9">
<div class="">
<select class="btn btn-primary form-select" v-model="category" required>
<option class="btn-light" value="" selected disabled>Select Category</option>
<option class="btn-light" v-for="(item, index) in categories" :key="item" :value="item">{{ item ?? 'Select Category' }}</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-6">
@* Model No Coding *@
<div class="form-group row">
<label for="modelNo" class="col-sm-3">Model No:</label>
<div class="col-sm-9">
<input type="text" id="modelNo" name="modelNo" class="form-control" required v-model="modelNo">
</div>
</div>
@* Min Quantity Coding *@
<div class="form-group row">
<label for="quantityProduct" class="col-sm-3">Quantity:</label>
<div class="col-sm-9">
<input type="number" id="quantityProduct" name="quantityProduct" class="form-control" min="0" required v-model="quantityProduct">
</div>
</div>
@* Image Product Coding *@
<div class="form-group row">
<label for="imageProduct" class="col-sm-3">Image:</label>
<div class="col-sm-9">
<input type="file" id="imageProduct" name="imageProduct" class="form-control" v-on:change="previewImage" accept="image/*" required>
<br>
<img v-if="imageSrc" :src="imageSrc" alt="Image Preview" class="img-thumbnail" style="width: 200px; margin-top: 10px;" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-9 offset-sm-3">
<button type="button" v-on:click="resetForm" class="btn btn-secondary">Reset</button>
<input type="submit" class="btn btn-primary">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script>
new Vue({
el: '#registerProduct',
data: {
productName: null,
manufacturer: '',
manufacturers: null,
category: '',
categories: ["Item", "Part", "Disposable"],
modelNo: null,
quantityProduct: null,
imageProduct: null,
manufactures: [],
showOtherManufacturer: false,
imageSrc: '',
},
mounted() {
// Fetch companies, depts, and products from the API
this.fetchManufactures();
this.fetchProducts();
},
methods: {
async fetchManufactures() {
try {
const response = await fetch('/api/Product/GetManufactures'); // Call the API
if (!response.ok) {
throw new Error('Failed to fetch manufactures');
}
const data = await response.json(); // Get the full response object
this.manufactures = data.manufacturer; // Extract the 'manufacturer' array
} catch (error) {
console.error('Error fetching manufactures:', error);
}
},
async fetchProducts() {
try {
const response = await fetch('/api/Product/GetProducts'); // Call the API
if (!response.ok) {
throw new Error('Failed to fetch products');
}
this.products = await response.json(); // Store the fetched products
} catch (error) {
console.error('Error fetching products:', error);
}
},
async addProduct() {
const existingProduct = this.products.find(p => p.modelNo === this.modelNo);
if (existingProduct) {
swal('Product Error', `The model number ${this.modelNo} already exists.`, 'error');
return; // Exit early if the modelNo exists
}
// Create the payload
const formData = {
productName: this.productName,
manufacturer: this.manufacturer,
category: this.category,
modelNo: this.modelNo,
quantityProduct: this.quantityProduct,
imageProduct: this.imageProduct
};
try {
// List of required fields
const requiredFields = ['productName', 'manufacturer', 'category', 'modelNo', 'quantityProduct', 'imageProduct'];
// Loop through required fields and check if any are null or empty
for (let field of requiredFields) {
if (this[field] === null || this[field] === '') {
swal('Product Error', `Please fill in required fields: ${field}.`, 'warning');
return; // Exit early if validation fails
}
}
// Proceed to send the data as raw JSON string
const response = await fetch('/api/Product', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData) // Convert the formData to a JSON string
});
if (!response.ok) {
const errorData = await response.json();
console.error('Error response:', errorData);
this.errorMessage = 'Error: ' + (errorData.message || 'Unknown error');
} else {
swal('Success!', 'Product form has been successfully submitted.', 'success');
this.resetForm();
}
} catch (error) {
console.error('Error:', error);
swal('Product Error', `An error occurred: ${error.message}`, 'error');
}
}
,
resetForm() {
this.productName = null;
this.manufacturer = '';
this.category = null;
this.modelNo = null;
this.quantityProduct = null;
this.imageProduct = null;
this.imageSrc = '';
const fileInput = document.getElementById('imageProduct');
if (fileInput) {
fileInput.value = ''; // Clear the file input value
}
},
// Update Select View
updateManufacturer(manufacturer) {
this.manufacturer = manufacturer;
this.showOtherManufacturer = false;
},
updateCategory(category) {
this.category = category;
},
// When User Presses Button Other
toggleOtherInput(type) {
if (type === 'manufacturer') {
this.showOtherManufacturer = true;
}
},
// User Inserting an Image
previewImage(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
this.imageSrc = e.target.result; // Show the image preview
this.imageProduct = e.target.result.split(',')[1]; // Get Base64 string (remove metadata)
};
reader.readAsDataURL(file);
} else {
this.imageSrc = '';
this.imageProduct = null;
}
},
async fetchManufactures() {
fetch('/InvMainAPI/ManufacturerList', {
method: 'POST'
})
.then(response => response.json())
.then(data => {
console.log(data);
if (data != null && data.length > 0)
{
this.manufacturers = data;
}
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
},
}
});
</script>