View
@{
Layout = "~/Views/Shared/_LayoutPageAdmin.cshtml";
}
@section Styles
{
<link rel="stylesheet" href="~/assets/vendor/pnotify/pnotify.custom.css" />
<link rel="stylesheet" href="~/assets/vendor/pnotify/pnotify.custom.sw.css" />
<link rel="stylesheet" href="~/assets/stylesheets/Module/MultiSelectBox/multiselectbox.css" />
<link rel="stylesheet" href="~/DataTables/datatables.min.css" />
<style type="text/css">
/* css on 29-4-2020 */
body {
color: #131111 !important;
}
.panel-accordion {
box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, .45);
}
.panel-body {
padding: 0px 0px 0px 2px!important;
}
table {
font-size: 14px !important;
border-radius: 5px;
}
label.control-label {
color: #131111 !important;
font-size: 14px !important;
}
input {
color: inherit !important;
font-size: inherit !important;
}
.actioncell .btn {
border-radius: 11px !important;
}
table > thead > tr > th {
color: #191919 !important;
}
.module {
min-height: 75vh;
margin-right: 2px;
margin-left: 2px;
margin-top: 2px;
border-radius: 4px;
background: RGBA(255, 255, 255, 1);
-webkit-box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, .45);
box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, .45);
}
#exTab3 {
padding-top:5px;
}
.panel-accordion {
box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, .45);
}
td.prrow {
padding: 6px !important;
}
/* Numeric Columnc for reports */
.NumericCol {
text-align: right;
}
th.dt-center, td.dt-center {
text-align: center;
}
table.dataTable thead .sorting::after,
table.dataTable thead .sorting_asc::after {
display: none;
}
table.dataTable thead .sorting_desc::after {
display: none;
}
table.dataTable thead .sorting {
background-image: url(https://datatables.net/media/images/sort_both.png);
background-repeat: no-repeat;
background-position: center right;
}
table.dataTable thead .sorting_asc {
background-image: url(https://datatables.net/media/images/sort_asc.png);
background-repeat: no-repeat;
background-position: center right;
}
table.dataTable thead .sorting_desc {
background-image: url(https://datatables.net/media/images/sort_desc.png);
background-repeat: no-repeat;
background-position: center right;
}
.vtop {
vertical-align: top !important;
}
div.dataTables_wrapper div.dataTables_filter {
text-align: center;
}
div.dataTables_wrapper div.dataTables_length select {
margin-right: 6px;
margin-left: 6px;
cursor: pointer;
}
div.dataTables_wrapper div.dataTables_processing {
border-radius: 100px;
top: 0%;
margin-top: 10%;
width: 168px;
font-size: 15px;
padding: 0.7em 0;
}
.dataTables_wrapper table {
width: 100% !important;
}
.dataTables_wrapper table thead th {
padding: 7px !important;
text-align: center;
}
div.dataTables_wrapper div.dataTables_paginate {
cursor: pointer;
}
.pagingrow {
margin-top: 25px;
}
.searchrow {
margin-top: 4px;
margin-bottom: 7px;
}
div.dataTables_wrapper div.dataTables_info {
padding-top: 2px;
}
.form-group:last-child, .form-group:last-of-type {
margin-bottom: 15px;
}
@@media (min-width: 768px) {
.pt-sm-c3, .py-sm-c3 {
padding-top: 0.59rem !important;
}
}
.table {
table-layout: fixed;
}
.drafticon {
font-size: 15px;
color: rgb(222, 80, 10);
}
.submittedicon {
font-size: 15px;
color: green;
}
.withdrawnicon {
font-size: 15px;
color: #de500a;
}
.cancelledicon {
font-size: 15px;
color: #d2322d;
}
.queryicon {
font-size: 15px;
color: #e66519;
}
.queryresponseicon {
font-size: 15px;
color: #47a447;
}
.pendingtradericon {
font-size: 15px;
color: #979c9c;
}
.pendingicon {
font-size: 15px;
color: #49b6bb;
}
.btnPrintapplication {
padding: 1px 6px;
}
.btnEditapplication {
padding: 1px 6px;
background-color: #1f9bbf !important;
border-color: #1f9bbf !important;
}
.btnEditinvoice, .btnEditproduct {
padding: 1px 6px;
background-color: #1f9bbf !important;
border-color: #1f9bbf !important;
}
.btnCopyinvoice, .btnCopyproduct {
padding: 1px 6px;
}
.btnDeleteinvoice, .btnDeleteproduct {
padding: 1px 6px;
background-color: #ec4b46 !important;
border-color: #ec4b46 !important;
}
.btnChangeVehicle {
padding: 1px 6px;
background-color: #ec4b46 !important;
border-color: #ec4b46 !important;
}
.btnCopyapplication {
padding: 1px 6px;
}
.enablepopover {
pointer-events: auto !important;
}
@@media(min-width: 768px) {
#changevehiclemodal {
width: 450px;
}
}
</style>
}
<div id="bg">
<input type="hidden" value="@Convert.ToString(Session["Role"])" id="HdnRole" />
<input type="hidden" value="@Convert.ToString(Session["ID"])" id="HdnID" />
<input type="hidden" value="@Convert.ToString(Session["UserName"])" id="HdnUserName" />
<input type="hidden" value="@Convert.ToString(Session["OGAType"])" id="HdnOGAType" />
<input type="hidden" id="HdnOperationMode" value="@ViewBag.OperationMode" />
<input type="hidden" id="HdnRulesId" value="@ViewBag.RulesId" />
<input type="hidden" id="currentpage" value="Risk Management" />
<div class="module">
<div id="exTab3" class="">
<div class="row">
<div class="col-sm-12 px-sm-4">
<div class="tab-content px-sm-5 py-sm-3 ml-sm-1" style="border-radius:4px;border:0px;box-shadow:0px 0px 0px 0px;">
@*Fee Management*@
<div class="py-sm-4 px-sm-4" style="padding-top:0.4rem!important;">
<div class="row" id="form1">
<form class="form-horizontal" novalidate="novalidate">
<div class="form-group col-lg-4">
<div class="col-lg-4">
<label class="ml-sm-0 px-sm-0 pt-sm-3 control-label text-left" for="ddlCondition">
Condition/If
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-sm-8 pt-sm-2">
<select class="form-control" name="ddlCondition" id="ddlCondition">
<option value="">Choose Option</option>
<option value="T">Trader</option>
<option value="IN">Importer Name</option>
<option value="IC">Import Country Name</option>
<option value="IT">IECode</option>
<option value="EN">Exporter Name</option>
<option value="EC">Export Country Name</option>
<option value="CD">HS Code</option>
<option value="MOD">Mode Of Transport</option>
</select>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-3 col-md-3 col-sm-12 mb-sm-3">
<div class="col-lg-4 col-md-4 col-sm-3 pl-sm-2 pr-sm-0 flex">
<label class="ml-sm-0 px-sm-0 pt-sm-3 control-label text-left" for="ddlOperator">
Operator
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-sm-8 pt-sm-2">
<select class="form-control" name="ddlOperator" id="ddlOperator">
<option value="">Choose Option</option>
<option value="Equal">Equal</option>
<option value="NotEqual">Not Equal</option>
</select>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-3 col-md-3 col-sm-12 mb-sm-3">
<div class="col-lg-3 col-md-4 col-sm-3 pl-sm-2 pr-sm-0 flex">
<label class="ml-sm-0 px-sm-0 pt-sm-3 control-label text-left" for="servicetype">
Value
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-sm-8 pt-sm-2">
<div id="dvDdlVaue" style="display:block;">
@Html.DropDownList("ddlvalue", new SelectList("", "0", "Select"), new { @class = "form-control", @perror = "next" })
</div>
</div>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
<div class="form-group col-lg-3">
<div class="col-lg-5 flex" style="padding-right:0px!important;">
<label class="ml-sm-0 control-label text-left" for="ddlChannel">
Channel <span class="required pt-sm-c3 pl-sm-2">*</span>
</label>
</div>
<div class="col-lg-7 pt-sm-2" style="padding-left:0px!important;">
<select class="form-control" name="ddlChannel" id="ddlChannel">
<option value="">Choose Option</option>
<option value="Green">Green</option>
<option value="Yellow">Yellow</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
</select>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-4 col-md-4 col-sm-12 mb-sm-3">
<div class="col-lg-4">
<label class="ml-sm-0 px-sm-0 control-label text-left" for="SpecialActions">
Special Actions
</label>
</div>
<div class="col-lg-8">
<textarea type="text" id="SpecialActions" cols="30" rows="2"></textarea>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-4 col-md-4 col-sm-12 mb-sm-3">
<div class="col-lg-4">
<label class="ml-sm-0 px-sm-0 control-label text-left" for="RuleName">
Rule Name
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-lg-8">
<input type="text" id="RuleName" name="RuleName" class="form-control" />
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
</form>
</div>
<div class="row">
<div class="col-lg-offset-9">
<button type="button" class="px-sm-5 mr-sm-4 my-sm-2 btn btn-primary SaveConfiguration">
Add rule
</button>
<button type="button" class="px-sm-5 my-sm-2 btn btn-warning CancelConfiguration">
Cancel
</button>
</div>
</div>
<div class="panel-body pb-sm-3">
<div class="col-md-5">
<div class="form-group">
<label class="control-label">Created Date Range</label>
<div class="input-daterange input-group" data-plugin-datepicker data-plugin-options='{"format":"mm/dd/yyyy","autoclose": true}'>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
<input type="text" class="form-control" name="start" id="StartDate" onkeydown="Allowonlytab()"
data-trigger="manual" data-toggle="popover" data-container="body" data-placement="top" data-content="Please Enter Valid Start Date">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" name="end" id="EndDate" onkeydown="Allowonlytab()"
data-trigger="manual" data-toggle="popover" data-container="body" data-placement="top" data-content="Please Enter Valid End Date">
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="control-label">Rule Name</label>
<input type="text" class="form-control input-sm" name="SearchRuleName" id="SearchRuleName" autocomplete="off">
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="padding-top:25px;">
<button type="button" class="btn btn-warning ClearSearch"><i class="fas fa-redo" aria-hidden="true"></i> Clear</button>
<button type="button" style="" class="ml-sm-4 btn btn-primary DeferLoad"><i class="fa fa-search" aria-hidden="true"></i> View</button>
</div>
</div>
</div>
<div class="row pt-sm-2">
<div class="col-sm-12 pb-sm-3">
<table class="table table-bordered table-striped mb-none" id="InvoiceGrid"></table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modalConfirmDelete" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog modal-dialog-center" id="deletepopup">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this rule?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="modalConfirmYes">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal" id="modalConfirmNo">No</button>
</div>
</div>
</div>
</div>
</div>
@section Scripts
{
<script src="~/DataTables/datatables.min.js"></script>
<script src="~/assets/vendor/jquery-validation/jquery.validate.js"></script>
<script src="~/assets/vendor/jquery-validation/additional-methods.js"></script>
<script src="~/assets/vendor/pnotify/pnotify.custom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.20/sorting/datetime-moment.js"></script>
<script type="text/javascript">
var dformat = "DD/MM/YYYY";
var datatableinit;
var datatableindex = [] , RuleListKey=[] , RuleListValue=[];
var RuleList = @Html.Raw(Json.Encode(ViewBag.Rules));
$.each(RuleList, function (key, value) { RuleListKey.push(key) })
$.each(RuleList, function (key, value) { RuleListValue.push(value) })
//
// Pipelining function for DataTables. To be used to the `ajax` option of DataTables
//
$.fn.dataTable.pipeline = function (opts) {
// Configuration options
var conf = $.extend({
pages: 5, // number of pages to cache
url: '', // script url
data: null, // function or object with parameters to send to the server
// matching how `ajax.data` works in DataTables
method: 'POST' // Ajax HTTP method
}, opts);
// Private variables for storing the cache
var cacheLower = -1;
var cacheUpper = null;
var cacheLastRequest = null;
var cacheLastJson = null;
return function (request, drawCallback, settings) {
var ajax = false;
var requestStart = request.start;
var drawStart = request.start;
var requestLength = request.length;
var requestEnd = requestStart + requestLength;
if (settings.clearCache) {
// API requested that the cache be cleared
ajax = true;
settings.clearCache = false;
}
else if (cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper) {
// outside cached data - need to make a request
ajax = true;
}
else if (JSON.stringify(request.order) !== JSON.stringify(cacheLastRequest.order) ||
JSON.stringify(request.columns) !== JSON.stringify(cacheLastRequest.columns) ||
JSON.stringify(request.search) !== JSON.stringify(cacheLastRequest.search)
) {
// properties changed (ordering, columns, searching)
ajax = true;
}
// Store the request for checking next time around
cacheLastRequest = $.extend(true, {}, request);
if (ajax) {
// Need data from the server
if (requestStart < cacheLower) {
requestStart = requestStart - (requestLength * (conf.pages - 1));
if (requestStart < 0) {
requestStart = 0;
}
}
cacheLower = requestStart;
cacheUpper = requestStart + (requestLength * conf.pages);
request.start = requestStart;
request.length = requestLength * conf.pages;
request.createdby = $("#HdnID").val();
// Provide the same `data` options as DataTables.
if (typeof conf.data === 'function') {
// As a function it is executed with the data object as an arg
// for manipulation. If an object is returned, it is used as the
// data object to submit
var d = conf.data(request);
if (d) {
$.extend(request, d);
}
}
else if ($.isPlainObject(conf.data)) {
// As an object, the data given extends the default
$.extend(request, conf.data);
}
settings.jqXHR = $.ajax({
"type": conf.method,
"url": conf.url,
"data": request,
"dataType": "json",
"cache": false,
"success": function (json) {
cacheLastJson = $.extend(true, {}, json);
if (cacheLower != drawStart) {
json.data.splice(0, drawStart - cacheLower);
}
if (requestLength >= -1) {
json.data.splice(requestLength, json.data.length);
}
drawCallback(json);
},
"error": function (err) {
$('.dataTables_processing').hide();
ErrorBox({
"ModalTitle": "Error",
"ErrorTitle": "Application list loading Error",
"Error": "Server Connection Refused."
}, function () { });
},
"complete": function (d) {
}
});
}
else {
json = $.extend(true, {}, cacheLastJson);
json.draw = request.draw; // Update the echo for each response
json.data.splice(0, requestStart - cacheLower);
json.data.splice(requestLength, json.data.length);
drawCallback(json);
}
}
};
// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. `table.clearPipeline().draw()`)
$.fn.dataTable.Api.register('clearPipeline()', function () {
return this.iterator('table', function (settings) {
settings.clearCache = true;
});
});
Array.prototype.myJoin = function (seperator, start, end) {
if (!start) start = 0;
if (!end) end = this.length - 1;
end++;
return this.slice(start, end).join(seperator);
};
function getTime() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
return mm + '-' + dd + '-' + yyyy;
}
Date.prototype.getMonthText = function () {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return months[this.getMonth()];
}
//Helper function
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
var OperationMode = ["Insert", "Update"];
var dformat = "DD/MM/YYYY";
var hscodeorderCount = 0;
var ddl_Condition = document.getElementById("ddlCondition"),
ddl_Operator = document.getElementById("ddlOperator"),
ddl_ddlvalue = document.getElementById("ddlvalue");
ddl_Channel = document.getElementById("ddlChannel");
var TraderList = @Html.Raw(Json.Encode(ViewBag.TraderName));
var CountryList = @Html.Raw(Json.Encode(ViewBag.CountryList));
var HsCodeList = @Html.Raw(Json.Encode(ViewBag.HSCodelist));
var TransporterList = @Html.Raw(Json.Encode(ViewBag.Transporter));
$(document).ready(function () {
LoadDDrp();
$(".DeferLoad").click();
$('body').popover(popOverSettings1);
});
function LoadDDrp() {
ddl_Condition.onchange = function () {
ddl_ddlvalue.options[0] = new Option("Choose Option", "0");
ddl_ddlvalue.length = 1; // remove all options bar first
if (this.selectedIndex < 0) return; // done
if ((this.value == "IN" || this.value == "EN" || this.value =="T") && TraderList != null)
{
TraderList.forEach(function (item, index) {
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else if ((this.value == "IC" || this.value == "EC") && CountryList != null)
{
debugger;
CountryList.forEach(function (item, index)
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else if ((this.value == "CD" || this.value == "CD") && HsCodeList != null)
{
HsCodeList.forEach(function (item, index)
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else if ((this.value == "MOD" || this.value == "MOD") && TransporterList != null)
{
TransporterList.forEach(function (item, index)
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option("Select", "0");
//TransporterList.forEach(function (item, index)
//{
// ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
//});
}
}
}
$.validator.addMethod("CheckRule", function (value, element) {
var result = false;
var data = {
"mode": $('#HdnOperationMode').val(),
"RuleName": $("#RuleName").val(),
"RuleId": $("#HdnRulesId").val() == "" ? 0 : parseInt($("#HdnRulesId").val())
};
$.ajax(
{
type: 'POST',
url: config.Urls.Rule.CheckExistingRule,
dataType: "json",
data: data,
async: false,
success: function (data) {
if (!data) {
result = true;
}
},
error: function (xhr, textStatus, errorThrown) {
ErrorBox({
"ModalTitle": "Error",
"ErrorTitle": "Invoice Number Validation Error",
"Error": "Server Connection Refused."
}, function () { });
}
});
return result;
}, 'Rule Already exist.');
$(".SaveConfiguration").click(function () {
debugger;
ClearFormError();
$("#RuleName").rules("add", { CheckRule: true });
var validated = $('#form1 form').valid();
if (validated) {
AddUpdateRules();
}
else {
$form1validator.focusInvalid();
}
});
function SetActionButtonText(mode) {
if (mode == "Insert") {
$('.SaveConfiguration').text('Add');
}
else {
$('.SaveConfiguration').text('Update');
}
}
function AddUpdateRules() {
DisplayLoaderOverlay('show');
NotifyLoading({
"Ptitle": "Save in Progress..",
"PMessage": "Updating configuration please wait...",
"hide": false
}, function () { });
setTimeout(
function () {
debugger;
var mode = $('#HdnOperationMode').val();
if (OperationMode.includes(mode)) {
// Creating Form Data object
var fileData = new FormData();
// Mapping Text input to Form data
var formdata = {
OperationMode: mode,
RuleId: $("#HdnRulesId").val() == "" ? 0 : parseInt($("#HdnRulesId").val()),
Channel: $("#ddlChannel").val(),
Condition: $("#ddlCondition").val(),
Operator: $("#ddlOperator").val(),
Value: $("#ddlvalue").val(),
SpecialActions: $("#SpecialActions").val(),
ConditionName: $("#ddlCondition option:selected").text(),
RuleName: $("#RuleName").val(),
}
fileData.append('FormData', JSON.stringify(formdata));
$.ajax({
url: config.Urls.Rule.AddUpdateRules,
type: 'POST',
async: false,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: fileData,
processData: false,
contentType: false,
success: function (res) {
PNotify.removeAll();
//timer for pnotify removal
setTimeout(
function () {
if (res.ErrorStatus == 0) {
DisplayLoaderOverlay('hide');
SetActionButtonText("Insert");
OnModalExit = function () {
$(".DeferLoad").click();
};
var alertData = "New Rule Added.";
if ($("#HdnRulesId").val()!= "" && $("#HdnRulesId").val() != undefined)
{
alertData ="Rule Updated as per Request."
}
Message =
{
"ModalTitle": "Success",
"SuccessTitle":""+ alertData +"",
"Info": ''
};
SuccessBox(Message, OnModalExit);
DisplayLoaderOverlay('hide');
ClearFormError();
ResetRulesSection();
}
else if (res.ErrorStatus == 2) {
NotifyLoading({
"Ptitle": "Session Expired",
"PMessage": "Redirecting to Login Page...",
"hide": false
}, function () { });
setTimeout(
function () {
window.location.href = config.Urls.SWHome.SWLoginPage;
}, 3000)
}
else {
DisplayLoaderOverlay('hide');
ErrorBox({
"ModalTitle": "Save Error",
"ErrorTitle": "Rate Configuration Data Update Failed",
"Error": res.ErrorMessage,
}, function () {
});
}
}, 650);
},
error: function (xhr, errorType, exception) {
PNotify.removeAll();
//timer for pnotify removal
setTimeout(
function () {
DisplayLoaderOverlay('hide');
ErrorBox({
"ModalTitle": "Save Error",
"ErrorTitle": "Rate Configuration Data Update Failed",
"Error": "Server Connection Refused."
}, function () { });
}, 650)
}
});
}
else {
PNotify.removeAll();
setTimeout(
function () {
DisplayLoaderOverlay('hide');
ErrorBox({
"ModalTitle": "Save Error",
"ErrorTitle": "Rate Configuration Data Update Failed",
"Error": "Invalid Operation Mode"
}, function () { });
}, 650)
}
}, 1000)
}
$(".CancelConfiguration").click(function () {
DisplayLoaderOverlay('hide');
SetActionButtonText("Insert");
$(".CancelConfiguration").hide();
ResetRulesSection();
$("#HdnRulesId").val('');
$('#HdnOperationMode').val("Insert");
});
function ResetRulesSection() {
ClearFormError();
$("#HdnRulesId").val('');
$('#HdnOperationMode').val("Insert");
$("#ddlOperator").val('');
$("#ddlChannel").val('');
$("#SpecialActions").val('');
$("#ddlvalue").val('')
$("#ddlCondition").prop("disabled", false);
$("#ddlCondition").val('');
$("#RuleName").val('');
SetActionButtonText("Insert");
$('.SaveConfiguration').text('Add');
$('.CancelConfiguration').hide();
}
$form1validator = $("#form1 form").validate({
ignore: ".ignore",
rules: {
"ddlCondition": {
required: true
},
"ddlOperator": {
required: true
},
"ddlvalue": {
required: true
//checkvalues: true
},
"ddlChannel": {
required: true,
},
"RuleName": {
required: true,
}
},
messages: {
"ddlCondition": {
required: "Please select Condition."
},
"ddlOperator": {
required: "Please select Operator."
},
"ddlvalue": {
required: "Please select vaue."
},
"ddlChannel": {
required: "Please select channel."
},
"RuleName": {
required: "Please enter Rule."
},
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
$(element).closest('.form-group').find('.multiselectform-group').removeClass('has-success').addClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').find('.placeholder').show();
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').find('.multiselectform-group').removeClass('has-error');
$(element).remove();
},
errorPlacement: function (error, element) {
$(element).closest('.form-group').find('.placeholder').hide();
if (element.attr("perror") == "next") {
error.insertAfter('.' + element.attr("id"));
error.addClass('pl-sm-0 pt-sm-1 mt-sm-1 mb-sm-0 show');
}
else {
element.parent().append(error);
error.addClass('pl-sm-0 pt-sm-1 mt-sm-1 mb-sm-0 show');
}
}
});
$.validator.addMethod('checkvalues', function (value) {
return (GetHSCodeUpdateList() != '');
});
function ClearFormError() {
$('#form1 .placeholder').show();
$("#form1 label.error").remove();
$("#form1 .error").removeClass("error");
$("#form1 .has-error").removeClass("has-error");
}
function ParseDataTable() {
return $('#InvoiceGrid').DataTable({
dom: "<'row searchrow'<'col-sm-4 ml-sm-4'l><'col-sm-3 hidden'B>>" +
"tr" +
"<'row pagingrow'<'col-sm-5 ml-sm-4'i><'col-sm-5 mr-sm-4 fright'p>>",
buttons:
[
{
extend: 'excel',
text: 'Export',
title: '',
className: "ExportExcel",
exportOptions: {
columns: ':not(.notexport)'
},
filename: function () {
return 'Exported Excel SW _' + getTime();
},
action: function (e, dt, node, config) {
var that = this;
dt.one('draw', function () {
$.fn.dataTable.ext.buttons.excelHtml5.action.call(that, e, dt, node, config);
})
dt.page.len(dt.page.info().recordsDisplay).clearPipeline().draw();
}
},
{
extend: 'pdf',
text: 'Export',
title: '',
className: "ExportPdf",
exportOptions: {
columns: ':not(.notexport)'
},
filename: function () {
return 'Exported Pdf SW _' + getTime();
},
action: function (e, dt, node, config) {
var that = this;
dt.one('draw', function () {
$.fn.dataTable.ext.buttons.pdfHtml5.action.call(that, e, dt, node, config);
});
dt.page.len(dt.page.info().recordsDisplay).clearPipeline().draw();
}
}, {
extend: 'print',
text: 'Print',
title: '',
className: "PrintPdf",
exportOptions: {
columns: ':not(.notexport)'
},
action: function (e, dt, node, config) {
var that = this;
dt.one('draw', function () {
$.fn.dataTable.ext.buttons.print.action.call(that, e, dt, node, config);
})
dt.page.len(dt.page.info().recordsDisplay).clearPipeline().draw();
}
}
],
deferLoading: true,
responsive: true,
bAutoWidth: true,
bProcessing: true,
proccessing: true,
serverSide: true,
contentType: "application/json",
ajax: $.fn.dataTable.pipeline({
url: config.Urls.Rule.FetchRules,
pages: 5 // number of pages to cache
}),
language: {
"search": "",
"searchPlaceholder": "Search...",
"processing": "<i class='fa fa-spinner fa-spin mr-sm-4'></i>Processing"
},
order: [[1, "desc"]],
columns: [
{
data: null,
name: "Sr",
title: "Sr. No.",
render: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
},
orderable: false,
className: "dt-center prrow vtop"
},
{
data: "RuleId",
name: "RuleId",
title: "Rule Name",
className: "prrow2 vtop",
visible:false
},
{
data: "RuleName",
name: "RuleName",
title: "Rule Name",
className: "prrow2 vtop",
},
{
data: "Condition",
name: "Condition",
title: "Condition / If",
className: "prrow vtop",
orderable: false,
visible : false
},
{
data: "ConditionName",
name: "ConditionName",
title: "Condition / If",
className: "prrow vtop",
orderable: true
},
{
data: "Operator",
name: "Operator",
title: "Operator",
className: "prrow vtop"
},
{
data: "Value",
name: "Value",
title: "Value",
className: "dt-body-center prrow vtop",
visible: false
},
{
data: "Channel",
name: "Channel",
orderable: false,
title: "Channel",
className: "prrow vtop"
},
{
data: "CreatedDate",
name: "CreatedDate",
title: "Created Date",
className: "prrow vtop",
render: function (value) {
if (value === null) return "";
return moment(value).format('DD MMM YYYY');
}
},
{
data: "SpecialActions",
name: "SpecialActions",
title: "Special Action",
className: "prrow vtop"
},
{
data: null,
name: "Action",
title: "Action",
orderable: false,
render: function (row) {
return GetInvoiceAction(row);
},
className: "dt-center actioncell prrow2 vtop"
}
],
columnDefs: [
{ targets: 0, width: "6%" },
{ targets: 2, width: "15%" },
{ targets: 3, width: "20%" },
{ targets: 4, width: "15%" },
{ targets: 5, width: "10%" },
],
initComplete: function () {
}
});
}
function ClearFormError() {
$('#form1 .placeholder').show();
$("#form1 label.error").remove();
$("#form1 .error").removeClass("error");
$("#form1 .has-error").removeClass("has-error");
}
$(document).on('click', '.btnEditinvoice', function () {
SetActionButtonText("Update");
ClearFormError();
$(".CancelConfiguration").show();
var Condition = $(this).attr('Condition');
var Operator = $(this).attr('Operator');
var Value = $(this).attr('Value');
var Channel = $(this).attr('Channel');
var SpecialActions = $(this).attr('SpecialActions');
var RuleName = $(this).attr('RuleName');
var id = $(this).val();
var RuleId = $(this).attr('RuleId');
$('#ddlCondition').val(Condition).change();
$("#ddlCondition").focus();
$("#ddlCondition").prop("disabled", true);
$("#ddlOperator").val(Operator);
$("#ddlvalue").val(Value);
$("#ddlChannel").val(Channel);
$("#SpecialActions").val(SpecialActions);
$("#RuleName").val(RuleName);
$("#HdnRulesId").val(RuleId);
$("#RuleId").val(RuleId);
$('#HdnOperationMode').val("Update");
});
function GetInvoiceAction(row) {
var res = "";
// edit invoice button
res += '<button type="button" id="btnEditInvoice" data-toggle="popover" class="btn btn-info btnEditinvoice actionbtn';
res += '" ';
res += 'title="" data-content="Edit Invoice"';
res += 'RuleId="' + row.RuleId + '" ';
res += 'Condition="' + row.Condition + '" Operator="' + row.Operator + '" Value ="' + row.Value + '" Channel ="' + row.Channel + '"SpecialActions ="' + row.SpecialActions + '"RuleName ="' + row.RuleName + '">'
res += '<i class="far fa-edit" aria-hidden="true" style="font-size: 1.2rem;"></i>';
res += '</button>';
// delete invoice button
res += '<button type="button" data-toggle="popover" class="btn btn-danger btnDeleteinvoice ml-sm-4 actionbtn';
res += '" ';
res += 'title="" data-content="Delete Invoice" ';
res += 'value="' + row.RuleId + '">';
res += '<i class="far fa-trash-alt" aria-hidden="true" style="font-size: 1.2rem;"></i>';
res += '</button>';
return res;
}
function ReloadRules() {
debugger;
if (!datatableinit)
{
datatableinit = ParseProductTable();
}
datatableinit.columns(0).search("2");
datatableinit.draw();
}
$(".DeferLoad").click(function () {
if (!datatableinit) {
datatableinit = ParseDataTable();
datatableindex['TranDate'] = datatableinit.column('ConditionName:name').index();
datatableindex['RuleName'] = datatableinit.column('RuleName:name').index();
}
Setdatatablesearch();
if (datatableinit.page.len() > 0 && datatableinit.page.len() != datatableinit.page.info().recordsDisplay) {
datatableinit.clearPipeline().draw();
}
else {
datatableinit.page.len(10).clearPipeline().draw();
}
});
function Reload() {
//$('#TransactionDate').val('');
if (datatableinit) {
Setdatatablesearch();
datatableinit.page.len(10).clearPipeline().draw();
}
}
autocomplete(document.getElementById("SearchRuleName"), RuleListValue);
$(".ClearSearch").click(function () {
$('#StartDate').popover("hide");
$('#EndDate').popover("hide");
$('#SearchRuleName').val('');
$('#StartDate').val('');
$('#EndDate').val('');
Reload();
});
function Setdatatablesearch()
{
datatableinit.columns(datatableindex['TranDate']).search('');
datatableinit.columns(datatableindex['RuleName']).search('');
var StartDate = $('#StartDate'),
EndDate = $('#EndDate')
var RuleNameSearch = $('#SearchRuleName');
if (StartDate.val() != '' && EndDate.val() != '') {
datatableinit.columns(datatableindex['TranDate']).search(StartDate.val() + ',' + EndDate.val());
}
if (RuleNameSearch != '') {
datatableinit.columns(datatableindex['RuleName']).search(RuleNameSearch.val());
}
}
var popOverSettings1 = {
placement: 'left',
trigger: 'hover',
container: 'body',
html: true,
selector: '.actionbtn,.transitstatus'
}
$(document).on('click', '.btnDeleteinvoice', function () {
//ResetInvoiceAddSection();
DeleteInvoicePopup($(this).val());
});
function DeleteInvoicePopup(RuleId) {
$('#modalConfirmDelete').modal({
backdrop: 'static',
keyboard: false
}).off('click', '#modalConfirmYes')
.on('click', '#modalConfirmYes', function (e) {
DeleteInvoice(RuleId);
});
}
function DeleteInvoice(RuleId) {
$.ajax({
url: config.Urls.Rule.DeleteRules,
type: 'POST',
async: false,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'RuleId': RuleId,
}),
success: function (result) {
$(".DeferLoad").click();
ResetRulesSection();
},
error: function (err) {
ErrorBox({
"ModalTitle": "Delete Error",
"ErrorTitle": "Transit Invoice Delete Error",
"Error": "Server Connection Refused."
}, function () { });
}
});
}
</script>
}
Controller :-
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Data;
using System.Web.Mvc;
using Newtonsoft.Json;
using NLP.Models;
using static NLP.Models.ApplicationReport;
using NLP.ViewModel;
using System.Linq.Expressions;
using LinqKit;
namespace NLP.Controllers
{
public class RiskController : Controller
{
// GET: Risk
public ActionResult Index()
{
return View();
}
public ActionResult DisplayRules()
{
ViewBag.TraderName = GetTraderName();
ViewBag.HSCodelist = GetHSCodeList();
ViewBag.CountryList = GetHSCountryList();
ViewBag.Transporter = GetTransportName();
ViewBag.OperationMode = "Insert";
ViewBag.Rules = GetRulesList();
return View();
}
Dictionary<string, string> GetRulesList()
{
using (var db = new SWAEntities())
{
var data=db.SW_Rules.Where(c=>c.IsDeleted==false).Select(c => new { c.RuleId, c.RuleName })
.ToDictionary(c => Convert.ToString(c.RuleId), c => c.RuleName);
return data;
}
}
//List<SelectListItem> GetRulesList()
//{
// using (var db = new SWAEntities())
// {
// return db.SW_Rules
// .Where(x => x.IsDeleted == false)
// .Select(x => new SelectListItem
// {
// Text = x.RuleName,
// Value = x.RuleId.ToString()
// }).Distinct().ToList();
// }
//}
List<SelectListItem> GetHSCodeList()
{
using (var db = new SWAEntities())
{
return db.MST_HSCodeTariffRates
.Where(x => x.isActive==true)
.Select(x => new SelectListItem
{
Text = x.HSCode,
Value = x.HSCode
}).Distinct().ToList();
}
}
List<SelectListItem> GetHSCountryList()
{
using (var db = new SWAEntities())
{
return db.MST_Country
.Where(x => x.IsDeleted == false)
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.CountryCode
}).Distinct().ToList();
}
}
List<SelectListItem> GetTransportName()
{
List<SelectListItem> mySkills = new List<SelectListItem>()
{ new SelectListItem {Text = "Air", Value = "Air"},
new SelectListItem { Text = "Sea", Value = "Sea" },
new SelectListItem { Text = "Road", Value = "Road" },
};
return mySkills;
}
List<SelectListItem> GetTraderName()
{
using (var db = new SWAEntities())
{
return db.NLP_RegistrationSW
.Where(x => x.IsActive == true && x.BusinessLine=="T")
.Select(x => new SelectListItem
{
Text = (x.FirstName+" "+ x.LastName),
Value = x.ID.ToString()
}).Distinct().ToList();
}
}
public ActionResult EditRateConfiguration(string ID)
{
ViewBag.TraderName = GetTraderName();
ViewBag.HSCodelist = GetHSCodeList();
ViewBag.CountryList = GetHSCountryList();
ViewBag.Transporter = GetTransportName();
ViewBag.HdnRulesId = ID;
ViewBag.OperationMode = "Update";
return View("~/Views/Risk/DisplayRules.cshtml");
}
[HttpPost]
public JsonResult AddUpdateRules()
{
var ErrorMessage = "";
int ErrorStatus = 0;
int RuleId = 0;
int CreatedBy = Convert.ToInt32(Session["ID"]);
Rules _ObjRules= JsonConvert.DeserializeObject<Rules>(Request["FormData"]);
if (ErrorStatus == 0)
{
try
{
using (var db = new SWAEntities())
{
if (_ObjRules.OperationMode == "Insert")
{
SW_Rules e = new SW_Rules()
{
Channel = _ObjRules.Channel,
Condition = _ObjRules.Condition,
Operator = _ObjRules.Operator,
Value = _ObjRules.Value,
SpecialActions = _ObjRules.SpecialActions,
CreatedDate = DateTime.Now,
CreatedBy= CreatedBy,
IsDeleted = false,
ConditionName=_ObjRules.ConditionName,
RuleName=_ObjRules.RuleName
};
var res = db.Set<SW_Rules>();
res.Add(e);
db.SaveChanges();
}
else if (_ObjRules.OperationMode == "Update")
{
RuleId = Convert.ToInt32(_ObjRules.RuleId);
var res = db.SW_Rules.Where(c => c.RuleId == RuleId).FirstOrDefault();
if (res != null)
{
res.UpdatedBy = _ObjRules.Createdby;
res.UpdatedDate = DateTime.Now;
res.Channel = _ObjRules.Channel;
res.Operator = _ObjRules.Operator;
res.Value = _ObjRules.Value;
res.SpecialActions = _ObjRules.SpecialActions;
res.ConditionName = _ObjRules.ConditionName;
res.RuleName = _ObjRules.RuleName;
}
db.SaveChanges();
}
else
{
ErrorStatus = 1;
ErrorMessage = "Invalid Operation";
}
if (ErrorStatus == 0)
{
}
}
}
catch (Exception ex)
{
ErrorStatus = 1;
ErrorMessage = "Something went Wrong - " + ex.ToString();
}
}
return Json(new
{
_ObjRules.RuleId,
ErrorStatus,
ErrorMessage
}, JsonRequestBehavior.AllowGet);
}
public JsonResult CheckExistingRule(string mode, string RuleName , int RuleId)
{
bool res = false;
int? CreatedBy = Convert.ToInt32(Session["ID"]);
using (var db = new SWAEntities())
{
if (mode == "Update")
{
res = db.SW_Rules.Any(c => c.RuleName == RuleName && c.IsDeleted == false && c.RuleId!=RuleId);
}
else
{
res = db.SW_Rules.Any(c => c.RuleName == RuleName && c.IsDeleted == false);
}
}
return new JsonResult { Data = res };
}
public JsonResult FetchRules(DataTableAjaxPostModel model)
{
//ViewBag.TraderName = GetTraderName();
//ViewBag.HSCodelist = GetHSCodeList();
//ViewBag.CountryList = GetHSCountryList();
//ViewBag.Transporter = GetTransportName();
//ViewBag.OperationMode = "Insert";
// action inside a standard controller
int filteredResultsCount;
int totalResultsCount;
var res = GetFilteredAppReportTransit(model, out filteredResultsCount, out totalResultsCount);
var result = new List<Rules>(res.Count);
foreach (var m in res)
{
var a = new Rules
{
RuleId=m.RuleId,
Condition=m.Condition,
Value=m.Value,
Channel=m.Channel,
SpecialActions=m.SpecialActions,
IsDeleted=m.IsDeleted,
Operator=m.Operator,
Createdby=m.Createdby,
ConditionName=m.ConditionName,
RuleName=m.RuleName,
CreatedDate=m.CreatedDate
};
result.Add(a);
};
return Json(new
{
// this is what datatables wants sending back
draw = model.draw,
recordsTotal = totalResultsCount,
recordsFiltered = filteredResultsCount,
data = result
});
}
public IList<Rules> GetFilteredAppReportTransit(DataTableAjaxPostModel model, out int filteredResultsCount, out int totalResultsCount)
{
var searchBy = (model.search != null) ? model.search.value : null;
var take = model.length;
var skip = model.start;
var createdby = model.createdby;
string sortBy = "";
bool sortDir = true;
if (model.order != null)
{
if (model.columns[model.order[0].column].name == "RuleId")
{
model.columns[model.order[0].column].name = "RuleId";
}
// in this example we just default sort on the 1st column
sortBy = model.columns[model.order[0].column].name;
sortDir = model.order[0].dir.ToLower() == "asc";
}
// search the dbase taking into consideration table sorting and paging
var result = GetApplicationFromDbTransit(model.columns, createdby, take, skip, sortBy, sortDir, out filteredResultsCount, out totalResultsCount);
if (result == null)
{
// empty collection...
return new List<Rules>();
}
return result;
}
public List<Rules> GetApplicationFromDbTransit(List<Column> columns, int createdby, int take, int skip, string sortBy, bool sortDir, out int filteredResultsCount, out int totalResultsCount)
{
int? created = Convert.ToInt32(Session["ID"]);
SWAEntities Db = new SWAEntities();
Expression<Func<Rules, bool>> whereClause = BuildDynamicWhereClauseTransit(Db, columns, createdby);
var result = Db.SW_Rules
.Where(s => s.IsDeleted == false && s.CreatedBy == created)
.OrderBy(s => s.CreatedDate)
.Select(m => new
{
m.RuleId,
m.Condition,
m.Value,
m.Channel,
m.SpecialActions,
m.CreatedBy,
m.Operator,
m.ConditionName,
m.RuleName,
m.CreatedDate
})
.OrderBy(sortBy, sortDir)
.Skip(skip)
.Take(take)
.AsEnumerable()
.Select(m =>
new Rules
{
RuleId=m.RuleId,
Condition=m.Condition,
Channel=m.Channel,
Value=m.Value,
SpecialActions=m.SpecialActions,
Operator=m.Operator,
Createdby=m.CreatedBy,
ConditionName=m.ConditionName,
RuleName=m.RuleName,
CreatedDate=m.CreatedDate
})
.ToList();
totalResultsCount = result.AsQueryable().Count();
filteredResultsCount = result.AsQueryable().Where(whereClause).Count();
result = result.AsQueryable().Where(whereClause).ToList();
if (take == -1)
{
take = filteredResultsCount;
}
return result;
}
private Expression<Func<Rules, bool>> BuildDynamicWhereClauseTransit(SWAEntities entities, List<Column> columns, int createdby)
{
var predicate = PredicateBuilder.New<Rules>(true); // true -where(true) return all
// Search for Date Range
if (String.IsNullOrWhiteSpace(columns[4].search.value) == false && columns[4].search.value != "null")
{
string[] daterange = columns[4].search.value.Split(',');
DateTime StartDate = DateTime.ParseExact(daterange[0], "MM/dd/yyyy", CultureInfo.InvariantCulture);
DateTime EndDate = DateTime.ParseExact(daterange[1], "MM/dd/yyyy", CultureInfo.InvariantCulture);
StartDate = StartDate.AddHours(0).AddMinutes(0).AddSeconds(0);
EndDate = EndDate.AddHours(23).AddMinutes(59).AddSeconds(59);
predicate = predicate.And(s => s.CreatedDate != null && s.CreatedDate >= StartDate && s.CreatedDate <= EndDate);
}
if (String.IsNullOrWhiteSpace(columns[2].search.value) == false && columns[2].search.value != "null")
{
var searchTerms = columns[2].search.value;
predicate = predicate.And(p => p.RuleName.Contains(searchTerms));
}
return predicate;
}
public ActionResult DeleteRules(int RuleId)
{
using (var db = new SWAEntities())
{
int invid = Convert.ToInt32(RuleId);
int? UpdatedBy = Convert.ToInt32(Session["ID"]);
var res = db.SW_Rules.Where(c => c.RuleId == invid && c.IsDeleted == false).FirstOrDefault();
if (res != null)
{
res.IsDeleted = true;
res.UpdatedBy = UpdatedBy;
res.UpdatedDate = DateTime.Now;
}
db.SaveChanges();
}
return Json("", JsonRequestBehavior.AllowGet);
}
}
}
@{
Layout = "~/Views/Shared/_LayoutPageAdmin.cshtml";
}
@section Styles
{
<link rel="stylesheet" href="~/assets/vendor/pnotify/pnotify.custom.css" />
<link rel="stylesheet" href="~/assets/vendor/pnotify/pnotify.custom.sw.css" />
<link rel="stylesheet" href="~/assets/stylesheets/Module/MultiSelectBox/multiselectbox.css" />
<link rel="stylesheet" href="~/DataTables/datatables.min.css" />
<style type="text/css">
/* css on 29-4-2020 */
body {
color: #131111 !important;
}
.panel-accordion {
box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, .45);
}
.panel-body {
padding: 0px 0px 0px 2px!important;
}
table {
font-size: 14px !important;
border-radius: 5px;
}
label.control-label {
color: #131111 !important;
font-size: 14px !important;
}
input {
color: inherit !important;
font-size: inherit !important;
}
.actioncell .btn {
border-radius: 11px !important;
}
table > thead > tr > th {
color: #191919 !important;
}
.module {
min-height: 75vh;
margin-right: 2px;
margin-left: 2px;
margin-top: 2px;
border-radius: 4px;
background: RGBA(255, 255, 255, 1);
-webkit-box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, .45);
box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, .45);
}
#exTab3 {
padding-top:5px;
}
.panel-accordion {
box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, .45);
}
td.prrow {
padding: 6px !important;
}
/* Numeric Columnc for reports */
.NumericCol {
text-align: right;
}
th.dt-center, td.dt-center {
text-align: center;
}
table.dataTable thead .sorting::after,
table.dataTable thead .sorting_asc::after {
display: none;
}
table.dataTable thead .sorting_desc::after {
display: none;
}
table.dataTable thead .sorting {
background-image: url(https://datatables.net/media/images/sort_both.png);
background-repeat: no-repeat;
background-position: center right;
}
table.dataTable thead .sorting_asc {
background-image: url(https://datatables.net/media/images/sort_asc.png);
background-repeat: no-repeat;
background-position: center right;
}
table.dataTable thead .sorting_desc {
background-image: url(https://datatables.net/media/images/sort_desc.png);
background-repeat: no-repeat;
background-position: center right;
}
.vtop {
vertical-align: top !important;
}
div.dataTables_wrapper div.dataTables_filter {
text-align: center;
}
div.dataTables_wrapper div.dataTables_length select {
margin-right: 6px;
margin-left: 6px;
cursor: pointer;
}
div.dataTables_wrapper div.dataTables_processing {
border-radius: 100px;
top: 0%;
margin-top: 10%;
width: 168px;
font-size: 15px;
padding: 0.7em 0;
}
.dataTables_wrapper table {
width: 100% !important;
}
.dataTables_wrapper table thead th {
padding: 7px !important;
text-align: center;
}
div.dataTables_wrapper div.dataTables_paginate {
cursor: pointer;
}
.pagingrow {
margin-top: 25px;
}
.searchrow {
margin-top: 4px;
margin-bottom: 7px;
}
div.dataTables_wrapper div.dataTables_info {
padding-top: 2px;
}
.form-group:last-child, .form-group:last-of-type {
margin-bottom: 15px;
}
@@media (min-width: 768px) {
.pt-sm-c3, .py-sm-c3 {
padding-top: 0.59rem !important;
}
}
.table {
table-layout: fixed;
}
.drafticon {
font-size: 15px;
color: rgb(222, 80, 10);
}
.submittedicon {
font-size: 15px;
color: green;
}
.withdrawnicon {
font-size: 15px;
color: #de500a;
}
.cancelledicon {
font-size: 15px;
color: #d2322d;
}
.queryicon {
font-size: 15px;
color: #e66519;
}
.queryresponseicon {
font-size: 15px;
color: #47a447;
}
.pendingtradericon {
font-size: 15px;
color: #979c9c;
}
.pendingicon {
font-size: 15px;
color: #49b6bb;
}
.btnPrintapplication {
padding: 1px 6px;
}
.btnEditapplication {
padding: 1px 6px;
background-color: #1f9bbf !important;
border-color: #1f9bbf !important;
}
.btnEditinvoice, .btnEditproduct {
padding: 1px 6px;
background-color: #1f9bbf !important;
border-color: #1f9bbf !important;
}
.btnCopyinvoice, .btnCopyproduct {
padding: 1px 6px;
}
.btnDeleteinvoice, .btnDeleteproduct {
padding: 1px 6px;
background-color: #ec4b46 !important;
border-color: #ec4b46 !important;
}
.btnChangeVehicle {
padding: 1px 6px;
background-color: #ec4b46 !important;
border-color: #ec4b46 !important;
}
.btnCopyapplication {
padding: 1px 6px;
}
.enablepopover {
pointer-events: auto !important;
}
@@media(min-width: 768px) {
#changevehiclemodal {
width: 450px;
}
}
</style>
}
<div id="bg">
<input type="hidden" value="@Convert.ToString(Session["Role"])" id="HdnRole" />
<input type="hidden" value="@Convert.ToString(Session["ID"])" id="HdnID" />
<input type="hidden" value="@Convert.ToString(Session["UserName"])" id="HdnUserName" />
<input type="hidden" value="@Convert.ToString(Session["OGAType"])" id="HdnOGAType" />
<input type="hidden" id="HdnOperationMode" value="@ViewBag.OperationMode" />
<input type="hidden" id="HdnRulesId" value="@ViewBag.RulesId" />
<input type="hidden" id="currentpage" value="Risk Management" />
<div class="module">
<div id="exTab3" class="">
<div class="row">
<div class="col-sm-12 px-sm-4">
<div class="tab-content px-sm-5 py-sm-3 ml-sm-1" style="border-radius:4px;border:0px;box-shadow:0px 0px 0px 0px;">
@*Fee Management*@
<div class="py-sm-4 px-sm-4" style="padding-top:0.4rem!important;">
<div class="row" id="form1">
<form class="form-horizontal" novalidate="novalidate">
<div class="form-group col-lg-4">
<div class="col-lg-4">
<label class="ml-sm-0 px-sm-0 pt-sm-3 control-label text-left" for="ddlCondition">
Condition/If
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-sm-8 pt-sm-2">
<select class="form-control" name="ddlCondition" id="ddlCondition">
<option value="">Choose Option</option>
<option value="T">Trader</option>
<option value="IN">Importer Name</option>
<option value="IC">Import Country Name</option>
<option value="IT">IECode</option>
<option value="EN">Exporter Name</option>
<option value="EC">Export Country Name</option>
<option value="CD">HS Code</option>
<option value="MOD">Mode Of Transport</option>
</select>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-3 col-md-3 col-sm-12 mb-sm-3">
<div class="col-lg-4 col-md-4 col-sm-3 pl-sm-2 pr-sm-0 flex">
<label class="ml-sm-0 px-sm-0 pt-sm-3 control-label text-left" for="ddlOperator">
Operator
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-sm-8 pt-sm-2">
<select class="form-control" name="ddlOperator" id="ddlOperator">
<option value="">Choose Option</option>
<option value="Equal">Equal</option>
<option value="NotEqual">Not Equal</option>
</select>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-3 col-md-3 col-sm-12 mb-sm-3">
<div class="col-lg-3 col-md-4 col-sm-3 pl-sm-2 pr-sm-0 flex">
<label class="ml-sm-0 px-sm-0 pt-sm-3 control-label text-left" for="servicetype">
Value
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-sm-8 pt-sm-2">
<div id="dvDdlVaue" style="display:block;">
@Html.DropDownList("ddlvalue", new SelectList("", "0", "Select"), new { @class = "form-control", @perror = "next" })
</div>
</div>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
<div class="form-group col-lg-3">
<div class="col-lg-5 flex" style="padding-right:0px!important;">
<label class="ml-sm-0 control-label text-left" for="ddlChannel">
Channel <span class="required pt-sm-c3 pl-sm-2">*</span>
</label>
</div>
<div class="col-lg-7 pt-sm-2" style="padding-left:0px!important;">
<select class="form-control" name="ddlChannel" id="ddlChannel">
<option value="">Choose Option</option>
<option value="Green">Green</option>
<option value="Yellow">Yellow</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
</select>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-4 col-md-4 col-sm-12 mb-sm-3">
<div class="col-lg-4">
<label class="ml-sm-0 px-sm-0 control-label text-left" for="SpecialActions">
Special Actions
</label>
</div>
<div class="col-lg-8">
<textarea type="text" id="SpecialActions" cols="30" rows="2"></textarea>
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
<div class="form-group col-lg-4 col-md-4 col-sm-12 mb-sm-3">
<div class="col-lg-4">
<label class="ml-sm-0 px-sm-0 control-label text-left" for="RuleName">
Rule Name
</label><span class="required pt-sm-c3 pl-sm-2">*</span>
</div>
<div class="col-lg-8">
<input type="text" id="RuleName" name="RuleName" class="form-control" />
<label class="pt-sm-1 mt-sm-1 mb-sm-0 invisible placeholder pull-right">g</label>
</div>
</div>
</form>
</div>
<div class="row">
<div class="col-lg-offset-9">
<button type="button" class="px-sm-5 mr-sm-4 my-sm-2 btn btn-primary SaveConfiguration">
Add rule
</button>
<button type="button" class="px-sm-5 my-sm-2 btn btn-warning CancelConfiguration">
Cancel
</button>
</div>
</div>
<div class="panel-body pb-sm-3">
<div class="col-md-5">
<div class="form-group">
<label class="control-label">Created Date Range</label>
<div class="input-daterange input-group" data-plugin-datepicker data-plugin-options='{"format":"mm/dd/yyyy","autoclose": true}'>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
<input type="text" class="form-control" name="start" id="StartDate" onkeydown="Allowonlytab()"
data-trigger="manual" data-toggle="popover" data-container="body" data-placement="top" data-content="Please Enter Valid Start Date">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" name="end" id="EndDate" onkeydown="Allowonlytab()"
data-trigger="manual" data-toggle="popover" data-container="body" data-placement="top" data-content="Please Enter Valid End Date">
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="control-label">Rule Name</label>
<input type="text" class="form-control input-sm" name="SearchRuleName" id="SearchRuleName" autocomplete="off">
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="padding-top:25px;">
<button type="button" class="btn btn-warning ClearSearch"><i class="fas fa-redo" aria-hidden="true"></i> Clear</button>
<button type="button" style="" class="ml-sm-4 btn btn-primary DeferLoad"><i class="fa fa-search" aria-hidden="true"></i> View</button>
</div>
</div>
</div>
<div class="row pt-sm-2">
<div class="col-sm-12 pb-sm-3">
<table class="table table-bordered table-striped mb-none" id="InvoiceGrid"></table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modalConfirmDelete" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog modal-dialog-center" id="deletepopup">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this rule?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" id="modalConfirmYes">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal" id="modalConfirmNo">No</button>
</div>
</div>
</div>
</div>
</div>
@section Scripts
{
<script src="~/DataTables/datatables.min.js"></script>
<script src="~/assets/vendor/jquery-validation/jquery.validate.js"></script>
<script src="~/assets/vendor/jquery-validation/additional-methods.js"></script>
<script src="~/assets/vendor/pnotify/pnotify.custom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.20/sorting/datetime-moment.js"></script>
<script type="text/javascript">
var dformat = "DD/MM/YYYY";
var datatableinit;
var datatableindex = [] , RuleListKey=[] , RuleListValue=[];
var RuleList = @Html.Raw(Json.Encode(ViewBag.Rules));
$.each(RuleList, function (key, value) { RuleListKey.push(key) })
$.each(RuleList, function (key, value) { RuleListValue.push(value) })
//
// Pipelining function for DataTables. To be used to the `ajax` option of DataTables
//
$.fn.dataTable.pipeline = function (opts) {
// Configuration options
var conf = $.extend({
pages: 5, // number of pages to cache
url: '', // script url
data: null, // function or object with parameters to send to the server
// matching how `ajax.data` works in DataTables
method: 'POST' // Ajax HTTP method
}, opts);
// Private variables for storing the cache
var cacheLower = -1;
var cacheUpper = null;
var cacheLastRequest = null;
var cacheLastJson = null;
return function (request, drawCallback, settings) {
var ajax = false;
var requestStart = request.start;
var drawStart = request.start;
var requestLength = request.length;
var requestEnd = requestStart + requestLength;
if (settings.clearCache) {
// API requested that the cache be cleared
ajax = true;
settings.clearCache = false;
}
else if (cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper) {
// outside cached data - need to make a request
ajax = true;
}
else if (JSON.stringify(request.order) !== JSON.stringify(cacheLastRequest.order) ||
JSON.stringify(request.columns) !== JSON.stringify(cacheLastRequest.columns) ||
JSON.stringify(request.search) !== JSON.stringify(cacheLastRequest.search)
) {
// properties changed (ordering, columns, searching)
ajax = true;
}
// Store the request for checking next time around
cacheLastRequest = $.extend(true, {}, request);
if (ajax) {
// Need data from the server
if (requestStart < cacheLower) {
requestStart = requestStart - (requestLength * (conf.pages - 1));
if (requestStart < 0) {
requestStart = 0;
}
}
cacheLower = requestStart;
cacheUpper = requestStart + (requestLength * conf.pages);
request.start = requestStart;
request.length = requestLength * conf.pages;
request.createdby = $("#HdnID").val();
// Provide the same `data` options as DataTables.
if (typeof conf.data === 'function') {
// As a function it is executed with the data object as an arg
// for manipulation. If an object is returned, it is used as the
// data object to submit
var d = conf.data(request);
if (d) {
$.extend(request, d);
}
}
else if ($.isPlainObject(conf.data)) {
// As an object, the data given extends the default
$.extend(request, conf.data);
}
settings.jqXHR = $.ajax({
"type": conf.method,
"url": conf.url,
"data": request,
"dataType": "json",
"cache": false,
"success": function (json) {
cacheLastJson = $.extend(true, {}, json);
if (cacheLower != drawStart) {
json.data.splice(0, drawStart - cacheLower);
}
if (requestLength >= -1) {
json.data.splice(requestLength, json.data.length);
}
drawCallback(json);
},
"error": function (err) {
$('.dataTables_processing').hide();
ErrorBox({
"ModalTitle": "Error",
"ErrorTitle": "Application list loading Error",
"Error": "Server Connection Refused."
}, function () { });
},
"complete": function (d) {
}
});
}
else {
json = $.extend(true, {}, cacheLastJson);
json.draw = request.draw; // Update the echo for each response
json.data.splice(0, requestStart - cacheLower);
json.data.splice(requestLength, json.data.length);
drawCallback(json);
}
}
};
// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. `table.clearPipeline().draw()`)
$.fn.dataTable.Api.register('clearPipeline()', function () {
return this.iterator('table', function (settings) {
settings.clearCache = true;
});
});
Array.prototype.myJoin = function (seperator, start, end) {
if (!start) start = 0;
if (!end) end = this.length - 1;
end++;
return this.slice(start, end).join(seperator);
};
function getTime() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
return mm + '-' + dd + '-' + yyyy;
}
Date.prototype.getMonthText = function () {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return months[this.getMonth()];
}
//Helper function
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
var OperationMode = ["Insert", "Update"];
var dformat = "DD/MM/YYYY";
var hscodeorderCount = 0;
var ddl_Condition = document.getElementById("ddlCondition"),
ddl_Operator = document.getElementById("ddlOperator"),
ddl_ddlvalue = document.getElementById("ddlvalue");
ddl_Channel = document.getElementById("ddlChannel");
var TraderList = @Html.Raw(Json.Encode(ViewBag.TraderName));
var CountryList = @Html.Raw(Json.Encode(ViewBag.CountryList));
var HsCodeList = @Html.Raw(Json.Encode(ViewBag.HSCodelist));
var TransporterList = @Html.Raw(Json.Encode(ViewBag.Transporter));
$(document).ready(function () {
LoadDDrp();
$(".DeferLoad").click();
$('body').popover(popOverSettings1);
});
function LoadDDrp() {
ddl_Condition.onchange = function () {
ddl_ddlvalue.options[0] = new Option("Choose Option", "0");
ddl_ddlvalue.length = 1; // remove all options bar first
if (this.selectedIndex < 0) return; // done
if ((this.value == "IN" || this.value == "EN" || this.value =="T") && TraderList != null)
{
TraderList.forEach(function (item, index) {
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else if ((this.value == "IC" || this.value == "EC") && CountryList != null)
{
debugger;
CountryList.forEach(function (item, index)
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else if ((this.value == "CD" || this.value == "CD") && HsCodeList != null)
{
HsCodeList.forEach(function (item, index)
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else if ((this.value == "MOD" || this.value == "MOD") && TransporterList != null)
{
TransporterList.forEach(function (item, index)
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
});
}
else
{
ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option("Select", "0");
//TransporterList.forEach(function (item, index)
//{
// ddl_ddlvalue.options[ddl_ddlvalue.options.length] = new Option(item.Text, item.Value);
//});
}
}
}
$.validator.addMethod("CheckRule", function (value, element) {
var result = false;
var data = {
"mode": $('#HdnOperationMode').val(),
"RuleName": $("#RuleName").val(),
"RuleId": $("#HdnRulesId").val() == "" ? 0 : parseInt($("#HdnRulesId").val())
};
$.ajax(
{
type: 'POST',
url: config.Urls.Rule.CheckExistingRule,
dataType: "json",
data: data,
async: false,
success: function (data) {
if (!data) {
result = true;
}
},
error: function (xhr, textStatus, errorThrown) {
ErrorBox({
"ModalTitle": "Error",
"ErrorTitle": "Invoice Number Validation Error",
"Error": "Server Connection Refused."
}, function () { });
}
});
return result;
}, 'Rule Already exist.');
$(".SaveConfiguration").click(function () {
debugger;
ClearFormError();
$("#RuleName").rules("add", { CheckRule: true });
var validated = $('#form1 form').valid();
if (validated) {
AddUpdateRules();
}
else {
$form1validator.focusInvalid();
}
});
function SetActionButtonText(mode) {
if (mode == "Insert") {
$('.SaveConfiguration').text('Add');
}
else {
$('.SaveConfiguration').text('Update');
}
}
function AddUpdateRules() {
DisplayLoaderOverlay('show');
NotifyLoading({
"Ptitle": "Save in Progress..",
"PMessage": "Updating configuration please wait...",
"hide": false
}, function () { });
setTimeout(
function () {
debugger;
var mode = $('#HdnOperationMode').val();
if (OperationMode.includes(mode)) {
// Creating Form Data object
var fileData = new FormData();
// Mapping Text input to Form data
var formdata = {
OperationMode: mode,
RuleId: $("#HdnRulesId").val() == "" ? 0 : parseInt($("#HdnRulesId").val()),
Channel: $("#ddlChannel").val(),
Condition: $("#ddlCondition").val(),
Operator: $("#ddlOperator").val(),
Value: $("#ddlvalue").val(),
SpecialActions: $("#SpecialActions").val(),
ConditionName: $("#ddlCondition option:selected").text(),
RuleName: $("#RuleName").val(),
}
fileData.append('FormData', JSON.stringify(formdata));
$.ajax({
url: config.Urls.Rule.AddUpdateRules,
type: 'POST',
async: false,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: fileData,
processData: false,
contentType: false,
success: function (res) {
PNotify.removeAll();
//timer for pnotify removal
setTimeout(
function () {
if (res.ErrorStatus == 0) {
DisplayLoaderOverlay('hide');
SetActionButtonText("Insert");
OnModalExit = function () {
$(".DeferLoad").click();
};
var alertData = "New Rule Added.";
if ($("#HdnRulesId").val()!= "" && $("#HdnRulesId").val() != undefined)
{
alertData ="Rule Updated as per Request."
}
Message =
{
"ModalTitle": "Success",
"SuccessTitle":""+ alertData +"",
"Info": ''
};
SuccessBox(Message, OnModalExit);
DisplayLoaderOverlay('hide');
ClearFormError();
ResetRulesSection();
}
else if (res.ErrorStatus == 2) {
NotifyLoading({
"Ptitle": "Session Expired",
"PMessage": "Redirecting to Login Page...",
"hide": false
}, function () { });
setTimeout(
function () {
window.location.href = config.Urls.SWHome.SWLoginPage;
}, 3000)
}
else {
DisplayLoaderOverlay('hide');
ErrorBox({
"ModalTitle": "Save Error",
"ErrorTitle": "Rate Configuration Data Update Failed",
"Error": res.ErrorMessage,
}, function () {
});
}
}, 650);
},
error: function (xhr, errorType, exception) {
PNotify.removeAll();
//timer for pnotify removal
setTimeout(
function () {
DisplayLoaderOverlay('hide');
ErrorBox({
"ModalTitle": "Save Error",
"ErrorTitle": "Rate Configuration Data Update Failed",
"Error": "Server Connection Refused."
}, function () { });
}, 650)
}
});
}
else {
PNotify.removeAll();
setTimeout(
function () {
DisplayLoaderOverlay('hide');
ErrorBox({
"ModalTitle": "Save Error",
"ErrorTitle": "Rate Configuration Data Update Failed",
"Error": "Invalid Operation Mode"
}, function () { });
}, 650)
}
}, 1000)
}
$(".CancelConfiguration").click(function () {
DisplayLoaderOverlay('hide');
SetActionButtonText("Insert");
$(".CancelConfiguration").hide();
ResetRulesSection();
$("#HdnRulesId").val('');
$('#HdnOperationMode').val("Insert");
});
function ResetRulesSection() {
ClearFormError();
$("#HdnRulesId").val('');
$('#HdnOperationMode').val("Insert");
$("#ddlOperator").val('');
$("#ddlChannel").val('');
$("#SpecialActions").val('');
$("#ddlvalue").val('')
$("#ddlCondition").prop("disabled", false);
$("#ddlCondition").val('');
$("#RuleName").val('');
SetActionButtonText("Insert");
$('.SaveConfiguration').text('Add');
$('.CancelConfiguration').hide();
}
$form1validator = $("#form1 form").validate({
ignore: ".ignore",
rules: {
"ddlCondition": {
required: true
},
"ddlOperator": {
required: true
},
"ddlvalue": {
required: true
//checkvalues: true
},
"ddlChannel": {
required: true,
},
"RuleName": {
required: true,
}
},
messages: {
"ddlCondition": {
required: "Please select Condition."
},
"ddlOperator": {
required: "Please select Operator."
},
"ddlvalue": {
required: "Please select vaue."
},
"ddlChannel": {
required: "Please select channel."
},
"RuleName": {
required: "Please enter Rule."
},
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
$(element).closest('.form-group').find('.multiselectform-group').removeClass('has-success').addClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').find('.placeholder').show();
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').find('.multiselectform-group').removeClass('has-error');
$(element).remove();
},
errorPlacement: function (error, element) {
$(element).closest('.form-group').find('.placeholder').hide();
if (element.attr("perror") == "next") {
error.insertAfter('.' + element.attr("id"));
error.addClass('pl-sm-0 pt-sm-1 mt-sm-1 mb-sm-0 show');
}
else {
element.parent().append(error);
error.addClass('pl-sm-0 pt-sm-1 mt-sm-1 mb-sm-0 show');
}
}
});
$.validator.addMethod('checkvalues', function (value) {
return (GetHSCodeUpdateList() != '');
});
function ClearFormError() {
$('#form1 .placeholder').show();
$("#form1 label.error").remove();
$("#form1 .error").removeClass("error");
$("#form1 .has-error").removeClass("has-error");
}
function ParseDataTable() {
return $('#InvoiceGrid').DataTable({
dom: "<'row searchrow'<'col-sm-4 ml-sm-4'l><'col-sm-3 hidden'B>>" +
"tr" +
"<'row pagingrow'<'col-sm-5 ml-sm-4'i><'col-sm-5 mr-sm-4 fright'p>>",
buttons:
[
{
extend: 'excel',
text: 'Export',
title: '',
className: "ExportExcel",
exportOptions: {
columns: ':not(.notexport)'
},
filename: function () {
return 'Exported Excel SW _' + getTime();
},
action: function (e, dt, node, config) {
var that = this;
dt.one('draw', function () {
$.fn.dataTable.ext.buttons.excelHtml5.action.call(that, e, dt, node, config);
})
dt.page.len(dt.page.info().recordsDisplay).clearPipeline().draw();
}
},
{
extend: 'pdf',
text: 'Export',
title: '',
className: "ExportPdf",
exportOptions: {
columns: ':not(.notexport)'
},
filename: function () {
return 'Exported Pdf SW _' + getTime();
},
action: function (e, dt, node, config) {
var that = this;
dt.one('draw', function () {
$.fn.dataTable.ext.buttons.pdfHtml5.action.call(that, e, dt, node, config);
});
dt.page.len(dt.page.info().recordsDisplay).clearPipeline().draw();
}
}, {
extend: 'print',
text: 'Print',
title: '',
className: "PrintPdf",
exportOptions: {
columns: ':not(.notexport)'
},
action: function (e, dt, node, config) {
var that = this;
dt.one('draw', function () {
$.fn.dataTable.ext.buttons.print.action.call(that, e, dt, node, config);
})
dt.page.len(dt.page.info().recordsDisplay).clearPipeline().draw();
}
}
],
deferLoading: true,
responsive: true,
bAutoWidth: true,
bProcessing: true,
proccessing: true,
serverSide: true,
contentType: "application/json",
ajax: $.fn.dataTable.pipeline({
url: config.Urls.Rule.FetchRules,
pages: 5 // number of pages to cache
}),
language: {
"search": "",
"searchPlaceholder": "Search...",
"processing": "<i class='fa fa-spinner fa-spin mr-sm-4'></i>Processing"
},
order: [[1, "desc"]],
columns: [
{
data: null,
name: "Sr",
title: "Sr. No.",
render: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
},
orderable: false,
className: "dt-center prrow vtop"
},
{
data: "RuleId",
name: "RuleId",
title: "Rule Name",
className: "prrow2 vtop",
visible:false
},
{
data: "RuleName",
name: "RuleName",
title: "Rule Name",
className: "prrow2 vtop",
},
{
data: "Condition",
name: "Condition",
title: "Condition / If",
className: "prrow vtop",
orderable: false,
visible : false
},
{
data: "ConditionName",
name: "ConditionName",
title: "Condition / If",
className: "prrow vtop",
orderable: true
},
{
data: "Operator",
name: "Operator",
title: "Operator",
className: "prrow vtop"
},
{
data: "Value",
name: "Value",
title: "Value",
className: "dt-body-center prrow vtop",
visible: false
},
{
data: "Channel",
name: "Channel",
orderable: false,
title: "Channel",
className: "prrow vtop"
},
{
data: "CreatedDate",
name: "CreatedDate",
title: "Created Date",
className: "prrow vtop",
render: function (value) {
if (value === null) return "";
return moment(value).format('DD MMM YYYY');
}
},
{
data: "SpecialActions",
name: "SpecialActions",
title: "Special Action",
className: "prrow vtop"
},
{
data: null,
name: "Action",
title: "Action",
orderable: false,
render: function (row) {
return GetInvoiceAction(row);
},
className: "dt-center actioncell prrow2 vtop"
}
],
columnDefs: [
{ targets: 0, width: "6%" },
{ targets: 2, width: "15%" },
{ targets: 3, width: "20%" },
{ targets: 4, width: "15%" },
{ targets: 5, width: "10%" },
],
initComplete: function () {
}
});
}
function ClearFormError() {
$('#form1 .placeholder').show();
$("#form1 label.error").remove();
$("#form1 .error").removeClass("error");
$("#form1 .has-error").removeClass("has-error");
}
$(document).on('click', '.btnEditinvoice', function () {
SetActionButtonText("Update");
ClearFormError();
$(".CancelConfiguration").show();
var Condition = $(this).attr('Condition');
var Operator = $(this).attr('Operator');
var Value = $(this).attr('Value');
var Channel = $(this).attr('Channel');
var SpecialActions = $(this).attr('SpecialActions');
var RuleName = $(this).attr('RuleName');
var id = $(this).val();
var RuleId = $(this).attr('RuleId');
$('#ddlCondition').val(Condition).change();
$("#ddlCondition").focus();
$("#ddlCondition").prop("disabled", true);
$("#ddlOperator").val(Operator);
$("#ddlvalue").val(Value);
$("#ddlChannel").val(Channel);
$("#SpecialActions").val(SpecialActions);
$("#RuleName").val(RuleName);
$("#HdnRulesId").val(RuleId);
$("#RuleId").val(RuleId);
$('#HdnOperationMode').val("Update");
});
function GetInvoiceAction(row) {
var res = "";
// edit invoice button
res += '<button type="button" id="btnEditInvoice" data-toggle="popover" class="btn btn-info btnEditinvoice actionbtn';
res += '" ';
res += 'title="" data-content="Edit Invoice"';
res += 'RuleId="' + row.RuleId + '" ';
res += 'Condition="' + row.Condition + '" Operator="' + row.Operator + '" Value ="' + row.Value + '" Channel ="' + row.Channel + '"SpecialActions ="' + row.SpecialActions + '"RuleName ="' + row.RuleName + '">'
res += '<i class="far fa-edit" aria-hidden="true" style="font-size: 1.2rem;"></i>';
res += '</button>';
// delete invoice button
res += '<button type="button" data-toggle="popover" class="btn btn-danger btnDeleteinvoice ml-sm-4 actionbtn';
res += '" ';
res += 'title="" data-content="Delete Invoice" ';
res += 'value="' + row.RuleId + '">';
res += '<i class="far fa-trash-alt" aria-hidden="true" style="font-size: 1.2rem;"></i>';
res += '</button>';
return res;
}
function ReloadRules() {
debugger;
if (!datatableinit)
{
datatableinit = ParseProductTable();
}
datatableinit.columns(0).search("2");
datatableinit.draw();
}
$(".DeferLoad").click(function () {
if (!datatableinit) {
datatableinit = ParseDataTable();
datatableindex['TranDate'] = datatableinit.column('ConditionName:name').index();
datatableindex['RuleName'] = datatableinit.column('RuleName:name').index();
}
Setdatatablesearch();
if (datatableinit.page.len() > 0 && datatableinit.page.len() != datatableinit.page.info().recordsDisplay) {
datatableinit.clearPipeline().draw();
}
else {
datatableinit.page.len(10).clearPipeline().draw();
}
});
function Reload() {
//$('#TransactionDate').val('');
if (datatableinit) {
Setdatatablesearch();
datatableinit.page.len(10).clearPipeline().draw();
}
}
autocomplete(document.getElementById("SearchRuleName"), RuleListValue);
$(".ClearSearch").click(function () {
$('#StartDate').popover("hide");
$('#EndDate').popover("hide");
$('#SearchRuleName').val('');
$('#StartDate').val('');
$('#EndDate').val('');
Reload();
});
function Setdatatablesearch()
{
datatableinit.columns(datatableindex['TranDate']).search('');
datatableinit.columns(datatableindex['RuleName']).search('');
var StartDate = $('#StartDate'),
EndDate = $('#EndDate')
var RuleNameSearch = $('#SearchRuleName');
if (StartDate.val() != '' && EndDate.val() != '') {
datatableinit.columns(datatableindex['TranDate']).search(StartDate.val() + ',' + EndDate.val());
}
if (RuleNameSearch != '') {
datatableinit.columns(datatableindex['RuleName']).search(RuleNameSearch.val());
}
}
var popOverSettings1 = {
placement: 'left',
trigger: 'hover',
container: 'body',
html: true,
selector: '.actionbtn,.transitstatus'
}
$(document).on('click', '.btnDeleteinvoice', function () {
//ResetInvoiceAddSection();
DeleteInvoicePopup($(this).val());
});
function DeleteInvoicePopup(RuleId) {
$('#modalConfirmDelete').modal({
backdrop: 'static',
keyboard: false
}).off('click', '#modalConfirmYes')
.on('click', '#modalConfirmYes', function (e) {
DeleteInvoice(RuleId);
});
}
function DeleteInvoice(RuleId) {
$.ajax({
url: config.Urls.Rule.DeleteRules,
type: 'POST',
async: false,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'RuleId': RuleId,
}),
success: function (result) {
$(".DeferLoad").click();
ResetRulesSection();
},
error: function (err) {
ErrorBox({
"ModalTitle": "Delete Error",
"ErrorTitle": "Transit Invoice Delete Error",
"Error": "Server Connection Refused."
}, function () { });
}
});
}
</script>
}
Controller :-
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Data;
using System.Web.Mvc;
using Newtonsoft.Json;
using NLP.Models;
using static NLP.Models.ApplicationReport;
using NLP.ViewModel;
using System.Linq.Expressions;
using LinqKit;
namespace NLP.Controllers
{
public class RiskController : Controller
{
// GET: Risk
public ActionResult Index()
{
return View();
}
public ActionResult DisplayRules()
{
ViewBag.TraderName = GetTraderName();
ViewBag.HSCodelist = GetHSCodeList();
ViewBag.CountryList = GetHSCountryList();
ViewBag.Transporter = GetTransportName();
ViewBag.OperationMode = "Insert";
ViewBag.Rules = GetRulesList();
return View();
}
Dictionary<string, string> GetRulesList()
{
using (var db = new SWAEntities())
{
var data=db.SW_Rules.Where(c=>c.IsDeleted==false).Select(c => new { c.RuleId, c.RuleName })
.ToDictionary(c => Convert.ToString(c.RuleId), c => c.RuleName);
return data;
}
}
//List<SelectListItem> GetRulesList()
//{
// using (var db = new SWAEntities())
// {
// return db.SW_Rules
// .Where(x => x.IsDeleted == false)
// .Select(x => new SelectListItem
// {
// Text = x.RuleName,
// Value = x.RuleId.ToString()
// }).Distinct().ToList();
// }
//}
List<SelectListItem> GetHSCodeList()
{
using (var db = new SWAEntities())
{
return db.MST_HSCodeTariffRates
.Where(x => x.isActive==true)
.Select(x => new SelectListItem
{
Text = x.HSCode,
Value = x.HSCode
}).Distinct().ToList();
}
}
List<SelectListItem> GetHSCountryList()
{
using (var db = new SWAEntities())
{
return db.MST_Country
.Where(x => x.IsDeleted == false)
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.CountryCode
}).Distinct().ToList();
}
}
List<SelectListItem> GetTransportName()
{
List<SelectListItem> mySkills = new List<SelectListItem>()
{ new SelectListItem {Text = "Air", Value = "Air"},
new SelectListItem { Text = "Sea", Value = "Sea" },
new SelectListItem { Text = "Road", Value = "Road" },
};
return mySkills;
}
List<SelectListItem> GetTraderName()
{
using (var db = new SWAEntities())
{
return db.NLP_RegistrationSW
.Where(x => x.IsActive == true && x.BusinessLine=="T")
.Select(x => new SelectListItem
{
Text = (x.FirstName+" "+ x.LastName),
Value = x.ID.ToString()
}).Distinct().ToList();
}
}
public ActionResult EditRateConfiguration(string ID)
{
ViewBag.TraderName = GetTraderName();
ViewBag.HSCodelist = GetHSCodeList();
ViewBag.CountryList = GetHSCountryList();
ViewBag.Transporter = GetTransportName();
ViewBag.HdnRulesId = ID;
ViewBag.OperationMode = "Update";
return View("~/Views/Risk/DisplayRules.cshtml");
}
[HttpPost]
public JsonResult AddUpdateRules()
{
var ErrorMessage = "";
int ErrorStatus = 0;
int RuleId = 0;
int CreatedBy = Convert.ToInt32(Session["ID"]);
Rules _ObjRules= JsonConvert.DeserializeObject<Rules>(Request["FormData"]);
if (ErrorStatus == 0)
{
try
{
using (var db = new SWAEntities())
{
if (_ObjRules.OperationMode == "Insert")
{
SW_Rules e = new SW_Rules()
{
Channel = _ObjRules.Channel,
Condition = _ObjRules.Condition,
Operator = _ObjRules.Operator,
Value = _ObjRules.Value,
SpecialActions = _ObjRules.SpecialActions,
CreatedDate = DateTime.Now,
CreatedBy= CreatedBy,
IsDeleted = false,
ConditionName=_ObjRules.ConditionName,
RuleName=_ObjRules.RuleName
};
var res = db.Set<SW_Rules>();
res.Add(e);
db.SaveChanges();
}
else if (_ObjRules.OperationMode == "Update")
{
RuleId = Convert.ToInt32(_ObjRules.RuleId);
var res = db.SW_Rules.Where(c => c.RuleId == RuleId).FirstOrDefault();
if (res != null)
{
res.UpdatedBy = _ObjRules.Createdby;
res.UpdatedDate = DateTime.Now;
res.Channel = _ObjRules.Channel;
res.Operator = _ObjRules.Operator;
res.Value = _ObjRules.Value;
res.SpecialActions = _ObjRules.SpecialActions;
res.ConditionName = _ObjRules.ConditionName;
res.RuleName = _ObjRules.RuleName;
}
db.SaveChanges();
}
else
{
ErrorStatus = 1;
ErrorMessage = "Invalid Operation";
}
if (ErrorStatus == 0)
{
}
}
}
catch (Exception ex)
{
ErrorStatus = 1;
ErrorMessage = "Something went Wrong - " + ex.ToString();
}
}
return Json(new
{
_ObjRules.RuleId,
ErrorStatus,
ErrorMessage
}, JsonRequestBehavior.AllowGet);
}
public JsonResult CheckExistingRule(string mode, string RuleName , int RuleId)
{
bool res = false;
int? CreatedBy = Convert.ToInt32(Session["ID"]);
using (var db = new SWAEntities())
{
if (mode == "Update")
{
res = db.SW_Rules.Any(c => c.RuleName == RuleName && c.IsDeleted == false && c.RuleId!=RuleId);
}
else
{
res = db.SW_Rules.Any(c => c.RuleName == RuleName && c.IsDeleted == false);
}
}
return new JsonResult { Data = res };
}
public JsonResult FetchRules(DataTableAjaxPostModel model)
{
//ViewBag.TraderName = GetTraderName();
//ViewBag.HSCodelist = GetHSCodeList();
//ViewBag.CountryList = GetHSCountryList();
//ViewBag.Transporter = GetTransportName();
//ViewBag.OperationMode = "Insert";
// action inside a standard controller
int filteredResultsCount;
int totalResultsCount;
var res = GetFilteredAppReportTransit(model, out filteredResultsCount, out totalResultsCount);
var result = new List<Rules>(res.Count);
foreach (var m in res)
{
var a = new Rules
{
RuleId=m.RuleId,
Condition=m.Condition,
Value=m.Value,
Channel=m.Channel,
SpecialActions=m.SpecialActions,
IsDeleted=m.IsDeleted,
Operator=m.Operator,
Createdby=m.Createdby,
ConditionName=m.ConditionName,
RuleName=m.RuleName,
CreatedDate=m.CreatedDate
};
result.Add(a);
};
return Json(new
{
// this is what datatables wants sending back
draw = model.draw,
recordsTotal = totalResultsCount,
recordsFiltered = filteredResultsCount,
data = result
});
}
public IList<Rules> GetFilteredAppReportTransit(DataTableAjaxPostModel model, out int filteredResultsCount, out int totalResultsCount)
{
var searchBy = (model.search != null) ? model.search.value : null;
var take = model.length;
var skip = model.start;
var createdby = model.createdby;
string sortBy = "";
bool sortDir = true;
if (model.order != null)
{
if (model.columns[model.order[0].column].name == "RuleId")
{
model.columns[model.order[0].column].name = "RuleId";
}
// in this example we just default sort on the 1st column
sortBy = model.columns[model.order[0].column].name;
sortDir = model.order[0].dir.ToLower() == "asc";
}
// search the dbase taking into consideration table sorting and paging
var result = GetApplicationFromDbTransit(model.columns, createdby, take, skip, sortBy, sortDir, out filteredResultsCount, out totalResultsCount);
if (result == null)
{
// empty collection...
return new List<Rules>();
}
return result;
}
public List<Rules> GetApplicationFromDbTransit(List<Column> columns, int createdby, int take, int skip, string sortBy, bool sortDir, out int filteredResultsCount, out int totalResultsCount)
{
int? created = Convert.ToInt32(Session["ID"]);
SWAEntities Db = new SWAEntities();
Expression<Func<Rules, bool>> whereClause = BuildDynamicWhereClauseTransit(Db, columns, createdby);
var result = Db.SW_Rules
.Where(s => s.IsDeleted == false && s.CreatedBy == created)
.OrderBy(s => s.CreatedDate)
.Select(m => new
{
m.RuleId,
m.Condition,
m.Value,
m.Channel,
m.SpecialActions,
m.CreatedBy,
m.Operator,
m.ConditionName,
m.RuleName,
m.CreatedDate
})
.OrderBy(sortBy, sortDir)
.Skip(skip)
.Take(take)
.AsEnumerable()
.Select(m =>
new Rules
{
RuleId=m.RuleId,
Condition=m.Condition,
Channel=m.Channel,
Value=m.Value,
SpecialActions=m.SpecialActions,
Operator=m.Operator,
Createdby=m.CreatedBy,
ConditionName=m.ConditionName,
RuleName=m.RuleName,
CreatedDate=m.CreatedDate
})
.ToList();
totalResultsCount = result.AsQueryable().Count();
filteredResultsCount = result.AsQueryable().Where(whereClause).Count();
result = result.AsQueryable().Where(whereClause).ToList();
if (take == -1)
{
take = filteredResultsCount;
}
return result;
}
private Expression<Func<Rules, bool>> BuildDynamicWhereClauseTransit(SWAEntities entities, List<Column> columns, int createdby)
{
var predicate = PredicateBuilder.New<Rules>(true); // true -where(true) return all
// Search for Date Range
if (String.IsNullOrWhiteSpace(columns[4].search.value) == false && columns[4].search.value != "null")
{
string[] daterange = columns[4].search.value.Split(',');
DateTime StartDate = DateTime.ParseExact(daterange[0], "MM/dd/yyyy", CultureInfo.InvariantCulture);
DateTime EndDate = DateTime.ParseExact(daterange[1], "MM/dd/yyyy", CultureInfo.InvariantCulture);
StartDate = StartDate.AddHours(0).AddMinutes(0).AddSeconds(0);
EndDate = EndDate.AddHours(23).AddMinutes(59).AddSeconds(59);
predicate = predicate.And(s => s.CreatedDate != null && s.CreatedDate >= StartDate && s.CreatedDate <= EndDate);
}
if (String.IsNullOrWhiteSpace(columns[2].search.value) == false && columns[2].search.value != "null")
{
var searchTerms = columns[2].search.value;
predicate = predicate.And(p => p.RuleName.Contains(searchTerms));
}
return predicate;
}
public ActionResult DeleteRules(int RuleId)
{
using (var db = new SWAEntities())
{
int invid = Convert.ToInt32(RuleId);
int? UpdatedBy = Convert.ToInt32(Session["ID"]);
var res = db.SW_Rules.Where(c => c.RuleId == invid && c.IsDeleted == false).FirstOrDefault();
if (res != null)
{
res.IsDeleted = true;
res.UpdatedBy = UpdatedBy;
res.UpdatedDate = DateTime.Now;
}
db.SaveChanges();
}
return Json("", JsonRequestBehavior.AllowGet);
}
}
}