PSTW_CentralizeSystem/Areas/Inventory/Views/ItemMovement/ItemRequest.cshtml
2025-02-24 21:53:19 +08:00

624 lines
29 KiB
Plaintext

@{
ViewData["Title"] = "Product Request";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartialUser.cshtml");
<div id="requestProduct" class="row">
<!-- Document Preview Modal -->
<div id="documentModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Document Preview</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body text-center">
<img id="documentPreview" src="" alt="Document" class="img-fluid" style="max-height: 80vh;">
</div>
</div>
</div>
</div>
<div class="row card">
<div class="card-header">
<h2>Pending Request</h2>
<button id="addRequestBtn" class="btn btn-success col-md-3 col-lg-3 m-1 col-12"><i class="fa fa-plus"></i>&nbsp;Add Request</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="requestDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
</div>
</div>
<div class="row card">
<div class="card-header">
<h2>Complete Request</h2>
</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="settledrequestDatatable" style=" width:100%;border-style: solid; border-width: 1px"></table>
</div>
</div>
<div class="modal fade" id="requestModal" tabindex="-1" role="dialog" aria-labelledby="addRequestModalLabel" 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="addRequestModalLabel">Add Request</h5>
<button type="button" class="closeModal" data-dismiss="modal" aria-label="Close" v-on:click="showRequestModal=false">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="container-fluid">
<form v-on:submit.prevent="addRequest" data-aos="fade-right">
<div class=" 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">
<h3 class="register-heading">PRODUCT REQUEST</h3>
<div class="row register-form">
<div class="col-md-13">
<!-- Product Dropdown -->
<div class="form-group row">
<label class="col-sm-4 col-form-label">Product</label>
<div class="col-sm-8">
<select class="btn btn-primary form-select" v-model="productId" 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>
<!-- Category Dropdown -->
<div class="form-group row">
<label class="col-sm-4 col-form-label">Category:</label>
<div class="col-sm-8">
<div class="">
<select class="btn btn-primary form-select" v-model="productCategory" 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>
<!-- Quantity Input -->
<div class="form-group row d-flex align-items-center">
<label class="col-sm-4 col-form-label">Quantity:</label>
<div class="col-sm-8">
<input type="number" class="form-control" v-model="quantity" required />
</div>
</div>
<!-- Station Dropdown -->
<div class="form-group row">
<label class="col-sm-4 col-form-label">Station:</label>
<div class="col-sm-8">
<select class="btn btn-primary form-select" v-model="stationId" required>
<option class="btn-light" value="" disabled selected>Select Station</option>
<option class="btn-light" v-for="(item, index) in stations" :key="index" :value="item.stationId">
{{ item.stationName }}
</option>
</select>
</div>
</div>
<!-- Remark Input (Wider) -->
<div class="form-group row d-flex align-items-center">
<label class="col-sm-4 col-form-label">Remark:</label>
<div class="col-sm-8">
<input type="text" class="form-control col-md-10" v-model="remark" />
</div>
</div>
<!-- Document/Picture Input -->
<div class="form-group row d-flex align-items-center">
<label class="col-sm-4 col-form-label">Document/Picture:</label>
<div class="col-sm-8">
<input type="file" id="document" name="document" class="form-control-file" v-on:change="handleFileUpload" accept="image/png, image/jpeg, application/pdf" />
</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('#requestProduct');
// Attach a click event listener to elements with the class 'btn-success'.
$('#addRequestBtn').on('click', function () {
$('#requestModal').modal('show');
});
$('.closeModal').on('click', function () {
$('.modal').modal('hide');
});
});
const app = Vue.createApp({
data() {
return {
requestId : null,
userId : null,
stationId : null,
productId : null,
remark: "",
document: null,
quantity: 0,
status: "",
requestDate : null,
approvalDate : null,
productCategory: "",
productName: null,
productCategory: null,
stations: [],
selectedProduct: "",
selectedStation: "",
selectedCategory: "",
categories: ["Asset", "Part", "Disposable"],
showRequestModal: false,
loading: false,
products: [],
request: [],
currentUser: null,
}
},
async mounted() {
this.fetchProducts();
this.fetchStation();
await this.fetchUser();
await Promise.all([
this.fetchRequest(),
]);
},
computed: {
showProduct() {
if (!this.selectedProduct) {
return []; // No company selected, return empty list
}
const product = this.products.find(c => c.productId === this.selectedProduct);
return product ? product : {};
},
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
this.document = e.target.result.split(',')[1]; // Get Base64 string (remove metadata)
};
reader.readAsDataURL(file);
} else {
this.document = null;
}
},
async addRequest() {
try {
const requiredFields = ['stationId', 'productId', 'quantity', 'productCategory'];
this.userId = this.currentUser.id;
this.status = "Requested";
this.requestDate = new Date().toISOString();
// Loop through required fields and check if any are null or empty
for (let field of requiredFields) {
if (!this[field]) {
alert('Request Error', `Please fill in required fields: ${field}.`, 'warning');
return;
}
}
// Prepare data as JSON (No file upload)
const requestData = {
ProductId: this.productId,
StationId: this.stationId,
UserId: this.userId,
ProductCategory: this.productCategory,
RequestQuantity: this.quantity,
remark: this.remark || '',
status: this.status,
requestDate: this.requestDate,
approvalDate: this.approvalDate ? this.approvalDate : null,
document: this.document
};
$('.modal').modal('hide');
// Send the data to the API
const response = await fetch('/InvMainAPI/AddRequest', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
});
if (response.ok) {
alert('Success!', 'Request form has been successfully submitted.', 'success');
const requestItem = await response.json();
this.request.push(requestItem);
this.fetchRequest();
this.resetForm();
} else {
throw new Error('Failed to submit form.');
}
} catch (error) {
console.error('Error:', error);
alert('Inventory PSTW Error', `An error occurred: ${error.message}`, 'error');
}
},
initiateTable() {
self = this;
this.requestDatatable = $('#requestDatatable').DataTable({
"data": this.request.filter(request => request.status == "Requested"),
"columns": [
{
"title": "Request ID",
"data": "requestId",
"createdCell": function (td, cellData, rowData, row, col) {
// Assign a unique ID to the <td> element
$(td).attr('id', `qr${cellData}`);
},
},
{
"title": "Product Id",
"data": "productId",
},
{
"title": "Product Category",
"data": "productCategory",
},
{
"title": "Request Quantity",
"data": "requestQuantity",
},
{
"title": "Document / Picture",
"data": "document",
"render": function (data, type, full, meta) {
if (!data) {
return "No Document";
}
// Check if the document is an image based on file extension
var isImage = /\.(jpeg|jpg|png|gif)$/i.test(data);
var isPdf = /\.pdf$/i.test(data);
if (isImage) {
return `<a href="${data}" target="_blank" data-lightbox="image-1">
<img src="${data}" alt="Image" class="img-thumbnail" style="width: 100px; height: 100px;" />
</a>`;
}
else if (isPdf) {
return `<a href="${data}" target="_blank">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/PDF_file_icon.svg"
alt="PDF Document" class="img-thumbnail"
style="width: 50px; height: 50px;" />
<br>View PDF
</a>`;
} else {
return `<a href="${data}" target="_blank">Download File</a>`;
}
},
},
{
"title": "Remark",
"data": "remarkUser",
},
{
"title": "Request Date",
"data": "requestDate",
},
{
"title": "Status",
"data": "status",
},
{
"title": "Delete",
"data": "requestId",
"render": function (data) {
var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
return deleteButton;
},
"className": "align-middle",
// "title": "Delete",
// "data": "requestId",
// "render": function (data, type, row) {
// if (row.status === "Approved" || row.status === "Rejected") {
// return `<button type="button" class="btn btn-danger delete-btn" data-id="${data}" disabled>Delete</button>`;
// } else {
// return `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
// }
// },
// "className": "align-middle",
}
],
responsive: true,
});
this.requestDatatable = $('#settledrequestDatatable').DataTable({
"data": this.request.filter(request => request.status !== "Requested"),
"columns": [
{
"title": "Request ID",
"data": "requestId",
"createdCell": function (td, cellData, rowData, row, col) {
// Assign a unique ID to the <td> element
$(td).attr('id', `qr${cellData}`);
},
},
{
"title": "Product Id",
"data": "productId",
},
{
"title": "Product Category",
"data": "productCategory",
},
{
"title": "Request Quantity",
"data": "requestQuantity",
},
{
"title": "Document / Picture",
"data": "document",
"render": function (data, type, full, meta) {
if (!data) {
return "No Document";
}
// Check if the document is an image based on file extension
var isImage = /\.(jpeg|jpg|png|gif)$/i.test(data);
var isPdf = /\.pdf$/i.test(data);
if (isImage) {
return `<a href="${data}" target="_blank" data-lightbox="image-1">
<img src="${data}" alt="Image" class="img-thumbnail" style="width: 100px; height: 100px;" />
</a>`;
} else if (isPdf) {
return `<a href="${data}" target="_blank">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/87/PDF_file_icon.svg"
alt="PDF Document" class="img-thumbnail"
style="width: 50px; height: 50px;" />
<br>View PDF
</a>`;
} else {
return `<a href="${data}" target="_blank">Download File</a>`;
}
},
},
{
"title": "Remark",
"data": "remarkUser",
},
{
"title": "Remark (Master)",
"data": "remarkMasterInv",
},
{
"title": "Request Date",
"data": "requestDate",
},
{
"title": "Approval Date",
"data": "approvalDate",
},
{
"title": "Status",
"data": "status",
}
],
responsive: true,
});
$('#requestDatatable tbody').off('click', '.delete-btn');
$('#requestDatatable tbody').on('click', '.delete-btn', function () {
const requestId = $(this).data('id');
self.deleteRequestItem(requestId);
});
this.loading = false;
},
async fetchRequest() {
try
{
const response = await fetch(`/InvMainAPI/ItemRequestListEachUser/${this.userId}`,
{
method: 'GET', // Specify the HTTP method
headers: {
'Content-Type': 'application/json', // Set content type
}
});
if (!response.ok) {
throw new Error('Failed to fetch request List');
}
this.request = await response.json();
if ($.fn.dataTable.isDataTable('#requestDatatable')) {
$('#requestDatatable').DataTable().clear().destroy();
}
if ($.fn.dataTable.isDataTable('#settledrequestDatatable')) {
$('#settledrequestDatatable').DataTable().clear().destroy();
}
this.initiateTable();
}
catch (error) {
console.error('Error fetching request List:', error);
}
},
async fetchProducts() {
try {
const response = await fetch('/InvMainAPI/ProductList', {
method: 'POST', // Specify the HTTP method
headers: {
'Content-Type': 'application/json', // Set content type
}
});
if (!response.ok) {
throw new Error('Failed to fetch products');
}
this.products = await response.json();
}
catch (error) {
console.error('Error fetching products:', error);
}
},
async fetchStation() {
try {
const response = await fetch('/InvMainAPI/StationList', {
method: 'POST', // Specify the HTTP method
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch suppliers');
}
this.stations = await response.json(); // Get the full response object
} catch (error) {
console.error('Error fetching suppliers:', error);
}
},
async fetchUser() {
try {
const response = await fetch(`/IdentityAPI/GetUserInformation/`, {
method: 'POST',
});
if (response.ok) {
const data = await response.json();
this.currentUser = data?.userInfo || null;
this.userId = await this.currentUser.id;
}
else {
console.error(`Failed to fetch user: ${response.statusText}`);
}
}
catch (error) {
console.error('There was a problem with the fetch operation:', error);
}
},
resetForm() {
this.requestId = null;
this.userId = null;
this.stationId = null;
this.productId = null;
this.remark = "";
this.document = null;
this.quantity = 0;
this.status = "";
this.requestDate = null;
this.approvalDate = null;
this.productCategory = "";
this.productName = null;
this.productCategory = null;
this.stations = [];
this.selectedProduct = "";
this.selectedStation = "";
this.selectedCategory = "";
this.showRequestModal = false;
this.loading = false;
this.product = [];
this.request = [];
this.currentUser = null;
},
async deleteRequestItem(requestId) {
if (!confirm("Are you sure you want to delete this request?")) {
return false;
}
try {
const response = await fetch(`/InvMainAPI/DeleteRequest/${requestId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});
const result = await response.json();
if (result.success) {
alert(result.message);
if ($.fn.dataTable.isDataTable('#requestDatatable')) {
const table = $('#requestDatatable').DataTable();
table.row($(`.delete-btn[data-id="${requestId}"]`).closest('tr')).remove().draw();
}
this.request = this.request.filter(req => req.requestId !== requestId);
} else {
alert(result.message);
}
}
catch (error) {
console.error("Error deleting item:", error);
alert("An error occurred while deleting the item.");
}
finally {
this.loading = false;
}
},
},
});
</script>
}