EnVisageOnline/Main/Source/EnVisage/Scripts/Plugins/resolveForm.js

299 lines
15 KiB
JavaScript

/* ===========================================================
* resolveForm.js
* ===========================================================
* Copyright 2017 Prevu
* ========================================================== */
(function ($) {
"use strict"; // jshint ;_;
/* resolveForm CLASS DEFINITION
* ====================== */
var resolveForm = function (element, options) {
this.init(element, options);
};
resolveForm.prototype = {
constructor: resolveForm,
init: function (element, options) {
var plugin = this;
plugin.$options = options;
plugin.$container = $(element);
if (!plugin.$options.namePrefix) {
plugin.$options.namePrefix = plugin.$container.find('.name-prefix').data('value');
}
if (!plugin.$options.projectId || plugin.$options.projectId === C_EMPTY_GUID) {
throw "Required projectId not set. Init resolve form control cannot be performed.";
}
if (!plugin.$options.validateItemsUrl) {
throw "Required validate items URL not set. Init resolve form control cannot be performed.";
}
plugin.$form = plugin.$container.parents('form');
plugin.$container.append('<input class="project-id" type="hidden"/>');
plugin.$container.append('<input class="start-date" type="hidden"/>');
plugin.$container.append('<input class="end-date" type="hidden"/>');
if (!plugin.$form) {
throw "resolveForm widget requries ascendant form tag";
}
plugin.$dataset = [];
plugin.$table = plugin.$container.find(".tbl-conflicts");
plugin.$loader = plugin.$container.find('.loadRotator');
return true;
},
validate: function (startDate, endDate, fnCallback) {
var plugin = this;
if (startDate)
plugin.$container.find('.start-date').val(startDate);
if (endDate)
plugin.$container.find('.end-date').val(endDate);
var data = buildData(plugin);
blockUI();
var request
try {
request = getAntiXSRFRequest(plugin.$options.validateItemsUrl, data);
$.ajax(request).success(function (result, status, headers, config) {
handleAjaxResponse(result, function (response) {
if (result.Html) {
plugin.$container.html(result.Html);
plugin.initForm();
}
}, function (response) {
if (result.Html) {
plugin.$container.html(result.Html);
plugin.initForm();
}
}, null, plugin.$form, plugin.$options.namePrefix);
var hasConflicts = (plugin.$container.find('.has-conflicts').val() || '').toLowerCase() === 'true';
// run event handler if any
if (typeof plugin.$options.postRenderCallback === 'function')
plugin.$options.postRenderCallback(result.Status, hasConflicts);
// run callback passed directly to validate method if any
if (typeof fnCallback === 'function')
fnCallback(result.Status, hasConflicts);
unblockUI();
}).error(function (data, status, headers, config) {
console.debug('validate', request);
console.error('An error occurred in validate method');
showErrorModal('Project dependency validation error', 'We are sorry but there was an error while valiadting project dependencies, please try again later. If the error continues, contact administrators to fix the problem', '000019');
unblockUI();
});
} catch (e) {
console.debug('validate', request);
console.error('An error occurred in validate method while validating entered dependency conflicts resolve plan', '000020');
showErrorModal();
unblockUI();
}
},
initForm: function () {
var plugin = this;
plugin.$container.find('input.item-action').off("change.resolveForm").on("change.resolveForm", function () {
plugin.onChange(this);
});
var dateOptions = {
format: 'mm/dd/yyyy',
autoclose: true,
orientation: $('body').hasClass('right-to-left') ? "auto right" : 'auto auto',
startDate: plugin.$options.minStartDate,
endDate: plugin.$options.maxEndDate
};
$.each(plugin.$container.find('.item-custom-start-date'), function (index, item) {
$(item).datepicker(dateOptions).off("change.resolveForm").on("change.resolveForm", function () {
plugin.onChange(this);
});
});
$.each(plugin.$container.find('input.item-action'), function (index, item) {
plugin.onChange(this, true);
});
$.validator.unobtrusive.parseDynamicContent(plugin.$form, true);
},
onChange: function (element, skipSubmit) {
var plugin = this;
var container = $(element).parents('.item');
var action = container.find('input.item-action:checked').val();
// set datepicker limits
var minAvailableScenarioStartDate = container.find('input.item-min-available-scenario-start-date').val();
var maxAvailableScenarioStartDate = container.find('input.item-max-available-scenario-start-date').val();
var type = parseInt(container.find('input.item-type').val());
if (type === 0) {
container.find('.item-custom-start-date').data('datepicker').setStartDate(minAvailableScenarioStartDate);
container.find('.item-custom-start-date').data('datepicker').setEndDate(maxAvailableScenarioStartDate);
}
if (action === 'CustomMove') {
container.find('.item-date-required').val(true);
container.find('.item-custom').show();
}
else {
container.find('.item-date-required').val(false);
container.find('.item-custom').hide();
}
if (!skipSubmit)
plugin.validate();
},
getData: function () {
var plugin = this;
return buildData(plugin);
},
setDeletedItems: function (dependencies) {
var plugin = this;
// clear all items added in previous submission
var loopItems = plugin.$container.find('.item');
for (var i = 0; i < loopItems.length; i++) {
var isDeleted = loopItems.eq(i).find('.item-isdeleted').val().toLowerCase();
if (isDeleted === 'true') {
loopItems.eq(i).remove();
}
}
if (!dependencies)
return;
// add new items to be gathered during next submission
var items = $.isArray(dependencies) ? dependencies : [dependencies];
$.each(items, function (index, obj) {
var item = $('<div class="item item-new" style="display:none;"></div>');
$('<input type="hidden" class="item-id" value="' + obj.Id + '" />').appendTo(item);
$('<input type="hidden" class="item-sourceproject-id" value="' + obj.SourceProjectId + '" />').appendTo(item);
$('<input type="hidden" class="item-targetproject-id" value="' + obj.TargetProjectId + '" />').appendTo(item);
$('<input type="hidden" class="item-project-id" value="' + obj.ProjectId + '" />').appendTo(item);
$('<input type="hidden" class="item-type" value="' + obj.Type + '" />').appendTo(item);
$('<input type="hidden" class="item-isnew" value="' + obj.IsNew + '" />').appendTo(item);
$('<input type="hidden" class="item-isdeleted" value="' + obj.IsDeleted + '" />').appendTo(item);
$('<input type="radio" checked="checked" class="item-action" value="RemoveDependency" />').appendTo(item);
plugin.$container.append(item);
});
},
clearItems: function () {
plugin.$container.find('.item').remove();
},
setNewItems: function (dependencies) {
var plugin = this;
// clear all items added in previous submission except those which could be already modified by user
var loopItems = plugin.$container.find('.item');
var items = dependencies == null ? [] : $.isArray(dependencies) ? dependencies : [dependencies];
for (var i = 0; i < loopItems.length; i++) {
var isNew = loopItems.eq(i).find('.item-isnew').val().toLowerCase();
if (isNew === 'true') {
let sourceId = loopItems.eq(i).find('.item-sourceproject-id').val();
let targetId = loopItems.eq(i).find('.item-targetproject-id').val();
let keepMe = false;
for (var j = 0; j < items.length; j++) {
var obj = items[j];
if (sourceId === obj.SourceProjectId && targetId === obj.TargetProjectId) {
keepMe = true;
// update type field to keep it up to date
loopItems.eq(i).find('.item-type').val(obj.Type);
break;
}
}
if (keepMe)
items.splice(j, 1);
else
loopItems.eq(i).remove();
}
}
// add new items to be gathered during next submission
$.each(items, function (index, obj) {
var item = $('<div class="item item-new" style="display:none;"></div>');
$('<input type="hidden" class="item-id" value="' + obj.Id + '" />').appendTo(item);
$('<input type="hidden" class="item-sourceproject-id" value="' + obj.SourceProjectId + '" />').appendTo(item);
$('<input type="hidden" class="item-targetproject-id" value="' + obj.TargetProjectId + '" />').appendTo(item);
$('<input type="hidden" class="item-project-id" value="' + obj.ProjectId + '" />').appendTo(item);
$('<input type="hidden" class="item-type" value="' + obj.Type + '" />').appendTo(item);
$('<input type="hidden" class="item-isnew" value="' + obj.IsNew + '" />').appendTo(item);
$('<input type="hidden" class="item-isdeleted" value="' + obj.IsDeleted + '" />').appendTo(item);
$('<input type="radio" checked="checked" class="item-action" value="DontMove" />').appendTo(item);
plugin.$container.append(item);
});
},
destroy: function () {
var plugin = this;
var e = $.Event('destroy');
plugin.$container.trigger(e);
if (e.isDefaultPrevented())
return;
plugin.$container
.off('.resolveForm')
.removeData('resolveForm');
plugin.$form = null;
plugin.$dataset = null;
plugin.$table = null;
plugin.$loader = null;
plugin.$container.children().remove();
plugin.$container = null;
}
};
function startLoading(plugin) {
plugin.$table.find('tbody tr:not(.empty)').remove();
plugin.$table.hide();
plugin.$addButton.hide();
plugin.$loader.show();
}
function stopLoading(plugin) {
plugin.$loader.hide();
plugin.$addButton.show();
plugin.$table.show();
}
function buildData(plugin) {
var data = {
ProjectId: plugin.$options.projectId,
ScenarioId: plugin.$options.scenarioId,
StartDate: plugin.$container.find('.start-date').val(),
EndDate: plugin.$container.find('.end-date').val(),
ResolvePlan: [],
}
$.each(plugin.$container.find('.item'), function (index, item) {
data.ResolvePlan[index] = {
ProjectId: $(item).find('.item-project-id').val(),
Action: $(item).find('.item-action:checked').val(),
SourceProjectId: $(item).find('.item-sourceproject-id').val(),
TargetProjectId: $(item).find('.item-targetproject-id').val(),
Id: $(item).find('.item-id').val(),
Level: $(item).find('.item-level').val(),
ProjectName: $(item).find('.item-project-name').val(),
SourceEndDate: $(item).find('.item-source-end-date').val(),
SourceProjectName: $(item).find('.item-sourceproject-name').val(),
SourceStartDate: $(item).find('.item-source-start-date').val(),
TargetEndDate: $(item).find('.item-target-end-date').val(),
TargetProjectName: $(item).find('.item-targetproject-name').val(),
TargetStartDate: $(item).find('.item-target-start-date').val(),
Type: $(item).find('.item-type').val(),
MoveStartDate: $(item).find('.item-custom-start-date').val(),
MoveEndDate: $(item).find('.item-custom-end-date').val(),
OldStartDate: $(item).find('.item-old-start-date').val(),
OldEndDate: $(item).find('.item-old-end-date').val(),
IsNew: $(item).find('.item-isnew').val(),
IsDeleted: $(item).find('.item-isdeleted').val(),
};
});
return data;
}
/* resolveForm PLUGIN DEFINITION
* ======================= */
$.fn.resolveForm = function (option, args) {
return this.each(function () {
var $this = $(this),
plugin = $this.data('resolveForm'),
options = $.extend({}, $.fn.resolveForm.defaults, $this.data(), typeof option === 'object' && option);
if (plugin && options.forceReinit) {
plugin.$form.html("");
plugin.destroy();
plugin = undefined;
}
if (!plugin) {
$this.data('resolveForm', (plugin = new resolveForm(this, options)));
}
if (typeof option === 'string')
plugin[option].apply(plugin, [].concat(args));
});
};
$.fn.resolveForm.defaults = {
validateItemsUrl: '/Project/ValidateDependencyConflicts',
postRenderCallback: null,
projectId: null,
namePrefix: 'model.',
minStartDate: null,
maxEndDate: null
};
$.fn.resolveForm.Constructor = resolveForm;
}(jQuery));