PSTW_CentralizeSystem/Areas/Inventory/Views/ItemMovement/ItemRequest.cshtml
2025-03-14 07:44:19 +08:00

681 lines
33 KiB
Plaintext

@{
ViewData["Title"] = "Product Request";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@await Html.PartialAsync("~/Areas/Inventory/Views/_InventoryPartialUser.cshtml")
<style>
.dropdown {
position: relative;
width: 100%;
}
.dropdown-toggle-box {
display: flex;
align-items: center;
border: 1px solid #ddd;
border-radius: 5px;
overflow: hidden;
}
.dropdown-toggle-box input {
flex: 1;
border: none;
padding: 8px;
}
.dropdown-btn {
border: none;
background-color: #007bff;
color: white;
padding: 8px 12px;
cursor: pointer;
}
.dropdown-content {
position: absolute;
width: 100%;
max-height: 200px;
overflow-y: auto;
background: #fff;
border: 1px solid #ddd;
z-index: 10;
}
.dropdown-content option {
padding: 10px;
cursor: pointer;
display: block;
}
.dropdown-content option:hover {
background-color: #f1f1f1;
}
.modal-body img {
max-width: 100%; /* Ensure it fits the modal */
max-height: 150px; /* Adjust max height */
display: block;
margin: auto;
}
</style>
<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 Name -->
<div class="form-group row">
<label class="col-sm-2 col-form-label">Product</label>
<div class="col-sm-8">
<div class="dropdown" v-click-outside="closeDropdown">
<!-- Button + Input dalam satu box -->
<div class="dropdown-toggle-box" v-on:click="dropdownOpen = !dropdownOpen">
<input type="text" class="form-control" v-model="searchQuery"
placeholder="Search product..." v-on:focus="dropdownOpen = true" v-on:click.stop />
<button type="button" class="btn btn-primary dropdown-btn" v-on:click.stop="dropdownOpen = !dropdownOpen">
</button>
</div>
<!-- Dropdown list -->
<div v-if="dropdownOpen" class="dropdown-content" v-on:click.stop>
<div v-for="(item, index) in filteredProducts"
:key="index" class="dropdown-item" v-on:mousedown.prevent="selectProduct(item)">
{{ item.productName + ' (' + item.modelNo + ')' }}
</div>
</div>
</div>
</div>
</div>
<!-- Category Dropdown -->
<div class="form-group row">
<label class="col-sm-2 col-form-label">Category:</label>
<div class="col-sm-8">
<input type="text" id="category" name="category" v-model="showProduct.category" class="form-control" readonly />
</div>
</div>
<!-- Image Product Dropdown-->
<div class="form-group row align-items-center">
<label for="imageProduct" class="col-sm-2 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>
<!-- Modal -->
<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>
<!-- Quantity Input -->
<div class="form-group row d-flex align-items-center">
<label class="col-sm-2 col-form-label">Quantity:</label>
<div class="col-sm-8">
<input type="number" class="form-control" v-model="quantity" required />
</div>
</div>
@* Who will assign to *@
<div class="form-group row">
<label class="col-sm-2 col-form-label">Item Assignment : </label>
<div class="col-sm-8">
<div class="dropdown">
<select class="btn btn-primary dropdown-toggle col-md-12" v-model="assign"required>
<option class="btn-light" value="" selected disabled>Select Assignment Type</option>
<option class="btn-light" v-for="(item, index) in assigns" :key="item" :value="item">{{ item ?? 'Select Assignment Type' }}</option>
</select>
</div>
</div>
</div>
<!-- Station Dropdown -->
<div class="form-group row" v-if="assign === 'Station'">
<label class="col-sm-2 col-form-label">Station:</label>
<div class="col-sm-8">
<div class="dropdown">
<select class="btn btn-primary dropdown-toggle col-md-12" data-toggle="dropdown" aria-expanded="false" v-model="stationId" required>
<option class="btn-light" value="" disabled selected>Select Station</option>
<option v-if="stations.length === 0" class="btn-light" disabled>No Station Assigned to You</option>
<option class="btn-light" v-for="(item, index) in stations" :key="index" :value="item.stationId">
{{ item.stationName }}
</option>
</select>
</div>
</div>
</div>
<!-- Remark Input (Wider) -->
<div class="form-group row d-flex align-items-center">
<label class="col-sm-2 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-2 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 : "",
productId : "",
remark: "",
document: null,
quantity: 0,
status: "",
requestDate : null,
approvalDate : null,
productCategory: "",
assign: "",
productName: null,
searchQuery: "",
dropdownOpen: false,
stations: [],
selectedProduct: "",
selectedStation: "",
selectedCategory: "",
assigns: ["Self-Assign", "Station"],
showRequestModal: false,
loading: false,
products: [],
request: [],
currentUser: null,
}
},
async mounted() {
this.fetchProducts();
await this.fetchUser();
await Promise.all([
this.fetchStation(),
this.fetchRequest(),
]);
},
computed: {
showProduct() {
if (!this.productId) {
return []; // No company selected, return empty list
}
const product = this.products.find(c => c.productId === this.productId);
this.productCategory = product.category;
return product ? product : {};
},
filteredProducts() {
return this.products.filter(item =>
item.productName.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
item.modelNo.toLowerCase().includes(this.searchQuery.toLowerCase())
);
}
},
methods: {
closeDropdown() {
this.dropdownOpen = false; // Tutup dropdown
},
selectProduct(item) {
this.selectedProduct = item;
this.productId = item.productId;
this.searchQuery = item.productName + " (" + item.modelNo + ")";
this.dropdownOpen = false;
},
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 = ['productId', 'quantity', 'assign'];
// 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;
}
}
if (this.assign === "Station"){
if (this.stationId == null) {
alert('Request Error', `Please fill in required fields : Station.`, 'warning');
return;
}
}
if (this.assign === "Self-Assign"){
this.stationId = null;
}
this.userId = this.currentUser.id;
this.status = "Requested";
const now = new Date();
this.requestDate = new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString();
// Prepare data as JSON (No file upload)
const requestData = {
ProductId: this.productId,
StationId: this.stationId,
UserId: this.userId,
ProductCategory: this.productCategory,
RequestQuantity: this.quantity,
remarkUser: this.remark || '',
remarkMasterInv: '',
status: this.status,
requestDate: this.requestDate,
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) {
this.resetForm();
alert('Success!', 'Request form has been successfully submitted.', 'success');
const requestItem = await response.json();
this.request.push(requestItem);
this.fetchRequest();
} 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() {
let self = this;
function renderDocument(data, full) {
if (!data) return "No Document";
let isImage = /\.(jpeg|jpg|png|gif)$/i.test(data);
let 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>`;
}
}
function renderDeleteButton(data) {
return `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
}
this.pendingRequestDatatable = $('#requestDatatable').DataTable({
"data": this.request.filter(req => req.status === "Requested"),
"columns": [
{ "title": "Request ID", "data": "requestID", "createdCell": (td, cellData) => $(td).attr('id', `qr${cellData}`) },
{ "title": "Product Name", "data": "productName", "render": (data, type, full) => renderDocument(full.productPicture) },
{ "title": "Product Category", "data": "productCategory" },
{ "title": "Request Quantity", "data": "requestQuantity" },
{ "title": "Document / Picture", "data": "document", "render": (data, type, full) => renderDocument(data) },
{ "title": "Remark", "data": "remarkUser" },
{ "title": "Station Deploy", "data": "stationName", "render": (data) => data || "Self Assign" },
{ "title": "Request Date", "data": "requestDate" },
{ "title": "Status", "data": "status" },
{ "title": "Delete", "data": "requestID", "render": renderDeleteButton, "className": "align-middle" }
],
responsive: true,
});
this.settledRequestDatatable = $('#settledrequestDatatable').DataTable({
"data": this.request.filter(req => req.status !== "Requested"),
"columns": [
{ "title": "Request ID", "data": "requestID", "createdCell": (td, cellData) => $(td).attr('id', `qr${cellData}`) },
{ "title": "Status", "data": "status" },
{ "title": "Product Name", "data": "productName", "render": (data, type, full) => renderDocument(full.productPicture) },
{ "title": "Product Category", "data": "productCategory" },
{ "title": "Request Quantity", "data": "requestQuantity" },
{ "title": "Station Deploy", "data": "stationName", "render": (data) => data || "Self Assign" },
{ "title": "Document / Picture", "data": "document", "render": (data, type, full) => renderDocument(data) },
{ "title": "Remark", "data": "remarkUser" },
{ "title": "Remark (Master)", "data": "remarkMasterInv" },
{ "title": "Request Date", "data": "requestDate" },
{ "title": "Approval Date", "data": "approvalDate" }
],
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');
}
const data = await response.json();
this.stations = data.filter(station => station.stationPicID === this.userId);
} 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.searchQuery = "";
this.stationId = "";
this.productId = "";
this.remark = "";
this.document = null;
this.quantity = 0;
this.status = "";
this.requestDate = null;
this.approvalDate = null;
this.productCategory = "";
this.assign = "",
this.productName = null;
this.selectedProduct = "";
this.selectedStation = "";
this.selectedCategory = "";
this.showRequestModal = false;
this.loading = false;
},
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;
}
},
},
directives: {
clickOutside: {
beforeMount(el, binding) {
el.clickOutsideEvent = (event) => {
if (!(el.contains(event.target))) {
binding.value?.(); // Guna optional chaining untuk elak error
}
};
document.body.addEventListener("click", el.clickOutsideEvent);
},
unmounted(el) {
document.body.removeEventListener("click", el.clickOutsideEvent);
}
}
}
});
</script>
}