initial commit

This commit is contained in:
2026-07-21 15:03:40 +07:00
commit 5c20bb8a9e
2752 changed files with 864209 additions and 0 deletions
@@ -0,0 +1,32 @@
@page
@{
ViewData["Title"] = "Email Confirm";
}
<div id="app" class="container-fluid" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<div class="row">
<div class="col-md-12 text-center mb-3">
<h3 class="text-dark">Email Confirm</h3>
<a asp-page="/Index" class="">
<p><i class="fas fa-home me-2 text-warning"></i><span class="text-dark">INDOTALENT</span></p>
</a>
</div>
<div class="col-md-12">
<p>Please wait...</p>
<p>Email confirmation is in progress.</p>
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/EmailConfirm.cshtml.js"></script>
}
@@ -0,0 +1,71 @@
const App = {
setup() {
const state = Vue.reactive({
isSubmitting: false,
});
const emailConfirmation = async (email, code) => {
try {
const response = await AxiosManager.get(`/Security/ConfirmEmail?email=${email}&code=${code}`, {});
return response;
} catch (error) {
console.error('Error during emailConfirmation:', error);
throw error;
}
}
Vue.onMounted(async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const params = new URLSearchParams(window.location.search);
const email = params.get('email');
const code = params.get('code');
if (email && code) {
const response = await emailConfirmation(email, code);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Email Confirmation Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/Accounts/Login';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Email Confirmation Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} else {
Swal.fire({
icon: 'error',
title: 'Email Confirmation Failed',
text: 'Email or code is missing in the URL query string.',
confirmButtonText: 'Try Again'
});
}
} catch (e) {
console.error('page init error:', e);
} finally {
state.isSubmitting = false;
}
});
return {
state
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,67 @@
@page
@{
ViewData["Title"] = "Forgot Password";
}
<div class="container-fluid" id="app" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<form v-on:submit.prevent="handleSubmit">
<div class="input-group mb-3">
<input id="Email"
name="Email"
type="email"
class="form-control"
placeholder="name@example.com"
v-model="state.email"
v-on:input="state.errors.email = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<label v-if="state.errors.email" class="text-danger">{{ state.errors.email }}</label>
<div class="row">
<div class="col-8">
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary btn-block">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Reset' }}</span>
</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i>
Sign up using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i>
Sign up using Google+
</a>
</div>
<p class="mb-1">
<a asp-page="/Accounts/Login" class="text-center">I already have a membership</a>
</p>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/ForgotPassword.cshtml.js"></script>
}
@@ -0,0 +1,87 @@
const App = {
setup() {
const state = Vue.reactive({
email: '',
isSubmitting: false,
errors: {
email: ''
}
});
const validateForm = () => {
state.errors.email = '';
let isValid = true;
if (!state.email) {
state.errors.email = 'Email is required.';
isValid = false;
} else if (!/\S+@\S+\.\S+/.test(state.email)) {
state.errors.email = 'Please enter a valid email address.';
isValid = false;
}
return isValid;
};
const forgotPassword = async (email) => {
try {
const response = await AxiosManager.post('/Security/ForgotPassword', {
email
});
return response;
} catch (error) {
throw error;
}
}
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) return;
const response = await forgotPassword(state.email);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Reset Password Successful',
text: 'Please check your email. You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Reset Password Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,32 @@
@page
@{
ViewData["Title"] = "Forgot Password Confirmation";
}
<div class="container-fluid" id="app" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<div class="row">
<div class="col-md-12 text-center mb-3">
<h3 class="text-dark">Forgot Password Confirm</h3>
<a asp-page="/Index" class="">
<p><i class="fas fa-home me-2 text-warning"></i><span class="text-dark">INDOTALENT</span></p>
</a>
</div>
<div class="col-md-12">
<p>Please wait...</p>
<p>Password reset is in progress.</p>
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/ForgotPasswordConfirmation.cshtml.js"></script>
}
@@ -0,0 +1,71 @@
const App = {
setup() {
const state = Vue.reactive({
isSubmitting: false,
});
const forgotPasswordConfirmation = async (email, code, tempPassword) => {
try {
const response = await AxiosManager.get(`/Security/ForgotPasswordConfirmation?email=${email}&code=${code}&tempPassword=${tempPassword}`, {});
return response;
} catch (error) {
console.error('Error during ForgotPasswordConfirmation:', error);
throw error;
}
}
Vue.onMounted(async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const params = new URLSearchParams(window.location.search);
const email = params.get('email');
const code = params.get('code');
const tempPassword = params.get('tempPassword');
if (email && code && tempPassword) {
const response = await forgotPasswordConfirmation(email, code, tempPassword);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Password Reset Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/Accounts/Login';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Password Reset Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} else {
Swal.fire({
icon: 'error',
title: 'Password Reset Failed',
text: 'Email or code is missing in the URL query string.',
confirmButtonText: 'Try Again'
});
}
} catch (e) {
console.error('page init error:', e);
} finally {
state.isSubmitting = false;
}
});
return {
state
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,91 @@
@page
@{
ViewData["Title"] = "Login";
}
<div id="app" class="container-fluid" v-cloak>
<div class="card-body login-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<form v-on:submit.prevent="handleSubmit">
<div class="input-group mb-3">
<input id="Email"
name="Email"
type="email"
class="form-control"
placeholder="name@example.com"
v-model="state.email"
v-on:input="state.errors.email = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<label v-if="state.errors.email" class="text-danger">{{ state.errors.email }}</label>
<div class="input-group mb-3">
<input id="Password"
name="Password"
type="password"
class="form-control"
placeholder="Password"
v-model="state.password"
v-on:input="state.errors.password = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<label v-if="state.errors.password" class="text-danger">{{ state.errors.password }}</label>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary btn-block">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Log In' }}</span>
</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center mb-3">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i> Sign in using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i> Sign in using Google+
</a>
</div>
<!-- /.social-auth-links -->
<p class="mb-1">
<a asp-page="/Accounts/ForgotPassword">Forgot Password</a>
</p>
<p class="mb-0">
<a asp-page="/Accounts/Register" class="text-center">Register a new membership</a>
</p>
</div>
</div>
@section scripts {
<script type ="module" src="~/FrontEnd/Pages/Accounts/Login.cshtml.js"></script>
}
@@ -0,0 +1,94 @@
const App = {
setup() {
const state = Vue.reactive({
email: '',
password: '',
isSubmitting: false,
errors: {
email: '',
password: ''
}
});
const validateForm = () => {
state.errors.email = '';
state.errors.password = '';
let isValid = true;
if (!state.email) {
state.errors.email = 'Email is required.';
isValid = false;
} else if (!/\S+@\S+\.\S+/.test(state.email)) {
state.errors.email = 'Please enter a valid email address.';
isValid = false;
}
if (!state.password) {
state.errors.password = 'Password is required.';
isValid = false;
} else if (state.password.length < 6) {
state.errors.password = 'Password must be at least 6 characters.';
isValid = false;
}
return isValid;
};
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = await AxiosManager.post('/Security/Login', {
email: state.email,
password: state.password
});
if (response.data.code === 200) {
StorageManager.saveLoginResult(response.data);
Swal.fire({
icon: 'success',
title: 'Login Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/Profiles/MyProfile';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Login Failed',
text: response.data.message || 'Please check your credentials.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,42 @@
@page
@{
ViewData["Title"] = "Logout";
}
<div class="container-fluid" id="app" v-cloak>
<div class="card-body login-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<div class="social-auth-links text-center mb-3">
<div class="row">
<div class="col-md-12">
<form v-on:submit.prevent="handleSubmit">
<div class="form-group mb-2 text-center">
<p>Are you sure you want to log out?</p>
<p>Click the button below to confirm and log out completely.</p>
</div>
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary w-100 mb-2">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Log Out' }}</span>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Accounts/Logout.cshtml.js"></script>
}
@@ -0,0 +1,69 @@
const App = {
setup() {
const state = Vue.reactive({
isSubmitting: false,
});
const logout = async () => {
try {
const response = await AxiosManager.post('/Security/Logout', {
userId: StorageManager.getUserId()
});
return response;
} catch (error) {
throw error;
}
}
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const response = await logout();
if (response.data.code === 200) {
StorageManager.clearStorage();
Swal.fire({
icon: 'success',
title: 'Logout Successful',
text: 'You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Logout Failed',
text: response.data.message ?? 'Logout Failed.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,149 @@
@page
@{
ViewData["Title"] = "Register";
}
<div id="app" class="container-fluid" v-cloak>
<div class="card-body register-card-body">
<p class="login-box-msg">@ViewData["Title"]</p>
<form v-on:submit.prevent="handleSubmit">
<div class="input-group mb-3">
<input id="Email"
name="Email"
type="email"
placeholder="Enter Email"
class="form-control"
v-model="state.email"
v-on:input="state.errors.email = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<label v-if="state.errors.email" class="text-danger small">{{ state.errors.email }}</label>
<div class="input-group mb-3">
<input id="CompanyName"
name="CompanyName"
type="text"
placeholder="Enter Company Name"
class="form-control"
v-model="state.companyName">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-edit"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input id="FirstName"
name="FirstName"
type="text"
placeholder="Enter First Name"
class="form-control"
v-model="state.firstName"
v-on:input="state.errors.firstName = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-edit"></span>
</div>
</div>
</div>
<label v-if="state.errors.firstName" class="text-danger small">{{ state.errors.firstName }}</label>
<div class="input-group mb-3">
<input id="LastName"
name="LastName"
type="text"
placeholder="Enter Last Name"
class="form-control"
v-model="state.lastName"
v-on:input="state.errors.lastName = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-edit"></span>
</div>
</div>
</div>
<label v-if="state.errors.lastName" class="text-danger small">{{ state.errors.lastName }}</label>
<div class="input-group mb-3">
<input id="Password"
name="Password"
type="password"
placeholder="Enter Password"
class="form-control"
v-model="state.password"
v-on:input="state.errors.password = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<label v-if="state.errors.password" class="text-danger small">{{ state.errors.password }}</label>
<div class="input-group mb-3">
<input id="ConfirmPassword"
name="ConfirmPassword"
type="password"
placeholder="Re-type Password"
class="form-control"
v-model="state.confirmPassword"
v-on:input="state.errors.confirmPassword = ''">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<label v-if="state.errors.confirmPassword" class="text-danger small">{{ state.errors.confirmPassword }}</label>
<div class="row">
<div class="col-8">
<div class="icheck-primary">
<input type="checkbox">
<label for="remember">
Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-4">
<button type="submit"
v-bind:disabled="state.isSubmitting"
class="btn btn-primary btn-block">
<span class="spinner-border spinner-border-sm me-2"
v-if="state.isSubmitting"
role="status"
aria-hidden="true"></span>
<span>{{ state.isSubmitting ? '...' : 'Register' }}</span>
</button>
</div>
<!-- /.col -->
</div>
</form>
<div class="social-auth-links text-center">
<p>- OR -</p>
<a href="#" class="btn btn-block btn-primary">
<i class="fab fa-facebook mr-2"></i>
Sign up using Facebook
</a>
<a href="#" class="btn btn-block btn-danger">
<i class="fab fa-google-plus mr-2"></i>
Sign up using Google+
</a>
</div>
<p class="mb-1">
<a asp-page="/Accounts/ForgotPassword">I forgot my password</a>
</p>
<p class="mb-1">
<a asp-page="/Accounts/Login" class="text-center">I already have a membership</a>
</p>
</div>
</div>
@section scripts {
<script type="module" src="~/FrontEnd/Pages/Accounts/Register.cshtml.js"></script>
}
@@ -0,0 +1,123 @@
const App = {
setup() {
const state = Vue.reactive({
email: '',
password: '',
confirmPassword: '',
firstName: '',
lastName: '',
companyName: '',
isSubmitting: false,
errors: {
email: '',
password: '',
confirmPassword: '',
firstName: '',
lastName: ''
}
});
const validateForm = () => {
// Reset errors
state.errors.email = '';
state.errors.password = '';
state.errors.confirmPassword = '';
state.errors.firstName = '';
state.errors.lastName = '';
let isValid = true;
if (!state.email) {
state.errors.email = 'Email is required.';
isValid = false;
} else if (!/\S+@\S+\.\S+/.test(state.email)) {
state.errors.email = 'Please enter a valid email address.';
isValid = false;
}
if (!state.password) {
state.errors.password = 'Password is required.';
isValid = false;
} else if (state.password.length < 6) {
state.errors.password = 'Password must be at least 6 characters.';
isValid = false;
}
if (!state.confirmPassword) {
state.errors.confirmPassword = 'Confirm Password is required.';
isValid = false;
} else if (state.password !== state.confirmPassword) {
state.errors.confirmPassword = 'Passwords do not match.';
isValid = false;
}
if (!state.firstName) {
state.errors.firstName = 'First Name is required.';
isValid = false;
}
if (!state.lastName) {
state.errors.lastName = 'Last Name is required.';
isValid = false;
}
return isValid;
};
const handleSubmit = async () => {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) return;
const response = await AxiosManager.post('/Security/Register', {
email: state.email,
password: state.password,
confirmPassword: state.confirmPassword,
firstName: state.firstName,
lastName: state.lastName,
companyName: state.companyName
});
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Register Successful',
text: 'Please check your email. You are being redirected...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
window.location.href = '/';
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Register Failed',
text: response.data.message || 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message || 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
};
return {
state,
handleSubmit
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,3 @@
@{
Layout = "~/FrontEnd/Pages/Shared/AdminLTE/_Auth.cshtml";
}
@@ -0,0 +1,160 @@
@page
@attribute [Authorize(Roles = "Companies")]
@{
ViewData["Title"] = "My Company";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row mb-0">
<!-- Main Info -->
<div class="col-md-12">
<div class="card mb-3">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
<div class="col-md-6">
<label for="Currency">Currency</label>
<input ref="currencyRef" v-model="state.currency" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.currency }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea ref="descriptionRef" v-model="state.description" class="form-control" rows="3"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-0">
<!-- Address -->
<div class="col-md-12">
<div class="card mb-3">
<div class="card-header">
<h5>Address</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Street">Street</label>
<input ref="streetRef" v-model="state.street" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.street }}</label>
</div>
<div class="col-md-6">
<label for="City">City</label>
<input ref="cityRef" v-model="state.city" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.city }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="State">State</label>
<input ref="stateRef" v-model="state.state" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.state }}</label>
</div>
<div class="col-md-6">
<label for="ZipCode">Zip Code</label>
<input ref="zipCodeRef" v-model="state.zipCode" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.zipCode }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Country">Country</label>
<input ref="countryRef" v-model="state.country" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.country }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mb-0">
<!-- Communication -->
<div class="col-md-12">
<div class="card mb-3">
<div class="card-header">
<h5>Communication</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="PhoneNumber">Phone Number</label>
<input ref="phoneNumberRef" v-model="state.phoneNumber" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.phoneNumber }}</label>
</div>
<div class="col-md-6">
<label for="FaxNumber">Fax Number</label>
<input ref="faxNumberRef" v-model="state.faxNumber" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.faxNumber }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="EmailAddress">Email Address</label>
<input ref="emailAddressRef" v-model="state.emailAddress" type="email" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.emailAddress }}</label>
</div>
<div class="col-md-6">
<label for="Website">Website</label>
<input ref="websiteRef" v-model="state.website" type="url" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.website }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Companies/MyCompany.cshtml.js"></script>
}
@@ -0,0 +1,596 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: 'Edit Company',
id: '',
name: '',
description: '',
currency: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
phoneNumber: '',
faxNumber: '',
emailAddress: '',
website: '',
errors: {
name: '',
currency: '',
street: '',
city: '',
state: '',
zipCode: '',
phoneNumber: '',
emailAddress: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const currencyRef = Vue.ref(null);
const streetRef = Vue.ref(null);
const cityRef = Vue.ref(null);
const stateRef = Vue.ref(null);
const zipCodeRef = Vue.ref(null);
const countryRef = Vue.ref(null);
const phoneNumberRef = Vue.ref(null);
const faxNumberRef = Vue.ref(null);
const emailAddressRef = Vue.ref(null);
const websiteRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Company/GetCompanyList', {});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (
id, name, description, currency, street, city, state, zipCode, country,
phoneNumber, faxNumber, emailAddress, website, updatedById
) => {
try {
const response = await AxiosManager.post('/Company/UpdateCompany', {
id,
name,
description,
currency,
street,
city,
state,
zipCode,
country,
phoneNumber,
faxNumber,
emailAddress,
website,
updatedById
});
return response;
} catch (error) {
throw error;
}
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 150, minWidth: 150 },
{ field: 'currency', headerText: 'Currency', width: 150, minWidth: 150 },
{ field: 'street', headerText: 'Street', width: 150, minWidth: 150 },
{ field: 'phoneNumber', headerText: 'Phone#', width: 150, minWidth: 150 },
{ field: 'emailAddress', headerText: 'Email', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'currency', 'street', 'phoneNumber', 'emailAddress', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
state.currency = selectedRecord.currency ?? '';
state.street = selectedRecord.street ?? '';
state.city = selectedRecord.city ?? '';
state.state = selectedRecord.state ?? '';
state.zipCode = selectedRecord.zipCode ?? '';
state.country = selectedRecord.country ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.faxNumber = selectedRecord.faxNumber ?? '';
state.emailAddress = selectedRecord.emailAddress ?? '';
state.website = selectedRecord.website ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
const formattedData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
state.mainData = formattedData;
},
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const currencyText = {
obj: null,
create: () => {
currencyText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Currency',
});
currencyText.obj.appendTo(currencyRef.value);
},
refresh: () => {
if (currencyText.obj) {
currencyText.obj.value = state.currency;
}
}
};
const streetText = {
obj: null,
create: () => {
streetText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Street',
});
streetText.obj.appendTo(streetRef.value);
},
refresh: () => {
if (streetText.obj) {
streetText.obj.value = state.street;
}
}
};
const cityText = {
obj: null,
create: () => {
cityText.obj = new ej.inputs.TextBox({
placeholder: 'Enter City',
});
cityText.obj.appendTo(cityRef.value);
},
refresh: () => {
if (cityText.obj) {
cityText.obj.value = state.city;
}
}
};
const stateText = {
obj: null,
create: () => {
stateText.obj = new ej.inputs.TextBox({
placeholder: 'Enter State',
});
stateText.obj.appendTo(stateRef.value);
},
refresh: () => {
if (stateText.obj) {
stateText.obj.value = state.state;
}
}
};
const zipCodeText = {
obj: null,
create: () => {
zipCodeText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Zip Code',
});
zipCodeText.obj.appendTo(zipCodeRef.value);
},
refresh: () => {
if (zipCodeText.obj) {
zipCodeText.obj.value = state.zipCode;
}
}
};
const countryText = {
obj: null,
create: () => {
countryText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Country',
});
countryText.obj.appendTo(countryRef.value);
},
refresh: () => {
if (countryText.obj) {
countryText.obj.value = state.country;
}
}
};
const phoneNumberText = {
obj: null,
create: () => {
phoneNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Phone Number',
});
phoneNumberText.obj.appendTo(phoneNumberRef.value);
},
refresh: () => {
if (phoneNumberText.obj) {
phoneNumberText.obj.value = state.phoneNumber;
}
}
};
const faxNumberText = {
obj: null,
create: () => {
faxNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Fax Number',
});
faxNumberText.obj.appendTo(faxNumberRef.value);
},
refresh: () => {
if (faxNumberText.obj) {
faxNumberText.obj.value = state.faxNumber;
}
}
};
const emailAddressText = {
obj: null,
create: () => {
emailAddressText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Email Address',
});
emailAddressText.obj.appendTo(emailAddressRef.value);
},
refresh: () => {
if (emailAddressText.obj) {
emailAddressText.obj.value = state.emailAddress;
}
}
};
const websiteText = {
obj: null,
create: () => {
websiteText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Website',
});
websiteText.obj.appendTo(websiteRef.value);
},
refresh: () => {
if (websiteText.obj) {
websiteText.obj.value = state.website;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.currency,
(newVal, oldVal) => {
state.errors.currency = '';
currencyText.refresh();
}
);
Vue.watch(
() => state.street,
(newVal, oldVal) => {
state.errors.street = '';
streetText.refresh();
}
);
Vue.watch(
() => state.city,
(newVal, oldVal) => {
state.errors.city = '';
cityText.refresh();
}
);
Vue.watch(
() => state.state,
(newVal, oldVal) => {
state.errors.state = '';
stateText.refresh();
}
);
Vue.watch(
() => state.zipCode,
(newVal, oldVal) => {
state.errors.zipCode = '';
zipCodeText.refresh();
}
);
Vue.watch(
() => state.country,
(newVal, oldVal) => {
countryText.refresh();
}
);
Vue.watch(
() => state.phoneNumber,
(newVal, oldVal) => {
state.errors.phoneNumber = '';
phoneNumberText.refresh();
}
);
Vue.watch(
() => state.faxNumber,
(newVal, oldVal) => {
faxNumberText.refresh();
}
);
Vue.watch(
() => state.emailAddress,
(newVal, oldVal) => {
state.errors.emailAddress = '';
emailAddressText.refresh();
}
);
Vue.watch(
() => state.website,
(newVal, oldVal) => {
websiteText.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
// Validation
let isValid = true;
Object.keys(state.errors).forEach(field => {
state.errors[field] = '';
if (!state[field] && ['name', 'currency', 'street', 'city', 'state', 'zipCode', 'phoneNumber', 'emailAddress'].includes(field)) {
state.errors[field] = `${field.charAt(0).toUpperCase() + field.slice(1)} is required.`;
isValid = false;
}
});
if (!isValid) return;
const response = await services.updateMainData(
state.id,
state.name,
state.description,
state.currency,
state.street,
state.city,
state.state,
state.zipCode,
state.country,
state.phoneNumber,
state.faxNumber,
state.emailAddress,
state.website,
StorageManager.getUserId()
);
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Page will be refreshed...',
timer: 1000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
location.reload();
}, 1000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Companies']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
currencyText.create();
streetText.create();
cityText.create();
stateText.create();
zipCodeText.create();
countryText.create();
phoneNumberText.create();
faxNumberText.create();
emailAddressText.create();
websiteText.create();
mainModal.create();
mainModalRef.value.addEventListener('hidden.bs.modal', () => {
Object.keys(state).forEach(key => {
if (typeof state[key] === 'string') {
state[key] = '';
}
});
state.errors = {
name: '',
currency: '',
street: '',
city: '',
state: '',
zipCode: '',
phoneNumber: '',
emailAddress: ''
};
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', () => { });
});
return {
state,
mainGridRef,
mainModalRef,
nameRef,
currencyRef,
streetRef,
cityRef,
stateRef,
zipCodeRef,
countryRef,
phoneNumberRef,
faxNumberRef,
emailAddressRef,
websiteRef,
handler
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,72 @@
@page
@attribute [Authorize(Roles = "CustomerCategories")]
@{
ViewData["Title"] = "Customer Category List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/CustomerCategories/CustomerCategoryList.cshtml.js"></script>
}
@@ -0,0 +1,306 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
description: '',
errors: {
name: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/CustomerCategory/GetCustomerCategoryList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, description, createdById) => {
try {
const response = await AxiosManager.post('/CustomerCategory/CreateCustomerCategory', {
name, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, description, updatedById) => {
try {
const response = await AxiosManager.post('/CustomerCategory/UpdateCustomerCategory', {
id, name, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/CustomerCategory/DeleteCustomerCategory', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
}
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
let isValid = true;
// name validation
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!isValid) return;
const response = state.id === ''
? await services.createMainData(state.name, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.description = '';
state.errors = {
name: ''
};
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowCategorying: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Customer Category';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Customer Category';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Customer Category?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['CustomerCategories']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
mainModal.create();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
mainModalRef,
nameRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,100 @@
@page
@attribute [Authorize(Roles = "CustomerContacts")]
@{
ViewData["Title"] = "Customer Contact List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" class="form-control" placeholder="" readonly />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="PhoneNumber">PhoneNumber</label>
<input ref="phoneNumberRef" v-model="state.phoneNumber" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.phoneNumber"></label>
</div>
<div class="col-md-6">
<label for="EmailAddress">EmailAddress</label>
<input ref="emailAddressRef" v-model="state.emailAddress" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.emailAddress"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="JobTitle">JobTitle</label>
<input ref="jobTitleRef" v-model="state.jobTitle" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.jobTitle"></label>
</div>
<div class="col-md-6">
<label for="CustomerId">Customer</label>
<div ref="customerIdRef"></div>
<label class="text-danger" v-text="state.errors.customerId"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/CustomerContacts/CustomerContactList.cshtml.js"></script>
}
@@ -0,0 +1,548 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
customerListLookupData: [],
mainTitle: null,
id: '',
name: '',
jobTitle: '',
phoneNumber: '',
emailAddress: '',
description: '',
customerId: null,
errors: {
name: '',
jobTitle: '',
phoneNumber: '',
emailAddress: '',
customerId: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const jobTitleRef = Vue.ref(null);
const phoneNumberRef = Vue.ref(null);
const emailAddressRef = Vue.ref(null);
const customerIdRef = Vue.ref(null);
const validateForm = function () {
state.errors.name = '';
state.errors.jobTitle = '';
state.errors.phoneNumber = '';
state.errors.emailAddress = '';
state.errors.customerId = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!state.jobTitle) {
state.errors.jobTitle = 'Job Title is required.';
isValid = false;
}
if (!state.phoneNumber) {
state.errors.phoneNumber = 'Phone number is required.';
isValid = false;
}
if (!state.emailAddress) {
state.errors.emailAddress = 'Email address is required.';
isValid = false;
}
if (!state.customerId) {
state.errors.customerId = 'Customer is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.number = '';
state.jobTitle = '';
state.phoneNumber = '';
state.emailAddress = '';
state.description = '';
state.customerId = null;
state.errors = {
name: '',
jobTitle: '',
phoneNumber: '',
emailAddress: '',
customerId: ''
};
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/CustomerContact/GetCustomerContactList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, jobTitle, phoneNumber, emailAddress, description, customerId, createdById) => {
try {
const response = await AxiosManager.post('/CustomerContact/CreateCustomerContact', {
name, jobTitle, phoneNumber, emailAddress, description, customerId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, jobTitle, phoneNumber, emailAddress, description, customerId, updatedById) => {
try {
const response = await AxiosManager.post('/CustomerContact/UpdateCustomerContact', {
id, name, jobTitle, phoneNumber, emailAddress, description, customerId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/CustomerContact/DeleteCustomerContact', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getCustomerListLookupData: async () => {
try {
const response = await AxiosManager.get('/Customer/GetCustomerList', {});
return response;
} catch (error) {
throw error;
}
}
};
const methods = {
populateCustomerListLookupData: async () => {
const response = await services.getCustomerListLookupData();
state.customerListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name'
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
},
refresh: () => {
if (numberText.obj) {
numberText.obj.value = state.number;
}
}
};
const jobTitleText = {
obj: null,
create: () => {
jobTitleText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Job Title'
});
jobTitleText.obj.appendTo(jobTitleRef.value);
},
refresh: () => {
if (jobTitleText.obj) {
jobTitleText.obj.value = state.jobTitle;
}
}
};
const phoneNumberText = {
obj: null,
create: () => {
phoneNumberText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Phone Number'
});
phoneNumberText.obj.appendTo(phoneNumberRef.value);
},
refresh: () => {
if (phoneNumberText.obj) {
phoneNumberText.obj.value = state.phoneNumber;
}
}
};
const emailAddressText = {
obj: null,
create: () => {
emailAddressText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Email Address'
});
emailAddressText.obj.appendTo(emailAddressRef.value);
},
refresh: () => {
if (emailAddressText.obj) {
emailAddressText.obj.value = state.emailAddress;
}
}
};
const customerListLookup = {
obj: null,
create: () => {
if (state.customerListLookupData && Array.isArray(state.customerListLookupData)) {
customerListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.customerListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Customer',
change: (e) => {
state.customerId = e.value;
}
});
customerListLookup.obj.appendTo(customerIdRef.value);
} else {
console.error('Customer list lookup data is not available or invalid.');
}
},
refresh: () => {
if (customerListLookup.obj) {
customerListLookup.obj.value = state.customerId;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.jobTitle,
(newVal, oldVal) => {
state.errors.jobTitle = '';
jobTitleText.refresh();
}
);
Vue.watch(
() => state.phoneNumber,
(newVal, oldVal) => {
state.errors.phoneNumber = '';
phoneNumberText.refresh();
}
);
Vue.watch(
() => state.emailAddress,
(newVal, oldVal) => {
state.errors.emailAddress = '';
emailAddressText.refresh();
}
);
Vue.watch(
() => state.customerId,
(newVal, oldVal) => {
state.errors.customerId = '';
customerListLookup.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.jobTitle, state.phoneNumber, state.emailAddress, state.description, state.customerId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.jobTitle, state.phoneNumber, state.emailAddress, state.description, state.customerId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Customer Contact';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.name = response?.data?.content?.data.name ?? '';
state.jobTitle = response?.data?.content?.data.jobTitle ?? '';
state.phoneNumber = response?.data?.content?.data.phoneNumber ?? '';
state.emailAddress = response?.data?.content?.data.emailAddress ?? '';
state.description = response?.data?.content?.data.description ?? '';
state.customerId = response?.data?.content?.data.customerId ?? '';
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['CustomerContacts']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateCustomerListLookupData();
customerListLookup.create();
nameText.create();
numberText.create();
jobTitleText.create();
phoneNumberText.create();
emailAddressText.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', () => {
resetFormState();
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', resetFormState);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['customerName']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'customerName', headerText: 'Customer', width: 150, minWidth: 150 },
{ field: 'jobTitle', headerText: 'Job Title', width: 150, minWidth: 150 },
{ field: 'phoneNumber', headerText: 'Phone', width: 150, minWidth: 150 },
{ field: 'emailAddress', headerText: 'Email', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'customerName', 'jobTitle', 'phoneNumber', 'emailAddress', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Customer Contact';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Customer Contact';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.jobTitle = selectedRecord.jobTitle ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.emailAddress = selectedRecord.emailAddress ?? '';
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Customer Contact?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.jobTitle = selectedRecord.jobTitle ?? '';
state.phoneNumber = selectedRecord.phoneNumber ?? '';
state.emailAddress = selectedRecord.emailAddress ?? '';
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
nameRef,
numberRef,
jobTitleRef,
phoneNumberRef,
emailAddressRef,
customerIdRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,72 @@
@page
@attribute [Authorize(Roles = "CustomerGroups")]
@{
ViewData["Title"] = "Customer Group List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/CustomerGroups/CustomerGroupList.cshtml.js"></script>
}
@@ -0,0 +1,306 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
description: '',
errors: {
name: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/CustomerGroup/GetCustomerGroupList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, description, createdById) => {
try {
const response = await AxiosManager.post('/CustomerGroup/CreateCustomerGroup', {
name, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, description, updatedById) => {
try {
const response = await AxiosManager.post('/CustomerGroup/UpdateCustomerGroup', {
id, name, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/CustomerGroup/DeleteCustomerGroup', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
}
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
let isValid = true;
// name validation
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!isValid) return;
const response = state.id === ''
? await services.createMainData(state.name, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.description = '';
state.errors = {
name: ''
};
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Customer Group';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Customer Group';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Customer Group?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['CustomerGroups']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
mainModal.create();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
mainModalRef,
nameRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,229 @@
@page
@attribute [Authorize(Roles = "Customers")]
@{
ViewData["Title"] = "Customer List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.mainTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="card mb-3">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.name"></label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" class="form-control" placeholder="" readonly />
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CustomerGroupId">Customer Group</label>
<div ref="customerGroupIdRef"></div>
<label class="text-danger" v-text="state.errors.customerGroupId"></label>
</div>
<div class="col-md-6">
<label for="CustomerCategoryId">Customer Category</label>
<div ref="customerCategoryIdRef"></div>
<label class="text-danger" v-text="state.errors.customerCategoryId"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" class="form-control" rows="3" placeholder=""></textarea>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Address</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Street">Street</label>
<input ref="streetRef" v-model="state.street" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.street"></label>
</div>
<div class="col-md-6">
<label for="City">City</label>
<input ref="cityRef" v-model="state.city" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.city"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="State">State</label>
<input ref="stateRef" v-model="state.state" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.state"></label>
</div>
<div class="col-md-6">
<label for="ZipCode">Zip Code</label>
<input ref="zipCodeRef" v-model="state.zipCode" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.zipCode"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Country">Country</label>
<input ref="countryRef" v-model="state.country" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.country"></label>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Communication</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="PhoneNumber">Phone Number</label>
<input ref="phoneNumberRef" v-model="state.phoneNumber" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.phoneNumber"></label>
</div>
<div class="col-md-6">
<label for="FaxNumber">Fax Number</label>
<input ref="faxNumberRef" v-model="state.faxNumber" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.faxNumber"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="EmailAddress">Email</label>
<input ref="emailAddressRef" v-model="state.emailAddress" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.emailAddress"></label>
</div>
<div class="col-md-6">
<label for="Website">Website</label>
<input ref="websiteRef" v-model="state.website" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.website"></label>
</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">
<h5>Social Media</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-4">
<label for="WhatsApp">WhatsApp</label>
<input ref="whatsAppRef" v-model="state.whatsApp" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.whatsApp"></label>
</div>
<div class="col-md-4">
<label for="LinkedIn">LinkedIn</label>
<input ref="linkedInRef" v-model="state.linkedIn" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.linkedIn"></label>
</div>
<div class="col-md-4">
<label for="Facebook">Facebook</label>
<input ref="facebookRef" v-model="state.facebook" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.facebook"></label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-4">
<label for="Instagram">Instagram</label>
<input ref="instagramRef" v-model="state.instagram" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.instagram"></label>
</div>
<div class="col-md-4">
<label for="TwitterX">Twitter/X</label>
<input ref="twitterXRef" v-model="state.twitterX" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.twitterX"></label>
</div>
<div class="col-md-4">
<label for="TikTok">TikTok</label>
<input ref="tikTokRef" v-model="state.tikTok" class="form-control" placeholder="" />
<label class="text-danger" v-text="state.errors.tikTok"></label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" ref="manageContactModalRef" id="ManageContactModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" v-text="state.manageContactTitle"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Customer Contact</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Customers/CustomerList.cshtml.js"></script>
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,186 @@
@page
@attribute [Authorize(Roles = "Dashboards")]
@{
ViewData["Title"] = "Default Dashboard";
}
<div id="app" v-cloak>
<div class="form-card" id="formcard">
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-chart-line fa-3x" style="color: #E94649;"></i>
<div class="ms-3">
<p class="mb-2">Sales</p>
<h6 class="mb-0 text-end"><span ref="cardSalesQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-undo-alt fa-3x" style="color: #F6B53F;"></i>
<div class="ms-3">
<p class="mb-2">Sales Rtrn.</p>
<h6 class="mb-0 text-end"><span ref="cardSalesReturnQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-shopping-cart fa-3x text-primary"></i>
<div class="ms-3">
<p class="mb-2">Purchase</p>
<h6 class="mb-0 text-end"><span ref="cardPurchaseQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-undo fa-3x" style="color: #C4C24A;"></i>
<div class="ms-3">
<p class="mb-2">Purchase Rtrn.</p>
<h6 class="mb-0 text-end"><span ref="cardPurchaseReturnQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-truck fa-3x" style="color: #C4C24A;"></i>
<div class="ms-3">
<p class="mb-2">Delivery Order</p>
<h6 class="mb-0 text-end"><span ref="cardDeliveryOrderQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-boxes fa-3x text-primary"></i>
<div class="ms-3">
<p class="mb-2">Goods Receive</p>
<h6 class="mb-0 text-end"><span ref="cardGoodsReceiveQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-sign-out-alt fa-3x" style="color: #F6B53F;"></i>
<div class="ms-3">
<p class="mb-2">Transfer Out</p>
<h6 class="mb-0 text-end"><span ref="cardTransferOutQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
<div class="col-sm-6 col-xl-3">
<div class="bg-white rounded d-flex align-items-center justify-content-between p-4">
<i class="fas fa-sign-in-alt fa-3x" style="color: #E94649"></i>
<div class="ms-3">
<p class="mb-2">Transfer In</p>
<h6 class="mb-0 text-end"><span ref="cardTransferInQtyRef"></span> Qty.</h6>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Customer Group</h6>
<a href="/SalesReports/SalesReportList">Sales</a>
</div>
<div ref="customerGroupChartRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Vendor Group</h6>
<a href="/PurchaseReports/PurchaseReportList">Purchases</a>
</div>
<div ref="vendorGroupChartRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Customer Category</h6>
<a href="/SalesReports/SalesReportList">Sales</a>
</div>
<div ref="customerCategoryChartRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Vendor Category</h6>
<a href="/PurchaseReports/PurchaseReportList">Purchases</a>
</div>
<div ref="vendorCategoryChartRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Latest Sales</h6>
<a href="/SalesOrders/SalesOrderList">Sales</a>
</div>
<div ref="salesOrderGridRef" align="center"></div>
</div>
</div>
<div class="col-sm-12 col-xl-6">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Latest Purchase</h6>
<a href="/PurchaseOrders/PurchaseOrderList">Purchases</a>
</div>
<div ref="purchaseOrderGridRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4">
<div class="col-sm-12 col-xl-12">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Inventory Stock</h6>
<a href="/StockReports/StockReportList">Stocks</a>
</div>
<div ref="stockChartRef" align="center"></div>
</div>
</div>
</div>
</div>
<div class="container-fluid pt-4 px-4">
<div class="row g-4 mb-4">
<div class="col-sm-12 col-xl-12">
<div class="bg-white text-center rounded p-4">
<div class="d-flex align-items-center justify-content-between mb-4">
<h6 class="mb-0">Inventory Transaction</h6>
<a href="/TransactionReports/TransactionReportList">Transactions</a>
</div>
<div ref="inventoryTransactionGridRef" align="center"></div>
</div>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Dashboards/DefaultDashboard.cshtml.js"></script>
}
@@ -0,0 +1,337 @@
const App = {
setup() {
const state = Vue.reactive({
cardsData: {},
salesData: {},
purchaseData: {},
inventoryData: {}
});
const cardSalesQtyRef = Vue.ref(null);
const cardSalesReturnQtyRef = Vue.ref(null);
const cardPurchaseQtyRef = Vue.ref(null);
const cardPurchaseReturnQtyRef = Vue.ref(null);
const cardDeliveryOrderQtyRef = Vue.ref(null);
const cardGoodsReceiveQtyRef = Vue.ref(null);
const cardTransferOutQtyRef = Vue.ref(null);
const cardTransferInQtyRef = Vue.ref(null);
const salesOrderGridRef = Vue.ref(null);
const inventoryTransactionGridRef = Vue.ref(null);
const purchaseOrderGridRef = Vue.ref(null);
const customerGroupChartRef = Vue.ref(null);
const vendorGroupChartRef = Vue.ref(null);
const customerCategoryChartRef = Vue.ref(null);
const vendorCategoryChartRef = Vue.ref(null);
const stockChartRef = Vue.ref(null);
const services = {
getCardsData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetCardsDashboard', {});
return response;
} catch (error) {
throw error;
}
},
getSalesData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetSalesDashboard', {});
return response;
} catch (error) {
throw error;
}
},
getPurchaseData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetPurchaseDashboard', {});
return response;
} catch (error) {
throw error;
}
},
getInventoryData: async () => {
try {
const response = await AxiosManager.get('/Dashboard/GetInventoryDashboard', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateCardsData: async () => {
const response = await services.getCardsData();
state.cardsData = response?.data?.content?.data;
methods.populateCards();
},
populateSalesData: async () => {
const response = await services.getSalesData();
state.salesData = response?.data?.content?.data;
methods.populateSalesOrderGrid();
methods.populateSalesByCustomerGroupChart();
methods.populateSalesByCustomerCategoryChart();
},
populatePurchaseData: async () => {
const response = await services.getPurchaseData();
state.purchaseData = response?.data?.content?.data;
methods.populatePurchaseOrderGrid();
methods.populatePurchaseByVendorGroupChart();
methods.populatePurchaseByVendorCategoryChart();
},
populateInventoryData: async () => {
const response = await services.getInventoryData();
state.inventoryData = response?.data?.content?.data;
methods.populateInventoryTransactionGrid();
methods.populateInventoryStockChart();
},
populateCards: () => {
const cardsDashboard = state.cardsData?.cardsDashboard;
if (cardsDashboard) {
cardSalesQtyRef.value.textContent = cardsDashboard.salesTotal || 0;
cardSalesReturnQtyRef.value.textContent = cardsDashboard.salesReturnTotal || 0;
cardPurchaseQtyRef.value.textContent = cardsDashboard.purchaseTotal || 0;
cardPurchaseReturnQtyRef.value.textContent = cardsDashboard.purchaseReturnTotal || 0;
cardDeliveryOrderQtyRef.value.textContent = cardsDashboard.deliveryOrderTotal || 0;
cardGoodsReceiveQtyRef.value.textContent = cardsDashboard.goodsReceiveTotal || 0;
cardTransferOutQtyRef.value.textContent = cardsDashboard.transferOutTotal || 0;
cardTransferInQtyRef.value.textContent = cardsDashboard.transferInTotal || 0;
} else {
console.error('CardsDashboard data is not available.');
}
},
populateSalesOrderGrid: () => {
const salesOrderDashboard = state.salesData?.salesOrderDashboard ?? [];
new ej.grids.Grid({
dataSource: salesOrderDashboard,
allowFiltering: false,
allowSorting: true,
allowSelection: false,
allowGrouping: false,
allowTextWrap: false,
allowResizing: false,
allowPaging: true,
allowExcelExport: false,
sortSettings: { columns: [{ field: 'orderDate', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 10 },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'salesOrder.orderDate', headerText: 'Order Date', width: 70, type: 'dateTime', format: 'yyyy-MM-dd', textAlign: 'Left' },
{ field: 'salesOrder.number', headerText: '#Number', width: 90 },
{ field: 'product.name', headerText: 'Product', width: 150 },
{ field: 'total', headerText: 'Total', width: 70, type: 'number', format: 'N2', textAlign: 'Right' },
],
}, salesOrderGridRef.value);
},
populateInventoryTransactionGrid: () => {
const inventoryTransactionDashboard = state.inventoryData?.inventoryTransactionDashboard ?? [];
new ej.grids.Grid({
dataSource: inventoryTransactionDashboard,
allowFiltering: false,
allowSorting: true,
allowSelection: false,
allowGrouping: false,
allowTextWrap: false,
allowResizing: false,
allowPaging: true,
allowExcelExport: false,
sortSettings: { columns: [{ field: 'movementDate', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 10 },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'movementDate', headerText: 'Date', width: 150, format: 'yyyy-MM-dd', textAlign: 'Left', type: 'dateTime' },
{ field: 'warehouse.name', headerText: 'Warehouse', width: 150 },
{ field: 'product.name', headerText: 'Product', width: 150 },
{ field: 'number', headerText: 'Number', width: 150 },
{ field: 'stock', headerText: 'Movement', width: 100, type: 'number', format: '+0.00;-0.00;0.00', textAlign: 'Right' },
{ field: 'moduleName', headerText: 'Module Name', width: 150 },
{ field: 'moduleCode', headerText: 'Module Code', width: 150 },
{ field: 'moduleNumber', headerText: 'Module Number', width: 150 },
{ field: 'warehouseFrom.name', headerText: 'Warehouse From', width: 150 },
{ field: 'warehouseTo.name', headerText: 'Warehouse To', width: 150 },
],
}, inventoryTransactionGridRef.value);
},
populatePurchaseOrderGrid: () => {
const purchaseOrderDashboard = state.purchaseData?.purchaseOrderDashboard ?? [];
new ej.grids.Grid({
dataSource: purchaseOrderDashboard,
allowFiltering: false,
allowSorting: true,
allowSelection: false,
allowGrouping: false,
allowTextWrap: false,
allowResizing: false,
allowPaging: true,
allowExcelExport: false,
sortSettings: { columns: [{ field: 'orderDate', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 10 },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'purchaseOrder.orderDate', headerText: 'Order Date', width: 70, type: 'dateTime', format: 'yyyy-MM-dd', textAlign: 'Left' },
{ field: 'purchaseOrder.number', headerText: '#Number', width: 90 },
{ field: 'product.name', headerText: 'Product', width: 150 },
{ field: 'total', headerText: 'Total', width: 70, type: 'number', format: 'N2', textAlign: 'Right' },
],
}, purchaseOrderGridRef.value);
},
populateSalesByCustomerGroupChart: () => {
const salesByCustomerGroupDashboard = state.salesData?.salesByCustomerGroupDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: salesByCustomerGroupDashboard,
title: 'Sales by Customer Group',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
customerGroupChartRef.value);
},
populatePurchaseByVendorGroupChart: () => {
const purchaseByVendorGroupDashboard = state.purchaseData?.purchaseByVendorGroupDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: purchaseByVendorGroupDashboard,
title: 'Purchase by Vendor Group',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
vendorGroupChartRef.value);
},
populateSalesByCustomerCategoryChart: () => {
const salesByCustomerCategoryDashboard = state.salesData?.salesByCustomerCategoryDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: salesByCustomerCategoryDashboard,
title: 'Sales by Customer Category',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
customerCategoryChartRef.value);
},
populatePurchaseByVendorCategoryChart: () => {
const purchaseByVendorCategoryDashboard = state.purchaseData?.purchaseByVendorCategoryDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: ej.base.Browser.isDevice ? -45 : 0, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: purchaseByVendorCategoryDashboard,
title: 'Purchase by Vendor Category',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { enableHighlight: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
vendorCategoryChartRef.value);
},
populateInventoryStockChart: () => {
const inventoryStockDashboard = state.inventoryData?.inventoryStockDashboard ?? [];
new ej.charts.Chart(
{
primaryXAxis: {
valueType: 'Category', interval: 1, majorGridLines: { width: 0 }, majorTickLines: { width: 0 }, labelIntersectAction: 'None', labelRotation: -15, minorTickLines: { width: 0 }
},
chartArea: { border: { width: 0 } },
primaryYAxis: {
title: 'Quantity',
majorTickLines: { width: 0 }, lineStyle: { width: 0 },
},
series: inventoryStockDashboard,
title: 'Stock by Warehouse',
tooltip: { enable: true, header: "<b>${point.tooltip}</b>", shared: true },
legendSettings: { visible: true },
palettes: ["#E94649", "#F6B53F", "#009CFF", "#C4C24A"],
},
stockChartRef.value);
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Dashboards']);
await SecurityManager.validateToken();
await methods.populateCardsData();
await methods.populateSalesData();
await methods.populatePurchaseData();
await methods.populateInventoryData();
} catch (e) {
console.error('page init error:', e);
}
});
return {
cardSalesQtyRef,
cardSalesReturnQtyRef,
cardPurchaseQtyRef,
cardPurchaseReturnQtyRef,
cardDeliveryOrderQtyRef,
cardGoodsReceiveQtyRef,
cardTransferOutQtyRef,
cardTransferInQtyRef,
salesOrderGridRef,
inventoryTransactionGridRef,
purchaseOrderGridRef,
customerGroupChartRef,
vendorGroupChartRef,
customerCategoryChartRef,
vendorCategoryChartRef,
stockChartRef,
state,
methods
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,128 @@
@page
@attribute [Authorize(Roles = "DeliveryOrders")]
@{
ViewData["Title"] = "Delivery Order List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="DeliveryDate">Delivery Date</label>
<input ref="deliveryDateRef"/>
<label class="text-danger">{{ state.errors.deliveryDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="SalesOrderId">Sales Order</label>
<div ref="salesOrderIdRef"></div>
<label class="text-danger">{{ state.errors.salesOrderId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Delivery Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/DeliveryOrders/DeliveryOrderList.cshtml.js"></script>
}
@@ -0,0 +1,874 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
salesOrderListLookupData: [],
statusListLookupData: [],
secondaryData: [],
productListLookupData: [],
warehouseListLookupData: [],
mainTitle: null,
id: '',
number: '',
deliveryDate: '',
description: '',
salesOrderId: null,
status: null,
errors: {
deliveryDate: '',
salesOrderId: '',
status: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const deliveryDateRef = Vue.ref(null);
const salesOrderIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.deliveryDate = '';
state.errors.salesOrderId = '';
state.errors.status = '';
let isValid = true;
if (!state.deliveryDate) {
state.errors.deliveryDate = 'Delivery date is required.';
isValid = false;
}
if (!state.salesOrderId) {
state.errors.salesOrderId = 'Sales Order is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.deliveryDate = '';
state.description = '';
state.salesOrderId = null;
state.status = null;
state.errors = {
deliveryDate: '',
salesOrderId: '',
status: '',
description: ''
};
state.secondaryData = [];
};
const orderDatePicker = {
obj: null,
create: () => {
orderDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.deliveryDate ? new Date(state.deliveryDate) : null,
change: (e) => {
state.deliveryDate = e.value;
}
});
orderDatePicker.obj.appendTo(deliveryDateRef.value);
},
refresh: () => {
if (orderDatePicker.obj) {
orderDatePicker.obj.value = state.deliveryDate ? new Date(state.deliveryDate) : null;
}
}
};
Vue.watch(
() => state.deliveryDate,
(newVal, oldVal) => {
orderDatePicker.refresh();
state.errors.deliveryDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const salesOrderListLookup = {
obj: null,
create: () => {
if (state.salesOrderListLookupData && Array.isArray(state.salesOrderListLookupData)) {
salesOrderListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.salesOrderListLookupData,
fields: { value: 'id', text: 'number' },
placeholder: 'Select Sales Order',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('number', 'startsWith', e.text, true);
}
e.updateData(state.salesOrderListLookupData, query);
},
change: (e) => {
state.salesOrderId = e.value;
}
});
salesOrderListLookup.obj.appendTo(salesOrderIdRef.value);
}
},
refresh: () => {
if (salesOrderListLookup.obj) {
salesOrderListLookup.obj.value = state.salesOrderId
}
},
};
Vue.watch(
() => state.salesOrderId,
(newVal, oldVal) => {
salesOrderListLookup.refresh();
state.errors.salesOrderId = '';
}
);
const statusListLookup = {
obj: null,
create: () => {
if (state.statusListLookupData && Array.isArray(state.statusListLookupData)) {
statusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.statusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
statusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (statusListLookup.obj) {
statusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
statusListLookup.refresh();
state.errors.status = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/DeliveryOrder/GetDeliveryOrderList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (deliveryDate, description, status, salesOrderId, createdById) => {
try {
const response = await AxiosManager.post('/DeliveryOrder/CreateDeliveryOrder', {
deliveryDate, description, status, salesOrderId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, deliveryDate, description, status, salesOrderId, updatedById) => {
try {
const response = await AxiosManager.post('/DeliveryOrder/UpdateDeliveryOrder', {
id, deliveryDate, description, status, salesOrderId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/DeliveryOrder/DeleteDeliveryOrder', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getSalesOrderListLookupData: async () => {
try {
const response = await AxiosManager.get('/SalesOrder/GetSalesOrderList', {});
return response;
} catch (error) {
throw error;
}
},
getDeliveryOrderStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/DeliveryOrder/GetDeliveryOrderStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/DeliveryOrderGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, warehouseId, productId, movement, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/DeliveryOrderCreateInvenTrans', {
moduleId, warehouseId, productId, movement, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, warehouseId, productId, movement, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/DeliveryOrderUpdateInvenTrans', {
id, warehouseId, productId, movement, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/DeliveryOrderDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
deliveryDate: new Date(item.deliveryDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateSalesOrderListLookupData: async () => {
const response = await services.getSalesOrderListLookupData();
state.salesOrderListLookupData = response?.data?.content?.data;
},
populateDeliveryOrderStatusListLookupData: async () => {
const response = await services.getDeliveryOrderStatusListLookupData();
state.statusListLookupData = response?.data?.content?.data;
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateSecondaryData: async (deliveryOrderId) => {
try {
const response = await services.getSecondaryData(deliveryOrderId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.movement ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
onMainModalHidden: () => {
state.errors.deliveryDate = '';
state.errors.salesOrderId = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.deliveryDate, state.description, state.status, state.salesOrderId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.deliveryDate, state.description, state.status, state.salesOrderId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Delivery Order';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['DeliveryOrders']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden());
await methods.populateSalesOrderListLookupData();
await methods.populateDeliveryOrderStatusListLookupData();
numberText.create();
orderDatePicker.create();
salesOrderListLookup.create();
statusListLookup.create();
await secondaryGrid.create(state.secondaryData);
await methods.populateProductListLookupData();
await methods.populateWarehouseListLookupData();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden());
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'deliveryDate', headerText: 'Delivery Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'salesOrderNumber', headerText: 'Sales Order', width: 150, minWidth: 150 },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'deliveryDate', 'salesOrderNumber', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Delivery Order';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Delivery Order';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.deliveryDate = selectedRecord.deliveryDate ? new Date(selectedRecord.deliveryDate) : null;
state.description = selectedRecord.description ?? '';
state.salesOrderId = selectedRecord.salesOrderId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Delivery Order?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.deliveryDate = selectedRecord.deliveryDate ? new Date(selectedRecord.deliveryDate) : null;
state.description = selectedRecord.description ?? '';
state.salesOrderId = selectedRecord.salesOrderId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/DeliveryOrders/DeliveryOrderPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'warehouseName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'warehouseId',
headerText: 'Warehouse',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const warehouse = state.warehouseListLookupData.find(item => item.id === data[field]);
return warehouse ? `${warehouse.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const warehouseElem = document.createElement('input');
return warehouseElem;
},
read: () => {
return warehouseObj.value;
},
destroy: function () {
warehouseObj.destroy();
},
write: function (args) {
warehouseObj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.warehouseId,
placeholder: 'Select a Warehouse',
floatLabelType: 'Never'
});
warehouseObj.appendTo(args.element);
}
}
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'numberName' },
value: args.rowData.productId,
change: function (e) {
if (movementObj) {
movementObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'movement',
headerText: 'Movement',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
const movementElem = document.createElement('input');
return movementElem;
},
read: () => {
return movementObj.value;
},
destroy: function () {
movementObj.destroy();
},
write: function (args) {
movementObj = new ej.inputs.NumericTextBox({
value: args.rowData.movement ?? 0,
});
movementObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
numberRef,
deliveryDateRef,
salesOrderIdRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,234 @@
@page
@attribute [Authorize(Roles = "DeliveryOrders")]
@{
ViewData["Title"] = "Delivery Order PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Delivery Order</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Customer Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.customer.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.customerAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.customer.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.customer.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Delivery Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.deliveryDate }}</td>
</tr>
<tr>
<td><strong>Reference:</strong></td>
<td>{{ state.referenceNumber }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Warehouse</th>
<th>Product</th>
<th>Movement</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product + item.warehouse">
<td>{{ item.warehouse }}</td>
<td>{{ item.product }}</td>
<td>{{ item.movement }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Movement:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/DeliveryOrders/DeliveryOrderPdf.cshtml.js"></script>
}
@@ -0,0 +1,151 @@
const App = {
setup() {
const state = Vue.reactive({
number: '',
deliveryDate: new Date(),
referenceNumber: '',
pdfTransactionList: [],
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
customer: {
name: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
emailAddress: '',
phoneNumber: ''
},
customerAddress: '',
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/DeliveryOrder/GetDeliveryOrderSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || state.pdfData;
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.customer = pdfData.salesOrder?.customer;
state.customerAddress = [
state.customer.street,
state.customer.city,
state.customer.state,
state.customer.zipCode,
state.customer.country
].filter(Boolean).join(', ');
state.number = pdfData?.number;
state.deliveryDate = DateFormatManager.formatToLocale(state.deliveryDate);
state.referenceNumber = pdfData?.salesOrder?.number;
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
warehouse: item.warehouse?.name || 'Unknown',
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim() || 'Unknown Product',
movement: item.movement || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.movement || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`delivery-order-${state.pdfData.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['DeliveryOrders']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,128 @@
@page
@attribute [Authorize(Roles = "GoodsReceives")]
@{
ViewData["Title"] = "Goods Receive List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="ReceiveDate">Receive Date</label>
<input ref="receiveDateRef">
<label class="text-danger">{{ state.errors.receiveDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="PurchaseOrderId">Purchase Order</label>
<div ref="purchaseOrderIdRef"></div>
<label class="text-danger">{{ state.errors.purchaseOrderId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Receive Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/GoodsReceives/GoodsReceiveList.cshtml.js"></script>
}
@@ -0,0 +1,871 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
purchaseOrderListLookupData: [],
goodsReceiveStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
warehouseListLookupData: [],
mainTitle: null,
id: '',
number: '',
receiveDate: '',
description: '',
purchaseOrderId: null,
status: null,
errors: {
receiveDate: '',
purchaseOrderId: '',
status: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const receiveDateRef = Vue.ref(null);
const purchaseOrderIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.receiveDate = '';
state.errors.purchaseOrderId = '';
state.errors.status = '';
let isValid = true;
if (!state.receiveDate) {
state.errors.receiveDate = 'Receive date is required.';
isValid = false;
}
if (!state.purchaseOrderId) {
state.errors.purchaseOrderId = 'Purchase Order is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.receiveDate = '';
state.description = '';
state.purchaseOrderId = null;
state.status = null;
state.errors = {
receiveDate: '',
purchaseOrderId: '',
status: '',
description: ''
};
state.secondaryData = [];
};
const receiveDatePicker = {
obj: null,
create: () => {
receiveDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.receiveDate ? new Date(state.receiveDate) : null,
change: (e) => {
state.receiveDate = e.value;
}
});
receiveDatePicker.obj.appendTo(receiveDateRef.value);
},
refresh: () => {
if (receiveDatePicker.obj) {
receiveDatePicker.obj.value = state.receiveDate ? new Date(state.receiveDate) : null;
}
}
};
Vue.watch(
() => state.receiveDate,
(newVal, oldVal) => {
receiveDatePicker.refresh();
state.errors.receiveDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const purchaseOrderListLookup = {
obj: null,
create: () => {
if (state.purchaseOrderListLookupData && Array.isArray(state.purchaseOrderListLookupData)) {
purchaseOrderListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.purchaseOrderListLookupData,
fields: { value: 'id', text: 'number' },
placeholder: 'Select Purchase Order',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('number', 'startsWith', e.text, true);
}
e.updateData(state.purchaseOrderListLookupData, query);
},
change: (e) => {
state.purchaseOrderId = e.value;
}
});
purchaseOrderListLookup.obj.appendTo(purchaseOrderIdRef.value);
}
},
refresh: () => {
if (purchaseOrderListLookup.obj) {
purchaseOrderListLookup.obj.value = state.purchaseOrderId
}
},
};
Vue.watch(
() => state.purchaseOrderId,
(newVal, oldVal) => {
purchaseOrderListLookup.refresh();
state.errors.purchaseOrderId = '';
}
);
const goodsReceiveStatusListLookup = {
obj: null,
create: () => {
if (state.goodsReceiveStatusListLookupData && Array.isArray(state.goodsReceiveStatusListLookupData)) {
goodsReceiveStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.goodsReceiveStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
goodsReceiveStatusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (goodsReceiveStatusListLookup.obj) {
goodsReceiveStatusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
goodsReceiveStatusListLookup.refresh();
state.errors.status = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/GoodsReceive/GetGoodsReceiveList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (receiveDate, description, status, purchaseOrderId, createdById) => {
try {
const response = await AxiosManager.post('/GoodsReceive/CreateGoodsReceive', {
receiveDate, description, status, purchaseOrderId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, receiveDate, description, status, purchaseOrderId, updatedById) => {
try {
const response = await AxiosManager.post('/GoodsReceive/UpdateGoodsReceive', {
id, receiveDate, description, status, purchaseOrderId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/GoodsReceive/DeleteGoodsReceive', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getPurchaseOrderListLookupData: async () => {
try {
const response = await AxiosManager.get('/PurchaseOrder/GetPurchaseOrderList', {});
return response;
} catch (error) {
throw error;
}
},
getGoodsReceiveStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/GoodsReceive/GetGoodsReceiveStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/GoodsReceiveGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, warehouseId, productId, movement, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/GoodsReceiveCreateInvenTrans', {
moduleId, warehouseId, productId, movement, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, warehouseId, productId, movement, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/GoodsReceiveUpdateInvenTrans', {
id, warehouseId, productId, movement, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/GoodsReceiveDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
receiveDate: new Date(item.receiveDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populatePurchaseOrderListLookupData: async () => {
const response = await services.getPurchaseOrderListLookupData();
state.purchaseOrderListLookupData = response?.data?.content?.data;
},
populateGoodsReceiveStatusListLookupData: async () => {
const response = await services.getGoodsReceiveStatusListLookupData();
state.goodsReceiveStatusListLookupData = response?.data?.content?.data;
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateSecondaryData: async (goodsReceiveId) => {
try {
const response = await services.getSecondaryData(goodsReceiveId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.movement ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
onMainModalHidden: () => {
state.errors.receiveDate = '';
state.errors.purchaseOrderId = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.receiveDate, state.description, state.status, state.purchaseOrderId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.receiveDate, state.description, state.status, state.purchaseOrderId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Goods Receive';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['GoodsReceives']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populatePurchaseOrderListLookupData();
await methods.populateGoodsReceiveStatusListLookupData();
numberText.create();
receiveDatePicker.create();
purchaseOrderListLookup.create();
goodsReceiveStatusListLookup.create();
await secondaryGrid.create(state.secondaryData);
await methods.populateProductListLookupData();
await methods.populateWarehouseListLookupData();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'receiveDate', headerText: 'Receive Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'purchaseOrderNumber', headerText: 'Purchase Order', width: 150, minWidth: 150 },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'receiveDate', 'purchaseOrderNumber', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Goods Receive';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Goods Receive';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.receiveDate = selectedRecord.receiveDate ? new Date(selectedRecord.receiveDate) : null;
state.description = selectedRecord.description ?? '';
state.purchaseOrderId = selectedRecord.purchaseOrderId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Goods Receive?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.receiveDate = selectedRecord.receiveDate ? new Date(selectedRecord.receiveDate) : null;
state.description = selectedRecord.description ?? '';
state.purchaseOrderId = selectedRecord.purchaseOrderId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/GoodsReceives/GoodsReceivePdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'warehouseName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'warehouseId',
headerText: 'Warehouse',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const warehouse = state.warehouseListLookupData.find(item => item.id === data[field]);
return warehouse ? `${warehouse.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const warehouseElem = document.createElement('input');
return warehouseElem;
},
read: () => {
return warehouseObj.value;
},
destroy: function () {
warehouseObj.destroy();
},
write: function (args) {
warehouseObj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.warehouseId,
placeholder: 'Select a Warehouse',
floatLabelType: 'Never'
});
warehouseObj.appendTo(args.element);
}
}
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'numberName' },
value: args.rowData.productId,
change: function (e) {
if (movementObj) {
movementObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'movement',
headerText: 'Movement',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number',
format: 'N2', textAlign: 'Right',
edit: {
create: () => {
const movementElem = document.createElement('input');
return movementElem;
},
read: () => {
return movementObj.value;
},
destroy: function () {
movementObj.destroy();
},
write: function (args) {
movementObj = new ej.inputs.NumericTextBox({
value: args.rowData.movement ?? 0,
});
movementObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
numberRef,
receiveDateRef,
purchaseOrderIdRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,234 @@
@page
@attribute [Authorize(Roles = "GoodsReceives")]
@{
ViewData["Title"] = "Goods Receive PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Goods Receive</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Vendor Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.vendor.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.vendorAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.vendor.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.vendor.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Receive Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.date }}</td>
</tr>
<tr>
<td><strong>Reference:</strong></td>
<td>{{ state.reference }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Warehouse</th>
<th>Product</th>
<th>Movement</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product + item.warehouse">
<td>{{ item.warehouse }}</td>
<td>{{ item.product }}</td>
<td>{{ item.movement }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Movement:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/GoodsReceives/GoodsReceivePdf.cshtml.js"></script>
}
@@ -0,0 +1,150 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
vendor: {
name: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
emailAddress: '',
phoneNumber: ''
},
vendorAddress: '',
number: '',
date: '',
reference: '',
pdfTransactionList: [],
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/GoodsReceive/GetGoodsReceiveSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || {};
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.vendor = pdfData.purchaseOrder?.vendor || {};
state.vendorAddress = [
state.vendor.street,
state.vendor.city,
state.vendor.state,
state.vendor.zipCode,
state.vendor.country
].filter(Boolean).join(', ');
state.number = pdfData?.number || '';
state.date = DateFormatManager.formatToLocale(pdfData?.receiveDate) || '';
state.reference = pdfData?.purchaseOrder?.number || '';
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
warehouse: item.warehouse?.name || '',
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim(),
movement: item.movement || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.movement || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`goods-receive-${state.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['GoodsReceives']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,13 @@
@page
@{
Layout = "~/FrontEnd/Pages/Shared/_Layout.cshtml";
ViewData["Title"] = "Home page";
}
<div class="lock-overlay">
<h1 class="lock-welcome">INDOTALENT WHMS</h1>
<a asp-area="" asp-page="/Accounts/Login" class="lock-login">
<i class="fas fa-lock lock-icon"></i>
</a>
</div>
@@ -0,0 +1,19 @@
@page
@attribute [Authorize(Roles = "MovementReports")]
@{
ViewData["Title"] = "Movement Report List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/MovementReports/MovementReportList.cshtml.js"></script>
}
@@ -0,0 +1,91 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: []
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/InventoryTransaction/GetInventoryTransactionList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc),
movementDate: new Date(item.movementDate)
}));
},
onMainModalHidden: () => {
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['MovementReports']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.pivotview.PivotView({
height: '240px',
width: '100%',
dataSourceSettings: {
dataSource: dataSource,
expandAll: true,
filters: [],
columns: [
{ name: 'moduleCode' },
],
rows: [
{ name: 'productName' },
{ name: 'warehouseName' }
],
values: [
{ name: 'stock' }
],
},
showToolbar: true,
showFieldList: false,
displayOption: { view: "Table" },
showGroupingBar: false,
showValuesButton: true,
groupingBarSettings: { showFieldsPanel: true },
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
return {
mainGridRef,
state,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,125 @@
@page
@attribute [Authorize(Roles = "NegativeAdjustments")]
@{
ViewData["Title"] = "Negative Adjustment List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="AdjustmentDate">Adjustment Date</label>
<input ref="adjustmentDateRef">
<label class="text-danger">{{ state.errors.adjustmentDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
<div class="col-md-6">
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Delivery Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/NegativeAdjustments/NegativeAdjustmentList.cshtml.js"></script>
}
@@ -0,0 +1,799 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
negativeAdjustmentStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
warehouseListLookupData: [],
mainTitle: null,
id: '',
number: '',
adjustmentDate: '',
description: '',
status: null,
errors: {
adjustmentDate: '',
status: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const adjustmentDateRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.adjustmentDate = '';
state.errors.status = '';
let isValid = true;
if (!state.adjustmentDate) {
state.errors.adjustmentDate = 'Adjustment date is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.adjustmentDate = '';
state.description = '';
state.status = null;
state.errors = {
adjustmentDate: '',
status: '',
description: ''
};
state.secondaryData = [];
};
const adjustmentDatePicker = {
obj: null,
create: () => {
adjustmentDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.adjustmentDate ? new Date(state.adjustmentDate) : null,
change: (e) => {
state.adjustmentDate = e.value;
}
});
adjustmentDatePicker.obj.appendTo(adjustmentDateRef.value);
},
refresh: () => {
if (adjustmentDatePicker.obj) {
adjustmentDatePicker.obj.value = state.adjustmentDate ? new Date(state.adjustmentDate) : null;
}
}
};
Vue.watch(
() => state.adjustmentDate,
(newVal, oldVal) => {
adjustmentDatePicker.refresh();
state.errors.adjustmentDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const negativeAdjustmentStatusListLookup = {
obj: null,
create: () => {
if (state.negativeAdjustmentStatusListLookupData && Array.isArray(state.negativeAdjustmentStatusListLookupData)) {
negativeAdjustmentStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.negativeAdjustmentStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
negativeAdjustmentStatusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (negativeAdjustmentStatusListLookup.obj) {
negativeAdjustmentStatusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
negativeAdjustmentStatusListLookup.refresh();
state.errors.status = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/NegativeAdjustment/GetNegativeAdjustmentList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (adjustmentDate, description, status, createdById) => {
try {
const response = await AxiosManager.post('/NegativeAdjustment/CreateNegativeAdjustment', {
adjustmentDate, description, status, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, adjustmentDate, description, status, updatedById) => {
try {
const response = await AxiosManager.post('/NegativeAdjustment/UpdateNegativeAdjustment', {
id, adjustmentDate, description, status, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/NegativeAdjustment/DeleteNegativeAdjustment', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getNegativeAdjustmentStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/NegativeAdjustment/GetNegativeAdjustmentStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/NegativeAdjustmentGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, warehouseId, productId, movement, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/NegativeAdjustmentCreateInvenTrans', {
moduleId, warehouseId, productId, movement, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, warehouseId, productId, movement, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/NegativeAdjustmentUpdateInvenTrans', {
id, warehouseId, productId, movement, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/NegativeAdjustmentDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
adjustmentDate: new Date(item.adjustmentDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateNegativeAdjustmentStatusListLookupData: async () => {
const response = await services.getNegativeAdjustmentStatusListLookupData();
state.negativeAdjustmentStatusListLookupData = response?.data?.content?.data;
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateSecondaryData: async (negativeAdjustmentId) => {
try {
const response = await services.getSecondaryData(negativeAdjustmentId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.movement ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
onMainModalHidden: () => {
state.errors.adjustmentDate = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.adjustmentDate, state.description, state.status, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.adjustmentDate, state.description, state.status, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Negative Adjustment';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['NegativeAdjustments']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateNegativeAdjustmentStatusListLookupData();
numberText.create();
adjustmentDatePicker.create();
negativeAdjustmentStatusListLookup.create();
await secondaryGrid.create(state.secondaryData);
await methods.populateProductListLookupData();
await methods.populateWarehouseListLookupData();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'adjustmentDate', headerText: 'Adjustment Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'adjustmentDate', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Negative Adjustment';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Negative Adjustment';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.adjustmentDate = selectedRecord.adjustmentDate ? new Date(selectedRecord.adjustmentDate) : null;
state.description = selectedRecord.description ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Negative Adjustment?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.adjustmentDate = selectedRecord.adjustmentDate ? new Date(selectedRecord.adjustmentDate) : null;
state.description = selectedRecord.description ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/NegativeAdjustments/NegativeAdjustmentPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'warehouseName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'warehouseId',
headerText: 'Warehouse',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const warehouse = state.warehouseListLookupData.find(item => item.id === data[field]);
return warehouse ? `${warehouse.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const warehouseElem = document.createElement('input');
return warehouseElem;
},
read: () => {
return warehouseObj.value;
},
destroy: function () {
warehouseObj.destroy();
},
write: function (args) {
warehouseObj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.warehouseId,
placeholder: 'Select a Warehouse',
floatLabelType: 'Never'
});
warehouseObj.appendTo(args.element);
}
}
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'numberName' },
value: args.rowData.productId,
change: function (e) {
if (movementObj) {
movementObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'movement',
headerText: 'Movement',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
const movementElem = document.createElement('input');
return movementElem;
},
read: () => {
return movementObj.value;
},
destroy: function () {
movementObj.destroy();
},
write: function (args) {
movementObj = new ej.inputs.NumericTextBox({
value: args.rowData.movement ?? 0,
});
movementObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
numberRef,
adjustmentDateRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,204 @@
@page
@attribute [Authorize(Roles = "NegativeAdjustments")]
@{
ViewData["Title"] = "Negative Adjustment PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Negative Adjustment</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Adjustment Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.date }}</td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Warehouse</th>
<th>Product</th>
<th>Movement</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product + item.warehouse">
<td>{{ item.warehouse }}</td>
<td>{{ item.product }}</td>
<td>{{ item.movement }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Movement:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/NegativeAdjustments/NegativeAdjustmentPdf.cshtml.js"></script>
}
@@ -0,0 +1,128 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
number: '',
date: '',
pdfTransactionList: [],
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/NegativeAdjustment/GetNegativeAdjustmentSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || {};
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.number = pdfData?.number || '';
state.date = DateFormatManager.formatToLocale(pdfData?.adjustmentDate) || '';
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
warehouse: item.warehouse?.name || '',
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim(),
movement: item.movement || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.movement || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`negative-adjustment-${state.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['NegativeAdjustments']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,19 @@
@page
@attribute [Authorize(Roles = "NumberSequences")]
@{
ViewData["Title"] = "Number Sequence List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/NumberSequences/NumberSequenceList.cshtml.js"></script>
}
@@ -0,0 +1,114 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/NumberSequence/GetNumberSequenceList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
const formattedData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
state.mainData = formattedData;
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'entityName', headerText: 'Entity Name', width: 200, minWidth: 200 },
{ field: 'prefix', headerText: 'Prefix', width: 100, minWidth: 100 },
{ field: 'suffix', headerText: 'Suffix', width: 100, minWidth: 100 },
{ field: 'lastUsedCount', headerText: 'Last Used Count', width: 100, minWidth: 100 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['entityName', 'prefix', 'suffix', 'lastUsedCount', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => { },
rowDeselected: () => { },
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['NumberSequences']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
mainGridRef
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,125 @@
@page
@attribute [Authorize(Roles = "PositiveAdjustments")]
@{
ViewData["Title"] = "Positive Adjustment List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="AdjustmentDate">Adjustment Date</label>
<input ref="adjustmentDateRef">
<label class="text-danger">{{ state.errors.adjustmentDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
<div class="col-md-6">
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Delivery Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/PositiveAdjustments/PositiveAdjustmentList.cshtml.js"></script>
}
@@ -0,0 +1,799 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
positiveAdjustmentStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
warehouseListLookupData: [],
mainTitle: null,
id: '',
number: '',
adjustmentDate: '',
description: '',
status: null,
errors: {
adjustmentDate: '',
status: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const adjustmentDateRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.adjustmentDate = '';
state.errors.status = '';
let isValid = true;
if (!state.adjustmentDate) {
state.errors.adjustmentDate = 'Adjustment date is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.adjustmentDate = '';
state.description = '';
state.status = null;
state.errors = {
adjustmentDate: '',
status: '',
description: ''
};
state.secondaryData = [];
};
const adjustmentDatePicker = {
obj: null,
create: () => {
adjustmentDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.adjustmentDate ? new Date(state.adjustmentDate) : null,
change: (e) => {
state.adjustmentDate = e.value;
}
});
adjustmentDatePicker.obj.appendTo(adjustmentDateRef.value);
},
refresh: () => {
if (adjustmentDatePicker.obj) {
adjustmentDatePicker.obj.value = state.adjustmentDate ? new Date(state.adjustmentDate) : null;
}
}
};
Vue.watch(
() => state.adjustmentDate,
(newVal, oldVal) => {
adjustmentDatePicker.refresh();
state.errors.adjustmentDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const positiveAdjustmentStatusListLookup = {
obj: null,
create: () => {
if (state.positiveAdjustmentStatusListLookupData && Array.isArray(state.positiveAdjustmentStatusListLookupData)) {
positiveAdjustmentStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.positiveAdjustmentStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
positiveAdjustmentStatusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (positiveAdjustmentStatusListLookup.obj) {
positiveAdjustmentStatusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
positiveAdjustmentStatusListLookup.refresh();
state.errors.status = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/PositiveAdjustment/GetPositiveAdjustmentList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (adjustmentDate, description, status, createdById) => {
try {
const response = await AxiosManager.post('/PositiveAdjustment/CreatePositiveAdjustment', {
adjustmentDate, description, status, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, adjustmentDate, description, status, updatedById) => {
try {
const response = await AxiosManager.post('/PositiveAdjustment/UpdatePositiveAdjustment', {
id, adjustmentDate, description, status, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/PositiveAdjustment/DeletePositiveAdjustment', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getPositiveAdjustmentStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/PositiveAdjustment/GetPositiveAdjustmentStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/PositiveAdjustmentGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, warehouseId, productId, movement, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/PositiveAdjustmentCreateInvenTrans', {
moduleId, warehouseId, productId, movement, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, warehouseId, productId, movement, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/PositiveAdjustmentUpdateInvenTrans', {
id, warehouseId, productId, movement, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/PositiveAdjustmentDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
adjustmentDate: new Date(item.adjustmentDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populatePositiveAdjustmentStatusListLookupData: async () => {
const response = await services.getPositiveAdjustmentStatusListLookupData();
state.positiveAdjustmentStatusListLookupData = response?.data?.content?.data;
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateSecondaryData: async (positiveAdjustmentId) => {
try {
const response = await services.getSecondaryData(positiveAdjustmentId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.movement ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
onMainModalHidden: () => {
state.errors.adjustmentDate = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.adjustmentDate, state.description, state.status, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.adjustmentDate, state.description, state.status, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Positive Adjustment';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PositiveAdjustments']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populatePositiveAdjustmentStatusListLookupData();
numberText.create();
adjustmentDatePicker.create();
positiveAdjustmentStatusListLookup.create();
await secondaryGrid.create(state.secondaryData);
await methods.populateProductListLookupData();
await methods.populateWarehouseListLookupData();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'adjustmentDate', headerText: 'Adjustment Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'adjustmentDate', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Positive Adjustment';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Positive Adjustment';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.adjustmentDate = selectedRecord.adjustmentDate ? new Date(selectedRecord.adjustmentDate) : null;
state.description = selectedRecord.description ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Positive Adjustment?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.adjustmentDate = selectedRecord.adjustmentDate ? new Date(selectedRecord.adjustmentDate) : null;
state.description = selectedRecord.description ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/PositiveAdjustments/PositiveAdjustmentPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'warehouseName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'warehouseId',
headerText: 'Warehouse',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const warehouse = state.warehouseListLookupData.find(item => item.id === data[field]);
return warehouse ? `${warehouse.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const warehouseElem = document.createElement('input');
return warehouseElem;
},
read: () => {
return warehouseObj.value;
},
destroy: function () {
warehouseObj.destroy();
},
write: function (args) {
warehouseObj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.warehouseId,
placeholder: 'Select a Warehouse',
floatLabelType: 'Never'
});
warehouseObj.appendTo(args.element);
}
}
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'numberName' },
value: args.rowData.productId,
change: function (e) {
if (movementObj) {
movementObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'movement',
headerText: 'Movement',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
const movementElem = document.createElement('input');
return movementElem;
},
read: () => {
return movementObj.value;
},
destroy: function () {
movementObj.destroy();
},
write: function (args) {
movementObj = new ej.inputs.NumericTextBox({
value: args.rowData.movement ?? 0,
});
movementObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
numberRef,
adjustmentDateRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,204 @@
@page
@attribute [Authorize(Roles = "PositiveAdjustments")]
@{
ViewData["Title"] = "Positive Adjustment PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Positive Adjustment</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Adjustment Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.date }}</td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Warehouse</th>
<th>Product</th>
<th>Movement</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product + item.warehouse">
<td>{{ item.warehouse }}</td>
<td>{{ item.product }}</td>
<td>{{ item.movement }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Movement:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/PositiveAdjustments/PositiveAdjustmentPdf.cshtml.js"></script>
}
@@ -0,0 +1,128 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
number: '',
date: '',
pdfTransactionList: [],
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/PositiveAdjustment/GetPositiveAdjustmentSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || {};
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.number = pdfData?.number || '';
state.date = DateFormatManager.formatToLocale(pdfData?.adjustmentDate) || '';
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
warehouse: item.warehouse?.name || '',
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim(),
movement: item.movement || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.movement || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`positive-adjustment-${state.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PositiveAdjustments']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,72 @@
@page
@attribute [Authorize(Roles = "ProductGroups")]
@{
ViewData["Title"] = "Product Group List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/ProductGroups/ProductGroupList.cshtml.js"></script>
}
@@ -0,0 +1,342 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
description: '',
errors: {
name: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
const validateForm = function () {
state.errors.name = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.description = '';
state.errors = {
name: ''
};
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/ProductGroup/GetProductGroupList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, description, createdById) => {
try {
const response = await AxiosManager.post('/ProductGroup/CreateProductGroup', {
name, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, description, updatedById) => {
try {
const response = await AxiosManager.post('/ProductGroup/UpdateProductGroup', {
id, name, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/ProductGroup/DeleteProductGroup', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Product Group';
state.id = response?.data?.content?.data.id ?? '';
state.name = response?.data?.content?.data.name ?? '';
state.description = response?.data?.content?.data.description ?? '';
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['ProductGroups']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', () => {
resetFormState();
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', resetFormState);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Product Group';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Product Group';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Product Group?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
nameRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,101 @@
@page
@attribute [Authorize(Roles = "Products")]
@{
ViewData["Title"] = "Product List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="UnitPrice">Unit Price</label>
<input ref="unitPriceRef" v-model="state.unitPrice">
<label class="text-danger">{{ state.errors.unitPrice }}</label>
</div>
<div class="col-md-6">
<label for="UnitMeasureId">Unit Measure</label>
<div ref="unitMeasureIdRef"></div>
<label class="text-danger">{{ state.errors.unitMeasureId }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="ProductGroupId">Product Group</label>
<div ref="productGroupIdRef"></div>
<label class="text-danger">{{ state.errors.productGroupId }}</label>
</div>
<div class="col-md-6">
<div class="form-check mt-4">
<input v-model="state.physical" id="Physical" name="Physical" type="checkbox" class="form-check-input">
<label for="Physical" class="form-check-label">Is Physical Product?</label>
</div>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Products/ProductList.cshtml.js"></script>
}
@@ -0,0 +1,555 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
productGroupListLookupData: [],
unitMeasureListLookupData: [],
mainTitle: null,
id: '',
name: '',
number: '',
unitPrice: '',
description: '',
productGroupId: null,
unitMeasureId: null,
physical: false,
errors: {
name: '',
unitPrice: '',
productGroupId: '',
unitMeasureId: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const productGroupIdRef = Vue.ref(null);
const unitMeasureIdRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const unitPriceRef = Vue.ref(null);
const validateForm = function () {
state.errors.name = '';
state.errors.unitPrice = '';
state.errors.productGroupId = '';
state.errors.unitMeasureId = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!state.unitPrice) {
state.errors.unitPrice = 'Unit price is required.';
isValid = false;
} else if (!/^\d+(\.\d{1,2})?$/.test(state.unitPrice)) {
state.errors.unitPrice = 'Unit price must be a numeric value with up to two decimal places.';
isValid = false;
}
if (!state.productGroupId) {
state.errors.productGroupId = 'ProductGroup is required.';
isValid = false;
}
if (!state.unitMeasureId) {
state.errors.unitMeasureId = 'UnitMeasure is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.number = '';
state.unitPrice = '';
state.description = '';
state.productGroupId = null;
state.unitMeasureId = null;
state.physical = false;
state.errors = {
name: '',
unitPrice: '',
productGroupId: '',
unitMeasureId: ''
};
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, unitPrice, physical, description, productGroupId, unitMeasureId, createdById) => {
try {
const response = await AxiosManager.post('/Product/CreateProduct', {
name, unitPrice, physical, description, productGroupId, unitMeasureId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, unitPrice, physical, description, productGroupId, unitMeasureId, updatedById) => {
try {
const response = await AxiosManager.post('/Product/UpdateProduct', {
id, name, unitPrice, physical, description, productGroupId, unitMeasureId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Product/DeleteProduct', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductGroupListLookupData: async () => {
try {
const response = await AxiosManager.get('/ProductGroup/GetProductGroupList', {});
return response;
} catch (error) {
throw error;
}
},
getUnitMeasureListLookupData: async () => {
try {
const response = await AxiosManager.get('/UnitMeasure/GetUnitMeasureList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateProductGroupListLookupData: async () => {
const response = await services.getProductGroupListLookupData();
state.productGroupListLookupData = response?.data?.content?.data;
},
populateUnitMeasureListLookupData: async () => {
const response = await services.getUnitMeasureListLookupData();
state.unitMeasureListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const productGroupListLookup = {
obj: null,
create: () => {
if (state.productGroupListLookupData && Array.isArray(state.productGroupListLookupData)) {
productGroupListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.productGroupListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Product Group',
popupHeight: '200px',
change: (e) => {
state.productGroupId = e.value;
}
});
productGroupListLookup.obj.appendTo(productGroupIdRef.value);
} else {
console.error('ProductGroup list lookup data is not available or invalid.');
}
},
refresh: () => {
if (productGroupListLookup.obj) {
productGroupListLookup.obj.value = state.productGroupId;
}
},
};
const unitMeasureListLookup = {
obj: null,
create: () => {
if (state.unitMeasureListLookupData && Array.isArray(state.unitMeasureListLookupData)) {
unitMeasureListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.unitMeasureListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Unit Measure',
popupHeight: '200px',
change: (e) => {
state.unitMeasureId = e.value;
}
});
unitMeasureListLookup.obj.appendTo(unitMeasureIdRef.value);
} else {
console.error('UnitMeasure list lookup data is not available or invalid.');
}
},
refresh: () => {
if (unitMeasureListLookup.obj) {
unitMeasureListLookup.obj.value = state.unitMeasureId;
}
},
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
},
refresh: () => {
if (numberText.obj) {
numberText.obj.value = state.number;
}
}
};
const unitPriceNumber = {
obj: null,
create: () => {
unitPriceNumber.obj = new ej.inputs.NumericTextBox({
format: 'n2',
placeholder: 'Enter Unit Price',
min: 0,
step: 0.01,
validateDecimalOnType: true
});
unitPriceNumber.obj.appendTo(unitPriceRef.value);
},
refresh: () => {
if (unitPriceNumber.obj) {
unitPriceNumber.obj.value = state.unitPrice;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.number,
(newVal, oldVal) => {
numberText.refresh();
}
);
Vue.watch(
() => state.unitPrice,
(newVal, oldVal) => {
state.errors.unitPrice = '';
unitPriceNumber.refresh();
}
);
Vue.watch(
() => state.productGroupId,
(newVal, oldVal) => {
state.errors.productGroupId = '';
productGroupListLookup.refresh();
}
);
Vue.watch(
() => state.unitMeasureId,
(newVal, oldVal) => {
state.errors.unitMeasureId = '';
unitMeasureListLookup.refresh();
}
);
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.unitPrice, state.physical, state.description, state.productGroupId, state.unitMeasureId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.unitPrice, state.physical, state.description, state.productGroupId, state.unitMeasureId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Product';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.name = response?.data?.content?.data.name ?? '';
state.unitPrice = response?.data?.content?.data.unitPrice ?? '';
state.description = response?.data?.content?.data.description ?? '';
state.productGroupId = response?.data?.content?.data.productGroupId ?? '';
state.unitMeasureId = response?.data?.content?.data.unitMeasureId ?? '';
state.physical = response?.data?.content?.data.physical ?? false;
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Products']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateProductGroupListLookupData();
productGroupListLookup.create();
await methods.populateUnitMeasureListLookupData();
unitMeasureListLookup.create();
nameText.create();
numberText.create();
unitPriceNumber.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', () => {
resetFormState();
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', resetFormState);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['productGroupName']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 200, minWidth: 200 },
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'productGroupName', headerText: 'Product Group', width: 150, minWidth: 150 },
{ field: 'unitPrice', headerText: 'Unit Price', width: 150, minWidth: 150, format: 'N2' },
{ field: 'unitMeasureName', headerText: 'Unit Measure', width: 150, minWidth: 150 },
{ field: 'physical', headerText: 'Physical Product', width: 200, minWidth: 200, textAlign: 'Center', type: 'boolean', displayAsCheckBox: true },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'name', 'productGroupName', 'unitPrice', 'unitMeasureName', 'physical', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Product';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Product';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.unitPrice = selectedRecord.unitPrice ?? '';
state.description = selectedRecord.description ?? '';
state.productGroupId = selectedRecord.productGroupId ?? '';
state.unitMeasureId = selectedRecord.unitMeasureId ?? '';
state.physical = selectedRecord.physical ?? false;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Product?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.name = selectedRecord.name ?? '';
state.unitPrice = selectedRecord.unitPrice ?? '';
state.description = selectedRecord.description ?? '';
state.productGroupId = selectedRecord.productGroupId ?? '';
state.unitMeasureId = selectedRecord.unitMeasureId ?? '';
state.physical = selectedRecord.physical ?? false;
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
productGroupIdRef,
unitMeasureIdRef,
nameRef,
numberRef,
unitPriceRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,167 @@
@page
@attribute [Authorize(Roles = "Profiles")]
@{
ViewData["Title"] = "My Profile";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.userId" id="UserId" name="UserId" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-0">
<div class="col-md-6">
<label for="FirstName">First Name</label>
<input ref="firstNameRef" v-model="state.firstName" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.firstName }}</label>
</div>
<div class="col-md-6">
<label for="LastName">Last Name</label>
<input ref="lastNameRef" v-model="state.lastName" type="text" class="form-control" placeholder="">
<label class="text-danger">{{ state.errors.lastName }}</label>
</div>
</div>
<div class="row mb-0">
<div class="col-12">
<label for="CompanyName">Company Name</label>
<textarea ref="companyNameRef" v-model="state.companyName" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
<!-- Modal untuk Change Password -->
<div class="modal fade" ref="changePasswordModalRef" id="ChangePasswordModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.changePasswordTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.userId" id="UserId" name="UserId" />
<form id="ChangePasswordForm">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-header bg-primary text-white">
Old Password
</div>
<div class="card-body">
<div class="mb-3">
<label for="OldPassword">Old Password</label>
<input ref="oldPasswordRef" v-model="state.oldPassword" type="password" class="form-control" placeholder="Enter old password">
<label class="text-danger">{{ state.errors.oldPassword }}</label>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header bg-success text-white">
New Password
</div>
<div class="card-body">
<div class="mb-3">
<label for="NewPassword">New Password</label>
<input ref="newPasswordRef" v-model="state.newPassword" type="password" class="form-control" placeholder="Enter new password">
<label class="text-danger">{{ state.errors.newPassword }}</label>
</div>
<div class="mb-3">
<label for="ConfirmNewPassword">Confirm New Password</label>
<input ref="confirmNewPasswordRef" v-model="state.confirmNewPassword" type="password" class="form-control" placeholder="Confirm new password">
<label class="text-danger">{{ state.errors.confirmNewPassword }}</label>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" id="ChangePasswordSaveButton" class="btn btn-primary" v-on:click="handler.handleChangePassword">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">Save</span>
<span v-else>Saving...</span>
</button>
</div>
</div>
</div>
</div>
<!-- Modal untuk Change Avatar -->
<div class="modal fade" ref="changeAvatarModalRef" id="ChangeAvatarModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.changeAvatarTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.userId" id="UserId" name="UserId" />
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Uploader Area</h5>
</div>
<div class="card-body">
<form ref="imageUploadRef" id="ImageUpload" class="dropzone"></form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Profiles/MyProfile.cshtml.js"></script>
}
@@ -0,0 +1,465 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
userId: '',
firstName: '',
lastName: '',
companyName: '',
oldPassword: '',
newPassword: '',
confirmNewPassword: '',
mainTitle: 'Edit MyProfile',
changePasswordTitle: 'Change Password',
changeAvatarTitle: 'Change Avatar',
errors: {
firstName: '',
lastName: '',
oldPassword: '',
newPassword: '',
confirmNewPassword: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const changePasswordModalRef = Vue.ref(null);
const changeAvatarModalRef = Vue.ref(null);
const firstNameRef = Vue.ref(null);
const lastNameRef = Vue.ref(null);
const companyNameRef = Vue.ref(null);
const oldPasswordRef = Vue.ref(null);
const newPasswordRef = Vue.ref(null);
const confirmNewPasswordRef = Vue.ref(null);
const imageUploadRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Security/GetMyProfileList?userId=' + StorageManager.getUserId(), {});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (userId, firstName, lastName, companyName) => {
try {
const response = await AxiosManager.post('/Security/UpdateMyProfile', {
userId, firstName, lastName, companyName
});
return response;
} catch (error) {
throw error;
}
},
updatePasswordData: async (userId, oldPassword, newPassword, confirmNewPassword) => {
try {
const response = await AxiosManager.post('/Security/UpdateMyProfilePassword', {
userId, oldPassword, newPassword, confirmNewPassword
});
return response;
} catch (error) {
throw error;
}
},
uploadImage: async (file) => {
const formData = new FormData();
formData.append('file', file);
try {
const response = await AxiosManager.post('/FileImage/UploadImage', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
return response;
} catch (error) {
throw error;
}
},
updateAvatarData: async (userId, avatar) => {
try {
const response = await AxiosManager.post('/Security/UpdateMyProfileAvatar', {
userId, avatar
});
return response;
} catch (error) {
throw error;
}
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'firstName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'firstName', headerText: 'First Name', width: 200, minWidth: 200 },
{ field: 'lastName', headerText: 'Last Name', width: 200, minWidth: 200 },
{ field: 'companyName', headerText: 'Company Name', width: 400, minWidth: 400 },
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ type: 'Separator' },
{ text: 'Change Password', tooltipText: 'Change Password', id: 'ChangePasswordCustom' },
{ text: 'Change Avatar', tooltipText: 'Change Avatar', id: 'ChangeAvatarCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], false);
mainGrid.obj.autoFitColumns(['firstName', 'lastName', 'companyName']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'ChangePasswordCustom', 'ChangeAvatarCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'EditCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.userId = selectedRecord.id ?? '';
state.firstName = selectedRecord.firstName ?? '';
state.lastName = selectedRecord.lastName ?? '';
state.companyName = selectedRecord.companyName ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'ChangePasswordCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.userId = selectedRecord.id ?? '';
changePasswordModal.obj.show();
}
}
if (args.item.id === 'ChangeAvatarCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.userId = selectedRecord.id ?? '';
changeAvatarModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const handler = {
handleSubmit: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
state.errors.firstName = '';
state.errors.lastName = '';
let isValid = true;
// Validasi firstName
if (!state.firstName) {
state.errors.firstName = 'First Name is required.';
isValid = false;
}
// Validasi lastName
if (!state.lastName) {
state.errors.lastName = 'Last Name is required.';
isValid = false;
}
if (!isValid) {
state.isSubmitting = false;
return;
}
try {
const response = await services.updateMainData(state.userId, state.firstName, state.lastName, state.companyName);
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
handleChangePassword: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
state.errors.oldPassword = '';
state.errors.newPassword = '';
state.errors.confirmNewPassword = '';
let isValid = true;
// old password validation
if (!state.oldPassword) {
state.errors.oldPassword = 'Old Password is required.';
isValid = false;
} else if (state.oldPassword.length < 6) {
state.errors.oldPassword = 'Old Password must be at least 6 characters.';
isValid = false;
}
// new password validation
if (!state.newPassword) {
state.errors.newPassword = 'New Password is required.';
isValid = false;
} else if (state.newPassword.length < 6) {
state.errors.newPassword = 'New Password must be at least 6 characters.';
isValid = false;
}
// confirm new password validation
if (!state.confirmNewPassword) {
state.errors.confirmNewPassword = 'Confirm New Password is required.';
isValid = false;
} else if (state.confirmNewPassword.length < 6) {
state.errors.confirmNewPassword = 'Confirm New Password must be at least 6 characters.';
isValid = false;
}
if (!isValid) {
state.isSubmitting = false;
return;
}
try {
const response = await services.updatePasswordData(state.userId, state.oldPassword, state.newPassword, state.confirmNewPassword);
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
changePasswordModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
handleFileUpload: async (file) => {
try {
const response = await services.uploadImage(file);
if (response.status === 200) {
const imageName = response?.data?.content?.imageName;
await services.updateAvatarData(state.userId, imageName);
StorageManager.saveAvatar(imageName);
Swal.fire({
icon: "success",
title: "Upload Successful",
text: "Your image has been uploaded successfully!",
text: 'Page will be refreshed...',
timer: 1000,
showConfirmButton: false
});
setTimeout(() => {
changeAvatarModal.obj.hide();
location.reload();
}, 1000);
} else {
Swal.fire({
icon: "error",
title: "Upload Failed",
text: response.message ?? "An error occurred during upload."
});
}
} catch (error) {
Swal.fire({
icon: "error",
title: "Upload Failed",
text: "An unexpected error occurred."
});
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data;
},
};
Vue.onMounted(async () => {
Dropzone.autoDiscover = false;
try {
await SecurityManager.authorizePage(['Profiles']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
changePasswordModal.create();
changeAvatarModal.create();
initDropzone();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
let dropzoneInitialized = false;
const initDropzone = () => {
if (!dropzoneInitialized && imageUploadRef.value) {
dropzoneInitialized = true;
const dropzoneInstance = new Dropzone(imageUploadRef.value, {
url: "api/FileImage/UploadImage",
paramName: "file",
maxFilesize: 5,
acceptedFiles: "image/*",
addRemoveLinks: true,
dictDefaultMessage: "Drag and drop an image here to upload",
autoProcessQueue: false,
init: function () {
this.on("addedfile", async function (file) {
await handler.handleFileUpload(file);
});
}
});
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const changePasswordModal = {
obj: null,
create: () => {
changePasswordModal.obj = new bootstrap.Modal(changePasswordModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const changeAvatarModal = {
obj: null,
create: () => {
changeAvatarModal.obj = new bootstrap.Modal(changeAvatarModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
state,
mainGridRef,
mainModalRef,
changePasswordModalRef,
changeAvatarModalRef,
firstNameRef,
lastNameRef,
companyNameRef,
oldPasswordRef,
newPasswordRef,
confirmNewPasswordRef,
imageUploadRef,
handler
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,143 @@
@page
@attribute [Authorize(Roles = "PurchaseOrders")]
@{
ViewData["Title"] = "Purchase Order List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderDate">Order Date</label>
<input ref="orderDateRef" />
<label class="text-danger">{{ state.errors.orderDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="VendorId">Vendor</label>
<div ref="vendorIdRef"></div>
<label class="text-danger">{{ state.errors.vendorId }}</label>
</div>
<div class="col-md-6">
<label for="TaxId">Tax</label>
<div ref="taxIdRef"></div>
<label class="text-danger">{{ state.errors.taxId }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderStatus">Order Status</label>
<div ref="orderStatusRef"></div>
<label class="text-danger">{{ state.errors.orderStatus }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Purchase Order Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Payment Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Subtotal</span>
<span id="SubTotalAmount">{{ state.subTotalAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Tax</span>
<span id="TaxAmount">{{ state.taxAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Amount</span>
<span id="TotalAmount" class="fw-bold text-success">{{ state.totalAmount }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseOrders/PurchaseOrderList.cshtml.js"></script>
}
@@ -0,0 +1,988 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
vendorListLookupData: [],
taxListLookupData: [],
purchaseOrderStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
mainTitle: null,
id: '',
number: '',
orderDate: '',
description: '',
vendorId: null,
taxId: null,
orderStatus: null,
errors: {
orderDate: '',
vendorId: '',
taxId: '',
orderStatus: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
subTotalAmount: '0.00',
taxAmount: '0.00',
totalAmount: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const orderDateRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const vendorIdRef = Vue.ref(null);
const taxIdRef = Vue.ref(null);
const orderStatusRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const validateForm = function () {
state.errors.orderDate = '';
state.errors.vendorId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
let isValid = true;
if (!state.orderDate) {
state.errors.orderDate = 'Order date is required.';
isValid = false;
}
if (!state.vendorId) {
state.errors.vendorId = 'Vendor is required.';
isValid = false;
}
if (!state.taxId) {
state.errors.taxId = 'Tax is required.';
isValid = false;
}
if (!state.orderStatus) {
state.errors.orderStatus = 'Order status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.orderDate = '';
state.description = '';
state.vendorId = null;
state.taxId = null;
state.orderStatus = null;
state.errors = {
orderDate: '',
vendorId: '',
taxId: '',
orderStatus: '',
description: ''
};
state.secondaryData = [];
state.subTotalAmount = '0.00';
state.taxAmount = '0.00';
state.totalAmount = '0.00';
state.showComplexDiv = false;
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/PurchaseOrder/GetPurchaseOrderList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (orderDate, description, orderStatus, taxId, vendorId, createdById) => {
try {
const response = await AxiosManager.post('/PurchaseOrder/CreatePurchaseOrder', {
orderDate, description, orderStatus, taxId, vendorId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, orderDate, description, orderStatus, taxId, vendorId, updatedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrder/UpdatePurchaseOrder', {
id, orderDate, description, orderStatus, taxId, vendorId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrder/DeletePurchaseOrder', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getVendorListLookupData: async () => {
try {
const response = await AxiosManager.get('/Vendor/GetVendorList', {});
return response;
} catch (error) {
throw error;
}
},
getTaxListLookupData: async () => {
try {
const response = await AxiosManager.get('/Tax/GetTaxList', {});
return response;
} catch (error) {
throw error;
}
},
getPurchaseOrderStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/PurchaseOrder/GetPurchaseOrderStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (purchaseOrderId) => {
try {
const response = await AxiosManager.get('/PurchaseOrderItem/GetPurchaseOrderItemByPurchaseOrderIdList?purchaseOrderId=' + purchaseOrderId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (unitPrice, quantity, summary, productId, purchaseOrderId, createdById) => {
try {
const response = await AxiosManager.post('/PurchaseOrderItem/CreatePurchaseOrderItem', {
unitPrice, quantity, summary, productId, purchaseOrderId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, unitPrice, quantity, summary, productId, purchaseOrderId, updatedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrderItem/UpdatePurchaseOrderItem', {
id, unitPrice, quantity, summary, productId, purchaseOrderId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/PurchaseOrderItem/DeletePurchaseOrderItem', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
}
};
const methods = {
populateVendorListLookupData: async () => {
const response = await services.getVendorListLookupData();
state.vendorListLookupData = response?.data?.content?.data;
},
populateTaxListLookupData: async () => {
const response = await services.getTaxListLookupData();
state.taxListLookupData = response?.data?.content?.data;
},
populatePurchaseOrderStatusListLookupData: async () => {
const response = await services.getPurchaseOrderStatusListLookupData();
state.purchaseOrderStatusListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
orderDate: new Date(item.orderDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateSecondaryData: async (purchaseOrderId) => {
try {
const response = await services.getSecondaryData(purchaseOrderId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshPaymentSummary(purchaseOrderId);
} catch (error) {
state.secondaryData = [];
}
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data;
},
refreshPaymentSummary: async (id) => {
const record = state.mainData.find(item => item.id === id);
if (record) {
state.subTotalAmount = NumberFormatManager.formatToLocale(record.beforeTaxAmount ?? 0);
state.taxAmount = NumberFormatManager.formatToLocale(record.taxAmount ?? 0);
state.totalAmount = NumberFormatManager.formatToLocale(record.afterTaxAmount ?? 0);
}
},
handleFormSubmit: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
if (!validateForm()) {
state.isSubmitting = false;
return;
}
try {
const response = state.id === ''
? await services.createMainData(state.orderDate, state.description, state.orderStatus, state.taxId, state.vendorId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.orderDate, state.description, state.orderStatus, state.taxId, state.vendorId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Purchase Order';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.orderDate = response?.data?.content?.data.orderDate ? new Date(response.data.content.data.orderDate) : null;
state.description = response?.data?.content?.data.description ?? '';
state.vendorId = response?.data?.content?.data.vendorId ?? '';
state.taxId = response?.data?.content?.data.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(response?.data?.content?.data.orderStatus ?? '');
state.showComplexDiv = true;
await methods.refreshPaymentSummary(state.id);
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 1000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
onMainModalHidden: () => {
state.errors.orderDate = '';
state.errors.vendorId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
taxListLookup.trackingChange = false;
}
};
const vendorListLookup = {
obj: null,
create: () => {
if (state.vendorListLookupData && Array.isArray(state.vendorListLookupData)) {
vendorListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.vendorListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Vendor',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('name', 'startsWith', e.text, true);
}
e.updateData(state.vendorListLookupData, query);
},
change: (e) => {
state.vendorId = e.value;
}
});
vendorListLookup.obj.appendTo(vendorIdRef.value);
}
},
refresh: () => {
if (vendorListLookup.obj) {
vendorListLookup.obj.value = state.vendorId;
}
}
};
const taxListLookup = {
obj: null,
trackingChange: false,
create: () => {
if (state.taxListLookupData && Array.isArray(state.taxListLookupData)) {
taxListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.taxListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Tax',
change: async (e) => {
state.taxId = e.value;
if (e.isInteracted && taxListLookup.trackingChange) {
await methods.handleFormSubmit();
}
}
});
taxListLookup.obj.appendTo(taxIdRef.value);
}
},
refresh: () => {
if (taxListLookup.obj) {
taxListLookup.obj.value = state.taxId;
}
}
};
const purchaseOrderStatusListLookup = {
obj: null,
create: () => {
if (state.purchaseOrderStatusListLookupData && Array.isArray(state.purchaseOrderStatusListLookupData)) {
purchaseOrderStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.purchaseOrderStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select an Order Status',
change: (e) => {
state.orderStatus = e.value;
}
});
purchaseOrderStatusListLookup.obj.appendTo(orderStatusRef.value);
}
},
refresh: () => {
if (purchaseOrderStatusListLookup.obj) {
purchaseOrderStatusListLookup.obj.value = state.orderStatus;
}
}
};
const orderDatePicker = {
obj: null,
create: () => {
orderDatePicker.obj = new ej.calendars.DatePicker({
format: 'yyyy-MM-dd',
value: state.orderDate ? new Date(state.orderDate) : null,
change: (e) => {
state.orderDate = e.value;
}
});
orderDatePicker.obj.appendTo(orderDateRef.value);
},
refresh: () => {
if (orderDatePicker.obj) {
orderDatePicker.obj.value = state.orderDate ? new Date(state.orderDate) : null;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
}
};
Vue.watch(
() => state.orderDate,
(newVal, oldVal) => {
orderDatePicker.refresh();
state.errors.orderDate = '';
}
);
Vue.watch(
() => state.vendorId,
(newVal, oldVal) => {
vendorListLookup.refresh();
state.errors.vendorId = '';
}
);
Vue.watch(
() => state.taxId,
(newVal, oldVal) => {
taxListLookup.refresh();
state.errors.taxId = '';
}
);
Vue.watch(
() => state.orderStatus,
(newVal, oldVal) => {
purchaseOrderStatusListLookup.refresh();
state.errors.orderStatus = '';
}
);
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: { columns: ['vendorName'] },
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'orderDate', headerText: 'PO Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'vendorName', headerText: 'Vendor', width: 200, minWidth: 200 },
{ field: 'orderStatusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'taxName', headerText: 'Tax', width: 150, minWidth: 150 },
{ field: 'afterTaxAmount', headerText: 'Total Amount', width: 150, minWidth: 150, format: 'N2' },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'orderDate', 'vendorName', 'orderStatusName', 'taxName', 'afterTaxAmount', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Purchase Order';
resetFormState();
state.secondaryData = [];
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Purchase Order';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.vendorId = selectedRecord.vendorId ?? '';
state.taxId = selectedRecord.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = true;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Purchase Order?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.vendorId = selectedRecord.vendorId ?? '';
state.taxId = selectedRecord.taxId ?? '';
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = false;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/PurchaseOrders/PurchaseOrderPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'productName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
let productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: () => {
productObj.destroy();
},
write: (args) => {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.productId,
change: (e) => {
const selectedProduct = state.productListLookupData.find(item => item.id === e.value);
if (selectedProduct) {
args.rowData.productId = selectedProduct.id;
if (numberObj) {
numberObj.value = selectedProduct.number;
}
if (priceObj) {
priceObj.value = selectedProduct.unitPrice;
}
if (summaryObj) {
summaryObj.value = selectedProduct.description;
}
if (quantityObj) {
quantityObj.value = 1;
const total = selectedProduct.unitPrice * quantityObj.value;
if (totalObj) {
totalObj.value = total;
}
}
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'unitPrice',
headerText: 'Unit Price',
width: 200, validationRules: { required: true }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let priceElem = document.createElement('input');
return priceElem;
},
read: () => {
return priceObj.value;
},
destroy: () => {
priceObj.destroy();
},
write: (args) => {
priceObj = new ej.inputs.NumericTextBox({
value: args.rowData.unitPrice ?? 0,
change: (e) => {
if (quantityObj && totalObj) {
const total = e.value * quantityObj.value;
totalObj.value = total;
}
}
});
priceObj.appendTo(args.element);
}
}
},
{
field: 'quantity',
headerText: 'Quantity',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let quantityElem = document.createElement('input');
return quantityElem;
},
read: () => {
return quantityObj.value;
},
destroy: () => {
quantityObj.destroy();
},
write: (args) => {
quantityObj = new ej.inputs.NumericTextBox({
value: args.rowData.quantity ?? 0,
change: (e) => {
if (priceObj && totalObj) {
const total = e.value * priceObj.value;
totalObj.value = total;
}
}
});
quantityObj.appendTo(args.element);
}
}
},
{
field: 'total',
headerText: 'Total',
width: 200, validationRules: { required: false }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let totalElem = document.createElement('input');
return totalElem;
},
read: () => {
return totalObj.value;
},
destroy: () => {
totalObj.destroy();
},
write: (args) => {
totalObj = new ej.inputs.NumericTextBox({
value: args.rowData.total ?? 0,
readonly: true
});
totalObj.appendTo(args.element);
}
}
},
{
field: 'productNumber',
headerText: 'Product Number',
allowEditing: false,
width: 180,
edit: {
create: () => {
let numberElem = document.createElement('input');
return numberElem;
},
read: () => {
return numberObj.value;
},
destroy: () => {
numberObj.destroy();
},
write: (args) => {
numberObj = new ej.inputs.TextBox();
numberObj.value = args.rowData.productNumber;
numberObj.readonly = true;
numberObj.appendTo(args.element);
}
}
},
{
field: 'summary',
headerText: 'Summary',
width: 200,
edit: {
create: () => {
let summaryElem = document.createElement('input');
return summaryElem;
},
read: () => {
return summaryObj.value;
},
destroy: () => {
summaryObj.destroy();
},
write: (args) => {
summaryObj = new ej.inputs.TextBox();
summaryObj.value = args.rowData.summary;
summaryObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
const purchaseOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.createSecondaryData(data?.unitPrice, data?.quantity, data?.summary, data?.productId, purchaseOrderId, userId);
await methods.populateSecondaryData(purchaseOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'save' && args.action === 'edit') {
const purchaseOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.updateSecondaryData(data?.id, data?.unitPrice, data?.quantity, data?.summary, data?.productId, purchaseOrderId, userId);
await methods.populateSecondaryData(purchaseOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'delete') {
const purchaseOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data[0];
await services.deleteSecondaryData(data?.id, userId);
await methods.populateSecondaryData(purchaseOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
}
await methods.populateMainData();
mainGrid.refresh();
await methods.refreshPaymentSummary(state.id);
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseOrders']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateVendorListLookupData();
vendorListLookup.create();
await methods.populateTaxListLookupData();
taxListLookup.create();
await methods.populatePurchaseOrderStatusListLookupData();
purchaseOrderStatusListLookup.create();
orderDatePicker.create();
numberText.create();
await methods.populateProductListLookupData();
await secondaryGrid.create(state.secondaryData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
return {
mainGridRef,
mainModalRef,
orderDateRef,
numberRef,
vendorIdRef,
taxIdRef,
orderStatusRef,
secondaryGridRef,
state,
methods,
handler: {
handleSubmit: methods.handleFormSubmit
}
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,246 @@
@page
@attribute [Authorize(Roles = "PurchaseOrders")]
@{
ViewData["Title"] = "Purchase Order PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Purchase Order</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Vendor Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.vendor.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.vendorAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.vendor.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.vendor.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Order Information</th>
</tr>
<tr>
<td><strong>Order Number:</strong></td>
<td>{{ state.orderNumber }}</td>
</tr>
<tr>
<td><strong>Order Date:</strong></td>
<td>{{ state.orderDate }}</td>
</tr>
<tr>
<td><strong>Currency:</strong></td>
<td>{{ state.orderCurrency }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Product Number</th>
<th>Product Name</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.items" :key="item.productNumber">
<td>{{ item?.product?.number }}</td>
<td>{{ item?.product?.name }}</td>
<td>{{ item?.unitPrice }}</td>
<td>{{ item?.quantity }}</td>
<td>{{ item?.total }}</td>
</tr>
</tbody>
</table>
<div class="payment-summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold;">Subtotal:</td>
<td style="text-align: right;">{{ state.subTotal }}</td>
</tr>
<tr>
<td style="font-weight: bold;">Tax:</td>
<td style="text-align: right;">{{ state.tax }}</td>
</tr>
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Amount:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.totalAmount }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.payment-summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.payment-summary .column {
width: 48%;
}
.payment-summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseOrders/PurchaseOrderPdf.cshtml.js"></script>
}
@@ -0,0 +1,145 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
vendor: {
name: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
emailAddress: '',
phoneNumber: ''
},
vendorAddress: '',
orderNumber: '',
orderDate: '',
orderCurrency: '',
subTotal: '',
tax: '',
totalAmount: '',
items: [],
isDownloading: false
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/PurchaseOrder/GetPurchaseOrderSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
const pdfData = response?.data?.content?.data || {};
state.items = pdfData.purchaseOrderItemList || [];
state.vendor = pdfData.vendor || {};
state.orderNumber = pdfData.number || '';
state.orderDate = DateFormatManager.formatToLocale(pdfData.orderDate) || '';
state.orderCurrency = StorageManager.getCompany()?.currency || '';
state.subTotal = NumberFormatManager.formatToLocale(pdfData.beforeTaxAmount) || '';
state.tax = NumberFormatManager.formatToLocale(pdfData.taxAmount) || '';
state.totalAmount = NumberFormatManager.formatToLocale(pdfData.afterTaxAmount) || '';
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
state.vendorAddress = [
state.vendor.street,
state.vendor.city,
state.vendor.state,
state.vendor.zipCode,
state.vendor.country
].filter(Boolean).join(', ');
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`purchase-order-${state.orderNumber || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseOrders']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,19 @@
@page
@attribute [Authorize(Roles = "PurchaseReports")]
@{
ViewData["Title"] = "Purchase Report List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseReports/PurchaseReportList.cshtml.js"></script>
}
@@ -0,0 +1,130 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: []
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/PurchaseOrderItem/GetPurchaseOrderItemList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['purchaseOrderNumber']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'purchaseOrderNumber', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'vendorName', headerText: 'Vendor', width: 200, minWidth: 200 },
{ field: 'purchaseOrderNumber', headerText: 'PurchaseOrder', width: 200, minWidth: 200 },
{ field: 'productNumber', headerText: 'Product Number', width: 200, minWidth: 200 },
{ field: 'productName', headerText: 'Product Name', width: 200, minWidth: 200 },
{ field: 'unitPrice', headerText: 'Unit Price', width: 150, minWidth: 150, format: 'N2' },
{ field: 'quantity', headerText: 'Quantity', width: 150, minWidth: 150 },
{ field: 'total', headerText: 'Total', width: 150, minWidth: 150, format: 'N2' },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
aggregates: [
{
columns: [
{
type: 'Sum',
field: 'total',
groupCaptionTemplate: 'Total: ${Sum}',
format: 'N2'
}
]
}
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['vendorName', 'purchaseOrderNumber', 'productNumber', 'productName', 'unitPrice', 'quantity', 'total', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => { },
rowDeselected: () => { },
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseReports']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
state,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,128 @@
@page
@attribute [Authorize(Roles = "PurchaseReturns")]
@{
ViewData["Title"] = "Purchase Return List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="ReturnDate">Return Date</label>
<input ref="returnDateRef">
<label class="text-danger">{{ state.errors.returnDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="GoodsReceiveId">Goods Receive</label>
<div ref="goodsReceiveIdRef"></div>
<label class="text-danger">{{ state.errors.goodsReceiveId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Return Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseReturns/PurchaseReturnList.cshtml.js"></script>
}
@@ -0,0 +1,871 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
goodsReceiveListLookupData: [],
purchaseReturnStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
warehouseListLookupData: [],
mainTitle: null,
id: '',
number: '',
returnDate: '',
description: '',
goodsReceiveId: null,
status: null,
errors: {
returnDate: '',
goodsReceiveId: '',
status: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const returnDateRef = Vue.ref(null);
const goodsReceiveIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.returnDate = '';
state.errors.goodsReceiveId = '';
state.errors.status = '';
let isValid = true;
if (!state.returnDate) {
state.errors.returnDate = 'Return date is required.';
isValid = false;
}
if (!state.goodsReceiveId) {
state.errors.goodsReceiveId = 'Goods Receive is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.returnDate = '';
state.description = '';
state.goodsReceiveId = null;
state.status = null;
state.errors = {
returnDate: '',
goodsReceiveId: '',
status: '',
description: ''
};
state.secondaryData = [];
};
const returnDatePicker = {
obj: null,
create: () => {
returnDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.returnDate ? new Date(state.returnDate) : null,
change: (e) => {
state.returnDate = e.value;
}
});
returnDatePicker.obj.appendTo(returnDateRef.value);
},
refresh: () => {
if (returnDatePicker.obj) {
returnDatePicker.obj.value = state.returnDate ? new Date(state.returnDate) : null;
}
}
};
Vue.watch(
() => state.returnDate,
(newVal, oldVal) => {
returnDatePicker.refresh();
state.errors.returnDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const goodsReceiveListLookup = {
obj: null,
create: () => {
if (state.goodsReceiveListLookupData && Array.isArray(state.goodsReceiveListLookupData)) {
goodsReceiveListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.goodsReceiveListLookupData,
fields: { value: 'id', text: 'number' },
placeholder: 'Select Goods Receive',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('number', 'startsWith', e.text, true);
}
e.updateData(state.goodsReceiveListLookupData, query);
},
change: (e) => {
state.goodsReceiveId = e.value;
}
});
goodsReceiveListLookup.obj.appendTo(goodsReceiveIdRef.value);
}
},
refresh: () => {
if (goodsReceiveListLookup.obj) {
goodsReceiveListLookup.obj.value = state.goodsReceiveId
}
},
};
Vue.watch(
() => state.goodsReceiveId,
(newVal, oldVal) => {
goodsReceiveListLookup.refresh();
state.errors.goodsReceiveId = '';
}
);
const purchaseReturnStatusListLookup = {
obj: null,
create: () => {
if (state.purchaseReturnStatusListLookupData && Array.isArray(state.purchaseReturnStatusListLookupData)) {
purchaseReturnStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.purchaseReturnStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
purchaseReturnStatusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (purchaseReturnStatusListLookup.obj) {
purchaseReturnStatusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
purchaseReturnStatusListLookup.refresh();
state.errors.status = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/PurchaseReturn/GetPurchaseReturnList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (returnDate, description, status, goodsReceiveId, createdById) => {
try {
const response = await AxiosManager.post('/PurchaseReturn/CreatePurchaseReturn', {
returnDate, description, status, goodsReceiveId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, returnDate, description, status, goodsReceiveId, updatedById) => {
try {
const response = await AxiosManager.post('/PurchaseReturn/UpdatePurchaseReturn', {
id, returnDate, description, status, goodsReceiveId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/PurchaseReturn/DeletePurchaseReturn', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getGoodsReceiveListLookupData: async () => {
try {
const response = await AxiosManager.get('/GoodsReceive/GetGoodsReceiveList', {});
return response;
} catch (error) {
throw error;
}
},
getPurchaseReturnStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/PurchaseReturn/GetPurchaseReturnStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/PurchaseReturnGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, warehouseId, productId, movement, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/PurchaseReturnCreateInvenTrans', {
moduleId, warehouseId, productId, movement, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, warehouseId, productId, movement, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/PurchaseReturnUpdateInvenTrans', {
id, warehouseId, productId, movement, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/PurchaseReturnDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
returnDate: new Date(item.returnDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateGoodsReceiveListLookupData: async () => {
const response = await services.getGoodsReceiveListLookupData();
state.goodsReceiveListLookupData = response?.data?.content?.data;
},
populatePurchaseReturnStatusListLookupData: async () => {
const response = await services.getPurchaseReturnStatusListLookupData();
state.purchaseReturnStatusListLookupData = response?.data?.content?.data;
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateSecondaryData: async (purchaseReturnId) => {
try {
const response = await services.getSecondaryData(purchaseReturnId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.movement ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
onMainModalHidden: () => {
state.errors.returnDate = '';
state.errors.goodsReceiveId = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.returnDate, state.description, state.status, state.goodsReceiveId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.returnDate, state.description, state.status, state.goodsReceiveId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Purchase Return';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseReturns']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateGoodsReceiveListLookupData();
await methods.populatePurchaseReturnStatusListLookupData();
numberText.create();
returnDatePicker.create();
goodsReceiveListLookup.create();
purchaseReturnStatusListLookup.create();
await secondaryGrid.create(state.secondaryData);
await methods.populateProductListLookupData();
await methods.populateWarehouseListLookupData();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'returnDate', headerText: 'Return Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'goodsReceiveNumber', headerText: 'Goods Receive', width: 150, minWidth: 150 },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'returnDate', 'goodsReceiveNumber', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Purchase Return';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Purchase Return';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.returnDate = selectedRecord.returnDate ? new Date(selectedRecord.returnDate) : null;
state.description = selectedRecord.description ?? '';
state.goodsReceiveId = selectedRecord.goodsReceiveId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Purchase Return?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.returnDate = selectedRecord.returnDate ? new Date(selectedRecord.returnDate) : null;
state.description = selectedRecord.description ?? '';
state.goodsReceiveId = selectedRecord.goodsReceiveId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/PurchaseReturns/PurchaseReturnPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'warehouseName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible:
false
},
{
field: 'warehouseId',
headerText: 'Warehouse',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const warehouse = state.warehouseListLookupData.find(item => item.id === data[field]);
return warehouse ? `${warehouse.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const warehouseElem = document.createElement('input');
return warehouseElem;
},
read: () => {
return warehouseObj.value;
},
destroy: function () {
warehouseObj.destroy();
},
write: function (args) {
warehouseObj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.warehouseId,
placeholder: 'Select a Warehouse',
floatLabelType: 'Never'
});
warehouseObj.appendTo(args.element);
}
}
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'numberName' },
value: args.rowData.productId,
change: function (e) {
if (movementObj) {
movementObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'movement',
headerText: 'Movement',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
const movementElem = document.createElement('input');
return movementElem;
},
read: () => {
return movementObj.value;
},
destroy: function () {
movementObj.destroy();
},
write: function (args) {
movementObj = new ej.inputs.NumericTextBox({
value: args.rowData.movement ?? 0,
});
movementObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
numberRef,
returnDateRef,
goodsReceiveIdRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,234 @@
@page
@attribute [Authorize(Roles = "PurchaseReturns")]
@{
ViewData["Title"] = "Purchase Return PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Purchase Return</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Vendor Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.vendor.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.vendorAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.vendor.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.vendor.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Return Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.date }}</td>
</tr>
<tr>
<td><strong>Reference:</strong></td>
<td>{{ state.reference }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Warehouse</th>
<th>Product</th>
<th>Movement</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product + item.warehouse">
<td>{{ item.warehouse }}</td>
<td>{{ item.product }}</td>
<td>{{ item.movement }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Movement:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/PurchaseReturns/PurchaseReturnPdf.cshtml.js"></script>
}
@@ -0,0 +1,150 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
vendor: {
name: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
emailAddress: '',
phoneNumber: ''
},
vendorAddress: '',
number: '',
date: '',
reference: '',
pdfTransactionList: [],
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/PurchaseReturn/GetPurchaseReturnSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || {};
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.vendor = pdfData.goodsReceive?.purchaseOrder?.vendor || {};
state.vendorAddress = [
state.vendor.street,
state.vendor.city,
state.vendor.state,
state.vendor.zipCode,
state.vendor.country
].filter(Boolean).join(', ');
state.number = pdfData?.number || '';
state.date = DateFormatManager.formatToLocale(pdfData?.returnDate) || '';
state.reference = pdfData?.goodsReceive?.number || '';
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
warehouse: item.warehouse?.name || '',
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim(),
movement: item.movement || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.movement || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`purchase-return-${state.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['PurchaseReturns']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,19 @@
@page
@attribute [Authorize(Roles = "Roles")]
@{
ViewData["Title"] = "Role List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Roles/RoleList.cshtml.js"></script>
}
@@ -0,0 +1,109 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: []
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Security/GetRoleList', {});
return response;
} catch (error) {
throw error;
}
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'name', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 300, minWidth: 300 },
],
toolbar: [
'ExcelExport', 'Search',
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['name']);
},
excelExportComplete: () => { },
rowSelected: () => { },
rowDeselected: () => { },
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data;
},
init: async () => {
try {
await SecurityManager.authorizePage(['Roles']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
},
};
Vue.onMounted(() => {
methods.init();
});
return {
state,
mainGridRef
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,143 @@
@page
@attribute [Authorize(Roles = "SalesOrders")]
@{
ViewData["Title"] = "Sales Order List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderDate">Order Date</label>
<input ref="orderDateRef" />
<label class="text-danger">{{ state.errors.orderDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="CustomerId">Customer</label>
<div ref="customerIdRef"></div>
<label class="text-danger">{{ state.errors.customerId }}</label>
</div>
<div class="col-md-6">
<label for="TaxId">Tax</label>
<div ref="taxIdRef"></div>
<label class="text-danger">{{ state.errors.taxId }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="OrderStatus">Order Status</label>
<div ref="orderStatusRef"></div>
<label class="text-danger">{{ state.errors.orderStatus }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Sales Order Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Payment Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Subtotal</span>
<span id="SubTotalAmount">{{ state.subTotalAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2 border-bottom">
<span class="fw-bold">Tax</span>
<span id="TaxAmount">{{ state.taxAmount }}</span>
</div>
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Amount</span>
<span id="TotalAmount" class="fw-bold text-success">{{ state.totalAmount }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/SalesOrders/SalesOrderList.cshtml.js"></script>
}
@@ -0,0 +1,988 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
customerListLookupData: [],
taxListLookupData: [],
salesOrderStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
mainTitle: null,
id: '',
number: '',
orderDate: '',
description: '',
customerId: null,
taxId: null,
orderStatus: null,
errors: {
orderDate: '',
customerId: '',
taxId: '',
orderStatus: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
subTotalAmount: '0.00',
taxAmount: '0.00',
totalAmount: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const orderDateRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const customerIdRef = Vue.ref(null);
const taxIdRef = Vue.ref(null);
const orderStatusRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const validateForm = function () {
state.errors.orderDate = '';
state.errors.customerId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
let isValid = true;
if (!state.orderDate) {
state.errors.orderDate = 'Order date is required.';
isValid = false;
}
if (!state.customerId) {
state.errors.customerId = 'Customer is required.';
isValid = false;
}
if (!state.taxId) {
state.errors.taxId = 'Tax is required.';
isValid = false;
}
if (!state.orderStatus) {
state.errors.orderStatus = 'Order status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.orderDate = '';
state.description = '';
state.customerId = null;
state.taxId = null;
state.orderStatus = null;
state.errors = {
orderDate: '',
customerId: '',
taxId: '',
orderStatus: '',
description: ''
};
state.secondaryData = [];
state.subTotalAmount = '0.00';
state.taxAmount = '0.00';
state.totalAmount = '0.00';
state.showComplexDiv = false;
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/SalesOrder/GetSalesOrderList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (orderDate, description, orderStatus, taxId, customerId, createdById) => {
try {
const response = await AxiosManager.post('/SalesOrder/CreateSalesOrder', {
orderDate, description, orderStatus, taxId, customerId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, orderDate, description, orderStatus, taxId, customerId, updatedById) => {
try {
const response = await AxiosManager.post('/SalesOrder/UpdateSalesOrder', {
id, orderDate, description, orderStatus, taxId, customerId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/SalesOrder/DeleteSalesOrder', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getCustomerListLookupData: async () => {
try {
const response = await AxiosManager.get('/Customer/GetCustomerList', {});
return response;
} catch (error) {
throw error;
}
},
getTaxListLookupData: async () => {
try {
const response = await AxiosManager.get('/Tax/GetTaxList', {});
return response;
} catch (error) {
throw error;
}
},
getSalesOrderStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/SalesOrder/GetSalesOrderStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (salesOrderId) => {
try {
const response = await AxiosManager.get('/SalesOrderItem/GetSalesOrderItemBySalesOrderIdList?salesOrderId=' + salesOrderId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (unitPrice, quantity, summary, productId, salesOrderId, createdById) => {
try {
const response = await AxiosManager.post('/SalesOrderItem/CreateSalesOrderItem', {
unitPrice, quantity, summary, productId, salesOrderId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, unitPrice, quantity, summary, productId, salesOrderId, updatedById) => {
try {
const response = await AxiosManager.post('/SalesOrderItem/UpdateSalesOrderItem', {
id, unitPrice, quantity, summary, productId, salesOrderId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/SalesOrderItem/DeleteSalesOrderItem', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
}
};
const methods = {
populateCustomerListLookupData: async () => {
const response = await services.getCustomerListLookupData();
state.customerListLookupData = response?.data?.content?.data;
},
populateTaxListLookupData: async () => {
const response = await services.getTaxListLookupData();
state.taxListLookupData = response?.data?.content?.data;
},
populateSalesOrderStatusListLookupData: async () => {
const response = await services.getSalesOrderStatusListLookupData();
state.salesOrderStatusListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
orderDate: new Date(item.orderDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateSecondaryData: async (salesOrderId) => {
try {
const response = await services.getSecondaryData(salesOrderId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshPaymentSummary(salesOrderId);
} catch (error) {
state.secondaryData = [];
}
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data;
},
refreshPaymentSummary: async (id) => {
const record = state.mainData.find(item => item.id === id);
if (record) {
state.subTotalAmount = NumberFormatManager.formatToLocale(record.beforeTaxAmount ?? 0);
state.taxAmount = NumberFormatManager.formatToLocale(record.taxAmount ?? 0);
state.totalAmount = NumberFormatManager.formatToLocale(record.afterTaxAmount ?? 0);
}
},
handleFormSubmit: async () => {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 200));
if (!validateForm()) {
state.isSubmitting = false;
return;
}
try {
const response = state.id === ''
? await services.createMainData(state.orderDate, state.description, state.orderStatus, state.taxId, state.customerId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.orderDate, state.description, state.orderStatus, state.taxId, state.customerId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Sales Order';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
state.orderDate = response?.data?.content?.data.orderDate ? new Date(response.data.content.data.orderDate) : null;
state.description = response?.data?.content?.data.description ?? '';
state.customerId = response?.data?.content?.data.customerId ?? '';
state.taxId = response?.data?.content?.data.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(response?.data?.content?.data.orderStatus ?? '');
state.showComplexDiv = true;
await methods.refreshPaymentSummary(state.id);
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 1000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
onMainModalHidden: () => {
state.errors.orderDate = '';
state.errors.customerId = '';
state.errors.taxId = '';
state.errors.orderStatus = '';
taxListLookup.trackingChange = false;
}
};
const customerListLookup = {
obj: null,
create: () => {
if (state.customerListLookupData && Array.isArray(state.customerListLookupData)) {
customerListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.customerListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Customer',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('name', 'startsWith', e.text, true);
}
e.updateData(state.customerListLookupData, query);
},
change: (e) => {
state.customerId = e.value;
}
});
customerListLookup.obj.appendTo(customerIdRef.value);
}
},
refresh: () => {
if (customerListLookup.obj) {
customerListLookup.obj.value = state.customerId;
}
}
};
const taxListLookup = {
obj: null,
trackingChange: false,
create: () => {
if (state.taxListLookupData && Array.isArray(state.taxListLookupData)) {
taxListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.taxListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Tax',
change: async (e) => {
state.taxId = e.value;
if (e.isInteracted && taxListLookup.trackingChange) {
await methods.handleFormSubmit();
}
}
});
taxListLookup.obj.appendTo(taxIdRef.value);
}
},
refresh: () => {
if (taxListLookup.obj) {
taxListLookup.obj.value = state.taxId;
}
}
};
const salesOrderStatusListLookup = {
obj: null,
create: () => {
if (state.salesOrderStatusListLookupData && Array.isArray(state.salesOrderStatusListLookupData)) {
salesOrderStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.salesOrderStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select an Order Status',
change: (e) => {
state.orderStatus = e.value;
}
});
salesOrderStatusListLookup.obj.appendTo(orderStatusRef.value);
}
},
refresh: () => {
if (salesOrderStatusListLookup.obj) {
salesOrderStatusListLookup.obj.value = state.orderStatus;
}
}
};
const orderDatePicker = {
obj: null,
create: () => {
orderDatePicker.obj = new ej.calendars.DatePicker({
format: 'yyyy-MM-dd',
value: state.orderDate ? new Date(state.orderDate) : null,
change: (e) => {
state.orderDate = e.value;
}
});
orderDatePicker.obj.appendTo(orderDateRef.value);
},
refresh: () => {
if (orderDatePicker.obj) {
orderDatePicker.obj.value = state.orderDate ? new Date(state.orderDate) : null;
}
}
};
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
readonly: true
});
numberText.obj.appendTo(numberRef.value);
}
};
Vue.watch(
() => state.orderDate,
(newVal, oldVal) => {
orderDatePicker.refresh();
state.errors.orderDate = '';
}
);
Vue.watch(
() => state.customerId,
(newVal, oldVal) => {
customerListLookup.refresh();
state.errors.customerId = '';
}
);
Vue.watch(
() => state.taxId,
(newVal, oldVal) => {
taxListLookup.refresh();
state.errors.taxId = '';
}
);
Vue.watch(
() => state.orderStatus,
(newVal, oldVal) => {
salesOrderStatusListLookup.refresh();
state.errors.orderStatus = '';
}
);
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: { columns: ['customerName'] },
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'orderDate', headerText: 'SO Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'customerName', headerText: 'Customer', width: 200, minWidth: 200 },
{ field: 'orderStatusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'taxName', headerText: 'Tax', width: 150, minWidth: 150 },
{ field: 'afterTaxAmount', headerText: 'Total Amount', width: 150, minWidth: 150, format: 'N2' },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'orderDate', 'customerName', 'orderStatusName', 'taxName', 'afterTaxAmount', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Sales Order';
resetFormState();
state.secondaryData = [];
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Sales Order';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
state.taxId = selectedRecord.taxId ?? '';
taxListLookup.trackingChange = true;
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = true;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Sales Order?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.orderDate = selectedRecord.orderDate ? new Date(selectedRecord.orderDate) : null;
state.description = selectedRecord.description ?? '';
state.customerId = selectedRecord.customerId ?? '';
state.taxId = selectedRecord.taxId ?? '';
state.orderStatus = String(selectedRecord.orderStatus ?? '');
state.showComplexDiv = false;
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/SalesOrders/SalesOrderPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'productName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
let productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: () => {
productObj.destroy();
},
write: (args) => {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.productId,
change: (e) => {
const selectedProduct = state.productListLookupData.find(item => item.id === e.value);
if (selectedProduct) {
args.rowData.productId = selectedProduct.id;
if (numberObj) {
numberObj.value = selectedProduct.number;
}
if (priceObj) {
priceObj.value = selectedProduct.unitPrice;
}
if (summaryObj) {
summaryObj.value = selectedProduct.description;
}
if (quantityObj) {
quantityObj.value = 1;
const total = selectedProduct.unitPrice * quantityObj.value;
if (totalObj) {
totalObj.value = total;
}
}
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'unitPrice',
headerText: 'Unit Price',
width: 200, validationRules: { required: true }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let priceElem = document.createElement('input');
return priceElem;
},
read: () => {
return priceObj.value;
},
destroy: () => {
priceObj.destroy();
},
write: (args) => {
priceObj = new ej.inputs.NumericTextBox({
value: args.rowData.unitPrice ?? 0,
change: (e) => {
if (quantityObj && totalObj) {
const total = e.value * quantityObj.value;
totalObj.value = total;
}
}
});
priceObj.appendTo(args.element);
}
}
},
{
field: 'quantity',
headerText: 'Quantity',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let quantityElem = document.createElement('input');
return quantityElem;
},
read: () => {
return quantityObj.value;
},
destroy: () => {
quantityObj.destroy();
},
write: (args) => {
quantityObj = new ej.inputs.NumericTextBox({
value: args.rowData.quantity ?? 0,
change: (e) => {
if (priceObj && totalObj) {
const total = e.value * priceObj.value;
totalObj.value = total;
}
}
});
quantityObj.appendTo(args.element);
}
}
},
{
field: 'total',
headerText: 'Total',
width: 200, validationRules: { required: false }, type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
let totalElem = document.createElement('input');
return totalElem;
},
read: () => {
return totalObj.value;
},
destroy: () => {
totalObj.destroy();
},
write: (args) => {
totalObj = new ej.inputs.NumericTextBox({
value: args.rowData.total ?? 0,
readonly: true
});
totalObj.appendTo(args.element);
}
}
},
{
field: 'productNumber',
headerText: 'Product Number',
allowEditing: false,
width: 180,
edit: {
create: () => {
let numberElem = document.createElement('input');
return numberElem;
},
read: () => {
return numberObj.value;
},
destroy: () => {
numberObj.destroy();
},
write: (args) => {
numberObj = new ej.inputs.TextBox();
numberObj.value = args.rowData.productNumber;
numberObj.readonly = true;
numberObj.appendTo(args.element);
}
}
},
{
field: 'summary',
headerText: 'Summary',
width: 200,
edit: {
create: () => {
let summaryElem = document.createElement('input');
return summaryElem;
},
read: () => {
return summaryObj.value;
},
destroy: () => {
summaryObj.destroy();
},
write: (args) => {
summaryObj = new ej.inputs.TextBox();
summaryObj.value = args.rowData.summary;
summaryObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
const salesOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.createSecondaryData(data?.unitPrice, data?.quantity, data?.summary, data?.productId, salesOrderId, userId);
await methods.populateSecondaryData(salesOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'save' && args.action === 'edit') {
const salesOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data;
await services.updateSecondaryData(data?.id, data?.unitPrice, data?.quantity, data?.summary, data?.productId, salesOrderId, userId);
await methods.populateSecondaryData(salesOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
}
if (args.requestType === 'delete') {
const salesOrderId = state.id;
const userId = StorageManager.getUserId();
const data = args.data[0];
await services.deleteSecondaryData(data?.id, userId);
await methods.populateSecondaryData(salesOrderId);
secondaryGrid.refresh();
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
}
await methods.populateMainData();
mainGrid.refresh();
await methods.refreshPaymentSummary(state.id);
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['SalesOrders']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateCustomerListLookupData();
customerListLookup.create();
await methods.populateTaxListLookupData();
taxListLookup.create();
await methods.populateSalesOrderStatusListLookupData();
salesOrderStatusListLookup.create();
orderDatePicker.create();
numberText.create();
await methods.populateProductListLookupData();
await secondaryGrid.create(state.secondaryData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
return {
mainGridRef,
mainModalRef,
orderDateRef,
numberRef,
customerIdRef,
taxIdRef,
orderStatusRef,
secondaryGridRef,
state,
methods,
handler: {
handleSubmit: methods.handleFormSubmit
}
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,242 @@
@page
@attribute [Authorize(Roles = "SalesOrders")]
@{
ViewData["Title"] = "Sales Order PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Sales Order</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Customer Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.customer.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.customerAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.customer.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.customer.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Order Information</th>
</tr>
<tr>
<td><strong>Order Number:</strong></td>
<td>{{ state.orderNumber }}</td>
</tr>
<tr>
<td><strong>Order Date:</strong></td>
<td>{{ state.orderDate }}</td>
</tr>
<tr>
<td><strong>Currency:</strong></td>
<td>{{ state.orderCurrency }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Product Number</th>
<th>Product Name</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.items" :key="item.productNumber">
<td>{{ item?.product?.number }}</td>
<td>{{ item?.product?.name }}</td>
<td>{{ item?.unitPrice }}</td>
<td>{{ item?.quantity }}</td>
<td>{{ item?.total }}</td>
</tr>
</tbody>
</table>
<div class="payment-summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold;">Subtotal:</td>
<td style="text-align: right;">{{ state.subTotal }}</td>
</tr>
<tr>
<td style="font-weight: bold;">Tax:</td>
<td style="text-align: right;">{{ state.tax }}</td>
</tr>
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Amount:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.totalAmount }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.payment-summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.payment-summary .column {
width: 48%;
}
.payment-summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/SalesOrders/SalesOrderPdf.cshtml.js"></script>
}
@@ -0,0 +1,143 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
customer: {
name: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
emailAddress: '',
phoneNumber: ''
},
customerAddress: '',
orderNumber: '',
orderDate: '',
orderCurrency: '',
subTotal: '',
tax: '',
totalAmount: '',
items: [],
isDownloading: false
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/SalesOrder/GetSalesOrderSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
const pdfData = response?.data?.content?.data || {};
state.items = pdfData.salesOrderItemList || [];
state.customer = pdfData.customer || {};
state.orderNumber = pdfData.number || '';
state.orderDate = DateFormatManager.formatToLocale(pdfData.orderDate) || '';
state.orderCurrency = StorageManager.getCompany()?.currency || '';
state.subTotal = NumberFormatManager.formatToLocale(pdfData.beforeTaxAmount) || '';
state.tax = NumberFormatManager.formatToLocale(pdfData.taxAmount) || '';
state.totalAmount = NumberFormatManager.formatToLocale(pdfData.afterTaxAmount) || '';
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
state.customerAddress = [
state.customer.street,
state.customer.city,
state.customer.state,
state.customer.zipCode,
state.customer.country
].filter(Boolean).join(', ');
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`sales-order-${state.orderNumber || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['SalesOrders']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,19 @@
@page
@attribute [Authorize(Roles = "SalesReports")]
@{
ViewData["Title"] = "Sales Report List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/SalesReports/SalesReportList.cshtml.js"></script>
}
@@ -0,0 +1,130 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/SalesOrderItem/GetSalesOrderItemList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['salesOrderNumber']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'salesOrderNumber', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'customerName', headerText: 'Customer', width: 200, minWidth: 200 },
{ field: 'salesOrderNumber', headerText: 'SalesOrder', width: 200, minWidth: 200 },
{ field: 'productNumber', headerText: 'Product Number', width: 200, minWidth: 200 },
{ field: 'productName', headerText: 'Product Name', width: 200, minWidth: 200 },
{ field: 'unitPrice', headerText: 'Unit Price', width: 150, minWidth: 150, format: 'N2' },
{ field: 'quantity', headerText: 'Quantity', width: 150, minWidth: 150 },
{ field: 'total', headerText: 'Total', width: 150, minWidth: 150, format: 'N2' },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
aggregates: [
{
columns: [
{
type: 'Sum',
field: 'total',
groupCaptionTemplate: 'Total: ${Sum}',
format: 'N2'
}
]
}
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['customerName', 'salesOrderNumber', 'productNumber', 'productName', 'unitPrice', 'quantity', 'total', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => { },
rowDeselected: () => { },
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['SalesReports']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
state,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,128 @@
@page
@attribute [Authorize(Roles = "SalesReturns")]
@{
ViewData["Title"] = "Sales Return List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="ReturnDate">Return Date</label>
<input ref="returnDateRef">
<label class="text-danger">{{ state.errors.returnDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="DeliveryOrderId">Delivery Order</label>
<div ref="deliveryOrderIdRef"></div>
<label class="text-danger">{{ state.errors.deliveryOrderId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Return Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/SalesReturns/SalesReturnList.cshtml.js"></script>
}
@@ -0,0 +1,871 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
deliveryOrderListLookupData: [],
salesReturnStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
warehouseListLookupData: [],
mainTitle: null,
id: '',
number: '',
returnDate: '',
description: '',
deliveryOrderId: null,
status: null,
errors: {
returnDate: '',
deliveryOrderId: '',
status: '',
description: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const returnDateRef = Vue.ref(null);
const deliveryOrderIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.returnDate = '';
state.errors.deliveryOrderId = '';
state.errors.status = '';
let isValid = true;
if (!state.returnDate) {
state.errors.returnDate = 'Return date is required.';
isValid = false;
}
if (!state.deliveryOrderId) {
state.errors.deliveryOrderId = 'Delivery Order is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.returnDate = '';
state.description = '';
state.deliveryOrderId = null;
state.status = null;
state.errors = {
returnDate: '',
deliveryOrderId: '',
status: '',
description: ''
};
state.secondaryData = [];
};
const returnDatePicker = {
obj: null,
create: () => {
returnDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.returnDate ? new Date(state.returnDate) : null,
change: (e) => {
state.returnDate = e.value;
}
});
returnDatePicker.obj.appendTo(returnDateRef.value);
},
refresh: () => {
if (returnDatePicker.obj) {
returnDatePicker.obj.value = state.returnDate ? new Date(state.returnDate) : null;
}
}
};
Vue.watch(
() => state.returnDate,
(newVal, oldVal) => {
returnDatePicker.refresh();
state.errors.returnDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const deliveryOrderListLookup = {
obj: null,
create: () => {
if (state.deliveryOrderListLookupData && Array.isArray(state.deliveryOrderListLookupData)) {
deliveryOrderListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.deliveryOrderListLookupData,
fields: { value: 'id', text: 'number' },
placeholder: 'Select Delivery Order',
filterBarPlaceholder: 'Search',
sortOrder: 'Ascending',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('number', 'startsWith', e.text, true);
}
e.updateData(state.deliveryOrderListLookupData, query);
},
change: (e) => {
state.deliveryOrderId = e.value;
}
});
deliveryOrderListLookup.obj.appendTo(deliveryOrderIdRef.value);
}
},
refresh: () => {
if (deliveryOrderListLookup.obj) {
deliveryOrderListLookup.obj.value = state.deliveryOrderId;
}
},
};
Vue.watch(
() => state.deliveryOrderId,
(newVal, oldVal) => {
deliveryOrderListLookup.refresh();
state.errors.deliveryOrderId = '';
}
);
const salesReturnStatusListLookup = {
obj: null,
create: () => {
if (state.salesReturnStatusListLookupData && Array.isArray(state.salesReturnStatusListLookupData)) {
salesReturnStatusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.salesReturnStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
salesReturnStatusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (salesReturnStatusListLookup.obj) {
salesReturnStatusListLookup.obj.value = state.status
}
},
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
salesReturnStatusListLookup.refresh();
state.errors.status = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/SalesReturn/GetSalesReturnList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (returnDate, description, status, deliveryOrderId, createdById) => {
try {
const response = await AxiosManager.post('/SalesReturn/CreateSalesReturn', {
returnDate, description, status, deliveryOrderId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, returnDate, description, status, deliveryOrderId, updatedById) => {
try {
const response = await AxiosManager.post('/SalesReturn/UpdateSalesReturn', {
id, returnDate, description, status, deliveryOrderId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/SalesReturn/DeleteSalesReturn', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getDeliveryOrderListLookupData: async () => {
try {
const response = await AxiosManager.get('/DeliveryOrder/GetDeliveryOrderList', {});
return response;
} catch (error) {
throw error;
}
},
getSalesReturnStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/SalesReturn/GetSalesReturnStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/SalesReturnGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, warehouseId, productId, movement, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/SalesReturnCreateInvenTrans', {
moduleId, warehouseId, productId, movement, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, warehouseId, productId, movement, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/SalesReturnUpdateInvenTrans', {
id, warehouseId, productId, movement, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/SalesReturnDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
returnDate: new Date(item.returnDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateDeliveryOrderListLookupData: async () => {
const response = await services.getDeliveryOrderListLookupData();
state.deliveryOrderListLookupData = response?.data?.content?.data;
},
populateSalesReturnStatusListLookupData: async () => {
const response = await services.getSalesReturnStatusListLookupData();
state.salesReturnStatusListLookupData = response?.data?.content?.data;
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateSecondaryData: async (salesReturnId) => {
try {
const response = await services.getSecondaryData(salesReturnId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.movement ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
onMainModalHidden: () => {
state.errors.returnDate = '';
state.errors.deliveryOrderId = '';
state.errors.status = '';
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.returnDate, state.description, state.status, state.deliveryOrderId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.returnDate, state.description, state.status, state.deliveryOrderId, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Sales Return';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['SalesReturns']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateDeliveryOrderListLookupData();
await methods.populateSalesReturnStatusListLookupData();
numberText.create();
returnDatePicker.create();
deliveryOrderListLookup.create();
salesReturnStatusListLookup.create();
await secondaryGrid.create(state.secondaryData);
await methods.populateProductListLookupData();
await methods.populateWarehouseListLookupData();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'returnDate', headerText: 'Return Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'deliveryOrderNumber', headerText: 'Delivery Order', width: 150, minWidth: 150 },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'returnDate', 'deliveryOrderNumber', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Sales Return';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Sales Return';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.returnDate = selectedRecord.returnDate ? new Date(selectedRecord.returnDate) : null;
state.description = selectedRecord.description ?? '';
state.deliveryOrderId = selectedRecord.deliveryOrderId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Sales Return?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.returnDate = selectedRecord.returnDate ? new Date(selectedRecord.returnDate) : null;
state.description = selectedRecord.description ?? '';
state.deliveryOrderId = selectedRecord.deliveryOrderId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/SalesReturns/SalesReturnPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'warehouseName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'warehouseId',
headerText: 'Warehouse',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const warehouse = state.warehouseListLookupData.find(item => item.id === data[field]);
return warehouse ? `${warehouse.name}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const warehouseElem = document.createElement('input');
return warehouseElem;
},
read: () => {
return warehouseObj.value;
},
destroy: function () {
warehouseObj.destroy();
},
write: function (args) {
warehouseObj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.warehouseId,
placeholder: 'Select a Warehouse',
floatLabelType: 'Never'
});
warehouseObj.appendTo(args.element);
}
}
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
const productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'numberName' },
value: args.rowData.productId,
change: function (e) {
if (movementObj) {
movementObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(args.element);
}
}
},
{
field: 'movement',
headerText: 'Movement',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
const movementElem = document.createElement('input');
return movementElem;
},
read: () => {
return movementObj.value;
},
destroy: function () {
movementObj.destroy();
},
write: function (args) {
movementObj = new ej.inputs.NumericTextBox({
value: args.rowData.movement ?? 0,
});
movementObj.appendTo(args.element);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['Edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.warehouseId, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
numberRef,
returnDateRef,
deliveryOrderIdRef,
statusRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,234 @@
@page
@attribute [Authorize(Roles = "SalesReturns")]
@{
ViewData["Title"] = "Sales Return PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Sales Return</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Customer Information</th>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td>{{ state.customer.name }}</td>
</tr>
<tr>
<td><strong>Address:</strong></td>
<td>{{ state.customerAddress }}</td>
</tr>
<tr>
<td><strong>Email:</strong></td>
<td>{{ state.customer.emailAddress }}</td>
</tr>
<tr>
<td><strong>Phone:</strong></td>
<td>{{ state.customer.phoneNumber }}</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Return Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.date }}</td>
</tr>
<tr>
<td><strong>Reference:</strong></td>
<td>{{ state.reference }}</td>
</tr>
<tr>
<td><strong>_</strong></td>
<td></td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Warehouse</th>
<th>Product</th>
<th>Movement</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product + item.warehouse">
<td>{{ item.warehouse }}</td>
<td>{{ item.product }}</td>
<td>{{ item.movement }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Movement:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/SalesReturns/SalesReturnPdf.cshtml.js"></script>
}
@@ -0,0 +1,150 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
customer: {
name: '',
street: '',
city: '',
state: '',
zipCode: '',
country: '',
emailAddress: '',
phoneNumber: ''
},
customerAddress: '',
number: '',
date: '',
reference: '',
pdfTransactionList: [],
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/SalesReturn/GetSalesReturnSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || {};
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.customer = pdfData.deliveryOrder?.salesOrder?.customer || {};
state.customerAddress = [
state.customer.street,
state.customer.city,
state.customer.state,
state.customer.zipCode,
state.customer.country
].filter(Boolean).join(', ');
state.number = pdfData?.number || '';
state.date = DateFormatManager.formatToLocale(pdfData?.returnDate) || '';
state.reference = pdfData?.deliveryOrder?.number || '';
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
warehouse: item.warehouse?.name || '',
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim(),
movement: item.movement || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.movement || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`sales-return-${state.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['SalesReturns']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,128 @@
@page
@attribute [Authorize(Roles = "Scrappings")]
@{
ViewData["Title"] = "Scrapping List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="ScrappingDate">Scrapping Date</label>
<input ref="scrappingDateRef">
<label class="text-danger">{{ state.errors.scrappingDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="WarehouseId">Warehouse</label>
<div ref="warehouseIdRef"></div>
<label class="text-danger">{{ state.errors.warehouseId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Delivery Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Scrappings/ScrappingList.cshtml.js"></script>
}
@@ -0,0 +1,832 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
warehouseListLookupData: [],
scrappingStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
mainTitle: null,
id: '',
number: '',
scrappingDate: '',
description: '',
warehouseId: null,
status: null,
errors: {
scrappingDate: '',
warehouseId: '',
status: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const scrappingDateRef = Vue.ref(null);
const warehouseIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.scrappingDate = '';
state.errors.warehouseId = '';
state.errors.status = '';
let isValid = true;
if (!state.scrappingDate) {
state.errors.scrappingDate = 'Scrapping date is required.';
isValid = false;
}
if (!state.warehouseId) {
state.errors.warehouseId = 'Warehouse is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.scrappingDate = '';
state.description = '';
state.warehouseId = null;
state.status = null;
state.errors = {
scrappingDate: '',
warehouseId: '',
status: ''
};
state.secondaryData = [];
};
const scrappingDatePicker = {
obj: null,
create: () => {
scrappingDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.scrappingDate ? new Date(state.scrappingDate) : null,
change: (e) => {
state.scrappingDate = e.value;
}
});
scrappingDatePicker.obj.appendTo(scrappingDateRef.value);
},
refresh: () => {
if (scrappingDatePicker.obj) {
scrappingDatePicker.obj.value = state.scrappingDate ? new Date(state.scrappingDate) : null;
}
}
};
Vue.watch(
() => state.scrappingDate,
(newVal, oldVal) => {
scrappingDatePicker.refresh();
state.errors.scrappingDate = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const warehouseListLookup = {
obj: null,
create: () => {
if (state.warehouseListLookupData && Array.isArray(state.warehouseListLookupData)) {
warehouseListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Warehouse',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('name', 'startsWith', e.text, true);
}
e.updateData(state.warehouseListLookupData, query);
},
change: (e) => {
state.warehouseId = e.value;
}
});
warehouseListLookup.obj.appendTo(warehouseIdRef.value);
}
},
refresh: () => {
if (warehouseListLookup.obj) {
warehouseListLookup.obj.value = state.warehouseId;
}
}
};
Vue.watch(
() => state.warehouseId,
(newVal, oldVal) => {
warehouseListLookup.refresh();
state.errors.warehouseId = '';
}
);
const statusListLookup = {
obj: null,
create: () => {
if (state.scrappingStatusListLookupData && Array.isArray(state.scrappingStatusListLookupData)) {
statusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.scrappingStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
statusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (statusListLookup.obj) {
statusListLookup.obj.value = state.status;
}
}
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
statusListLookup.refresh();
state.errors.status = '';
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Scrapping/GetScrappingList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (scrappingDate, description, status, warehouseId, createdById) => {
try {
const response = await AxiosManager.post('/Scrapping/CreateScrapping', {
scrappingDate, description, status, warehouseId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, scrappingDate, description, status, warehouseId, updatedById) => {
try {
const response = await AxiosManager.post('/Scrapping/UpdateScrapping', {
id, scrappingDate, description, status, warehouseId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Scrapping/DeleteScrapping', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
getScrappingStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/Scrapping/GetScrappingStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/ScrappingGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, productId, movement, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/ScrappingCreateInvenTrans', {
moduleId, productId, movement, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, productId, movement, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/ScrappingUpdateInvenTrans', {
id, productId, movement, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/ScrappingDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
scrappingDate: new Date(item.scrappingDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateScrappingStatusListLookupData: async () => {
const response = await services.getScrappingStatusListLookupData();
state.scrappingStatusListLookupData = response?.data?.content?.data;
},
populateSecondaryData: async (scrappingId) => {
try {
const response = await services.getSecondaryData(scrappingId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.movement ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
onMainModalHidden: () => {
state.errors.scrappingDate = '';
state.errors.warehouseId = '';
state.errors.status = '';
},
submitMainData: async () => {
const isValid = validateForm();
if (!isValid) {
return { isValid, response: null };
}
try {
const response = state.id === ''
? await services.createMainData(state.scrappingDate, state.description, state.status, state.warehouseId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.scrappingDate, state.description, state.status, state.warehouseId, StorageManager.getUserId());
return { isValid, response };
} catch (error) {
return { isValid, response: null };
}
},
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const { isValid, response } = await methods.submitMainData();
if (!isValid) {
return;
}
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Scrapping';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Scrappings']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden());
await methods.populateWarehouseListLookupData();
warehouseListLookup.create();
await methods.populateScrappingStatusListLookupData();
statusListLookup.create();
scrappingDatePicker.create();
numberText.create();
await methods.populateProductListLookupData();
await secondaryGrid.create(state.secondaryData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden());
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'scrappingDate', headerText: 'Scrapping Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'warehouseName', headerText: 'Warehouse', width: 150, minWidth: 150 },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'scrappingDate', 'warehouseName', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Scrapping';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Scrapping';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.scrappingDate = selectedRecord.scrappingDate ? new Date(selectedRecord.scrappingDate) : null;
state.description = selectedRecord.description ?? '';
state.warehouseId = selectedRecord.warehouseId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Scrapping?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.scrappingDate = selectedRecord.scrappingDate ? new Date(selectedRecord.scrappingDate) : null;
state.description = selectedRecord.description ?? '';
state.warehouseId = selectedRecord.warehouseId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/Scrappings/ScrappingPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'productName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.productId,
change: function (e) {
if (movementObj) {
movementObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(productElem);
}
}
},
{
field: 'movement',
headerText: 'Movement',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] > 0;
}, 'Must be a positive number and not zero']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
movementElem = document.createElement('input');
return movementElem;
},
read: () => {
return movementObj.value;
},
destroy: function () {
movementObj.destroy();
},
write: function (args) {
movementObj = new ej.inputs.NumericTextBox({
value: args.rowData.movement ?? 0,
});
movementObj.appendTo(movementElem);
}
}
},
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.productId, args.data.movement, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
scrappingDateRef,
warehouseIdRef,
statusRef,
numberRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,216 @@
@page
@attribute [Authorize(Roles = "Scrappings")]
@{
ViewData["Title"] = "Scrapping PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Scrapping</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Warehouse Information</th>
</tr>
<tr>
<td><strong>Warehouse:</strong></td>
<td>{{ state.warehouse }}</td>
</tr>
<tr>
<td><strong></strong></td>
<td>_</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Scrapping Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.date }}</td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Product</th>
<th>Movement</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product">
<td>{{ item.product }}</td>
<td>{{ item.movement }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Movement:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/Scrappings/ScrappingPdf.cshtml.js"></script>
}
@@ -0,0 +1,130 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
warehouse: '',
number: '',
date: '',
pdfTransactionList: [],
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/Scrapping/GetScrappingSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || {};
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.warehouse = pdfData?.warehouse?.name || '';
state.number = pdfData?.number || '';
state.date = DateFormatManager.formatToLocale(pdfData?.scrappingDate) || '';
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim(),
movement: item.movement || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.movement || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`scrapping-${state.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Scrappings']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,107 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@ViewData["Title"]</title>
@await Html.PartialAsync("~/FrontEnd/Pages/Shared/AdminLTE/__css.cshtml")
@await RenderSectionAsync("styles", required: false)
<style>
[v-cloak] {
display: none !important;
}
</style>
@* vue *@
<script src="~/lib/vue/vue.global.prod.js"></script>
</head>
<body class="hold-transition sidebar-mini">
<!-- Site wrapper -->
<div class="wrapper">
<!-- Navbar -->
@await Html.PartialAsync("~/FrontEnd/Pages/Shared/AdminLTE/__navbar.cshtml")
<!-- /.navbar -->
<!-- Main Sidebar Container -->
@await Html.PartialAsync("~/FrontEnd/Pages/Shared/AdminLTE/__sidebar.cshtml")
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper p-4">
@Html.AntiForgeryToken()
@RenderBody()
</div>
<!-- /.content-wrapper -->
@await Html.PartialAsync("~/FrontEnd/Pages/Shared/AdminLTE/__footer.cshtml")
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<!-- /.control-sidebar -->
</div>
<!-- ./wrapper -->
@await Html.PartialAsync("~/FrontEnd/Pages/Shared/AdminLTE/__js.cshtml")
@await RenderSectionAsync("scripts", required: false)
<script>
document.addEventListener('DOMContentLoaded', async function () {
async function getAvatar() {
try {
const avatar = StorageManager.getAvatar();
const response = await AxiosManager.get('/FileImage/GetImage?imageName=' + avatar, {
responseType: 'blob'
});
if (response.status === 200) {
const reader = new FileReader();
reader.onloadend = function () {
const base64Image = reader.result;
document.getElementById('AvatarImageSide').src = base64Image;
};
reader.readAsDataURL(response.data);
} else {
console.error('Error:', response.statusText);
}
} catch (error) {
console.error('Error:', error);
}
}
getAvatar();
});
</script>
<script>
document.addEventListener('DOMContentLoaded', async function () {
async function getCompany() {
try {
const response = await AxiosManager.get('/Company/GetCompanyList', {});
const data = response?.data?.content?.data;
if (data && data.length > 0) {
StorageManager.saveCompany(data[0]);
const companyName = data[0]?.name ?? 'Default Company';
const companyWeb = data[0]?.website ?? '#';
const year = new Date().getFullYear();
const currency = data[0]?.currency ?? '---';
document.getElementById('footerContent').innerHTML =
`© ${year} <a href="${companyWeb}">${companyName}</a>, All Right Reserved.`;
document.getElementById('topbarContent').innerHTML =
`Currency: ${currency}`;
}
} catch (error) {
console.error('Error:', error);
}
}
getCompany();
});
</script>
</body>
</html>
@@ -0,0 +1,60 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@ViewData["Title"]</title>
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="~/adminlte/plugins/fontawesome-free/css/all.min.css">
<!-- icheck bootstrap -->
<link rel="stylesheet" href="~/adminlte/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="~/adminlte/css/adminlte.min.css">
@await RenderSectionAsync("styles", required: false)
<style>
[v-cloak] {
display: none !important;
}
</style>
@* vue *@
<script src="~/lib/vue/vue.global.prod.js"></script>
<!-- JavaScript Libraries -->
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js" defer></script>
<script src="~/lib/axios/axios.min.js" defer></script>
<script src="~/lib/sweetalert/sweetalert2v11.js" defer></script>
<script src="~/lib/indotalent/storage-manager.js" defer></script>
<script src="~/lib/indotalent/security-manager.js" defer></script>
<script src="~/lib/indotalent/axios-manager.js" defer></script>
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a asp-area="" asp-page="/Index"><b>INDOTALENT</b> WHMS.</a>
</div>
<!-- /.login-logo -->
<div class="card">
@RenderBody()
<!-- /.login-card-body -->
</div>
</div>
<!-- /.login-box -->
<!-- jQuery -->
<script src="~/adminlte/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="~/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="~/adminlte/js/adminlte.min.js"></script>
@await RenderSectionAsync("scripts", required: false)
</body>
</html>
@@ -0,0 +1,374 @@
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="~/adminlte/plugins/fontawesome-free/css/all.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="~/adminlte/css/adminlte.min.css">
<link href="~/lib/syncfusion/css/bootstrap5.css" rel="stylesheet" />
<script src="~/lib/syncfusion/js/ej2.min.js"></script>
<link href="~/lib/font-awesome/css/all.min.css" rel="stylesheet">
<link href="~/lib/bootstrap/dist/css/bootstrap-icons.css" rel="stylesheet">
<link href="~/lib/dropzone/dropzone.min.css" rel="stylesheet">
<style>
/* CUSTOM */
/*Form Group*/
.form-group {
margin-top: 10px;
}
/* For Syncfusion Grid */
.grid-container .e-gridcontent {
cursor: pointer;
}
.e-grid .e-row.e-altrow {
background-color: #F3F6F9;
}
.e-headertext {
padding-left: 5px;
}
.e-grid .e-gridpager .e-currentitem {
background-color: var(--primary);
color: #fff !important;
}
.e-grid .e-gridpager .e-numericitem {
color: var(--primary);
}
.e-contextmenu-wrapper ul .e-menu-item.e-selected, .e-contextmenu-container ul .e-menu-item.e-selected {
background-color: var(--primary);
color: #fff;
outline: 0 solid var(--primary);
outline-offset: 0;
}
.e-checkbox-wrapper .e-frame.e-stop, .e-css.e-checkbox-wrapper .e-frame.e-stop {
background-color: var(--primary);
border-color: var(--primary);
color: #fff;
}
.e-checkbox-wrapper .e-frame.e-check, .e-css.e-checkbox-wrapper .e-frame.e-check {
background-color: var(--primary);
border-color: var(--primary);
color: #fff;
}
.e-treeview .e-list-item.e-hover > .e-text-content .e-icon-collapsible {
color: #fff;
}
.e-treeview .e-list-item.e-hover > .e-text-content .e-icon-expandable {
color: #fff;
}
.e-treeview .e-list-item.e-hover > .e-text-content .e-list-text {
color: #fff;
}
.e-treeview .e-list-item.e-active.e-animation-active > .e-text-content .e-list-text {
color: #fff;
}
.e-treeview .e-list-item.e-active > .e-text-content {
background-color: #2a2a3c;
color: #fff;
}
.e-treeview .e-list-item.e-active > .e-fullrow {
background-color: #2a2a3c;
border-color: #2a2a3c;
}
.e-treeview .e-list-item.e-active.e-animation-active > .e-fullrow {
background-color: #2a2a3c;
border-color: #2a2a3c;
}
.e-treeview .e-list-item.e-hover > .e-fullrow {
background-color: #2a2a3c;
border-color: #2a2a3c;
}
.e-treeview .e-list-item.e-active.e-hover > .e-fullrow {
background-color: #2a2a3c;
border-color: #2a2a3c;
color: #fff;
}
.e-treeview .e-list-text {
color: #fff;
font-size: 14px;
}
.e-dropdownbase .e-list-item.e-item-focus, .e-dropdownbase .e-list-item.e-active, .e-dropdownbase .e-list-item.e-active.e-hover, .e-dropdownbase .e-list-item.e-hover {
background-color: var(--primary);
color: #fff;
}
.e-schedule .e-timeline-view .e-appointment, .e-schedule .e-timeline-month-view .e-appointment {
cursor: pointer;
}
.e-schedule .e-agenda-view .e-appointment {
border-left: 0px solid var(--primary);
cursor: pointer;
}
.e-quick-popup-wrapper .e-event-popup .e-popup-header .e-subject-wrap .e-subject {
border-left: 6px solid var(--primary);
}
.e-btn.e-primary, .e-css.e-btn.e-primary {
background-color: var(--primary);
border-color: var(--primary);
color: #fff;
}
.e-footer-content .e-btn.e-primary.e-flat:not([DISABLED]) {
background-color: var(--primary);
border-color: var(--primary);
color: #fff;
}
/*BS Navbar*/
.nav-tabs .nav-item .nav-link {
font-size: 0.9rem;
padding: 0.3rem 0.5rem;
}
.e-input-group, .e-input-group.e-control-wrapper {
border-radius: 0px;
}
.e-input-group.e-control-wrapper.e-disabled input.e-input {
background: var(--light);
}
/* Fieldset */
fieldset {
background-color: #fff;
width: 100%;
padding: 15px;
margin-left: 0px;
margin-right: 0px;
margin-top: 10px;
margin-bottom: 10px;
border: 1px solid #dee2e6;
}
/* For FormCard */
.form-card {
border: 1px solid #dee2e6;
width: 100%;
overflow-y: auto;
}
.form-card-header {
background-color: #ffffff;
color: #000000;
padding: 10px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
text-align: left;
}
.form-card-body {
background-color: #ffffff;
padding-top: 5px;
padding-right: 0;
padding-bottom: 5px;
padding-left: 0px;
}
.form-card-footer {
background-color: #ffffff;
color: #000000;
padding-top: 5px;
padding-right: 0;
padding-bottom: 5px;
padding-left: 0px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
text-align: left;
}
.form-label {
margin-bottom: 0px;
font-size: 0.875em;
}
.form-group {
margin-top: 0px;
}
.sticky-top {
z-index: 900 !important;
}
.content .navbar .navbar-nav .dropdown-item {
background-color: transparent !important;
}
.small-italic-left {
font-size: small;
font-style: italic;
text-align: left;
margin-bottom: -10px;
margin-left: 0px;
padding-top: 10px;
}
.small-italic {
font-size: small;
font-style: italic;
position: relative;
margin: 10px;
}
.small-italic::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
border-bottom: 1px solid #dee2e6;
}
</style>
<style>
/* CSS scrollbar sidebar */
#navbarnav::-webkit-scrollbar {
width: 12px;
}
#navbarnav::-webkit-scrollbar-track {
background-color: #191C24;
}
#navbarnav::-webkit-scrollbar-thumb {
background-color: #2a2a3c;
border-radius: 6px;
border: 3px solid #191C24;
transition: filter 0.3s;
}
#navbarnav::-webkit-scrollbar-thumb:hover {
cursor: pointer;
background-color: var(--dark);
}
</style>
<style>
/* CSS scrollbar other */
::-webkit-scrollbar {
width: 12px;
height: 12px;
}
::-webkit-scrollbar-track {
background-color: #f8f9fa;
}
::-webkit-scrollbar-thumb {
background-color: #dee2e6;
border-radius: 6px;
border: 3px solid #f8f9fa;
transition: filter 0.3s;
}
::-webkit-scrollbar-thumb:hover {
cursor: pointer;
background-color: var(--primary);
}
</style>
<style>
#navbarnav {
width: 250px;
height: 70vh;
overflow-y: auto;
}
a {
color: var(--primary);
}
.nav-link {
color: var(--primary);
}
.text-primary {
color: var(--primary) !important;
}
:root {
--primary: #1b84ff;
--bs-blue: #1b84ff;
--bs-primary: #1b84ff;
}
</style>
@* smaller form *@
<style>
.select2-container--bootstrap-5 .select2-results__option {
font-size: 0.9rem !important;
line-height: 1.5 !important;
}
form input.form-control,
form textarea.form-control,
form select.form-control,
.select2-container--bootstrap-5 .select2-selection {
height: calc(1.5em + 0.75rem + 2px);
padding: 0.375rem 0.75rem;
font-size: 0.9rem;
line-height: 1.5;
border-radius: 0.25rem;
box-shadow: none;
border: 1px solid #ced4da;
}
form textarea.form-control {
height: auto;
}
form .row.mb-3 {
margin-bottom: 0.5rem;
}
.card-header h5 {
font-size: 1rem;
margin-bottom: 0;
}
.card-body {
padding: 0.75rem;
}
</style>
@@ -0,0 +1,15 @@
@{
var companyName = "companyName";
var companyWeb = "companyWeb";
var year = DateTime.Now.Year;
}
<footer class="main-footer">
<div class="float-right d-none d-sm-block">
<!--/*** This app is free as long as you keep the footer authors credit link/attribution link/backlink. If you'd like to use the app without the footer authors credit link/attribution link/backlink, you can purchase the Credit Removal License from "https://store.indotalent.com". Thank you for your support. ***/-->
<b>Developed By:</b> <a href="https://store.indotalent.com">https://store.indotalent.com</a>
</div>
<small id="footerContent">
&copy; @year <a href="@companyWeb">@companyName</a>, All Right Reserved.
</small>
</footer>
@@ -0,0 +1,126 @@
<!-- jQuery -->
<script src="~/adminlte/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="~/adminlte/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="~/adminlte/js/adminlte.min.js"></script>
<!-- JavaScript Libraries -->
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="~/lib/axios/axios.min.js"></script>
<script src="~/lib/sweetalert/sweetalert2v11.js"></script>
<script src="~/lib/dropzone/dropzone.min.js"></script>
<script src="~/lib/indotalent/storage-manager.js"></script>
<script src="~/lib/indotalent/security-manager.js"></script>
<script src="~/lib/indotalent/axios-manager.js"></script>
<script src="~/lib/indotalent/number-format-manager.js"></script>
<script src="~/lib/indotalent/date-format-manager.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script>
// Sidebar Toggler
document.addEventListener('DOMContentLoaded', function() {
const sidebarToggler = document.querySelector('.sidebar-toggler');
if (sidebarToggler) {
sidebarToggler.addEventListener('click', function(event) {
document.querySelector('.sidebar').classList.toggle("open");
document.querySelector('.content').classList.toggle("open");
event.preventDefault();
});
}
});
var hideSpinnerAndShowContent = () => {
const spinner = document.getElementById('spinner');
if (spinner) {
spinner.classList.remove('show');
}
}
window.addEventListener('load', function () {
var formcard = document.getElementById('formcard');
if (formcard) {
var formcardPosition = sessionStorage.getItem('formcardPosition');
if (formcardPosition !== null) {
setTimeout(function () {
formcard.scrollTop = parseInt(formcardPosition);
sessionStorage.removeItem('formcardPosition');
}, 1000);
}
} else {
sessionStorage.setItem('formcardPosition', 0);
}
});
window.addEventListener('beforeunload', () => {
var formcard = document.getElementById('formcard');
if (formcard) {
sessionStorage.setItem('formcardPosition', formcard.scrollTop);
}
});
</script>
<script>
// for maintaining sidebar scroll position
document.addEventListener('DOMContentLoaded', function () {
var sidebar = document.getElementById('navbarnav');
if (sidebar) {
var scrollPosition = sessionStorage.getItem('sidebarScrollPosition');
if (scrollPosition !== null) {
setTimeout(() => {
sidebar.scrollTop = parseInt(scrollPosition);
sessionStorage.removeItem('sidebarScrollPosition');
}, 0);
}
sidebar.addEventListener('scroll', function () {
sessionStorage.setItem('sidebarScrollPosition', sidebar.scrollTop);
});
}
});
window.addEventListener('beforeunload', () => {
var sidebar = document.getElementById('navbarnav');
if (sidebar) {
sessionStorage.setItem('sidebarScrollPosition', sidebar.scrollTop);
}
});
</script>
<script>
function showStatusMessage(statusMessage) {
if (statusMessage && statusMessage.includes("Error")) {
new ej.notifications.Toast({
content: statusMessage,
cssClass: "e-toast-danger",
icon: 'e-error toast-icons',
position: { X: "Left", Y: "Top" }
}, '#Toast').show();
} else {
new ej.notifications.Toast({
content: statusMessage,
cssClass: "e-toast-success",
icon: 'e-success toast-icons',
position: { X: "Left", Y: "Top" }
}, '#Toast').show();
}
}
</script>
<script>
function formatNumberToN2(number) {
return Number(number).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
</script>
@@ -0,0 +1,34 @@
@{
}
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
<!-- Left navbar links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
</li>
</ul>
<!-- Right navbar links -->
<span class="mt-0" id="topbarContent">Currency: </span>
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a class="nav-link" data-toggle="dropdown" href="#">
<i class="fas fa-th-large"></i>
</a>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
<div class="dropdown-divider"></div>
<a asp-area="" asp-page="/Profiles/MyProfile" class="dropdown-item">
<i class="fas fa-users mr-2"></i> Profile
</a>
<div class="dropdown-divider"></div>
<form class="form-inline" asp-area="" asp-page="/Accounts/Logout">
<button type="submit" class="nav-link btn btn-link text-black dropdown-item"><i class="fas fa-lock mr-2"></i>Log Out</button>
</form>
<div class="dropdown-divider"></div>
</div>
</li>
</ul>
</nav>
@@ -0,0 +1,116 @@
@{
var userEmail = "Loading...";
var avatarUrl = "/noimage.png";
var appName = "WMS";
}
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<!-- Brand Logo -->
<a asp-area="" asp-page="/Dashboards/DefaultDashboard" class="brand-link d-flex justify-content-center align-items-center">
<span class="brand-text font-weight-light">@appName</span>
</a>
<!-- Sidebar -->
<div class="sidebar">
<!-- Sidebar user (optional) -->
<div class="user-panel mt-3 pb-3 mb-3 d-flex">
<div class="image">
<img id="AvatarImageSide" src="@avatarUrl" class="img-circle elevation-2" alt="User Image" style="width: 40px; height: 40px;">
</div>
<div class="info">
<a asp-area="" asp-page="/Profiles/MyProfile" class="d-block" id="userEmail">@userEmail</a>
</div>
</div>
<!-- Sidebar Menu -->
<nav class="mt-2">
<div id="navbarnav" class="navbar-nav w-100">
<div id="mainMenuContainer">
<div id="mainMenu"></div>
</div>
</div>
</nav>
<!-- /.sidebar-menu -->
</div>
<!-- /.sidebar -->
</aside>
@* _sidebar.cshtml *@
<script>
document.addEventListener('DOMContentLoaded', function () {
try {
const email = StorageManager.getEmail();
const userEmail = `${email}`;
document.getElementById('userEmail').textContent = userEmail;
const currentUrl = window.location.pathname;
const firstSegment = currentUrl.split('/')[1];
function filterMenu(menuData, userRoles) {
const childMenus = menuData.filter(menu => {
if (menu.navURL) {
const firstSegment = menu.navURL.split('/')[1];
return userRoles.some(role => role.toLowerCase() === firstSegment.toLowerCase());
}
return false;
});
const validChildIds = new Set(childMenus.map(menu => menu.id));
const parentIds = new Set(childMenus.map(menu => menu.pid));
return menuData.filter(menu => validChildIds.has(menu.id) || parentIds.has(menu.id));
}
function updateMenuSelection(menuData, segment) {
const parentMap = {};
menuData.forEach(item => {
parentMap[item.id] = item;
});
menuData.forEach(item => {
item.isSelected = false;
item.expanded = false;
if (item.navURL && item.navURL.includes(`/${segment}`)) {
item.isSelected = true;
let parentId = item.pid;
while (parentId) {
const parent = parentMap[parentId];
if (parent) {
parent.expanded = true;
parentId = parent.pid;
} else {
break;
}
}
}
});
return menuData;
}
const userRoles = StorageManager.getUserRoles();
let menuData = StorageManager.getMenuNavigation();
const filteredMenu = filterMenu(menuData, userRoles);
menuData = updateMenuSelection(filteredMenu, firstSegment);
const mainMenu = new ej.navigations.TreeView({
fullRowNavigable: true,
fields: {
dataSource: menuData,
id: 'id',
text: 'name',
selected: 'isSelected',
parentID: 'pid',
hasChildren: 'hasChild',
expanded: 'expanded',
navigateUrl: 'navURL',
},
enablePersistence: false,
});
mainMenu.appendTo('#mainMenu');
} catch (error) {
console.error('Error fetching data from StorageManager:', error);
}
});
</script>
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WHMS - .NET 9 - Warehouse & Inventory Management System</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="" name="keywords">
<meta content="" name="description">
@await Html.PartialAsync("__css")
@await RenderSectionAsync("Styles", required: false)
</head>
<body>
@RenderBody()
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
@@ -0,0 +1,46 @@
<!-- Google Web Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500&family=Roboto:wght@500;700;900&display=swap" rel="stylesheet">
<!-- Icon Font Stylesheet -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css" rel="stylesheet">
<style>
.lock-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #212529;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
flex-direction: column;
}
.lock-icon {
font-size: 3em;
color: #c2c7d0;
border: 2px solid #F6B53F;
border-radius: 10px;
padding: 20px;
}
.lock-welcome {
color: #c2c7d0;
font-size: 2em;
font-family: Heebo, sans-serif;
margin-bottom: 20px;
}
</style>
@@ -0,0 +1,128 @@
@page
@attribute [Authorize(Roles = "StockCounts")]
@{
ViewData["Title"] = "Stock Count List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="CountDate">Count Date</label>
<input ref="countDateRef">
<label class="text-danger">{{ state.errors.countDate }}</label>
</div>
<div class="col-md-6">
<label for="Number">Number</label>
<input ref="numberRef" v-model="state.number" readonly>
</div>
</div>
<div class="row mb-2">
<div class="col-md-6">
<label for="WarehouseId">Warehouse</label>
<div ref="warehouseIdRef"></div>
<label class="text-danger">{{ state.errors.warehouseId }}</label>
</div>
<div class="col-md-6">
<label for="Status">Status</label>
<div ref="statusRef"></div>
<label class="text-danger">{{ state.errors.status }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-md-12">
<label for="Description">Description</label>
<textarea class="form-control" rows="3" v-model="state.description"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="ComplexDiv" :style="{ display: state.showComplexDiv ? 'block' : 'none' }">
<div class="row mt-3">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Delivery Item</h5>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="grid-container">
<div ref="secondaryGridRef"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-md-12">
<div class="card shadow-sm">
<div class="card-header text-white">
<h5 class="mb-0">Summary</h5>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-md-6">
<div class="d-flex justify-content-between py-2">
<span class="fw-bold">Total Movement</span>
<span id="TotalMovement" class="fw-bold text-success">{{ state.totalMovementFormatted }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Submit' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Submitting...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/StockCounts/StockCountList.cshtml.js"></script>
}
@@ -0,0 +1,834 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
warehouseListLookupData: [],
stockCountStatusListLookupData: [],
secondaryData: [],
productListLookupData: [],
mainTitle: null,
id: '',
number: '',
countDate: '',
description: '',
warehouseId: null,
status: null,
errors: {
countDate: '',
warehouseId: '',
status: ''
},
showComplexDiv: false,
isSubmitting: false,
totalMovementFormatted: '0.00'
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const secondaryGridRef = Vue.ref(null);
const countDateRef = Vue.ref(null);
const warehouseIdRef = Vue.ref(null);
const statusRef = Vue.ref(null);
const numberRef = Vue.ref(null);
const validateForm = function () {
state.errors.countDate = '';
state.errors.warehouseId = '';
state.errors.status = '';
let isValid = true;
if (!state.countDate) {
state.errors.countDate = 'Count date is required.';
isValid = false;
}
if (!state.warehouseId) {
state.errors.warehouseId = 'Warehouse is required.';
isValid = false;
}
if (!state.status) {
state.errors.status = 'Status is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.number = '';
state.countDate = '';
state.description = '';
state.warehouseId = null;
state.status = null;
state.errors = {
countDate: '',
warehouseId: '',
status: ''
};
state.secondaryData = [];
};
const countDatePicker = {
obj: null,
create: () => {
countDatePicker.obj = new ej.calendars.DatePicker({
placeholder: 'Select Date',
format: 'yyyy-MM-dd',
value: state.countDate ? new Date(state.countDate) : null,
change: (e) => {
state.countDate = e.value;
}
});
countDatePicker.obj.appendTo(countDateRef.value);
},
refresh: () => {
if (countDatePicker.obj) {
countDatePicker.obj.value = state.countDate ? new Date(state.countDate) : null;
}
}
};
Vue.watch(
() => state.countDate,
(newVal, oldVal) => {
countDatePicker.refresh();
state.errors.countDate = '';
}
);
const warehouseListLookup = {
obj: null,
create: () => {
if (state.warehouseListLookupData && Array.isArray(state.warehouseListLookupData)) {
warehouseListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.warehouseListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Warehouse',
allowFiltering: true,
filtering: (e) => {
e.preventDefaultAction = true;
let query = new ej.data.Query();
if (e.text !== '') {
query = query.where('name', 'startsWith', e.text, true);
}
e.updateData(state.warehouseListLookupData, query);
},
change: (e) => {
state.warehouseId = e.value;
}
});
warehouseListLookup.obj.appendTo(warehouseIdRef.value);
}
},
refresh: () => {
if (warehouseListLookup.obj) {
warehouseListLookup.obj.value = state.warehouseId;
}
}
};
Vue.watch(
() => state.warehouseId,
(newVal, oldVal) => {
warehouseListLookup.refresh();
state.errors.warehouseId = '';
}
);
const statusListLookup = {
obj: null,
create: () => {
if (state.stockCountStatusListLookupData && Array.isArray(state.stockCountStatusListLookupData)) {
statusListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.stockCountStatusListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select Status',
allowFiltering: false,
change: (e) => {
state.status = e.value;
}
});
statusListLookup.obj.appendTo(statusRef.value);
}
},
refresh: () => {
if (statusListLookup.obj) {
statusListLookup.obj.value = state.status;
}
}
};
Vue.watch(
() => state.status,
(newVal, oldVal) => {
statusListLookup.refresh();
state.errors.status = '';
}
);
const numberText = {
obj: null,
create: () => {
numberText.obj = new ej.inputs.TextBox({
placeholder: '[auto]',
});
numberText.obj.appendTo(numberRef.value);
}
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/StockCount/GetStockCountList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (countDate, description, status, warehouseId, createdById) => {
try {
const response = await AxiosManager.post('/StockCount/CreateStockCount', {
countDate, description, status, warehouseId, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, countDate, description, status, warehouseId, updatedById) => {
try {
const response = await AxiosManager.post('/StockCount/UpdateStockCount', {
id, countDate, description, status, warehouseId, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/StockCount/DeleteStockCount', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getWarehouseListLookupData: async () => {
try {
const response = await AxiosManager.get('/Warehouse/GetWarehouseList', {});
return response;
} catch (error) {
throw error;
}
},
getStockCountStatusListLookupData: async () => {
try {
const response = await AxiosManager.get('/StockCount/GetStockCountStatusList', {});
return response;
} catch (error) {
throw error;
}
},
getSecondaryData: async (moduleId) => {
try {
const response = await AxiosManager.get('/InventoryTransaction/StockCountGetInvenTransList?moduleId=' + moduleId, {});
return response;
} catch (error) {
throw error;
}
},
createSecondaryData: async (moduleId, productId, qtySCCount, createdById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/StockCountCreateInvenTrans', {
moduleId, productId, qtySCCount, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateSecondaryData: async (id, productId, qtySCCount, updatedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/StockCountUpdateInvenTrans', {
id, productId, qtySCCount, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteSecondaryData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/InventoryTransaction/StockCountDeleteInvenTrans', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getProductListLookupData: async () => {
try {
const response = await AxiosManager.get('/Product/GetProductList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
countDate: new Date(item.countDate),
createdAtUtc: new Date(item.createdAtUtc)
}));
},
populateWarehouseListLookupData: async () => {
const response = await services.getWarehouseListLookupData();
state.warehouseListLookupData = response?.data?.content?.data.filter(warehouse => warehouse.systemWarehouse === false) || [];
},
populateStockCountStatusListLookupData: async () => {
const response = await services.getStockCountStatusListLookupData();
state.stockCountStatusListLookupData = response?.data?.content?.data;
},
populateSecondaryData: async (stockCountId) => {
try {
const response = await services.getSecondaryData(stockCountId);
state.secondaryData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
methods.refreshSummary();
} catch (error) {
state.secondaryData = [];
}
},
populateProductListLookupData: async () => {
const response = await services.getProductListLookupData();
state.productListLookupData = response?.data?.content?.data
.filter(product => product.physical === true)
.map(product => ({
...product,
numberName: `${product.number} - ${product.name}`
})) || [];
},
refreshSummary: () => {
const totalMovement = state.secondaryData.reduce((sum, record) => sum + (record.qtySCDelta ?? 0), 0);
state.totalMovementFormatted = NumberFormatManager.formatToLocale(totalMovement);
},
submitMainData: async () => {
const isValid = validateForm();
if (!isValid) {
return { isValid, response: null };
}
try {
const response = state.id === ''
? await services.createMainData(state.countDate, state.description, state.status, state.warehouseId, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.countDate, state.description, state.status, state.warehouseId, StorageManager.getUserId());
return { isValid, response };
} catch (error) {
return { isValid, response: null };
}
},
onMainModalHidden: () => {
resetFormState();
state.errors.countDate = '';
state.errors.warehouseId = '';
state.errors.status = '';
state.showComplexDiv = false;
}
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
const { isValid, response } = await methods.submitMainData();
if (!isValid) {
return;
}
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Stock Count';
state.id = response?.data?.content?.data.id ?? '';
state.number = response?.data?.content?.data.number ?? '';
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['StockCounts']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', methods.onMainModalHidden);
await methods.populateWarehouseListLookupData();
warehouseListLookup.create();
await methods.populateStockCountStatusListLookupData();
statusListLookup.create();
countDatePicker.create();
numberText.create();
await methods.populateProductListLookupData();
await secondaryGrid.create(state.secondaryData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', methods.onMainModalHidden);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'number', headerText: 'Number', width: 150, minWidth: 150 },
{ field: 'countDate', headerText: 'Count Date', width: 150, format: 'yyyy-MM-dd' },
{ field: 'warehouseName', headerText: 'Warehouse', width: 150, minWidth: 150 },
{ field: 'statusName', headerText: 'Status', width: 150, minWidth: 150 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
{ text: 'Print PDF', tooltipText: 'Print PDF', id: 'PrintPDFCustom' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
mainGrid.obj.autoFitColumns(['number', 'countDate', 'warehouseName', 'statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom', 'PrintPDFCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Stock Count';
resetFormState();
state.showComplexDiv = false;
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Stock Count';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.countDate = selectedRecord.countDate ? new Date(selectedRecord.countDate) : null;
state.description = selectedRecord.description ?? '';
state.warehouseId = selectedRecord.warehouseId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = true;
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Stock Count?';
state.id = selectedRecord.id ?? '';
state.number = selectedRecord.number ?? '';
state.countDate = selectedRecord.countDate ? new Date(selectedRecord.countDate) : null;
state.description = selectedRecord.description ?? '';
state.warehouseId = selectedRecord.warehouseId ?? '';
state.status = String(selectedRecord.status ?? '');
await methods.populateSecondaryData(selectedRecord.id);
secondaryGrid.refresh();
state.showComplexDiv = false;
mainModal.obj.show();
}
}
if (args.item.id === 'PrintPDFCustom') {
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
window.open('/StockCounts/StockCountPdf?id=' + (selectedRecord.id ?? ''), '_blank');
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const secondaryGrid = {
obj: null,
create: async (dataSource) => {
secondaryGrid.obj = new ej.grids.Grid({
height: 400,
dataSource: dataSource,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, showDeleteConfirmDialog: true, mode: 'Normal', allowEditOnDblClick: true },
allowFiltering: false,
allowSorting: true,
allowSelection: true,
allowGrouping: false,
allowTextWrap: true,
allowResizing: true,
allowPaging: false,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'productName', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: false,
showColumnMenu: false,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{
field: 'productId',
headerText: 'Product',
width: 250,
validationRules: { required: true },
disableHtmlEncode: false,
valueAccessor: (field, data, column) => {
const product = state.productListLookupData.find(item => item.id === data[field]);
return product ? `${product.numberName}` : '';
},
editType: 'dropdownedit',
edit: {
create: () => {
productElem = document.createElement('input');
return productElem;
},
read: () => {
return productObj.value;
},
destroy: function () {
productObj.destroy();
},
write: function (args) {
productObj = new ej.dropdowns.DropDownList({
dataSource: state.productListLookupData,
fields: { value: 'id', text: 'name' },
value: args.rowData.productId,
change: function (e) {
if (qtySCCountObj) {
qtySCCountObj.value = 1;
}
},
placeholder: 'Select a Product',
floatLabelType: 'Never'
});
productObj.appendTo(productElem);
}
}
},
{ field: 'qtySCSys', headerText: 'System Stock', width: 100, allowEditing: false, type: 'number', format: 'N2', textAlign: 'Right'},
{
field: 'qtySCCount',
headerText: 'Counted',
width: 200,
validationRules: {
required: true,
custom: [(args) => {
return args['value'] >= 0;
}, 'Must be a non-negative number']
},
type: 'number', format: 'N2', textAlign: 'Right',
edit: {
create: () => {
qtySCCountElem = document.createElement('input');
return qtySCCountElem;
},
read: () => {
return qtySCCountObj.value;
},
destroy: function () {
qtySCCountObj.destroy();
},
write: function (args) {
qtySCCountObj = new ej.inputs.NumericTextBox({
value: args.rowData.qtySCCount ?? 0,
});
qtySCCountObj.appendTo(qtySCCountElem);
}
}
},
{ field: 'qtySCDelta', headerText: 'Adjustment', width: 100, allowEditing: false, type: 'number', format: '+0.00;-0.00;0.00', textAlign: 'Right' },
],
toolbar: [
'ExcelExport',
{ type: 'Separator' },
'Add', 'Edit', 'Delete', 'Update', 'Cancel',
],
beforeDataBound: () => { },
dataBound: function () { },
excelExportComplete: () => { },
rowSelected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], false);
}
},
rowDeselected: () => {
if (secondaryGrid.obj.getSelectedRecords().length == 1) {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], true);
} else {
secondaryGrid.obj.toolbarModule.enableItems(['SecondaryGrid_edit'], false);
}
},
rowSelecting: () => {
if (secondaryGrid.obj.getSelectedRecords().length) {
secondaryGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'SecondaryGrid_excelexport') {
secondaryGrid.obj.excelExport();
}
},
actionComplete: async (args) => {
if (args.requestType === 'save' && args.action === 'add') {
try {
const response = await services.createSecondaryData(state.id, args.data.productId, args.data.qtySCCount, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Save Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'save' && args.action === 'edit') {
try {
const response = await services.updateSecondaryData(args.data.id, args.data.productId, args.data.qtySCCount, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Update Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Update Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
if (args.requestType === 'delete') {
try {
const response = await services.deleteSecondaryData(args.data[0].id, StorageManager.getUserId());
await methods.populateSecondaryData(state.id);
secondaryGrid.refresh();
if (response.data.code === 200) {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
timer: 2000,
showConfirmButton: false
});
} else {
Swal.fire({
icon: 'error',
title: 'Delete Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
}
}
methods.refreshSummary();
}
});
secondaryGrid.obj.appendTo(secondaryGridRef.value);
},
refresh: () => {
secondaryGrid.obj.setProperties({ dataSource: state.secondaryData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
secondaryGridRef,
countDateRef,
warehouseIdRef,
statusRef,
numberRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,220 @@
@page
@attribute [Authorize(Roles = "StockCounts")]
@{
ViewData["Title"] = "Stock Count PDF";
}
<div id="app" class="row">
<div class="col-12">
<div class="print-indicator" v-cloak>
<div class="content-wrapper">
<div>
<button id="download-pdf" class="btn btn-danger d-flex align-items-center" v-on:click="handler.downloadPDF" v-bind:disabled="state.isDownloading">
<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true" v-if="state.isDownloading"></span>
<span class="button-text" v-if="!state.isDownloading">
<i class="bi bi-file-earmark-pdf-fill me-2"></i> Download PDF
</span>
</button>
</div>
<div id="content" class="print-area">
<div class="company-info">
<h2>{{ state.company.name }}</h2>
<p>{{ state.companyAddress }}</p>
<p>Email: {{ state.company.emailAddress }} | Phone: {{ state.company.phoneNumber }}</p>
</div>
<h1>Stock Count</h1>
<div class="info-container">
<table class="details-table">
<tr>
<th colspan="2">Warehouse Information</th>
</tr>
<tr>
<td><strong>Warehouse:</strong></td>
<td>{{ state.warehouse }}</td>
</tr>
<tr>
<td><strong></strong></td>
<td>_</td>
</tr>
</table>
<table class="details-table">
<tr>
<th colspan="2">Stock Count Information</th>
</tr>
<tr>
<td><strong>Number:</strong></td>
<td>{{ state.number }}</td>
</tr>
<tr>
<td><strong>Date:</strong></td>
<td>{{ state.date }}</td>
</tr>
</table>
</div>
<table class="product-table" border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>Product</th>
<th>System Stock</th>
<th>Counted</th>
<th>Adjustment</th>
</tr>
</thead>
<tbody>
<tr v-for="item in state.mappedItems" :key="item.product">
<td>{{ item.product }}</td>
<td>{{ item.systemStock }}</td>
<td>{{ item.counted }}</td>
<td>{{ item.adjustment }}</td>
</tr>
</tbody>
</table>
<div class="summary">
<div class="column"></div>
<div class="column">
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
<tr>
<td style="font-weight: bold; font-size: 1.2em;">Total Counted:</td>
<td style="text-align: right; font-weight: bold; font-size: 1.2em; color: #2c3e50;">
{{ state.movementTotal }}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- CSS -->
<style>
.print-indicator {
display: flex;
justify-content: center;
align-items: flex-start;
height: 100vh;
background-color: #f8f9fa;
position: relative;
overflow-y: auto;
padding: 30px;
}
.content-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.print-area {
width: 210mm;
padding: 10mm;
background-color: white;
border: 1px dashed #cccccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#download-pdf {
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.company-info {
text-align: center;
margin-bottom: 20px;
}
.company-info h2 {
font-size: 24px;
margin: 0;
}
.company-info p {
margin: 5px 0;
font-size: 14px;
color: #555;
}
h1 {
text-align: center;
margin-bottom: 20px;
font-size: 28px;
color: #333;
}
.info-container {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
gap: 10px;
}
.details-table {
flex: 1;
padding: 5px 8px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th, .details-table td {
padding: 5px 10px;
border: 1px solid #ccc;
font-size: 14px;
}
.details-table th {
background-color: #f2f2f2;
text-align: left;
height: 35px;
vertical-align: middle;
}
.product-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
font-size: 14px;
}
.product-table th, .product-table td {
padding: 8px;
text-align: left;
}
.product-table th {
background-color: #f2f2f2;
}
.summary {
display: flex;
justify-content: space-between;
margin-top: 20px;
font-size: 14px;
}
.summary .column {
width: 48%;
}
.summary p {
margin: 5px 0;
text-align: right;
}
</style>
@section scripts {
<script src="~/FrontEnd/Pages/StockCounts/StockCountPdf.cshtml.js"></script>
}
@@ -0,0 +1,132 @@
const App = {
setup() {
const state = Vue.reactive({
company: {
name: '',
emailAddress: '',
phoneNumber: '',
street: '',
city: '',
state: '',
zipCode: '',
country: ''
},
companyAddress: '',
warehouse: '',
number: '',
date: '',
pdfTransactionList: [],
isDownloading: false,
mappedItems: [],
movementTotal: 0
});
const services = {
getPDFData: async (id) => {
try {
const response = await AxiosManager.get('/StockCount/GetStockCountSingle?id=' + id, {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populatePDFData: async (id) => {
const response = await services.getPDFData(id);
state.pdfData = response?.data?.content?.data || {};
state.pdfTransactionList = response?.data?.content?.transactionList || [];
methods.bindPDFControls();
},
bindPDFControls: () => {
const company = StorageManager.getCompany() || state.company;
state.company = {
name: company.name,
emailAddress: company.emailAddress,
phoneNumber: company.phoneNumber,
street: company.street,
city: company.city,
state: company.state,
zipCode: company.zipCode,
country: company.country
};
state.companyAddress = [
company.street,
company.city,
company.state,
company.zipCode,
company.country
].filter(Boolean).join(', ');
const pdfData = state.pdfData;
state.warehouse = pdfData?.warehouse?.name || '';
state.number = pdfData?.number || '';
state.date = DateFormatManager.formatToLocale(pdfData?.countDate) || '';
state.mappedItems = (state.pdfTransactionList || []).map(item => ({
product: `${item.product?.number || ''} ${item.product?.name || ''}`.trim(),
systemStock: item.qtySCSys || 0,
counted: item.qtySCCount || 0,
adjustment: item.stock || 0,
}));
let movementTotal = (state.pdfTransactionList || []).reduce((sum, item) => sum + (item.qtySCCount || 0), 0);
state.movementTotal = NumberFormatManager.formatToLocale(movementTotal);
}
};
const handler = {
downloadPDF: async () => {
state.isDownloading = true;
await new Promise(resolve => setTimeout(resolve, 500));
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF('p', 'mm', 'a4');
const content = document.getElementById('content');
await html2canvas(content, {
scale: 2,
useCORS: true
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210;
const pageHeight = 297;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let position = 0;
doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
doc.save(`stock-count-${state.number || 'unknown'}.pdf`);
});
} catch (error) {
console.error('Error generating PDF:', error);
} finally {
state.isDownloading = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['StockCounts']);
var urlParams = new URLSearchParams(window.location.search);
var id = urlParams.get('id');
await methods.populatePDFData(id ?? '');
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,19 @@
@page
@attribute [Authorize(Roles = "StockReports")]
@{
ViewData["Title"] = "Stock Report List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/StockReports/StockReportList.cshtml.js"></script>
}
@@ -0,0 +1,141 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: []
});
const mainGridRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/InventoryTransaction/GetInventoryStockList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc),
movementDate: new Date(item.movementDate)
}));
},
onMainModalHidden: () => {
}
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['StockReports']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
groupSettings: {
columns: ['productName']
},
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'warehouseName', headerText: 'Warehouse', width: 200 },
{ field: 'productName', headerText: 'Product Name', width: 200 },
{ field: 'productNumber', headerText: 'Product Number', width: 200 },
{ field: 'stock', headerText: 'Stock', width: 150, type: 'number', format: '+0.00;-0.00;0.00', textAlign: 'Right' },
{ field: 'statusName', headerText: 'Status', width: 100 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
aggregates: [
{
columns: [
{
type: 'Sum',
field: 'stock',
groupCaptionTemplate: 'Stock: ${Sum}',
format: 'N2'
}
]
}
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.autoFitColumns(['statusName', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
} else {
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
} else {
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
return {
mainGridRef,
state,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,77 @@
@page
@attribute [Authorize(Roles = "Taxs")]
@{
ViewData["Title"] = "Tax List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Tax Info</h5>
</div>
<div class="card-body">
<div class="row mb-3">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" type="text" v-model="state.name">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
<div class="col-md-6">
<label for="Percentage">Percentage</label>
<input ref="percentageRef" type="number" step="0.01" v-model="state.percentage">
<label class="text-danger">{{ state.errors.percentage }}</label>
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<label for="Description">Description</label>
<textarea id="Description" v-model="state.description" class="form-control" rows="3"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Taxs/TaxList.cshtml.js"></script>
}
@@ -0,0 +1,356 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
percentage: '',
description: '',
errors: {
name: '',
percentage: '',
description: ''
},
isSubmitting: false,
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const percentageRef = Vue.ref(null);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Tax/GetTaxList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, percentage, description, createdById) => {
try {
const response = await AxiosManager.post('/Tax/CreateTax', {
name, percentage, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, percentage, description, updatedById) => {
try {
const response = await AxiosManager.post('/Tax/UpdateTax', {
id, name, percentage, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Tax/DeleteTax', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
const formattedData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
state.mainData = formattedData;
}
};
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{
field: 'percentage',
headerText: 'Percentage',
width: 100,
minWidth: 100,
format: 'N2'
},
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'percentage', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length === 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Tax';
state.id = '';
state.name = '';
state.percentage = '';
state.description = '';
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Tax';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.percentage = selectedRecord.percentage ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Tax?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.percentage = selectedRecord.percentage ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const percentageText = {
obj: null,
create: () => {
percentageText.obj = new ej.inputs.NumericTextBox({
placeholder: 'Enter Percentage',
format: 'n2',
min: 0,
max: 100,
step: 0.01,
});
percentageText.obj.appendTo(percentageRef.value);
},
refresh: () => {
if (percentageText.obj) {
percentageText.obj.value = parseFloat(state.percentage);
}
}
};
const validateForm = function () {
state.errors.name = '';
state.errors.percentage = '';
state.errors.description = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!state.percentage || isNaN(parseFloat(state.percentage))) {
state.errors.percentage = 'Percentage is required and must be a number.';
isValid = false;
} else if (parseFloat(state.percentage) < 0 || parseFloat(state.percentage) > 100) {
state.errors.percentage = 'Percentage must be between 0 and 100.';
isValid = false;
}
return isValid;
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.percentage, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.percentage, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.percentage,
(newVal, oldVal) => {
state.errors.percentage = '';
percentageText.refresh();
}
);
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Taxs']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
nameText.create();
percentageText.create();
mainModal.create();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
return {
mainGridRef,
mainModalRef,
nameRef,
percentageRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,77 @@
@page
@attribute [Authorize(Roles = "TodoItems")]
@{
ViewData["Title"] = "Todo Item List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" aria-hidden="true" tabindex="-1" data-bs-focus="false" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<input type="hidden" v-model="state.id" id="Id" name="Id" />
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
<div class="col-md-6">
<label for="TodoId">Todo</label>
<div ref="todoIdRef"></div>
<label class="text-danger">{{ state.errors.todoId }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/TodoItems/TodoItemList.cshtml.js"></script>
}
@@ -0,0 +1,405 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
todoListLookupData: [],
mainTitle: null,
id: '',
name: '',
todoId: null,
description: '',
errors: {
name: '',
todoId: ''
},
isSubmitting: false
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const todoIdRef = Vue.ref(null);
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
const todoListLookup = {
obj: null,
create: () => {
if (state.todoListLookupData && Array.isArray(state.todoListLookupData)) {
todoListLookup.obj = new ej.dropdowns.DropDownList({
dataSource: state.todoListLookupData,
fields: { value: 'id', text: 'name' },
placeholder: 'Select a Todo',
popupHeight: '200px',
change: (e) => {
state.todoId = e.value;
}
});
todoListLookup.obj.appendTo(todoIdRef.value);
} else {
console.error('Todo list lookup data is not available or invalid.');
}
},
refresh: () => {
if (todoListLookup.obj) {
todoListLookup.obj.value = state.todoId;
}
},
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
Vue.watch(
() => state.todoId,
(newVal, oldVal) => {
state.errors.todoId = '';
todoListLookup.refresh();
}
);
const validateForm = function () {
state.errors.name = '';
state.errors.todoId = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
if (!state.todoId) {
state.errors.todoId = 'Todo is required.';
isValid = false;
}
return isValid;
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.todoId = null;
state.description = '';
state.errors = {
name: '',
todoId: ''
};
};
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/TodoItem/GetTodoItemList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, todoId, description, createdById) => {
try {
const response = await AxiosManager.post('/TodoItem/CreateTodoItem', {
name, todoId, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, todoId, description, updatedById) => {
try {
const response = await AxiosManager.post('/TodoItem/UpdateTodoItem', {
id, name, todoId, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/TodoItem/DeleteTodoItem', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
getTodoListLookupData: async () => {
try {
const response = await AxiosManager.get('/Todo/GetTodoList', {});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateTodoListLookupData: async () => {
const response = await services.getTodoListLookupData();
state.todoListLookupData = response?.data?.content?.data;
},
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.todoId, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.todoId, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
if (!state.deleteMode) {
state.mainTitle = 'Edit Todo Item';
state.id = response?.data?.content?.data.id ?? '';
state.name = response?.data?.content?.data.name ?? '';
state.todoId = response?.data?.content?.data.todoId ?? '';
state.description = response?.data?.content?.data.description ?? '';
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'success',
title: 'Delete Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
resetFormState();
}, 2000);
}
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['TodoItems']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await methods.populateTodoListLookupData();
todoListLookup.create();
nameText.create();
mainModal.create();
mainModalRef.value?.addEventListener('hidden.bs.modal', () => {
resetFormState();
});
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
Vue.onUnmounted(() => {
mainModalRef.value?.removeEventListener('hidden.bs.modal', resetFormState);
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'todoName', headerText: 'Todo', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'todoName', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: async (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Todo Item';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Todo Item';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.todoId = selectedRecord.todoId ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Todo Item?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.todoId = selectedRecord.todoId ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
return {
mainGridRef,
mainModalRef,
nameRef,
todoIdRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,71 @@
@page
@attribute [Authorize(Roles = "Todos")]
@{
ViewData["Title"] = "Todo List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
<div class="modal fade" ref="mainModalRef" id="MainModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ state.mainTitle }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="MainForm">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h5>Main Info</h5>
</div>
<div class="card-body">
<div class="row mb-2">
<div class="col-md-6">
<label for="Name">Name</label>
<input ref="nameRef" v-model="state.name">
<label class="text-danger">{{ state.errors.name }}</label>
</div>
</div>
<div class="row mb-2">
<div class="col-12">
<label for="Description">Description</label>
<textarea v-model="state.description" id="Description" name="Description" class="form-control" rows="3"></textarea>
<label class="text-danger">{{ state.errors.description }}</label>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button"
id="MainSaveButton"
class="btn"
v-bind:class="state.deleteMode ? 'btn-danger' : 'btn-primary'"
v-on:click="handler.handleSubmit"
v-bind:disabled="state.isSubmitting">
<span class="spinner-border spinner-border-sm me-2" v-if="state.isSubmitting" role="status" aria-hidden="true"></span>
<span v-if="!state.isSubmitting">{{ state.deleteMode ? 'Delete' : 'Save' }}</span>
<span v-else>{{ state.deleteMode ? 'Deleting...' : 'Saving...' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/Todos/TodoList.cshtml.js"></script>
}
@@ -0,0 +1,314 @@
const App = {
setup() {
const state = Vue.reactive({
mainData: [],
deleteMode: false,
mainTitle: null,
id: '',
name: '',
description: '',
errors: {
name: '',
description: ''
},
isSubmitting: false,
});
const mainGridRef = Vue.ref(null);
const mainModalRef = Vue.ref(null);
const nameRef = Vue.ref(null);
const nameText = {
obj: null,
create: () => {
nameText.obj = new ej.inputs.TextBox({
placeholder: 'Enter Name',
});
nameText.obj.appendTo(nameRef.value);
},
refresh: () => {
if (nameText.obj) {
nameText.obj.value = state.name;
}
}
};
Vue.watch(
() => state.name,
(newVal, oldVal) => {
state.errors.name = '';
nameText.refresh();
}
);
const services = {
getMainData: async () => {
try {
const response = await AxiosManager.get('/Todo/GetTodoList', {});
return response;
} catch (error) {
throw error;
}
},
createMainData: async (name, description, createdById) => {
try {
const response = await AxiosManager.post('/Todo/CreateTodo', {
name, description, createdById
});
return response;
} catch (error) {
throw error;
}
},
updateMainData: async (id, name, description, updatedById) => {
try {
const response = await AxiosManager.post('/Todo/UpdateTodo', {
id, name, description, updatedById
});
return response;
} catch (error) {
throw error;
}
},
deleteMainData: async (id, deletedById) => {
try {
const response = await AxiosManager.post('/Todo/DeleteTodo', {
id, deletedById
});
return response;
} catch (error) {
throw error;
}
},
};
const methods = {
populateMainData: async () => {
const response = await services.getMainData();
state.mainData = response?.data?.content?.data.map(item => ({
...item,
createdAtUtc: new Date(item.createdAtUtc)
}));
},
};
const handler = {
handleSubmit: async function () {
try {
state.isSubmitting = true;
await new Promise(resolve => setTimeout(resolve, 300));
if (!validateForm()) {
return;
}
const response = state.id === ''
? await services.createMainData(state.name, state.description, StorageManager.getUserId())
: state.deleteMode
? await services.deleteMainData(state.id, StorageManager.getUserId())
: await services.updateMainData(state.id, state.name, state.description, StorageManager.getUserId());
if (response.data.code === 200) {
await methods.populateMainData();
mainGrid.refresh();
Swal.fire({
icon: 'success',
title: state.deleteMode ? 'Delete Successful' : 'Save Successful',
text: 'Form will be closed...',
timer: 2000,
showConfirmButton: false
});
setTimeout(() => {
mainModal.obj.hide();
}, 2000);
} else {
Swal.fire({
icon: 'error',
title: state.deleteMode ? 'Delete Failed' : 'Save Failed',
text: response.data.message ?? 'Please check your data.',
confirmButtonText: 'Try Again'
});
}
} catch (error) {
Swal.fire({
icon: 'error',
title: 'An Error Occurred',
text: error.response?.data?.message ?? 'Please try again.',
confirmButtonText: 'OK'
});
} finally {
state.isSubmitting = false;
}
},
};
const validateForm = function () {
state.errors.name = '';
state.errors.description = '';
let isValid = true;
if (!state.name) {
state.errors.name = 'Name is required.';
isValid = false;
}
return isValid;
};
Vue.onMounted(async () => {
try {
await SecurityManager.authorizePage(['Todos']);
await SecurityManager.validateToken();
await methods.populateMainData();
await mainGrid.create(state.mainData);
await mainModal.create();
nameText.create();
} catch (e) {
console.error('page init error:', e);
} finally {
}
});
const mainGrid = {
obj: null,
create: async (dataSource) => {
mainGrid.obj = new ej.grids.Grid({
height: '240px',
dataSource: dataSource,
allowFiltering: true,
allowSorting: true,
allowSelection: true,
allowGrouping: true,
allowTextWrap: true,
allowResizing: true,
allowPaging: true,
allowExcelExport: true,
filterSettings: { type: 'CheckBox' },
sortSettings: { columns: [{ field: 'createdAtUtc', direction: 'Descending' }] },
pageSettings: { currentPage: 1, pageSize: 50, pageSizes: ["10", "20", "50", "100", "200", "All"] },
selectionSettings: { persistSelection: true, type: 'Single' },
autoFit: true,
showColumnMenu: true,
gridLines: 'Horizontal',
columns: [
{ type: 'checkbox', width: 60 },
{
field: 'id', isPrimaryKey: true, headerText: 'Id', visible: false
},
{ field: 'name', headerText: 'Name', width: 200, minWidth: 200 },
{ field: 'description', headerText: 'Description', width: 400, minWidth: 400 },
{ field: 'createdAtUtc', headerText: 'Created At UTC', width: 150, format: 'yyyy-MM-dd HH:mm' }
],
toolbar: [
'ExcelExport', 'Search',
{ type: 'Separator' },
{ text: 'Add', tooltipText: 'Add', prefixIcon: 'e-add', id: 'AddCustom' },
{ text: 'Edit', tooltipText: 'Edit', prefixIcon: 'e-edit', id: 'EditCustom' },
{ text: 'Delete', tooltipText: 'Delete', prefixIcon: 'e-delete', id: 'DeleteCustom' },
{ type: 'Separator' },
],
beforeDataBound: () => { },
dataBound: function () {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
mainGrid.obj.autoFitColumns(['name', 'description', 'createdAtUtc']);
},
excelExportComplete: () => { },
rowSelected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowDeselected: () => {
if (mainGrid.obj.getSelectedRecords().length == 1) {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], true);
} else {
mainGrid.obj.toolbarModule.enableItems(['EditCustom', 'DeleteCustom'], false);
}
},
rowSelecting: () => {
if (mainGrid.obj.getSelectedRecords().length) {
mainGrid.obj.clearSelection();
}
},
toolbarClick: (args) => {
if (args.item.id === 'MainGrid_excelexport') {
mainGrid.obj.excelExport();
}
if (args.item.id === 'AddCustom') {
state.deleteMode = false;
state.mainTitle = 'Add Todo';
resetFormState();
mainModal.obj.show();
}
if (args.item.id === 'EditCustom') {
state.deleteMode = false;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Edit Todo';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
if (args.item.id === 'DeleteCustom') {
state.deleteMode = true;
if (mainGrid.obj.getSelectedRecords().length) {
const selectedRecord = mainGrid.obj.getSelectedRecords()[0];
state.mainTitle = 'Delete Todo?';
state.id = selectedRecord.id ?? '';
state.name = selectedRecord.name ?? '';
state.description = selectedRecord.description ?? '';
mainModal.obj.show();
}
}
}
});
mainGrid.obj.appendTo(mainGridRef.value);
},
refresh: () => {
mainGrid.obj.setProperties({ dataSource: state.mainData });
}
};
const mainModal = {
obj: null,
create: () => {
mainModal.obj = new bootstrap.Modal(mainModalRef.value, {
backdrop: 'static',
keyboard: false
});
}
};
const resetFormState = () => {
state.id = '';
state.name = '';
state.description = '';
state.errors = {
name: '',
description: ''
};
};
return {
mainGridRef,
mainModalRef,
nameRef,
state,
handler,
};
}
};
Vue.createApp(App).mount('#app');
@@ -0,0 +1,19 @@
@page
@attribute [Authorize(Roles = "TransactionReports")]
@{
ViewData["Title"] = "Transaction Report List";
}
<div id="app" v-cloak>
<div class="row">
<div class="col-12">
<div class="grid-container">
<div ref="mainGridRef"></div>
</div>
</div>
</div>
</div>
@section scripts {
<script src="~/FrontEnd/Pages/TransactionReports/TransactionReportList.cshtml.js"></script>
}

Some files were not shown because too many files have changed in this diff Show More