');
if (this.UserNotification) {
this.soapSend('Logoff', '', this.UserNotification.url);
}
this.commonProperties.userID = null;
this.commonProperties.login;
this.commonProperties.loginName = '';
this.commonProperties.password = '';
this.commonProperties.database = '';
this.commonProperties.identityList = '';
}
this.setCommonPropertyValue('ignoreSessionTimeoutInSoapSend', undefined);
};
Aras.prototype.getVisiblePropertiesXPath = function Aras_getVisiblePropertiesXPath(itemTypeName, getForRelshipGrid) {
var xpath;
var isHidden = 'is_hidden' + (getForRelshipGrid ? '2' : '');
if (this.isAdminUser() && itemTypeName == 'ItemType') {
xpath = 'Relationships/Item[@type="Property" and (not(' + isHidden + ') or ' + isHidden + '="0" or name="label")]';
} else {
xpath = 'Relationships/Item[@type="Property" and (not(' + isHidden + ') or ' + isHidden + '="0")]';
}
return xpath;
};
Aras.prototype.XPathResult = function Aras_XPathResult(str) {
var path = '//Result';
if (str == undefined) {
return (path);
}
if (!str) {
return (path);
}
if (str == '') {
return (path);
}
return (path + str);
};
Aras.prototype.XPathFault = function Aras_XPathResult(str) {
var path = SoapConstants.EnvelopeBodyFaultXPath;
if (str == undefined) {
return (path);
}
if (!str) {
return (path);
}
if (str == '') {
return (path);
}
return (path + str);
};
Aras.prototype.XPathMessage = function Aras_XPathMessage(str) {
var path = '//Message';
if (str == undefined) {
return (path);
}
if (!str) {
return (path);
}
if (str == '') {
return (path);
}
return (path + str);
};
/*----------------------------------------
* hasMessage
*
* Purpose:
* check if xmldom (soap message) contains Message
*
* Arguments:
* xmlDom - xml document with soap message
*/
Aras.prototype.hasMessage = function Aras_hasMessage(xmlDom) {
return (xmlDom.selectSingleNode(this.XPathMessage()) != null);
};
/*----------------------------------------
* getMessageNode
*
* Arguments:
* xmlDom - xml document with soap message
*/
Aras.prototype.getMessageNode = function Aras_getMessageNode(xmlDom) {
return xmlDom.selectSingleNode(this.XPathMessage());
};
/**
* Method to validate the user and is used by the login method.
* The reason you do not see the users creadentions here is
* because they are automatically sent in the SOAP HTTP header.
* @param {Object} userInfo
* @returns {string}
*/
Aras.prototype.validateUser = function Aras_validateUser(userInfo) {
var ifResIsOK = function(res) {
if (res.getFaultCode() == 0) {
var node = res.results.selectSingleNode(this.XPathResult('/id'));
if (!node) {
return Promise.resolve(this.getResource('', 'aras_object.validate_user_wrong_innovator_sever_response'));
}
if (userInfo) {
userInfo.id = node.text;
node = res.results.selectSingleNode(this.XPathResult('/user_type'));
if (node) {
userInfo.user_type = node.text;
}
}
return 'ok';
} else {
return res.getFaultString();
}
}
var res = this.soapSend('ValidateUser', '');
if (!res) {
return this.getResource('', 'aras_object.validate_user_failed_communicate_with_innovator_server');
}
var passwordExpired_const = SoapConstants.SoapNamespace + ':Server.Authentication.PasswordIsExpired';
if (res.getFaultCode() == passwordExpired_const) {
var newPwd;
var d = this.createXMLDocument();
var xml = res.getMessageValue('password_validation_info');
if (!xml) {
xml = '';
}
d.loadXML('' + xml + ' ');
var methodCodeNd = d.selectSingleNode('/*/Item[@type=\'Method\']/method_code');
var variableNds = d.selectNodes('/*/Item[@type=\'Variable\']');
var variablesXml = undefined;
if (variableNds.length > 0) {
variablesXml = '';
for (var i = 0, l = variableNds.length; i < l; i++) {
variablesXml += variableNds[i].xml;
}
variablesXml += ' ';
}
var data = new Object();
data['title'] = this.getResource('', 'common.pwd_expired');
data['md5'] = this.getPassword();
data['oldMsg'] = this.getResource('', 'common.old_pwd');
data['newMsg1'] = this.getResource('', 'common.new_pwd');
data['newMsg2'] = this.getResource('', 'common.confirm_pwd');
data['errMsg1'] = this.getResource('', 'common.old_pwd_wrong');
data['errMsg2'] = this.getResource('', 'common.check_pwd_confirmation');
data['errMsg3'] = this.getResource('', 'common.pwd_empty');
data['check_empty'] = true;
data['code_to_check_pwd_policy'] = (methodCodeNd) ? methodCodeNd.text : this.getResource('', 'aras_object.return_method_check_password_policy_not_found');
data['vars_to_check_pwd_policy'] = variablesXml;
data.aras = this;
data.dialogWidth = 300;
data.dialogHeight = 180;
data.center = true;
data.content = 'changeMD5Dialog.html';
var wnd = aras.getMainWindow();
var arasDialog = (wnd.main || window).ArasModules.Dialog;
var processResult = function processResult (newPwd) {
if (newPwd === undefined) {
return this.getResource('', 'aras_object.new_password_not_set');
}
var r2 = this.soapSend('ChangeUserPassword', '' + newPwd + ' ');
if(r2.getFaultCode() != 0) {
var showDialog = function showDialog() {
return arasDialog.show('iframe', data).promise;
}
return this.AlertError(r2).then(showDialog).then(processResult.bind(this));
}
this.setPassword(newPwd, false);
ArasModules.soap(null, {
headers: {
'AUTHUSER': encodeURIComponent(this.getCurrentLoginName()),
'AUTHPASSWORD': this.getCurrentPassword(),
'DATABASE': encodeURIComponent(this.getDatabase()),
'LOCALE': this.getCommonPropertyValue('systemInfo_CurrentLocale'),
'TIMEZONE_NAME': this.getCommonPropertyValue('systemInfo_CurrentTimeZoneName')
}
});
res = this.soapSend('ValidateUser', '');
if (!res) {
return this.getResource('', 'aras_object.validate_user_failed_communicate_with_innovator_server');
}
return ifResIsOK.call(this, res);
}
return arasDialog.show('iframe', data).promise.then(processResult.bind(this));
}
else if (res.getFaultCode() == "SOAP-ENV:Server")
{
var d = this.createXMLDocument();
var xml = res.results.xml;
d.loadXML(xml);
var supportedSchema = d.selectSingleNode('//*[local-name()="supported_authentication_schema"]');
if (supportedSchema) {
var modeNode = supportedSchema.selectSingleNode('//*[local-name()="schema"][@name="AuthHeaders"]');
if (modeNode) {
switch(modeNode.getAttribute('mode')) {
case 'SHA256':
if (!aras.getVariable('fips_mode')) {
aras.setVariable('fips_mode', true);
return "repeat_call";
}
break;
case 'MD5':
if (aras.getVariable('fips_mode')) {
aras.setVariable('fips_mode', false);
return "repeat_call";
}
break;
}
}
}
}
return ifResIsOK.call(this, res);
};
/*-- generateNewGUID
*
* Method to generate a new ID by getting it from the server
*
*/
Aras.prototype.generateNewGUID = function Aras_generateNewGUID() {
return this.IomInnovator.getNewID();
};
/**
* Method to test ID value to be temporary.
*
* @param {string} id ID to test.
* @returns {boolean} is ID temporary.
*/
Aras.prototype.isTempID = function Aras_isTempID(id) {
if (id.substring(0, 6) === 'ms__id') {
return true;
} else {
var item = this.itemsCache.getItem(id);
if (!item) {
return false;
}
return (item.getAttribute('isTemp') === '1');
}
};
/*-- applyXsltString
*
* Method to transform a dom using the XSLT style sheet passed as string.
*
*/
Aras.prototype.applyXsltString = function(domObj, xslStr) {
var xsl = this.createXMLDocument();
xsl.loadXML(xslStr);
return domObj.transformNode(xsl);
};
/*-- applyXsltFile
*
* Method to transform a dom using the XSLT style sheet passed as a URL.
*
*/
Aras.prototype.applyXsltFile = function(domObj, xslFile) {
var xsl = this.createXMLDocument();
var xmlhttp = this.XmlHttpRequestManager.CreateRequest();
xmlhttp.open('GET', xslFile, false);
xmlhttp.send(null);
xsl.loadXML(xmlhttp.responseText);
return domObj.transformNode(xsl);
};
/*-- evalJavaScript
*
* Method to evaluate the JavaScript code in the Aras object space.
*
*/
Aras.prototype.evalJavaScript = function Aras_evalJavaScript(jsCode) {
eval('with(this){' + jsCode + '}');
};
/*-- printFrame
*
* Method to print the frame
* frame = the frame object
*
*/
Aras.prototype.printFrame = function Aras_printFrame(frame) {
frame.focus();
frame.print();
};
/*-- evalMethod
*
* Method to evaluate JavaScript stored as a Method item on the client side.
* methodNameOrNd = the name or id of the Method item or Method Node
* XMLinput = inDom or XML string that is loaded into the _top.inDom
* inArgs = arguments for method(can not be changed the object in evalMethod)
*
*/
Aras.prototype.evalMethod = function Aras_evalMethod(methodNameOrNd, XMLinput, inArgs) {
var isXmlNode = (typeof (XMLinput) === 'object') ? true : false;
var methodNd, methodName;
if (typeof (methodNameOrNd) === 'object') {
methodName = this.getItemProperty(methodNameOrNd, 'name');
methodNd = methodNameOrNd;
} else {
methodName = methodNameOrNd;
var propNames;
if (/^[0-9a-f]{32}$/i.test(methodName)) {
propNames = ["id", "name"];
} else {
propNames = ["name", "id"];
}
for (var i in propNames) {
methodNd = this.MetadataCache.GetClientMethodNd(methodName, propNames[i]);
if (methodNd) {
break;
}
}
}
if (!methodNd) {
this.AlertError(this.getResource('', 'aras_object.error_in_evalmethod', methodName), '', '');
return;
}
var methodCode = this.getItemProperty(methodNd, 'method_code');
var methodNameUpper = methodName.toUpperCase();
if ('ONCREATENEWPROJECT' === methodNameUpper) {
var mixedFlag = '/* METHOD WAS MIXED DYNAMICALLY BY ARAS OBJECT */\n\n\n\n',
oldSubString = 'var callbacks = {',
newSubString = 'var callbacks = {\n' +
'onload: function (dialog) {\n' +
' var windowToFocus = dialog.content.contentWindow;\n' +
' aras.browserHelper.setFocus(windowToFocus);\n' +
'},';
if (-1 === methodCode.indexOf(mixedFlag)) {
methodCode = mixedFlag + methodCode.replace(oldSubString, newSubString);
methodCode = mixedFlag + methodCode.replace(/\btop.aras\b/g, 'aras');
}
} else {
var methodNamesWithTopAras = ['PE_ADDCHANGEITEM', 'PE_CHOOSECMITEM', 'PE_GETSELECTEDITEMS', 'PE_CHOOSECMOPTIONS', 'PE_COMPLETENESSCHECK', 'PE_LAUNCHAMLEDITOR', 'AFTERPROJECTUPDATECLIENT',
'PM_CALL_SERVER_SIDE_SCHEDULE', 'PROJECT_CREATEPROJFROMTEMPLATE', 'PROJECT_CREATEPROJECTFROMPROJECT', 'PROJECT_CREATETEMPLATEFROMPROJ', 'PROJECT_CREATETEMPLATEFROMTEMPL',
'PROJECT_SHOWGANTTCHART'];
if (methodNamesWithTopAras.indexOf(methodNameUpper) !== -1) {
methodCode = methodCode.replace(/\btop.aras\b/g, 'aras');
var methodNamesWithTop = ['PE_COMPLETENESSCHECK', 'PE_GETSELECTEDITEMS', 'PE_CHOOSECMITEM'];
if (methodNamesWithTop.indexOf(methodNameUpper)) {
methodCode = methodCode.replace(/\btop\b/g, 'aras.getMostTopWindowWithAras(window)');
}
}
}
var inDom;
if (isXmlNode) {
inDom = XMLinput.ownerDocument;
} else {
inDom = this.createXMLDocument();
inDom.loadXML(XMLinput);
}
var self = this;
function evalMethod_work() {
var item = self.newIOMItem();
var itemNode;
item.dom = inDom;
if (isXmlNode) {
itemNode = XMLinput;
} else {
itemNode = item.dom.selectSingleNode('//Item');
}
if (itemNode) {
item.node = itemNode;
} else {
item.node = undefined;
}
item.setThisMethodImplementation(new Function('inDom, inArgs', methodCode));
return item.thisMethod(item.node, inArgs);
}
//var compatibilityMode = MethodCompatibilityMode.create(this.commonProperties.innovatorUpdateInfo.version, this.commonProperties.clientRevision, this);
var compatibilityMode = MethodCompatibilityMode.create("", this.commonProperties.clientRevision, this);
try {
compatibilityMode.enable();
if (!this.DEBUG) {
try {
return (evalMethod_work());
}
catch (excep) {
this.AlertError(this.getResource('', 'aras_object.method_failed', methodName), this.getResource('', 'aras_object.aras_object', excep.number, excep.description || excep.message), this.getResource('', 'common.client_side_err'));
return;
}
finally {
}
}
else
{
//IR-007020
var error1 = window.onerror;
window.onerror = null; //turn OFF our special handler
return (evalMethod_work());
//window.onerror = error1;
//error1 = null;
}
}
finally {
compatibilityMode.disable();
}
};
function AlertInternalCustomizationBase() {
/// Base class to implement customizations of AlertInternal
}
AlertInternalCustomizationBase.prototype.buttonsCellAlign = 'right';
AlertInternalCustomizationBase.prototype.DrawAdditionalContent = function AlertInternalCustomizationBase_DrawAdditionalContent(aras) {
/// Draws additiobal content on the dilaog. Draws nothing.
return '';
};
AlertInternalCustomizationBase.prototype.DrawButtons = function AlertInternalCustomizationBase_DrawButtons(aras) {
/// Draws buttons of the dilaog. Draws OK button.
return ' ';
};
AlertInternalCustomizationBase.prototype.GetDialogArguments = function AlertInternalCustomizationBase_GetDialogArguments(aras) {
return new Object();
};
function AlertInternalCustomizationForError(technicalErrorMessage, stackTrace) {
/// Customizations of AlertInternal specific to Error dialog
this.technicalErrorMessage = technicalErrorMessage;
this.stackTrace = stackTrace;
this.showDetails = Boolean(technicalErrorMessage || stackTrace);
if (this.showDetails) {
this.buttonsCellAlign = '';
} else {
this.buttonsCellAlign = 'right';
}
}
AlertInternalCustomizationForError.prototype = new AlertInternalCustomizationBase();
AlertInternalCustomizationForError.prototype.DrawAdditionalContent = function AlertInternalCustomizationForError_DrawAdditionalContent(aras) {
/// Draws additiobal content on the dilaog. Draws info area if required.
var standard = AlertInternalCustomizationBase.prototype.DrawAdditionalContent.call(this, aras);
var before;
if (this.showDetails) {
before =
'' +
this.DrawInfoAreaContent(aras);
} else {
before = '';
}
return before + standard;
};
AlertInternalCustomizationForError.prototype.DrawButtons = function AlertInternalCustomizationForError_DrawButtons(aras) {
/// Draws buttons of the dilaog. Draws OK and Cancel button.
var standard = AlertInternalCustomizationBase.prototype.DrawButtons.call(this, aras);
var before;
if (this.showDetails) {
before = '\n' +
' ' +
'' +
'';
} else {
before = '';
}
var after;
if (this.showDetails) {
after = ' ' +
'';
} else {
after = '';
}
return before + standard + after;
};
AlertInternalCustomizationForError.prototype.DrawInfoAreaContent = function AlertInternalCustomizationForError_DrawInfoAreaContent(aras) {
return '' +
'
' + aras.getResource('', 'aras_object.technical_message') + '
' + this.technicalErrorMessage +
'
' + aras.getResource('', 'aras_object.stack_trace') + '
' + this.stackTrace +
'
' +
'
';
};
AlertInternalCustomizationForError.prototype.GetDialogArguments = function AlertInternalCustomizationForError_GetDialogArguments(aras) {
var res = AlertInternalCustomizationBase.prototype.GetDialogArguments.call(this, aras);
res.ErrorDetails = this.GetErrorDetails();
return res;
};
AlertInternalCustomizationForError.prototype.GetErrorDetails = function AlertInternalCustomizationForError_GetErrorDetails() {
function ErrorDetails(technicalErrorMessage, stackTrace) {
if (!technicalErrorMessage) {
technicalErrorMessage = '';
}
if (!stackTrace) {
stackTrace = '';
}
this.technicalErrorMessage = technicalErrorMessage;
this.stackTrace = stackTrace;
}
ErrorDetails.prototype.GetCompleteDescription = function ErrorDetails_GetCompleteDescription() {
return this.technicalErrorMessage + this.stackTrace;
};
return new ErrorDetails(this.technicalErrorMessage, this.stackTrace);
};
function AlertInternalCustomizationForSOAPResultsError(soapResults) {
AlertInternalCustomizationForError.call(this, undefined, undefined);
this.soapResults = soapResults;
this.showDetails = true;
this.buttonsCellAlign = '';
this.drawResponseAsText = false;
if (soapResults) {
this.drawResponseAsText = Boolean(soapResults.getParseError());
}
}
AlertInternalCustomizationForSOAPResultsError.prototype = new AlertInternalCustomizationForError();
AlertInternalCustomizationForSOAPResultsError.prototype.DrawInfoAreaContent = function AlertInternalCustomizationForSOAPResultsError_DrawInfoAreaContent() {
var res = [];
res.push('' +
''
);
return res.join('');
};
AlertInternalCustomizationForSOAPResultsError.prototype.GetErrorDetails = function AlertInternalCustomizationForSOAPResultsError_GetErrorDetails() {
function ErrorDetails(soapResults) {
this.soapResults = soapResults;
}
ErrorDetails.prototype.GetCompleteDescription = function ErrorDetails_GetCompleteDescription() {
return this.soapResults.getResponseText();
};
return new ErrorDetails(this.soapResults);
};
AlertInternalCustomizationForSOAPResultsError.prototype.GetDialogArguments = function AlertInternalCustomizationForSOAPResultsError_GetDialogArguments(aras) {
var res = AlertInternalCustomizationForError.prototype.GetDialogArguments.call(this, aras);
res.aras = aras;
return res;
};
function AlertInternalCustomizationForIomError(iomError) {
AlertInternalCustomizationForSOAPResultsError.call(this, undefined);
this.iomError = iomError;
this.drawResponseAsText = false;
}
AlertInternalCustomizationForIomError.prototype = new AlertInternalCustomizationForSOAPResultsError();
AlertInternalCustomizationForIomError.prototype.GetErrorDetails = function AlertInternalCustomizationForIomError_GetErrorDetails() {
function ErrorDetails(iomError) {
this.iomError = iomError;
}
ErrorDetails.prototype.GetCompleteDescription = function ErrorDetails_GetCompleteDescription() {
return this.iomError.toString();
};
return new ErrorDetails(this.iomError);
};
function AlertInternalCustomizationForConfirm() {
}
AlertInternalCustomizationForConfirm.prototype = new AlertInternalCustomizationBase();
AlertInternalCustomizationForConfirm.prototype.DrawButtons = function AlertInternalCustomizationForConfirm_DrawButtons(aras) {
/// Draws buttons of the dilaog. Draws OK and Cancel button.
var standard = ' ';
var additional = ' ';
return standard + additional;
};
/*
* AlertError
* params: errorMessage = client-facing error message
* technicalErrorMessage = the technical error message
* stackTrace = the stack trace
* ardwin = the window to use
*
*/
Aras.prototype.AlertError = function Aras_AlertError(errorMessage, technicalErrorMessage, stackTrace, argwin) {
var customization;
if (errorMessage && typeof (errorMessage) !== 'string') {
if (SOAPResults.prototype.isPrototypeOf(errorMessage)) {
if (errorMessage.getFaultCode() === 'SOAP-ENV:Server.Authentication.SessionTimeout' && sessionStorage.getItem('ArasSessionCheck')) {
return Promise.resolve();
}
//passed argument is instance of SOAPResults
var soapResults = errorMessage;
var parseError = soapResults.getParseError();
customization = new AlertInternalCustomizationForSOAPResultsError(soapResults);
errorMessage = parseError ? this.getResource('', 'aras_object.invalid_soap_message') : soapResults.getFaultString();
} else if (errorMessage.isError) {
//passed argument is instance of IOM.Item with error description
customization = new AlertInternalCustomizationForIomError(errorMessage);
errorMessage = errorMessage.getErrorString();
} else {
customization = new AlertInternalCustomizationForError(technicalErrorMessage, stackTrace);
}
} else {
customization = new AlertInternalCustomizationForError(technicalErrorMessage, stackTrace);
}
return this.AlertInternal(errorMessage, 'error', argwin, customization);
};
Aras.prototype.AlertSuccess = function Aras_AlertSuccess(msg, argwin) {
this.AlertInternal(msg, 'success', argwin, new AlertInternalCustomizationBase());
};
Aras.prototype.AlertWarning = function Aras_AlertSuccess(msg, argwin) {
this.AlertInternal(msg, 'warning', argwin, new AlertInternalCustomizationBase());
};
Aras.prototype.AlertAboutSession = function Aras_AlertAboutSession() {
var formNd = this.getItemByName('Form', 'MySession', 0);
if (formNd) {
var width = this.getItemProperty(formNd, 'width') || 500;
var height = this.getItemProperty(formNd, 'height') || 320;
var param = {
title: 'About My Session',
formId: formNd.getAttribute('id'),
aras: this,
dialogWidth: width,
dialogHeight: height,
content: 'ShowFormAsADialog.html'
};
var win = this.getMostTopWindowWithAras(window);
(win.main || win).ArasModules.Dialog.show('iframe', param);
}
};
Aras.prototype.AlertAbout = function Aras_AlertAbout() {
this.AlertInternal(this.aboutInnovatorMessage, 'about', window, new AlertInternalCustomizationBase());
};
Aras.prototype.AlertInternal_1 = function Aras_AlertInternal_1(argwin) {
var win = window;
if (argwin && !this.isWindowClosed(argwin)) {
win = argwin;
}
var doc = null;
try {
doc = win.document;
}
catch (excep) {
}
var actEl = null;
if (doc) {
actEl = doc.activeElement;
}
if (actEl && actEl.tagName == 'FRAMESET') {
var frms = doc.getElementsByTagName('FRAME');
if (frms.length > 0) {
actEl = frms[0];;
}
}
try {
if (actEl) {
actEl.focus();
}
}
catch (excep) {
}
try {
win.focus();
}
catch (excep) {
}
return win;
};
/*
Displays a confirmation dialog box which contains a message and OK and Cancel buttons.
Parameters:
message - string. Message to display in a dialog.
win - parent window for the dialog.
Returns:
true - if a user clicked the OK button.
false - if a user clicked Cancel button.
*/
Aras.prototype.confirm = function Aras_confirm(message, ownerWindow) {
if (window.showModalDialog) {
var params = {
buttons: {
btnYes: this.getResource("", "common.ok"),
btnCancel: this.getResource("", "common.cancel")
},
defaultButton: "btnCancel",
aras: this,
message: message
};
var res = this.modalDialogHelper.show("DefaultModal", ownerWindow || window, params, {
dialogWidth: 300,
dialogHeight: 200,
center: true
}, "groupChgsDialog.html");
return res === "btnYes";
} else {
return window.confirm(message);
}
};
Aras.prototype.prompt = function Aras_prompt(msg, defValue, argwin) {
if (this.getCommonPropertyValue('exitWithoutSavingInProgress')) {
return;
}
var win = this.AlertInternal_1(argwin);
var htmlContent =
'' +
' ' +
' ' +
'' +
'' +
'
' +
'Script Prompt: ' +
' ' +
'
' +
'
' +
' ' +
'
' +
'
' +
'
' + msg + '
' +
'
' +
'
' +
'
';
var scriptContent =
'';
function writeContent(targetWindow) {
var doc = targetWindow.document;
doc.write(htmlContent);
doc.write(scriptContent);
}
var params = {};
params.writeContent = writeContent;
params.aras = this;
params.dialogWidth = 500;
params.dialogHeight = 170;
params.content = 'modalDialog.html';
params.title = this.getResource('', 'aras_object.aras_user_prompt');
return (win.main || win).ArasModules.Dialog.show('iframe', params).promise;
};
Aras.prototype.AlertInternal = function Aras_AlertInternal(msg, type, argwin, customization) {
// method used as content builder for alert dialog
if (this.getCommonPropertyValue('exitWithoutSavingInProgress')) {
return;
}
var win = this.getMostTopWindowWithAras(argwin || window);
argwin = (win.main || win);
var win = this.AlertInternal_1(argwin),
imageSrc, title, height,
imageTDStyle = 'padding: 20px 10px 0px 10px',
imageStyle = '',
msgTDStyle = 'padding-top:26px; padding-bottom:12px; padding-right:10px;';
switch (type) {
case 'success':
var successmessage_type = this.getPreferenceItemProperty('Core_GlobalLayout', null, 'core_successmessage_type');
title = this.getResource('', 'aras_object.aras_innovator');
imageStyle = 'max-width: 32px; max-height: 32px;';
imageSrc = this.getBaseURL() + '/images/Message.svg';
height = 130;
if ('Popup' == successmessage_type) {
var statusbarFrame;
var topWnd = this.getMostTopWindowWithAras(window);
if (topWnd.name == this.mainWindowName) {
statusbarFrame = topWnd.frames['statusbar'];
} else {
statusbarFrame = document.frames['statusbar'];
}
if (statusbarFrame) {
var popupNotification = statusbarFrame.contentWindow.PopupNotification.GetNotificationControl();
popupNotification.AddOrUpdate(popupNotification.Count, msg, imageSrc);
var timeClose = parseInt(this.getPreferenceItemProperty('Core_GlobalLayout', null, 'core_popupmessage_timeout'));
statusbarFrame.contentWindow.PopupNotification.ShowPopup(timeClose);
return;
} else {
console.error('Can\'t show popup: statusbar is not found.');
}
}
break;
case 'about':
title = this.getResource('', 'aras_object.about_aras_innovator');
imageSrc = '../images/aras-innovator.png';
imageStyle = 'width: 300px; height: 50px;';
imageTDStyle = 'padding-left:18px; padding-top: 15px;';
msgTDStyle += ' padding-left:40px;';
height = 330;
break;
case 'error':
title = this.getResource('', 'aras_object.error');
imageStyle = 'max-width: 48px; max-height: 48px;';
imageSrc = '../images/Error.svg';
height = 130;
break;
case 'warning':
title = this.getResource('', 'common.warning');
imageStyle = 'max-width: 48px; max-height: 48px;';
imageSrc = '../images/Warning.svg';
height = 130;
break;
}
var htmlContent =
'\n' +
' \n' +
'' + title + ' \n' +
'';
htmlContent +=
'\n' +
'\n' +
'\n' +
'\n' +
'
' +
'
' +
' ' +
' ' +
' ' +
' ';
if (type === 'about') {
htmlContent +=
' ' +
' ';
}
htmlContent +=
' ' +
' ' + msg + '
' +
' ' +
' ' +
'
' +
'
' +
'
' +
'
';
// additional content building
if (customization.showDetails) {
htmlContent +=
'' +
'
' +
customization.DrawAdditionalContent(this) +
'
' +
'
';
}
htmlContent += '';
function writeContent(w) {
var doc = w.document;
doc.write(htmlContent);
}
var params = customization.GetDialogArguments(this);
params.writeContent = writeContent;
params.aras = this;
params.title = title;
params.win = win;
params.dialogWidth = 500;
params.dialogHeight = height;
params.resizable = true;
params.content = 'modalDialog.html';
var self = this;
var wnd = win.ArasModules ? win : self.getMostTopWindowWithAras();
var dialog = wnd.ArasModules.Dialog.show("iframe", params).promise.then(function () {
var w = self.getMainWindow();
if (w && w.DoFocusAfterAlert) {
w.focus();
}
});
return dialog;
};
/*-- evalItemMethod
*
* Method to evaluate JavaScript stored as a Method item on the client side.
* methodName = the name of the Method item
* itemDom = the item dom
* addArgs = optional argument. Object with any additional parameters.
*/
Aras.prototype.evalItemMethod = function Aras_evalItemMethod(methodName, itemNode, addArgs) {
var methodNd = this.MetadataCache.GetClientMethodNd(methodName, 'name');
if (!methodNd) {
this.AlertError(this.getResource('', 'aras_object.erroe_eval_item_method', methodName), '', '');
return;
}
var methodCode = this.getItemProperty(methodNd, 'method_code'),
methodNameUpper = methodName.toUpperCase();
var methodNamesWithTopAras = ['PE_ADDCHANGEITEM', 'PE_CHOOSECMITEM', 'PE_GETSELECTEDITEMS', 'PE_CHOOSECMOPTIONS', 'PE_COMPLETENESSCHECK', 'PE_LAUNCHAMLEDITOR', 'AFTERPROJECTUPDATECLIENT',
'PM_CALL_SERVER_SIDE_SCHEDULE', 'PROJECT_CREATEPROJFROMTEMPLATE', 'PROJECT_CREATEPROJECTFROMPROJECT', 'PROJECT_CREATETEMPLATEFROMPROJ', 'PROJECT_CREATETEMPLATEFROMTEMPL',
'PROJECT_SHOWGANTTCHART', 'PROJECT_CFGSEARCHDIALOG4ASSGNMTS', 'PROJECTTIMEREPORT'];
if (methodNamesWithTopAras.indexOf(methodNameUpper) !== -1) {
methodCode = methodCode.replace(/\btop.aras\b/g, 'aras');
var methodNamesWithTop = ['PE_COMPLETENESSCHECK', 'PE_GETSELECTEDITEMS', 'PE_CHOOSECMITEM', 'PROJECT_CFGSEARCHDIALOG4ASSGNMTS'];
if (methodNamesWithTop.indexOf(methodNameUpper)) {
methodCode = methodCode.replace(/\btop\b/g, 'aras.getMostTopWindowWithAras(window)');
}
}
var self = this;
function evalItemMethod_work() {
var item = self.newIOMItem();
if (itemNode) {
item.dom = itemNode.ownerDocument;
item.node = itemNode;
}
item.setThisMethodImplementation(new Function('inDom', 'inArgs', methodCode));
return item.thisMethod(item.node, addArgs);
}
//var compatibilityMode = MethodCompatibilityMode.create(this.commonProperties.innovatorUpdateInfo.version, this.commonProperties.clientRevision, this);
var compatibilityMode = MethodCompatibilityMode.create("", this.commonProperties.clientRevision, this);
try {
compatibilityMode.enable();
if (!this.DEBUG) {
try {
return (evalItemMethod_work());
}
catch (excep) {
this.AlertError(this.getResource('', 'aras_object.method_failed', methodName), this.getResource('', 'aras_object.aras_object', excep.number, excep.description), this.getResource('', 'common.client_side_err'));
return;
}
finally {
}
} else {
return (evalItemMethod_work());
}
}
finally {
compatibilityMode.disable();
}
};
/*-- applyMethod
*
* Method to invoke an Innovator Method on the server side.
* action = the server action to be performed
* body = the message body for the action
*
*/
Aras.prototype.applyMethod = function Aras_applyMethod(action, body) {
var res = this.soapSend('ApplyMethod', '- ' + body + '
');
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
return res.getResultsBody();
};
/*-- applyItemMethod
*
* Method to invoke an action on an item on the server side.
* action = the the server action to be performed, which is the Innovator Method name
* type = the ItemType name
* body = the message body for the action
*
*/
Aras.prototype.applyItemMethod = function(action, type, body) {
var res = this.soapSend('ApplyItem', '- ' + body + '
');
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
return res.getResultsBody();
};
/*-- applyAML
*
* Method to apply an item on the server side.
* body = the message body for the item
*
*/
Aras.prototype.applyAML = function(body) {
var res = this.soapSend('ApplyAML', body);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
return res.getResultsBody();
};
/*-- compileMethod
*
* Method to compile VB or C# code on the server side to check syntax.
* body = the method item xml
*
*/
Aras.prototype.compileMethod = function(body) {
var res = this.soapSend('CompileMethod', body);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return '';
}
return res.getResultsBody();
};
/*-- applyItem
*
* Method to apply an item on the server side.
* body = the message body for the item
*
*/
Aras.prototype.applyItem = function Aras_applyItem(body) {
var res = this.soapSend('ApplyItem', body);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return '';
}
return res.getResultsBody();
};
Aras.prototype.canInvokeAction = function Aras_canInvokeActionImpl(actionId) {
var canInvokeAction = true;
if (actionId) {
// Request to Server should be changed to request to Cache in further implementations.
var action = this.newIOMItem('Action', 'get');
action.setID(actionId);
action.setAttribute('select', 'can_execute, location');
action = action.apply();
if (action.isError()) {
this.AlertError(action);
return false;
}
var canExecuteMethodName = action.getPropertyAttribute('can_execute', 'keyed_name');
var location = action.getProperty('location');
canInvokeAction = this.canInvokeActionImpl(canExecuteMethodName, location);
}
return canInvokeAction;
}
Aras.prototype.canInvokeActionImpl = function Aras_canInvokeActionImpl(methodName, location) {
var canInvokeAction = true;
if (methodName) {
if (location === 'client') {
// Result of 'this.evalMethod' can be value of any type (integer, string, boolean and etc.).
// For compatibility with "location === 'server'" logic:
// if value string 'true' or boolean true, canInvokeAction = true, in all other cases canInvokeAction = false
var evalResult = this.evalMethod(methodName);
//evalResult can be 'undefined'.
if (!evalResult || evalResult.toString() != 'true') {
canInvokeAction = false;
}
} else if (location === 'server') {
var canInvoketem = this.newIOMItem('Action', methodName);
canInvoketem = canInvoketem.apply();
if (canInvoketem.isError() || canInvoketem.getResult() != 'true') {
canInvokeAction = false;
}
}
}
return canInvokeAction;
};
/*-- invokeAction
*
* Invoke the Method associated with an action.
* action = the the Action item
*
*/
Aras.prototype.invokeAction = function Aras_invokeAction(action, itemTypeID, thisSelectedItemID) {
with (this) {
var self = this;
var statusId = showStatusMessage('status', getResource('', 'aras_object.invoking_action'), system_progressbar1_gif);
var name = getItemProperty(action, 'name');
var actionType = getItemProperty(action, 'type');
var target = getItemProperty(action, 'target');
var location = getItemProperty(action, 'location');
//alert(location);
var body = getItemProperty(action, 'body');
var onCompleteMethodName = this.getItemPropertyAttribute(action, 'on_complete', 'keyed_name');
var itemTypeName = null;
if (itemTypeID != undefined && itemTypeID) {
itemTypeName = getItemTypeName(itemTypeID);
}
var methodName = this.getItemPropertyAttribute(action, 'method', 'keyed_name');
var results;
var selectedItem;
if (actionType == 'item') {
var item_query = getItemProperty(action, 'item_query');
var xslt = '' +
'' +
'' +
' ' +
'' + item_query + ' ' +
' ';
var itemDom = createXMLDocument();
var doApplyQuery = false;
// IR-016631 "InvokeAction works wrong."
selectedItem = itemsCache.getItemByXPath('//Item[@id=\'' + thisSelectedItemID + '\' and (@isDirty=\'1\' or @isTemp=\'1\')]');
// if item isn't dirty and isn't temp
if (!selectedItem) {
// retrieve item from server
selectedItem = getItemById(itemTypeName, thisSelectedItemID, 0);
// seems, item was deleted
if (!selectedItem) {
AlertError(this.getResource('', 'aras_object.item_not_found', itemTypeName, thisSelectedItemID));
return;
}
if (item_query != '') {
itemDom.loadXML(selectedItem.xml);
doApplyQuery = true;
}
}
//request selectedItem from server via item_query transformation
if (doApplyQuery) {
// if item_query is invalid string(__is_new__ for example), then this request do not return anything and value from cache will be used.
var query = applyXsltString(itemDom, xslt);
if (query) {
var result = this.soapSend('ApplyItem', query);
//if nothing was received, then use item from cache or if it is not existed in cache use temp item.
if (result.getFaultCode() != 0) {
selectedItem = itemDom.documentElement;
} else {
var resultItem = result.getResult().selectSingleNode('Item');
mergeItem(selectedItem, resultItem);
}
}
}
if (location == 'server') {
var inDom = createXMLDocument();
inDom.loadXML(selectedItem.xml);
var inItem = inDom.selectSingleNode('//Item');
inItem.setAttribute('action', methodName);
var res = soapSend('ApplyItem', inItem.xml);
if (res.getFaultCode() != 0) {
this.AlertError(res);
clearStatusMessage(statusId);
return false;
}
results = res.getResultsBody();
} else if (location == 'front') {
var selectedItemXmlBeforeAction = selectedItem.xml;
var itemWasChangedDurinAction = false;
results = evalItemMethod(methodName, selectedItem, null);
if (selectedItem) {
itemWasChangedDurinAction = (selectedItemXmlBeforeAction !== selectedItem.xml);
if (itemWasChangedDurinAction && this.isLocked(selectedItem)) {
selectedItem.setAttribute('isDirty', '1');
this.uiReShowItemEx(thisSelectedItemID, selectedItem);
}
}
}
if (onCompleteMethodName) {
var methodArgs = new Object();
methodArgs.results = results;
results = evalItemMethod(onCompleteMethodName, selectedItem, methodArgs);
}
} else if (actionType == 'itemtype' || actionType == 'generic') {
if (location == 'server') {
if (body != '' && actionType == 'itemtype') {
results = applyItemMethod(methodName, itemTypeName, body);
} else if (body != '' && actionType == 'generic') {
results = applyMethod(methodName, body);
} else {
if (body == '') {
body = '' + thisSelectedItemID + ' ';
}
results = applyMethod(methodName, body);
}
} else if (location == 'client') {
var methodNode = this.MetadataCache.GetClientMethodNd(methodName, 'name');
results = evalMethod(methodName, body, methodNode);
if (onCompleteMethodName) {
var methodArgs = new Object();
methodArgs.results = results;
results = evalItemMethod(onCompleteMethodName, body, methodArgs);
}
}
}
var doc;
if (location == 'server') {
var subst = createXMLDocument();
subst.loadXML(results);
if (subst.documentElement) {
var content = subst.documentElement.text;
} else {
var content = '';
}
subst = null;
} else {
var content = results;
}
var tabsObj = this.getMainWindow().arasTabs;
var close = 'var close = function(callback) { \
if (!callback) { \
var tab = window.parent.document.querySelector("li[data-id=" + this.frameElement.id + "]"); \
tabsObj.removeTab(tab); \
} else { \
callback(true); \
} \
};';
var focus = 'var focus = function() { \
var tab = window.parent.document.querySelector("li[data-id=" + this.frameElement.id + "]"); \
tabsObj.selectTab(tab); \
};';
var createScript = function(win) {
var script = win.document.createElement('script');
script.textContent = 'var tabsObj = window.parent.arasTabs;';
script.textContent += close;
script.textContent += focus;
win.document.body.appendChild(script);
};
var openContentInTab = function (mode)
{
var winName = self.mainWindowName + '_' + self.getItemProperty(action, 'id');
var win;
mode = mode || 'window';
if (mode === 'window') {
winName = winName + '_' + Date.now();
}
var mainWindowDoc = self.getMainWindow().document;
var frame = mainWindowDoc.getElementById(winName);
if (!frame) {
win = tabsObj.open(aras.getScriptsURL() + 'blank.html', winName);
var tab = mainWindowDoc.querySelector('li[data-id="' + winName + '"]');
var title = ' ' + name;
tabsObj.updateTitleTab(title, tab);
} else {
win = frame.contentWindow;
win.focus();
}
// if content is very large doc.write(content) falls with errors(out of memory, example)
// so write content by parts
var contentLength = 250000;
var cycles = Math.ceil(content.length / contentLength);
for (var i = 0; i < cycles; i++) {
win.document.write(content.substring(i * contentLength, (i + 1) * contentLength));
}
win.document.write(' ');
win.document.body.style.background = '#fff';
if (!win.tabsObj) {
createScript(win);
}
};
switch (target) {
case 'window':
if (tabsObj) {
openContentInTab('window');
break;
}
var width = 710; // This is a printable page width.
var height = screen.height / 2;
var x = (screen.height - height) / 2;
var y = (screen.width - width) / 2;
var args = 'scrollbars=yes,resizable=yes,status,width=' + width + ',height=' + height + ',left=' + y + ',top=' + x;
var win = open('', '', args);
win.focus();
doc = win.document.open();
doc.write(content);
doc.close();
doc.title = name;
break;
case 'main':
var mainWindow = getMainWindow();
// Chrome does not cleans the window object on document.write
// differently from other browsers. Proof:
// https://stackoverflow.com/questions/12417121/document-open-document-write-not-properly-clearing-the-document-in-chrome-i
if (Browser.isCh())
{
if (mainWindow.work.onbeforeunload){
mainWindow.work.onbeforeunload();
}
makeItemsGridBlank(false);
}
doc = mainWindow.work.document.open();
doc.write(content);
doc.close();
break;
case 'none':
break;
case 'one window':
if (tabsObj) {
openContentInTab('one window');
break;
}
var targetWindow = getActionTargetWindow(name);
doc = targetWindow.document;
// if content is very large doc.write(content) falls with errors(out of memory, example)
// so write content by parts
var contentLength = 250000;
var cycles = Math.ceil(content.length / contentLength);
for (var i = 0; i < cycles; i++) {
doc.write(content.substring(i * contentLength, (i + 1) * contentLength));
}
doc.write(' ');
break;
}
clearStatusMessage(statusId);
}
};
Aras.prototype.runReport = function Aras_runReport(report, itemTypeID, item) {
if (!report) {
this.AlertError(this.getResource('', 'aras_object.failed_get_report'), '', '');
return;
}
var report_location = this.getItemProperty(report, 'location');
var self = this;
var results;
//alert(report_location);
if (report_location == "client") {
var result = this.runClientReport(report, itemTypeID, item);
if (result.then) {
result.then(processResults);
} else {
processResults(result);
}
}
else if (report_location == "server") {
results = this.runServerReport(report, itemTypeID, item);
var tmpDom = this.createXMLDocument();
if (results) {
tmpDom.loadXML(results);
results = tmpDom.documentElement.text;
}
processResults(results);
}
else if (report_location == "service") {
var url = this.getServerBaseURL() + "RSGateway.aspx?irs:Report=" + this.getItemProperty(report, "name");
var report_query = this.getItemProperty(report, "report_query");
if (report_query) {
var xslt = '' +
'' +
'' +
' ' +
' ' +
' ' + report_query + ' ' +
' ';
var itemDom = this.createXMLDocument();
if (item) {
itemDom.loadXML(item.xml);
} else {
var typeName;
if (itemTypeID) {
typeName = this.getItemTypeName(itemTypeID);
itemDom.loadXML('- ');
item = true;
}
}
var qryString = report_query;
if (item) {
qryString = this.applyXsltString(itemDom, xslt);
if (qryString) {
tmpDom = this.createXMLDocument();
tmpDom.loadXML(qryString);
qryString = tmpDom.documentElement.text;
}
}
if (qryString) {
url += '&' + qryString;
}
}
processResults(results);
}
function processResults (results) {
if (typeof (results) === "undefined") {
results = "";
}
else if (typeof (results) !== "string") {
results = results.toString();
}
// Transformation for vault-images
var substr = "vault:\/\/\/\?fileid\=";
var fileIdpos = results.toLowerCase().indexOf(substr);
while (fileIdpos != -1) {
var vaultUrl = results.substring(fileIdpos, fileIdpos + substr.length + 32);
fileIdpos += substr.length;
var fileId = vaultUrl.replace(/vault:\/\/\/\?fileid\=/i, "");
var vaultUrlwithToken = self.IomInnovator.getFileUrl(fileId, self.Enums.UrlType.SecurityToken);
results = results.replace(vaultUrl, vaultUrlwithToken);
var fileIdpos = results.toLowerCase().indexOf(substr, fileIdpos + 32);
}
// Add element
in result for correct loading picture.
var searchBaseTagRegExp = /[^]*? [^]*?<\/head>/i;
if (!searchBaseTagRegExp.test(results)) {
var base = " ";
results = results.replace(/<(head[^]*?)\/>/i, "<$1>");
results = results.replace(/()([^]*?<\/head>)/i, "$1" + base + "$2");
if (!searchBaseTagRegExp.test(results)) {
results = results.replace(//i, "$0" + "" + base + "");
}
}
//Chrome new window blocked non event user action
setTimeout(function() {
self.targetReport(report, report_location, url, results);
}, 0)
}
}
Aras.prototype.targetReport = function(report, report_location, url, results, doReturnWindow) {
var target = this.getItemProperty(report, 'target') || 'window';
var doc = null;
var self = this;
var tabsObj = this.getMainWindow().arasTabs;
var close = 'var close = function(callback) { \
if (!callback) { \
var tab = window.parent.document.querySelector("li[data-id=" + this.frameElement.id + "]"); \
tabsObj.removeTab(tab); \
} else { \
callback(true); \
} \
};';
var focus = 'var focus = function() { \
var tab = window.parent.document.querySelector("li[data-id=" + this.frameElement.id + "]"); \
tabsObj.selectTab(tab); \
};';
var createScript = function(win) {
var script = win.document.createElement('script');
script.textContent = 'var tabsObj = window.parent.arasTabs;';
script.textContent += 'window.opener = window.parent;';
script.textContent += close;
script.textContent += focus;
win.document.body.appendChild(script);
};
var openReportInTab = function(mode, report_location, url) {
var winName = self.mainWindowName + '_' + self.getItemProperty(report, 'id');
var win;
mode = mode || 'tab';
if (mode === 'tab' && report_location !== 'service') {
winName = winName + '_' + Date.now();
}
var mainWindowDoc = self.getMainWindow().document;
var frame = mainWindowDoc.getElementById(winName);
if (!frame) {
win = tabsObj.open(url || aras.getScriptsURL() + 'blank.html', winName);
var tab = mainWindowDoc.querySelector('li[data-id="' + winName + '"]');
var title = ' ' + self.getItemProperty(report, 'name');
tabsObj.updateTitleTab(title, tab);
} else {
win = frame.contentWindow;
win.focus();
}
if (report_location !== 'service') {
win.document.write(results);
win.document.write(' ');
win.document.body.style.background = '#fff';
}
if (!win.tabsObj) {
url ? win.frameElement.addEventListener('load', createScript.bind(null, win)) : createScript(win);
}
return win;
};
if (target == 'window') {
if (tabsObj) {
return openReportInTab('tab', report_location, url);
}
var width = 800, // This is a printable page width.
height = screen.availHeight / 2,
x = (screen.availHeight - height) / 2,
y = (screen.availWidth - width) / 2,
args = 'scrollbars=yes,resizable=yes,status=yes,width=' + width + ',height=' + height + ',left=' + y + ',top=' + x;
if (report_location == 'service') {
var win = open(url, '', args);
if (doReturnWindow) {
return win;
}
return;
}
var win = open('', '', args);
doc = win.document.open();
var name = this.getItemProperty(report, 'label');
if (!name) {
name = this.getItemProperty(report, 'name');
}
name = this.getResource('', 'aras_object.report_with_label', name);
doc.write(results);
doc.close();
win.document.title = name;
if (doReturnWindow) {
return win;
}
}
else if (target == 'main')
{
var mainWindow = this.getMainWindow();
if (report_location == 'service') {
var container = '';
doc = mainWindow.work.document.open();
doc.write(container);
doc.close();
return;
}
doc = mainWindow.work.document.open();
doc.write(results);
doc.close();
} else if (target == 'none') {
return;
} else if (target == 'one window') {
if (tabsObj)
{
return openReportInTab('one tab', report_location, url);
}
var targetWindow;
if (report_location == 'service') {
targetWindow = this.getActionTargetWindow(name, url);
return;
}
targetWindow = this.getActionTargetWindow(name);
doc = targetWindow.document;
doc.write(results);
doc.write(' ');
}
};
/*-- runClientReport
*
* Invoke the Method associated with a report.
* report = the the Report item
*
* parameter itemTypeID is ignored
*/
Aras.prototype.runClientReport = function Aras_runClientReport(report, itemTypeID, item) {
if (!report) {
this.AlertError(this.getResource('', 'aras_object.failed_get_report'), '', '');
return;
}
var results = '';
var selectedItem = item;
report = this.getItemFromServer('Report', report.getAttribute('id'), 'label,name,description,report_query,target,type,xsl_stylesheet,location,method(name,method_type,method_code)').node;
var reportType = this.getItemProperty(report, 'type');
var methodName = this.getItemPropertyAttribute(report, 'method', 'keyed_name');
if (methodName) {
results = reportType == 'item' ? this.evalItemMethod(methodName, selectedItem) : this.evalMethod(methodName, '');
} else {
var report_query = this.getItemProperty(report, 'report_query');
if (!report_query) {
if (reportType == 'item') {
report_query = '- ';
} else if (reportType == 'itemtype') {
report_query = '
- ';
} else if (reportType == 'generic') {
report_query = '';
}
}
if (report_query) {
var xslt = '
' +
'' +
' ' +
' ' +
' ' +
' ' + report_query + ' ' +
' ';
var itemDom = this.createXMLDocument();
if (item) {
itemDom.loadXML(item.xml);
}
var query = this.applyXsltString(itemDom, xslt);
if (query) {
results = this.applyItem(query);
} else {
results = this.applyItem(report_query);
}
var xsl_stylesheet = this.getItemProperty(report, 'xsl_stylesheet');
if (xsl_stylesheet) {
var xslt_stylesheetDOM = this.createXMLDocument();
xslt_stylesheetDOM.loadXML(xsl_stylesheet);
var toolLogicNode = xslt_stylesheetDOM.selectSingleNode('//script[@userData="Tool Logic"]');
if (toolLogicNode) {
toolLogicNode.parentNode.removeChild(toolLogicNode);
}
xsl_stylesheet = xslt_stylesheetDOM.xml;
var res = this.createXMLDocument();
res.loadXML(results);
if (reportType == 'item') {
res.loadXML('' + results + ' ');
} else {
res.loadXML(results);
}
results = this.applyXsltString(res, xsl_stylesheet);
}
}
}
return results;
};
Aras.prototype.runServerReport = function Aras_runServerReport(report, itemTypeID, item) {
if (!report) {
this.AlertError(this.getResource('', 'aras_object.failed_get_report'), '', '');
return;
}
var report_name = this.getItemProperty(report, 'name');
var AML = '';
if (item) {
var item_copy = item.cloneNode(true);
if (itemTypeID) {
item_copy.setAttribute('typeId', itemTypeID);
}
AML = item_copy.xml;
} else if (itemTypeID) {
AML = ' ';
}
var body = '' + report_name + ' ' + AML + ' ';
var results = this.applyMethod('Run Report', body);
return results;
};
/*-- setNodeElementWithAction
*
* Method to set the value of an element on the node
* and set action attribute on the node, if it is absent.
* The item is the node and the property is the element.
* node = the item object
* element = the property to set
* value = the value for the property
* apply_the_change_to_all_found = flag to signal if the change must be common or local
* action - action attribute to be set on the node. By default, if action is not defined
* and node action attribute != 'add' or != 'create' we set action 'update'
*/
Aras.prototype.setNodeElementWithAction = function Aras_setNodeElementWithAction(srcNode, element, value, apply_the_change_to_all_found, action) {
this.setNodeElement(srcNode, element, value, apply_the_change_to_all_found);
if (!srcNode.getAttribute('action') || (srcNode.getAttribute('action') != 'add') && (srcNode.getAttribute('action') != 'create')) {
if (action) {
srcNode.setAttribute('action', action);
} else {
srcNode.setAttribute('action', 'update');
}
}
};
/*-- setItemProperty/setNodeElement
*
* Method to set the value of an element on the node.
* The item is the node and the property is the element.
* node = the item object
* element = the property to set
* value = the value for the property
* apply_the_change_to_all_found = flag to signal if the change must be common or local
*/
Aras.prototype.setNodeElement = Aras.prototype.setItemProperty = function Aras_setItemProperty(srcNode, element, value, apply_the_change_to_all_found, itemTypeNd) {
if (apply_the_change_to_all_found === undefined) {
apply_the_change_to_all_found = true;
}
var id = srcNode.getAttribute('id');
var propertyName = element;
var propertyValue = value;
if (propertyValue == null) {
propertyValue = '';
}
function isEmptyElement(xmlElem) {
if (xmlElem) {
if (xmlElem.hasChildNodes() || xmlElem.attributes.length != 0) {
return false;
}
}
return true;
}
function getPropertyDataType(arasObj, itemTypeName, propertyName) {
var itemType = itemTypeNd ? itemTypeNd : arasObj.getItemTypeForClient(itemTypeName).node;
if (!itemType) {
return '';
}
var data_type = itemType.selectSingleNode('Relationships/Item[@type="Property"][name="' + propertyName + '"]/data_type');
if (data_type) {
return data_type.text;
}
return '';
}
var currDate = new Date();
var LastModifiedOn = currDate.getTime();
function setItemProperty_internal(arasObj, node) {
var elm = node.selectSingleNode(propertyName);
if (!elm) {
elm = node.appendChild(node.ownerDocument.createElement(propertyName));
}
if (elm.getAttribute('is_null') != '') {
elm.removeAttribute('is_null');
}
var elementWasEmpty = isEmptyElement(elm);
var item_Type = '';
var valueIsNode;
if (propertyValue.xml == undefined) {
valueIsNode = false;
elm.text = propertyValue;
} else {
valueIsNode = true;
elm.text = '';
var value2use = propertyValue;
//check if we insert node into itself
item_Type = propertyValue.getAttribute('type');
var item_ID = propertyValue.getAttribute('id');
var propertyValueClones = value2use.selectNodes('ancestor-or-self::Item[@type=\'' + item_Type + '\' and @id=\'' + item_ID + '\']');
var isACopyOfParent = false;
for (var i = 0; i < propertyValueClones.length; i++) {
if (propertyValue == propertyValueClones[i]) {
isACopyOfParent = true;
break;
}
}
if (isACopyOfParent || propertyValueWasTransfered) {
value2use = value2use.cloneNode(true);
}
propertyValueWasTransfered = true;
elm.appendChild(value2use);
}
var updateKeyedName = false;
if (elm.getAttribute('keyed_name') != null) {
updateKeyedName = true;
} else if (elementWasEmpty) {
var srcItemType = srcNode.getAttribute('type');
if (srcItemType) {
if (getPropertyDataType(arasObj, srcItemType, propertyName) == 'item') {
updateKeyedName = true;
}
}
}
if (updateKeyedName) {
var newKeyedName;
if (valueIsNode) {
newKeyedName = arasObj.getKeyedNameEx(propertyValue);
} else {
var propertyItemType = elm.getAttribute('type');
if (propertyItemType == null) {
propertyItemType = '';
}
newKeyedName = arasObj.getKeyedName(propertyValue, propertyItemType);
}
elm.setAttribute('keyed_name', newKeyedName);
elm.removeAttribute('discover_only');
if (propertyValue) {
var cachedItem = null;
if (item_Type == 'ItemType') {
cachedItem = arasObj.getItemTypeDictionary((valueIsNode ? propertyValue.getAttribute('id') : propertyValue), 'id');
if (cachedItem && cachedItem.node) {
cachedItem = cachedItem.node;
}
} else {
cachedItem = arasObj.itemsCache.getItem(valueIsNode ? propertyValue.getAttribute('id') : propertyValue);
}
if (cachedItem && cachedItem.getAttribute('discover_only') == '1') {
elm.setAttribute('discover_only', '1');
}
}
if (valueIsNode) {
var oldKeyedName = arasObj.getItemProperty(propertyValue, 'keyed_name');
if (!oldKeyedName && newKeyedName) {
arasObj.setItemProperty(propertyValue, 'keyed_name', newKeyedName, false);
}
}
}
node.setAttribute('LastModifiedOn', LastModifiedOn);
}
var node;
var skip_src_node = false;
var nodes = this.itemsCache.getItemsByXPath('//Item[@id=\'' + id + '\']');
var propertyValueWasTransfered = false;
if (apply_the_change_to_all_found) {
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
if (node === srcNode) {
skip_src_node = true;
}
setItemProperty_internal(this, node);
}
}
if (!skip_src_node) {
setItemProperty_internal(this, srcNode);
}
var oParent = srcNode;
var nds2MarkAsDirty = oParent.selectNodes('ancestor-or-self::Item');
var nd;
for (var i = 0; i < nds2MarkAsDirty.length; i++) {
nd = nds2MarkAsDirty[i];
if (this.isLockedByUser(nd)) {
nd.setAttribute('isDirty', '1');
}
}
return true;
};
/*-- getItemProperty/getNodeElement
*
* Method to get the value of an element on the node.
* The item is the node and the property is the element.
* node = the item object
* element = the property to set
*
*/
Aras.prototype.getItemProperty = Aras.prototype.getNodeElement = function(node, element, defaultVal) {
if (!node) {
return;
}
var value;
if (node.nodeName == 'Item' && element == 'id') {
value = node.getAttribute('id');
} else {
var tmpNd = node.selectSingleNode(element);
if (tmpNd) {
var tmpNd2 = tmpNd.selectSingleNode('Item');
if (tmpNd2) {
value = tmpNd2.getAttribute('id');
} else {
value = tmpNd.text;
}
} else {
value = (defaultVal === undefined ? '' : defaultVal);
}
}
return value;
};
Aras.prototype.setNodeTranslationElement = Aras.prototype.setItemTranslation = function Aras_setItemTranslation(srcNode, mlPropNm, value, lang) {
var pNd;
this.getItemTranslation(srcNode, mlPropNm, lang, null, function(foundNode) {
pNd = foundNode;
});
if (!pNd) {
pNd = this.browserHelper.createTranslationNode(srcNode, mlPropNm, this.translationXMLNsURI, this.translationXMLNdPrefix);
pNd = srcNode.appendChild(pNd);
pNd.setAttribute('xml:lang', lang);
}
if (value === null || value === undefined) {
value = '';
pNd.setAttribute('is_null', '1');
}
pNd.text = value;
};
Aras.prototype.getNodeTranslationElement = Aras.prototype.getItemTranslation = function Aras_getItemTranslation(srcNode, mlPropNm, lang, defaultVal, foundNodeCb) {
var pNd = this.browserHelper.getNodeTranslationElement(srcNode, mlPropNm, this.translationXMLNsURI, lang);
if (foundNodeCb) {
foundNodeCb(pNd);
}
if (!pNd) {
return (defaultVal === undefined ? '' : defaultVal);
}
return pNd.text;
};
Aras.prototype.setNodeTranslationElementAttribute = Aras.prototype.setItemTranslationAttribute = function Aras_setItemTranslationAttribute(srcNode, mlPropNm, lang, attribute, value) {
this.getItemTranslation(srcNode, mlPropNm, lang, null, function(foundNode) {
if (foundNode) {
foundNode.setAttribute(attribute, value);
}
});
};
Aras.prototype.getNodeTranslationElementAttribute = Aras.prototype.getItemTranslationAttribute = function Aras_getItemTranslationAttribute(srcNode, mlPropNm, lang, attribute, defaultVal) {
var r;
this.getItemTranslation(srcNode, mlPropNm, lang, null, function(foundNode) {
if (foundNode) {
r = foundNode.getAttribute(attribute);
}
});
if (r === undefined) {
r = (defaultVal === undefined ? '' : defaultVal);
}
return r;
};
Aras.prototype.removeItemTranslation = function Aras_removeItemTranslation(srcNode, mlPropNm, lang) {
this.getItemTranslation(srcNode, mlPropNm, lang, null, function(foundNode) {
if (foundNode) {
srcNode.removeChild(foundNode);
}
});
};
Aras.prototype.removeNodeTranslationElementAttribute = Aras.prototype.removeItemTranslationAttribute = function Aras_setItemTranslationAttribute(srcNode, mlPropNm, lang, attribute) {
this.getItemTranslation(srcNode, mlPropNm, lang, null, function(foundNode) {
if (foundNode) {
foundNode.removeAttribute(attribute);
}
});
};
/*-- setNodeElementAttribute/setItemPropertyAttribute
*
* Method to set the value of an attribute on an element on the node.
* The item is the node and the property is the element.
* node = the item object
* element = the property to set
* attribute = the name of the attribute
* value = the value for the attribute
*
*/
Aras.prototype.setNodeElementAttribute = Aras.prototype.setItemPropertyAttribute = function(node, element, attribute, value) {
if (!node) {
return;
}
var elm = node.selectSingleNode(element);
if (elm) {
elm.setAttribute(attribute, value);
} else {
this.newNodeElementAttribute(node, element, attribute, value);
}
};
/*-- getNodeElementAttribute/getItemPropertyAttribute
*
* Method to get the value of an attribute on an element on the node.
* The item is the node and the property is the element.
* node = the item object
* element = the property to get
* attribute = the name of the attribute
*
*/
Aras.prototype.getNodeElementAttribute = Aras.prototype.getItemPropertyAttribute = function(node, element, attribute) {
if (!node) {
return null;
}
var value = null;
var elm = node.selectSingleNode(element);
if (!elm) {
return null;
} else {
value = elm.getAttribute(attribute);
}
return value;
};
Aras.prototype.removeNodeElementAttribute = Aras.prototype.removeItemPropertyAttribute = function(node, element, attribute) {
var elm = node.selectSingleNode(element);
if (elm) {
elm.removeAttribute(attribute);
}
};
/*-- newNodeElementAttribute/newItemPropertyAttribute
*
* Method to create a new element (property) for the item node and set the value of an attribute on an element on the node.
* The item is the node and the property is the element.
* node = the item object
* element = the property to set
* attribute = the name of the attribute
* value = the value for the attribute
*
*/
Aras.prototype.newNodeElementAttribute = Aras.prototype.newItemPropertyAttribute = function(node, element, attribute, value) {
var elm = this.createXmlElement(element, node);
elm.setAttribute(attribute, value);
return elm;
};
/*-- getValueByXPath
*
* Method to get the text value for an element by XPath.
* xpath = the APath to the element
* node = the optional node otherwise use the global dom
*
*/
Aras.prototype.getValueByXPath = function(xpath, node) {
if (arguments.length < 2) {
var node = this.dom;
}
if (!node.selectSingleNode(xpath)) {
return;
}
return node.selectSingleNode(xpath).text;
};
/*-- getItemTypeByFormID
*
* Method to load a ItemType by Form ID
* id = the id for the Form item
*
*/
Aras.prototype.getItemTypeByFormID = function(id, ignoreFault) {
if (ignoreFault == undefined) {
ignoreFault = false;
}
var res = this.soapSend('GetItemTypeByFormID', ' ');
if (res.getFaultCode() != 0) {
if (!ignoreFault) {
this.AlertError(res);
}
return false;
}
var itemTypeID = res.results.selectSingleNode('//Item').getAttribute('id');
return this.getItemTypeDictionary(itemTypeID, 'id').node;
};
/*-- setUserWorkingDirectory
*
* Method to set the users working directory
* id = the id for the user
* workingDir = the working directory
*
*/
Aras.prototype.setUserWorkingDirectory = function(id, workingDir) {
var elm = this.createXmlElement('Item');
elm.setAttribute('id', id);
elm.setAttribute('workingDir', workingDir);
var res = this.soapSend('SetUserWorkingDirectory', elm.xml);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
};
/*-- getNextSequence
*
* Method to get the next value from a sequence item
* id = the id for the sequence (optional if seqName is used)
* seqName = the sequence name (optional is the id is used)
*
*/
Aras.prototype.getNextSequence = function(id, seqName) {
if (id == undefined) {
id = '';
}
var body = '- ';
if (seqName != undefined) {
body += '
' + seqName + ' ';
}
body += ' ';
var res = this.soapSend('GetNextSequence', body);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
return res.results.selectSingleNode(this.XPathResult()).text;
};
/*-- buildIdentityList
*
* Method to get list of identity IDs for those current user is a member.
* The list is a string and has following format:
* identityID,identityID,...,identityID
*
*/
Aras.prototype.buildIdentityList = function Aras_buildIdentityList(identityListSoapResults) {
if (identityListSoapResults.getFaultCode() != 0) {
this.AlertError(identityListSoapResults);
this.setIdentityList('');
} else {
this.setIdentityList(identityListSoapResults.results.selectSingleNode(this.XPathResult()).text);
}
return this.getIdentityList();
};
Aras.prototype.applySortOrder = function Aras_applySortOrder(relationshipsArray) {
//this method is for internal purposes only.
var arasObj = this;
function sortOrderComparer(nd1, nd2) {
var sortOrder1 = parseInt(arasObj.getItemProperty(nd1, 'sort_order'));
if (isNaN(sortOrder1)) {
return 1;
}
var sortOrder2 = parseInt(arasObj.getItemProperty(nd2, 'sort_order'));
if (isNaN(sortOrder2)) {
return -1;
}
if (sortOrder1 > sortOrder2) {
return 1;
} else if (sortOrder1 == sortOrder2) {
return 0;
}
return -1;
}
//relationshipsArray.sort(sortOrderComparer); doesn't work sometimes with error "Object doesn't support this property or method".
//in debugger I see that relationshipsArray.sort is defined but call relationshipsArray.sort() throws the exception
//work around:
var tmpArray = new Array();
for (var i = 0; i < relationshipsArray.length; i++) {
tmpArray.push(relationshipsArray[i]);
}
tmpArray.sort(sortOrderComparer);
for (var i = 0; i < relationshipsArray.length; i++) {
relationshipsArray[i] = tmpArray[i];
}
tmpArray = null;
};
Aras.prototype.getSeveralListsValues = function Aras_getSeveralListsValues(listsArray, is_bgrequest, readyResponseIfNeed) {
//this method is for internal purposes only.
var res = new Object();
var listIds = new Array();
var filterListIds = new Array();
var listsArrayCopy = new Array();
var typesArray = new Object();
for (var i = 0; i < listsArray.length; i++) {
var listDescr = listsArray[i];
var listId = listDescr.id;
var relType = listDescr.relType;
typesArray[listId] = relType;
if (is_bgrequest && !readyResponseIfNeed) {
var listDescrCopy = {id: listId, relType: relType};
listsArrayCopy.push(listDescrCopy);
}
var key = this.MetadataCache.CreateCacheKey('getSeveralListsValues-' + relType, listId);
if (!this.MetadataCache.GetItem(key)) {
if (relType == 'Value') {
listIds.push(listId);
} else if (relType == 'Filter Value') {
filterListIds.push(listId);
}
}
}
var response = readyResponseIfNeed;
if ((listIds.length != 0) || (filterListIds.length != 0)) {
if (!response) {
response = this.MetadataCache.GetList(listIds, filterListIds);
}
if (response.getFaultCode() != 0) {
return res;
}
var items = response.results.selectNodes(this.XPathResult('/Item'));
for (var i = 0; i < items.length; i++) {
var listNd = items[i];
var id = this.getItemProperty(listNd, 'id');
var key = this.MetadataCache.CreateCacheKey('getSeveralListsValues-' + typesArray[id], id);
this.MetadataCache.SetItem(key, listNd);
}
}
for (var i = 0; i < listsArray.length; i++) {
var valuesArr = [];
var listDescr = listsArray[i];
var listId = listDescr.id;
var key = this.MetadataCache.CreateCacheKey('getSeveralListsValues-' + typesArray[listId], listId);
var listNode = this.MetadataCache.GetItem(key);
if (listNode) {
var values = listNode.selectNodes('Relationships/Item');
for (var j = 0; j < values.length; j++) {
valuesArr.push(values[j]);
}
this.applySortOrder(valuesArr);
res[listNode.getAttribute('id')] = valuesArr;
}
}
// 1) add stubs for not found lists
// 2) mark lists as requested in the session for preloading in future sessions
for (var i = 0; i < listsArray.length; i++) {
var listDescr = listsArray[i];
var listId = listDescr.id;
var relType = listDescr.relType;
if (res[listId] === undefined) {
res[listId] = [];
}
}
return res;
};
Aras.prototype.getListValues_implementation = function Aras_getListValues_implementation(listID, relType, is_bgrequest) {
//this method is for internal purposes only.
var listsArray = [];
var listDescr = new Object();
listDescr.id = listID;
listDescr.relType = relType;
listsArray.push(listDescr);
var res = this.getSeveralListsValues(listsArray, is_bgrequest);
return res[listID];
};
/*-- getListValues
*
* Method to get the Values for a List item
* listId = the id for the List
*
*/
Aras.prototype.getListValues = function Aras_getListValues(listID, is_bgrequest) {
return this.getListValues_implementation(listID, 'Value', is_bgrequest);
};
/*-- getListFilterValues
*
* Method to get the Filter Value for a List item
* listId = the id for the List
*
*/
Aras.prototype.getListFilterValues = function Aras_getListFilterValues(listID, is_bgrequest) {
return this.getListValues_implementation(listID, 'Filter Value', is_bgrequest);
};
/*-- clearCache
*
* Method to clear the server cache
*
*/
Aras.prototype.clearCache = function() {
var res = this.soapSend('ClearCache', ' ');
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
return true;
};
/*-- getItemStyles
*
* Method to get the style for the item
* item - dom object for the item
*
*/
Aras.prototype.getItemStyles = function(item) {
if (!item) {
return null;
}
var css = this.getItemProperty(item, 'css');
if (css == '') {
return null;
}
var res = new Object();
var styles = css.split('\n');
var styleTmplt = new RegExp(/^\.(\w)+(\s)*\{(\w|\s|\:|\-|\#|\;)*\}$/);
for (var i = 0; i < styles.length; i++) {
var style = styles[i];
if (!styleTmplt.test(style)) {
continue;
}
var tmp = style.split('{');
var styleNm = tmp[0].substr(1).replace(/\s/g, '');
var propertiesStr = tmp[1].substr(0, tmp[1].length - 1);
var properties = propertiesStr.split(';');
var styleObj = new Object();
for (var j = 0; j < properties.length; j++) {
tmp = properties[j].split(':');
if (tmp.length == 2) {
var propNm = tmp[0].replace(/\s/g, '');
var propVl = tmp[1].replace(/\s/g, '');
if (propNm) {
styleObj[propNm] = propVl;
}
}
}
res[styleNm] = styleObj;
}
return res;
};
/*-- applyCellStyle
*
* Method to to apply the item style to teh grid cell
* cell - the grid cell object
* style - the style for the cell
* setBg - boolean to set the background for the cell
*
*/
Aras.prototype.applyCellStyle = function(cell, style, setBg) {
if (style['color']) {
cell.setTextColor(style['color']);
}
if (setBg && style['background-color']) {
cell.setBgColor_Experimental(style['background-color']);
}
if (style['font-family']) {
var font = style['font-family'].split(',')[0];
if (style['font-size']) {
font += '-' + style['font-size'].split('p')[0];
}
cell.setFont(font);
}
if (style['font-weight'] && style['font-weight'] == 'bold') {
cell.setTextBold();
}
};
Aras.prototype.preserveTags = function(str) {
if (str == undefined) {
return;
}
if (str == '') {
return str;
}
str = str.replace(/&/g, '&');
str = str.replace(//g, '>');
return str;
};
Aras.prototype.escapeXMLAttribute = function(strIn) {
if (strIn == undefined) {
return;
}
if (strIn == '') {
return strIn;
}
strIn = strIn.replace(/&/g, '&');
strIn = strIn.replace(//g, '>');
strIn = strIn.replace(/"/g, '"');
strIn = strIn.replace(/'/g, ''');
return strIn;
};
/*-- findMainArasObject
*
* Returns a pointer to the main Aras object (from the main window)
*
*/
Aras.prototype.findMainArasObject = function Aras_findMainArasObject() {
var isMainWindow = (this.getMainWindow().name == this.mainWindowName);
if (!isMainWindow) {
if (this.parentArasObj) {
return this.parentArasObj.findMainArasObject();
} else {
var topWnd = this.getMostTopWindowWithAras(window);
if (topWnd.opener && !this.isWindowClosed(topWnd.opener) && topWnd.opener.topWnd.aras) {
return topWnd.opener.topWnd.aras.findMainArasObject();
}
}
}
return this;
};
/*-- registerEventHandler
*
* Register Handler for event by win
* see fireEvent description for details
*/
Aras.prototype.registerEventHandler = function Aras_registerEventHandler(eventName, win, handler) {
var EvHandlers;
var topWnd = this.getMostTopWindowWithAras();
try {
EvHandlers = topWnd['Event Handlers'];
}
catch (excep) {
return false;
}
if (!EvHandlers) {
topWnd.eval('window[\'Event Handlers\'] = new Object();');
EvHandlers = topWnd['Event Handlers'];
}
if (!EvHandlers[eventName]) {
topWnd.eval('window[\'Event Handlers\'][\'' + eventName + '\'] = new Array();');
}
EvHandlers[eventName].push(handler);
return true;
};
/*-- unregisterEventHandler
*
* UnRegister Handler for event by win
*
*/
Aras.prototype.unregisterEventHandler = function Aras_unregisterEventHandler(eventName, win, handler) {
var EvHandlers;
var topWnd = this.getMostTopWindowWithAras();
try {
EvHandlers = topWnd['Event Handlers'];
}
catch (excep) {
return false;
}
if (!EvHandlers) {
return true;
}
var handlersArr = EvHandlers[eventName];
if (!handlersArr) {
return true;
}
for (var i = 0; i < handlersArr.length; i++) {
if (handlersArr[i] == handler) {
handlersArr.splice(i, 1);
return true;
}
}
return false;
};
/*-- fireEvent
*
* fires event in all windows
* supported events:
* "VariableChanged": {varName, varValue}
* "ItemLock": {itemID, itemNd, newLockedValue}
* "ItemSave": {itemID, itemNd}
*
*/
Aras.prototype.fireEvent = function Aras_fireEvent(eventName, params) {
var mainAras = this.findMainArasObject();
if (this != mainAras) {
return mainAras.fireEvent(eventName, params);
}
if (!eventName) {
return false;
}
var topWindow = this.getMostTopWindowWithAras(window);
for (var winId in this.windowsByName) {
if (!this.windowsByName.hasOwnProperty(winId)) {
continue;
}
var win = null;
try {
win = this.windowsByName[winId];
if (this.isWindowClosed(win)) {
continue;
}
if (this.getMostTopWindowWithAras(win) == topWindow) {
continue;
}
}
catch (excep) {
continue;
}
var EvHandlers = null;
try {
EvHandlers = this.getMostTopWindowWithAras(win)['Event Handlers'];
if (!EvHandlers) {
continue;
}
}
catch (excep) {
continue;
}
var handlersArr = EvHandlers[eventName];
if (!handlersArr) {
continue;
}
for (var i = 0; i < handlersArr.length; i++) {
try {
handlersArr[i](params);
}
catch (excep) {
}
}
}
var EvHandlers = topWindow['Event Handlers'];
if (!EvHandlers) {
return true;
}
var handlersArr = EvHandlers[eventName];
if (!handlersArr) {
return true;
}
var handlers2Remove = new Array();
for (var i = 0; i < handlersArr.length; i++) {
var f = handlersArr[i];
try {
f(params);
}
catch (e) {
// it's IE error code that means that a context of the method (handlersArr[i]) has already been freed and the method cannot be executed. Usually it would happen if window/iframe in which this method was
// initialized was destroyed/closed. It would be better unregister such handlers after its window/iframe was destroyed/closed so that this error isn't occur at all.
var resourceHasBeenFreedExceptionNumberInIE = -2146823277; // "Can't execute code from a freed script" IE error
if (e.number == resourceHasBeenFreedExceptionNumberInIE || this.Browser.isCh()) {
// temporary fix for issue IR-039156 "No save after remove row from BOM tab".
// The problem is that in Chrome browser "Can't execute code from a freed script" error hasn't a particular number/code so there is no possibility
// to understand that exactly this error has occured. So as a temp fix all errors in Chrome will not be thrown as an exception.
// todo In Innovator 12 we must remove this part of code (isCh() if) and make unregistering of 'ItemSaveListener' eventHandler on 'unload' event from Solutions/PLM/Import/Form/Part MultiLevel BOM.xml
handlers2Remove.push(f);
} else {
throw e;
}
}
}
for (var i = handlers2Remove.length - 1; i >= 0; i--) {
this.unregisterEventHandler(eventName, topWindow, handlers2Remove[i]);
}
};
Aras.prototype.getCurrentWindow = function Aras_getCurrentWindow() {
return window;
};
Aras.prototype.getMainWindow = function Aras_getMainWindow()
{
try
{
var mainWindow = this.getCommonPropertyValue('mainWindow');
if (mainWindow)
{
return mainWindow;
}
var topWindowWithAras = this.getMostTopWindowWithAras(window);
var isMainWindow = (topWindowWithAras.name == this.mainWindowName);
if (isMainWindow)
{
return topWindowWithAras;
}
//this function is to avoid explicit "top" usage
function getTopWindow(windowObj)
{
var win = windowObj ? windowObj : window;
while (win !== win.parent) {
//We should not care about any cross-domain case since "main window" case is not considered here
win = win.parent;
}
return win;
}
var topWnd = getTopWindow(), topWnd2;
if (topWnd.opener && !this.isWindowClosed(topWnd.opener))
{
topWnd2 = this.getMostTopWindowWithAras(topWnd.opener);
topWnd2 = this.isWindowClosed(topWnd2) ? null : topWnd2;
}
if (!topWnd2)
{
topWnd2 = this.getMostTopWindowWithAras(topWnd.dialogOpener);
topWnd2 = this.isWindowClosed(topWnd2) ? null : topWnd2;
}
return topWnd2 ? topWnd2.aras.getMainWindow() : topWnd;
}
catch (excep)
{
return null;
}
};
Aras.prototype.getMainArasObject = function Aras_getMainArasObject() {
var res = null;
var mainWnd = this.getMainWindow();
if (mainWnd && !this.isWindowClosed(mainWnd)) {
res = mainWnd.aras;
}
return res;
};
Aras.prototype.newQryItem = function Aras_newQryItem(itemTypeName) {
var mainArasObj = this.getMainArasObject();
if (mainArasObj && mainArasObj != this) {
return mainArasObj.newQryItem(itemTypeName);
}
else
{
var topWnd = this.getMostTopWindowWithAras(window);
return (new topWnd.QryItem(topWnd.aras, itemTypeName));
}
};
Aras.prototype.newObject = function Aras_newObject() {
var mainArasObj = this.getMainArasObject();
if (mainArasObj && mainArasObj != this) {
return mainArasObj.newObject();
} else {
return (new Object());
}
};
Aras.prototype.deletePropertyFromObject = function Aras_deletePropertyFromObject(obj, key) {
if (key in obj) {
return delete obj[key];
}
return true;
};
Aras.prototype.newIOMItem = function Aras_newIOMItem(itemTypeName, action) {
return this.IomInnovator.newItem(itemTypeName, action);
};
Aras.prototype.newIOMInnovator = function Aras_newIOMInnovator(contextAras) {
var mainArasObj = this.getMainArasObject();
if (mainArasObj && mainArasObj != this) {
return mainArasObj.newIOMInnovator(this);
} else {
//It's important to pass InnovatorServerConnector constructor by *contextAras* instead of *mainArasObj* so that IE could properly work with files selected by a user.
//A problem is that in IE we have no access to files created by any other window.
//So reading/sending/saving of the files must be performed in a context of the window created the files
//because for each new window there is a new Vault object (that is contained in own arasObject) and this Vault object works with files of the window.
//Note: previously each instance of InnovatorServerConnector was passed only by *mainArasObj*.
var serverConnection = new Aras.IOM.InnovatorServerConnector(contextAras || this);
var connector = this.IomFactory.CreateComISConnection(serverConnection);
return this.IomFactory.CreateInnovator(connector);
}
};
Aras.prototype.newArray = function Aras_newArray() {
var mainArasObj = this.getMainArasObject();
if (mainArasObj && mainArasObj != this) {
var str2eval = '';
for (var i = 0; i < arguments.length; i++) {
str2eval += 'args[' + i + '],';
}
if (str2eval != '') {
str2eval = str2eval.substr(0, str2eval.length - 1);
}
str2eval = 'return mainArasObj.newArray(' + str2eval + ');';
var f = new Function('mainArasObj', 'args', str2eval);
return f(mainArasObj, arguments);
} else {
var res;
if (arguments.length == 1) {
res = new Array(arguments[0]);
} else {
res = new Array();
for (var i = 0; i < arguments.length; i++) {
res.push(arguments[i]);
}
}
res.concat = function newArray_concat() {
var resArr = new Array();
for (var i = 0; i < this.length; i++) {
resArr[i] = this[i];
}
for (var i = 0; i < arguments.length; i++) {
if (arguments[i].pop) {
for (var j = 0; j < arguments[i].length; j++) {
resArr.push(arguments[i][j]);
}
} else {
resArr.push(arguments[i]);
}
}
return resArr;
};
return res;
}
};
Aras.prototype.getFileItemTypeID = function Aras_getFileItemTypeID() {
return this.getItemTypeId('File');
};
Aras.prototype.cloneForm = function Aras_cloneForm(formID, newFormName) {
if (!formID || !newFormName) {
return false;
}
var bodyStr = ' ';
var res = null;
with (this) {
var statusId = showStatusMessage('status', getResource('', 'aras_object.copying_form'), system_progressbar1_gif);
res = soapSend('CloneForm', bodyStr);
clearStatusMessage(statusId);
}
if (res.getFaultCode() != 0) {
var win = this.uiFindWindowEx(formID);
if (!win) {
win = window;
}
this.AlertError(res, win);
return false;
}
return true;
};
/**
* Return Vault Server url for current User
* @returns {string}
*/
Aras.prototype.getVaultServerURL = function Aras_getVaultServerURL() {
var vaultServerID = this.getVaultServerID();
if (!vaultServerID) {
return '';
}
if (this.vaultServerURL != undefined) {
return this.vaultServerURL;
}
var vaultNd = this.getItemById('Vault', vaultServerID, 0, '', 'vault_url,name');
if (!vaultNd) {
return '';
}
var vaultServerURL = this.getItemProperty(vaultNd, 'vault_url');
this.VaultServerURL = this.TransformVaultServerURL(vaultServerURL);
return this.VaultServerURL;
};
Aras.prototype.SyncWinInetAndDotNetCredentials = function Aras_SyncWinInetAndDotNetCredentials(baseUrl, authUrl, isDirectUrl) {
//it is possible to check some variable here to not send additional requests when windows auth is disabled.
//but in normal situation this is either 3 fast HEAD requests (when windows auth is disabled)
//or much more requests but when windows auth is enabled and we cannot get passwords from Protected Storage.
//thus for now I do not see a reason for a special check.
if (!isDirectUrl) {
this.WinInetCredentialsCollection.AddFromWinInet(baseUrl, baseUrl + '/WinInetHelper.aspx');
} else {
this.WinInetCredentialsCollection.AddFromWinInet(baseUrl, authUrl);
}
};
Aras.prototype.TransformVaultServerURL = function Aras_TransformVaultServerURL(url) {
var xform_url = this.VaultServerURLCache[url];
if (xform_url != undefined) {
return (xform_url);
}
var res = this.soapSend('TransformVaultServerURL', '' + url + ' ');
if (res.getFaultCode() != 0) {
this.AlertError(res);
return url;
}
var rb = res.getResult();
xform_url = rb.text;
var vaultBaseUrl = xform_url + '/..';
this.VaultServerURLCache[url] = xform_url;
return xform_url;
};
/**
* Get Vault Server ID for current User
* @returns {string} id of Vault Server
*/
Aras.prototype.getVaultServerID = function Aras_getVaultServerID() {
var userNd = null;
var tmpUserID = this.getCurrentUserID();
if (tmpUserID == this.getUserID()) {
userNd = this.getLoggedUserItem();
} else {
userNd = getItemFromServer('User', tmpUserID, 'default_vault').node;
}
if (!userNd) {
return '';
}
var vaultServerID = this.getItemProperty(userNd, 'default_vault');
return vaultServerID;
};
/**
* Create Xml Element. If parent variable exist, add element as child
* @param {string} elName element name to be created
* @param {} parent parent element
* @returns {}
*/
Aras.prototype.createXmlElement = function(elName, parent) {
var doc = this.createXMLDocument();
var element = doc.createElement(elName);
if (parent) {
parent.appendChild(element);
}
return element;
};
/*----------------------------------------
* createXMLDocument
*
* Purpose:
* provide simple way to create xml documents without specifing needed attributes each time
*
* Arguments:
* none
*/
Aras.prototype.createXMLDocument = function Aras_createXMLDocument() {
var mainArasObj = this.getMainArasObject();
if (mainArasObj && mainArasObj != this) {
return mainArasObj.createXMLDocument();
} else {
return new XmlDocument();
}
};
/**
* check if xmldom (soap message) contains Fault
* @param xmlDom xml document with soap message
* @param {boolean} ignoreZeroFault ignore zero faultcode or not
* @returns {boolean}
*/
Aras.prototype.hasFault = function Aras_hasFault(xmlDom, ignoreZeroFault) {
if (ignoreZeroFault) {
return (xmlDom.selectSingleNode(this.XPathFault('[faultcode!=\'0\']')) != null);
} else {
return (xmlDom.selectSingleNode(this.XPathFault()) != null);
}
};
/*----------------------------------------
* getFaultDetails
*
* Purpose:
* get text with fault details
*
* Arguments:
* xmlDom - xml document with soap message
*/
Aras.prototype.getFaultDetails = function Aras_getFaultDetails(xmlDom) {
var fdNd = xmlDom.selectSingleNode(this.XPathFault('/detail'));
if (fdNd == null) {
return '';
} else {
return fdNd.text;
}
};
/*----------------------------------------
* getFaultString
*
* Purpose:
* get text with faultstring
*
* Arguments:
* xmlDom - xml document with soap message
*/
Aras.prototype.getFaultString = function Aras_getFaultString(xmlDom) {
var fdNd = xmlDom.selectSingleNode(this.XPathFault('/faultstring'));
if (fdNd == null) {
return '';
} else {
return fdNd.text;
}
};
/*----------------------------------------
* getFaultString
*
* Purpose:
* get text with faultactor (contains stack trace)
*
* Arguments:
* xmlDom - xml document with soap message
*/
Aras.prototype.getFaultActor = function Aras_getFaultActor(xmlDom) {
var fdNd = xmlDom.selectSingleNode(this.XPathFault('/detail/legacy_faultactor'));
if (fdNd == null) {
return '';
} else {
return fdNd.text;
}
};
Aras.prototype.isInCache = function Aras_isInCache(itemID) {
return this.itemsCache.hasItem(itemID);
};
Aras.prototype.addToCache = function Aras_addToCache(item) {
if (!item) {
return (new CacheResponse(false, this.getResource('', 'aras_object.nothing_to_add'), item));
}
var itemID = item.getAttribute('id');
if (this.isInCache(itemID)) {
return (new CacheResponse(false, this.getResource('', 'aras_object.already_in_cache'), this.getFromCache(itemID)));
}
this.itemsCache.addItem(item);
return (new CacheResponse(true, '', this.getFromCache(itemID)));
};
Aras.prototype.updateInCache = function Aras_updateInCache(item) {
if (!item) {
return (new CacheResponse(false, this.getResource('', 'aras_object.nothing_to_update'), item));
}
var itemID = item.getAttribute('id');
this.itemsCache.updateItem(item);
return (new CacheResponse(true, '', this.getFromCache(itemID)));
};
Aras.prototype.updateInCacheEx = function Aras_updateInCacheEx(oldItm, newItm) {
if (!oldItm) {
return this.addToCache(newItm);
}
if (!newItm) {
return (new CacheResponse(false, this.getResource('', 'aras_object.nothing_to_update'), newItm));
}
var itemID = newItm.getAttribute('id');
this.itemsCache.updateItemEx(oldItm, newItm);
return (new CacheResponse(true, '', this.getFromCache(itemID)));
};
Aras.prototype.removeFromCache = function Aras_removeFromCache(item) {
if (!item) {
return (new CacheResponse(false, this.getResource('', 'aras_object.nothing_to_remove'), item));
}
var paramType = typeof (item);
var itemID;
if (paramType == 'string') {
itemID = item;
} else if (paramType == 'object') {
itemID = item.getAttribute('id');
}
if (this.isInCache(itemID)) {
this.itemsCache.deleteItem(itemID);
}
return (new CacheResponse(true, '', null));
};
Aras.prototype.getFromCache = function getFromCache(itemID) {
if (!itemID) {
return null;
} else {
return this.itemsCache.getItem(itemID);
}
};
Aras.prototype.isPropFilledOnServer = function isPropFilledOnServer(propName) {
if (!propName) {
return false;
}
var props = '^permission_id$|^created_on$|^created_by_id$|^config_id$';
return (propName.search(props) != -1);
};
Aras.prototype.generateExceptionDetails = function Aras_generateExceptionDetails(err, func) {
var resXMLDOM = this.createXMLDocument();
resXMLDOM.loadXML(' ');
var callStackCounter = 0;
var callStack = null;
function addChNode(pNode, chName, chValue) {
var tmp = pNode.appendChild(resXMLDOM.createElement(chName));
if (chValue != '') {
tmp.text = chValue;
}
return tmp;
}
function getFunctionName(func) {
if (!func) {
return this.getResource('', 'aras_object.incorrect_parameter');
}
if (typeof (func) != 'function') {
return this.getResource('', 'aras_object.not_function');
}
var funcDef = func.toString();
funcDef = funcDef.replace(/\/\*([^\*\/]|\*[^\/]|\/)*\*\//g, '');
funcDef = funcDef.replace(/^\s\/\/.*$/gm, '');
/^function([^\(]*)/.exec(funcDef);
var funcName = RegExp.$1;
funcName = funcName.replace(/\s/g, '');
return funcName;
}
function addCallStackEntry(aCaller) {
var funcName;
var funcBody;
if (aCaller) {
funcName = getFunctionName(aCaller);
funcBody = aCaller.toString();
} else {
funcName = 'global code';
funcBody = 'unknown';
}
var fNd = addChNode(callStack, 'function', '');
fNd.setAttribute('name', funcName);
fNd.setAttribute('order', callStackCounter);
var callArgsNd = addChNode(fNd, 'call_arguments', '');
if (aCaller) {
for (var i = 0; i < aCaller.arguments.length; i++) {
var argVal = aCaller.arguments[i];
var argType = 'string';
if (argVal != undefined) {
if (argVal.xml != undefined) {
argType = 'xml';
argVal = argVal.xml;
}
}
var argNd = addChNode(callArgsNd, 'argument', argVal);
argNd.setAttribute('order', i);
argNd.setAttribute('type', argType);
}
}
addChNode(fNd, 'body', funcBody);
callStackCounter++;
}
var root = resXMLDOM.documentElement;
try {
addChNode(root, 'number', err.number);
addChNode(root, 'message', err.message);
var aCaller = func;
callStack = addChNode(root, 'call_stack', '');
while (aCaller) {
addCallStackEntry(aCaller);
aCaller = aCaller.caller;
if (aCaller.caller.length) {
break;
}
}
addCallStackEntry(aCaller);
}
catch (ex2) {
root.text = ex2.message;
}
return resXMLDOM.xml;
};
Aras.prototype.showExceptionDetails = function Aras_showExceptionDetails(err) {
var anErr = err;
var aCaller = this.showExceptionDetails.caller;
var xmlDesc = this.generateExceptionDetails(anErr, aCaller);
var xmlDoc = this.createXMLDocument();
xmlDoc.loadXML(xmlDesc);
var exNd = xmlDoc.selectSingleNode('//Exception');
if (!exNd) {
return;
}
var self = this;
var htmlPrefix =
'' +
'function f(){window.clipboardData.setData("Text", document.getElementById("ta").value);} ' +
'' +
'' +
'';
htmlPrefix = htmlPrefix.replace(/'/g, '\\\\\\\'');
truncateExDetails();
var maxHtmlLen = 2070;
var dtls = exNd.xml;
dtls = dtls.replace(/'/g, '\\\\\\\'');
var maxLen = maxHtmlLen - htmlPrefix.length - htmlSfx.length - 4;
if (maxLen > 0 && dtls && dtls.length > maxLen) {
dtls = dtls.substr(0, maxLen) + '...';
}
if (maxLen <= 0) {
dtls = '';
}
var html = htmlPrefix + dtls + htmlSfx;
if (html.length > maxHtmlLen) {
html = html.substr(0, maxHtmlLen);
}
var options = {
dialogWidth: 500,
dialogHeight: 450,
center: true,
resizable: true,
content: "javascript:'" + html + "'"
};
window.ArasModules.Dialog.show("iframe", options);
function getNdVal(nd) {
if (!nd) {
return '';
}
return self.EscapeSpecialChars(nd.text);
}
function truncateExDetails() {
var nd;
var nds = exNd.selectNodes('call_stack/function/body');
for (var i = 0; i < nds.length; i++) {
nd = nds[i];
if (nd.text && nd.text.length > 80) {
nd.text = nd.text.substr(0, 80) + '...';
}
}
nds = exNd.selectNodes('call_stack/function/call_arguments/argument');
for (var i = 0; i < nds.length; i++) {
nd = nds[i];
if (nd.text && nd.text.length > 20) {
nd.text = nd.text.substr(0, 30) + '...';
}
}
}
};
Aras.prototype.copyRelationship = function Aras_copyRelationship(relationshipType, relationshipID) {
var relResult = this.getItemById(relationshipType, relationshipID, 0, undefined);
var sourceType = this.getItemPropertyAttribute(relResult, 'source_id', 'type');
var sourceID = this.getItemProperty(relResult, 'source_id');
var sourceKeyedName = this.getItemPropertyAttribute(relResult, 'source_id', 'keyed_name');
var relatedItem = this.getRelatedItem(relResult);
var relatedType = '';
var relatedID = '';
var relatedKeyedName = '';
if (!relatedItem || (relatedItem && '1' == relatedItem.getAttribute('is_polymorphic'))) {
var relType = this.getRelationshipType(this.getRelationshipTypeId(relationshipType));
if (!relType || relType.isError()) {
return;
}
relatedType = this.getItemPropertyAttribute(relType.node, 'related_id', 'name');
relatedKeyedName = this.getItemPropertyAttribute(relType.node, 'related_id', 'keyed_name');
} else {
relatedID = relatedItem.getAttribute('id');
relatedType = relatedItem.getAttribute('type');
relatedKeyedName = this.getItemProperty(relatedItem, 'keyed_name');
}
var clipboardItem = this.newObject();
clipboardItem.source_id = sourceID;
clipboardItem.source_itemtype = sourceType;
clipboardItem.source_keyedname = sourceKeyedName;
clipboardItem.relationship_id = relationshipID;
clipboardItem.relationship_itemtype = relationshipType;
clipboardItem.related_id = relatedID;
clipboardItem.related_itemtype = relatedType;
clipboardItem.related_keyedname = relatedKeyedName;
return clipboardItem;
};
Aras.prototype.pasteRelationship = function Aras_pasteRelationship(parentItem, clipboardItem, as_is, as_new, targetRelationshipTN, targetRelatedTN, showConfirmDlg) {
var self = this;
function getProperties4ItemType(itemTypeName) {
if (!itemTypeName) {
return;
}
var qryItem = new Item('ItemType', 'get');
qryItem.setAttribute('select', 'name');
qryItem.setAttribute('page', 1);
qryItem.setAttribute('pagesize', 9999);
qryItem.setProperty('name', itemTypeName);
var relationshipItem = new Item();
relationshipItem.setType('Property');
relationshipItem.setAction('get');
relationshipItem.setAttribute('select', 'name,data_type');
qryItem.addRelationship(relationshipItem);
var results = qryItem.apply();
if (results.isError()) {
self.AlertError(result);
return;
}
return results.getRelationships('Property');
}
function setRelated(targetItem) {
if (relatedType && relatedType !== 'File') {
var relatedItemType = self.getItemTypeForClient(relatedType, 'name');
if (relatedItemType.getProperty('is_dependent') == '1') {
as_new = true;
}
if (as_new == true) {
var queryItemRelated = new Item();
queryItemRelated.setType(relatedType);
queryItemRelated.setID(relatedID);
queryItemRelated.setAttribute('do_add', '0');
queryItemRelated.setAttribute('do_lock', '0');
queryItemRelated.setAction('copy');
var newRelatedItem = queryItemRelated.apply();
if (newRelatedItem.isError()) {
self.AlertError(self.getResource('', 'aras_object.failed_copy_related_item', newRelatedItem.getErrorDetail()), newRelatedItem.getErrorString(), newRelatedItem.getErrorSource());
return false;
}
targetItem.setRelatedItem(newRelatedItem);
}
}
}
if (as_is == undefined || as_new == undefined) {
var qryItem4RelationshipType = new Item();
qryItem4RelationshipType.setType('RelationshipType');
qryItem4RelationshipType.setProperty('name', relationshipType);
qryItem4RelationshipType.setAction('get');
qryItem4RelationshipType.setAttribute('select', 'copy_permissions, create_related');
var RelNode = qryItem4RelationshipType.apply();
if (as_is == undefined) {
as_is = (RelNode.getProperty('copy_permissions') == '1');
}
if (as_new == undefined) {
as_new = (RelNode.getProperty('create_related') == '1');
}
}
var statusId = this.showStatusMessage('status', this.getResource('', 'aras_object.pasting_in_progress'), system_progressbar1_gif);
if (!clipboardItem) {
return;
}
var relationshipType = clipboardItem.relationship_itemtype;
var relationshipID = clipboardItem.relationship_id;
var relatedID = clipboardItem.related_id;
var relatedType = clipboardItem.related_itemtype;
if (relationshipType == targetRelationshipTN) {
var qryItem4CopyRelationship = new Item();
qryItem4CopyRelationship.setType(relationshipType);
qryItem4CopyRelationship.setID(relationshipID);
qryItem4CopyRelationship.setAction('copy');
qryItem4CopyRelationship.setAttribute('do_add', '0');
qryItem4CopyRelationship.setAttribute('do_lock', '0');
var newRelationship = qryItem4CopyRelationship.apply();
if (newRelationship.isError()) {
this.AlertError(this.getResource('', 'aras_object.copy_operation_failed', newRelationship.getErrorDetail()), newRelationship.getErrorString(), newRelationship.getErrorSource());
this.clearStatusMessage(statusId);
return false;
}
newRelationship.removeProperty('source_id');
if (newRelationship.getType() == 'Property' && newRelationship.getProperty('data_type') == 'foreign') {
newRelationship.removeProperty('data_source');
newRelationship.removeProperty('foreign_property');
}
setRelated(newRelationship);
if (!parentItem.selectSingleNode('Relationships')) {
parentItem.appendChild(parentItem.ownerDocument.createElement('Relationships'));
}
var res = parentItem.selectSingleNode('Relationships').appendChild(newRelationship.node.cloneNode(true));
this.clearStatusMessage(statusId);
parentItem.setAttribute('isDirty', '1');
return res;
}
var topWnd = this.getMostTopWindowWithAras(window);
var item = new topWnd.Item(relationshipType, 'get');
item.setID(relationshipID);
var sourceItem = item.apply();
if (sourceItem.getAttribute('isNew') == '1') {
this.AlertError(this.getResource('', 'aras_object.failed_get_source_item'), '', '');
this.clearStatusMessage(statusId);
return false;
}
sourceRelationshipTN = sourceItem.getType();
var targetItem = new Item();
targetItem.setType(sourceRelationshipTN);
targetItem.setAttribute('typeId', sourceItem.getAttribute('typeId'));
if (targetRelationshipTN == undefined) {
targetRelationshipTN = sourceRelationshipTN;
}
if (sourceRelationshipTN != targetRelationshipTN) {
if ((!targetRelatedTN && !relatedType) || targetRelatedTN == relatedType) {
if (showConfirmDlg) {
var convert = this.confirm(this.getResource('', 'aras_object.you_attempting_paste_different_relationship_types', sourceRelationshipTN, targetRelationshipTN));
if (!convert) {
this.clearStatusMessage(statusId);
return this.getResource('', 'aras_object.user_abort');
}
}
targetItem.setType(targetRelationshipTN);
} else {
this.clearStatusMessage(statusId);
return false;
}
}
targetItem.setNewID();
targetItem.setAction('add');
targetItem.setAttribute('isTemp', '1');
parentItem.setAttribute('isDirty', '1');
var sourceProperties = getProperties4ItemType(sourceRelationshipTN);
var targetProperties = getProperties4ItemType(targetRelationshipTN);
var srcCount = sourceProperties.getItemCount();
var trgCount = targetProperties.getItemCount();
var sysProperties =
'^id$|' +
'^created_by_id$|' +
'^created_on$|' +
'^modified_by_id$|' +
'^modified_on$|' +
'^classification$|' +
'^keyed_name$|' +
'^current_state$|' +
'^state$|' +
'^locked_by_id$|' +
'^is_current$|' +
'^major_rev$|' +
'^minor_rev$|' +
'^is_released$|' +
'^not_lockable$|' +
'^css$|' +
'^source_id$|' +
'^behavior$|' +
'^sort_order$|' +
'^config_id$|' +
'^new_version$|' +
'^generation$|' +
'^managed_by_id$|' +
'^owned_by_id$|' +
'^history_id$|' +
'^relationship_id$';
if (as_is != true) {
sysProperties += '|^permission_id$';
}
var regSysProperties = new RegExp(sysProperties, 'ig');
for (var i = 0; i < srcCount; i++) {
var sourceProperty = sourceProperties.getItemByIndex(i);
var srcPropertyName = sourceProperty.getProperty('name');
var srcPropertyDataType = sourceProperty.getProperty('data_type');
if (srcPropertyName.search(regSysProperties) != -1) {
continue;
}
for (var j = 0; j < trgCount; ++j) {
var targetProperty = targetProperties.getItemByIndex(j);
var trgPropertyName = targetProperty.getProperty('name');
var trgPropertyDataType = targetProperty.getProperty('data_type');
if ((srcPropertyName == trgPropertyName) && (srcPropertyDataType == trgPropertyDataType)) {
var item = sourceItem.getPropertyItem(srcPropertyName);
if (!item) {
var value = sourceItem.getProperty(srcPropertyName);
targetItem.setProperty(srcPropertyName, value);
} else {
targetItem.setPropertyItem(srcPropertyName, item);
}
break;
}
}
}
setRelated(targetItem);
if (!parentItem.selectSingleNode('Relationships')) {
parentItem.appendChild(parentItem.ownerDocument.createElement('Relationships'));
}
var res = parentItem.selectSingleNode('Relationships').appendChild(targetItem.node.cloneNode(true));
this.clearStatusMessage(statusId);
return res;
};
Aras.prototype.isLCNCompatibleWithRT = function Aras_isLastCopyNodeCompatibleWithRelationshipType(targetRelatedTN) {
var sourceRelatedTN = this.clipboard.getLastCopyRelatedItemTypeName();
if (!sourceRelatedTN && !targetRelatedTN) {
return true;
}
if (sourceRelatedTN == targetRelatedTN) {
return true;
}
return false;
};
Aras.prototype.isLCNCompatibleWithRTOnly = function Aras_isLastCopyNodeCompatibleWithRelationshipTypeOnly(targetRelationshipTN) {
var sourceRelationshipTN = this.clipboard.getLastCopyRTName();
if (!sourceRelationshipTN && !targetRelationshipTN) {
return true;
}
if (sourceRelationshipTN == targetRelationshipTN) {
return true;
}
return false;
};
Aras.prototype.isLCNCompatibleWithIT = function Aras_isLastCopyNodeCompatibleWithItemType(itemTypeID) {
var clipboardItem = this.clipboard.getLastCopyItem();
return this.isClItemCompatibleWithIT(clipboardItem, itemTypeID);
};
Aras.prototype.isClItemCompatibleWithIT = function Aras_IsClipboardItemCompatibleWithItemType(clipboardItem, itemTypeID) {
var RelationshipTypeName = clipboardItem.relationship_itemtype;
if (!RelationshipTypeName || !itemTypeID) {
return false;
}
return this.getRelationshipTypeId(RelationshipTypeName) != '';
};
Aras.prototype.isClItemCompatibleWithRT = function Aras_IsClipboardItemCompatibleWithRelationshipType(clipboardItem, targetRelatedTN) {
var sourceRelatedTN = clipboardItem.related_itemtype;
if (!sourceRelatedTN && !targetRelatedTN) {
return true;
}
if (sourceRelatedTN == targetRelatedTN) {
return true;
}
return false;
};
/**
* Returns the Active and Pending tasks for the user (Workflow Activities, Project Activities, FMEA Action Items).
* The users tasks are those assigned to an Identity for which the user is a Member
* @param {string} inBasketViewMode
* @param {number} workflowTasks boolean AML value. 1 or 0
* @param {number} projectTasks boolean AML value. 1 or 0
* @param {number} actionTasks boolean AML value. 1 or 0
* @returns {}
*/
Aras.prototype.getAssignedTasks = function(inBasketViewMode, workflowTasks, projectTasks, actionTasks) {
var body = '' + inBasketViewMode + ' ';
body += '' + workflowTasks + ' ';
body += '' + projectTasks + ' ';
body += '' + actionTasks + ' ';
var statusId = this.showStatusMessage('status', this.getResource('', 'workflow_methods.getting_user_activities'), system_progressbar1_gif);
var res = this.soapSend('GetAssignedTasks', body);
if (statusId != -1) {
this.clearStatusMessage(statusId);
}
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
var r = res.getResult().selectSingleNode('./Item').text;
var s1 = r.indexOf('');
var s2 = r.indexOf(' ', s1);
if (r && s1 > -1 && s2 > -1) {
var s =
'' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ';
r = r.substr(0, s1) + s + r.substr(s2 + 8);
}
return r;
};
Aras.prototype.getFormForDisplay = function Aras_getFormForDisplay(id, mode) {
// this function is not a part of public API. please do not use it
var criteriaName = mode == 'by-name' ? 'name' : 'id';
var resIOMItem;
// if form is new return form from client cache
var formNd = this.itemsCache.getItem(id);
if (formNd && this.isTempEx(formNd)) {
resIOMItem = this.newIOMItem();
resIOMItem.dom = formNd.ownerDocument;
resIOMItem.node = formNd;
return resIOMItem;
}
res = this.MetadataCache.GetForm(id, criteriaName);
if (res.getFaultCode() != 0) {
var resIOMError = this.newIOMInnovator().newError(res.getFaultString());
return resIOMError;
}
res = res.getResult();
resIOMItem = this.newIOMItem();
resIOMItem.dom = res.ownerDocument;
resIOMItem.node = res.selectSingleNode('Item');
// Mark that the item type was requested by main thread in this session
var ftypeName;
try {
ftypeName = resIOMItem.getProperty('name');
} catch (exc) {
ftypeName = null;
}
return resIOMItem;
};
Aras.prototype.clearClientMetadataCache = function Aras_resetCachedMetadataOnClient() {
this.makeItemsGridBlank();
this.MetadataCache.ClearCache();
};
Aras.prototype.getCacheObject = function Aras_getCacheObject() {
//this is private internal function
var mainWnd = this.getMainWindow();
var Cache = mainWnd.Cache;
if (!Cache) {
Cache = this.newObject();
mainWnd.Cache = Cache;
}
//for now because there are places where cache is accessed directly instead of call to this function
if (!Cache.XmlResourcesUrls) {
Cache.XmlResourcesUrls = this.newObject();
}
if (!Cache.UIResources) {
Cache.UIResources = this.newObject();
}
return mainWnd.Cache;
};
/**
* Search item by specific criteria.
* @deprecated Use getItemTypeForClient() instead.
* @param {string} criteriaValue Value of criteria.
* @param {string} [criteriaName] Name of criteria for search. Can be 'id' or 'name'. 'name' by default.
* @returns {Object}
*/
Aras.prototype.getItemTypeDictionary = function Aras_getItemTypeDictionary(criteriaValue, criteriaName) {
return this.getItemTypeForClient(criteriaValue, criteriaName);
};
/**
* Search item by specific criteria.
* @param {string} criteriaValue Value of criteria.
* @param {string} [criteriaName] Name of criteria for search. Can be 'id' or 'name'. 'name' by default.
* @returns {Object}
*/
Aras.prototype.getItemTypeForClient = function Aras_getItemTypeForClient(criteriaValue, criteriaName) {
//this function is a very specific function. please use it only if it is critical for you
//and there is no another good way to solve your task.
var res = this.getItemTypeForClientFromCache(criteriaValue, criteriaName);
if (res.getFaultCode() != 0) {
var resIOMError = this.newIOMInnovator().newError(res.getFaultString());
return resIOMError;
}
res = res.getResult();
var resIOMItem = this.newIOMItem();
resIOMItem.dom = res.ownerDocument;
resIOMItem.node = res.selectSingleNode('Item');
return resIOMItem;
};
Aras.prototype.getItemTypeForClientFromCache = function Aras_getItemTypeForClientFromCache(criteriaValue, criteriaName) {
if (criteriaName === undefined) {
criteriaName = 'name';
}
if (criteriaName !== 'name' && criteriaName !== 'id') {
throw new Error(1, this.getResource('', 'aras_object.not_supported_criteria', criteriaName));
}
var res = this.MetadataCache.GetItemType(criteriaValue, criteriaName);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return res;
}
return res;
};
Aras.prototype.getItemTypeNodeForClient = function Aras_getItemTypeNodeForClient(criteriaValue, criteriaName) {
var res = this.getItemTypeForClientFromCache(criteriaValue, criteriaName);
if (res.getFaultCode() != 0) {
var resIOMError = this.newIOMInnovator().newError(res.getFaultString());
return resIOMError.node;
}
return res.getResult().selectSingleNode('Item');
};
Aras.prototype.getItemTypeId = function Aras_getItemTypeId(name) {
return this.MetadataCache.GetItemTypeId(name);
};
Aras.prototype.getItemTypeName = function Aras_getItemTypeName(id) {
return this.MetadataCache.GetItemTypeName(id);
};
Aras.prototype.getRelationshipTypeId = function Aras_getRelationshipTypeId(name) {
return this.MetadataCache.GetRelationshipTypeId(name);
};
Aras.prototype.getRelationshipTypeName = function Aras_getRelationshipTypeId(id) {
return this.MetadataCache.GetRelationshipTypeName(id);
};
Aras.prototype.getListId = function Aras_getListId(name) {
var key = this.MetadataCache.CreateCacheKey('getListId', name);
var result = this.MetadataCache.GetItem(key);
if (!result) {
var value = this.getItemFromServerByName('List', name, 'name', false);
if (!value) {
return '';
}
result = value.getID();
this.MetadataCache.SetItem(key, result);
}
return result;
};
Aras.prototype.getFormId = function Aras_getFormId(name) {
return this.MetadataCache.GetFormId(name);
};
Aras.prototype.getRelationshipType = function Aras_getRelationshipType(id) {
var res = this.MetadataCache.GetRelationshipType(id, 'id');
if (res.getFaultCode() != 0) {
this.AlertError(res);
}
res = res.getResult();
var resIOMItem = this.newIOMItem();
resIOMItem.dom = res.ownerDocument;
resIOMItem.node = res.selectSingleNode('Item');
return resIOMItem;
};
Aras.prototype.getLanguagesResultNd = function Aras_getLanguagesResultNd() {
var cacheKey = this.MetadataCache.CreateCacheKey('getLanguagesResultNd', 'Language');
var cachedItem = this.MetadataCache.GetItem(cacheKey);
if (cachedItem) {
return cachedItem.content;
}
var res = this.getMainWindow().arasMainWindowInfo.getLanguageResult;
if (res.getFaultCode() != 0) {
return null;
}
var langs = res.results.selectSingleNode(this.XPathResult(''));
cachedItem = aras.IomFactory.CreateCacheableContainer(langs, langs);
this.MetadataCache.SetItem(cacheKey, cachedItem);
return cachedItem.content;
};
Aras.prototype.getLocalesResultNd = function Aras_getLocalesResultNd() {
var cacheKey = this.MetadataCache.CreateCacheKey('getLocalesResultNd', 'Locale');
var cachedItem = this.MetadataCache.GetItem(cacheKey);
if (cachedItem) {
return cachedItem.content;
}
var res = this.soapSend('ApplyItem', ' ');
if (res.getFaultCode() != 0) {
return null;
}
var langs = res.results.selectSingleNode(this.XPathResult(''));
cachedItem = aras.IomFactory.CreateCacheableContainer(langs, langs);
this.MetadataCache.SetItem(cacheKey, cachedItem);
return cachedItem.content;
};
Aras.prototype.getItemFromServer = function Aras_getItemFromServer(itemTypeName, id, selectAttr, related_expand, language) {
if (!related_expand) {
related_expand = false;
}
if (!selectAttr) {
selectAttr = '';
}
var qry = this.getMostTopWindowWithAras(window).Item(itemTypeName, 'get');
qry.setAttribute('related_expand', (related_expand) ? '1' : '0');
qry.setAttribute('select', selectAttr);
qry.setProperty('id', id);
if (language) {
qry.setAttribute('language', language);
}
var results = qry.apply();
if (results.isEmpty()) {
return false;
}
if (results.isError()) {
this.AlertError(results);
return false;
}
return results.getItemByIndex(0);
};
Aras.prototype.getItemFromServerByName = function Aras_getItemFromServer(itemTypeName, name, selectAttr, related_expand) {
if (!related_expand) {
related_expand = false;
}
var qry = this.newIOMItem(itemTypeName, 'get');
qry.setAttribute('related_expand', (related_expand) ? '1' : '0');
qry.setAttribute('select', selectAttr);
qry.setProperty('name', name);
var results = qry.apply();
if (results.isEmpty()) {
return false;
}
if (results.isError()) {
this.AlertError(results);
return false;
}
return results.getItemByIndex(0);
};
Aras.prototype.getItemFromServerWithRels = function Aras_getItemFromServerWithRels(itemTypeName, id, itemSelect, reltypeName, relSelect, related_expand) {
if (!related_expand) {
related_expand = false;
}
var qry = this.getMostTopWindowWithAras(window).Item(itemTypeName, 'get');
qry.setProperty('id', id);
qry.setAttribute('select', itemSelect);
if (reltypeName) {
var topWnd = this.getMostTopWindowWithAras(window);
var rel = new topWnd.Item(reltypeName, 'get');
rel.setAttribute('select', relSelect);
rel.setAttribute('related_expand', (related_expand) ? '1' : '0');
qry.addRelationship(rel);
}
var results = qry.apply();
if (results.isEmpty()) {
return false;
}
if (results.isError()) {
this.AlertError(results);
return false;
}
return results.getItemByIndex(0);
};
/**
* @deprecated
*/
Aras.prototype.getFile = function Aras_getFile(value, fileSelect) {
var topWnd = this.getMostTopWindowWithAras(window);
var qry = new topWnd.Item('File', 'get');
qry.setAttribute('select', fileSelect);
qry.setID(value);
var results = qry.apply();
if (results.isEmpty()) {
return false;
}
if (results.isError()) {
this.AlertError(results);
return false;
}
return results.getItemByIndex(0);
};
Aras.prototype.refreshWindows = function Aras_refreshWindows(message, results, saveChanges) {
if (saveChanges == undefined) {
saveChanges = true;
}
// Skip the refresh if this is the unlock portion of the "Save, Unlock and Close" operation.
if (!saveChanges) {
return;
}
// If no IDs modified then nothing to refresh.
var nodeWithIDs = message.selectSingleNode('event[@name=\'ids_modified\']');
if (!(nodeWithIDs && results)) {
return;
}
// Get list of modified IDs
var IDsArray = nodeWithIDs.getAttribute('value').split('|');
// Refresh changed items in main window grid
try {
var mainWindow = this.getMainWindow();
if (mainWindow.work.isItemsGrid) {
var grid = mainWindow.work.grid;
for (var chID = 0; chID < IDsArray.length; chID++) {
var schID = IDsArray[chID];
//new item
var itmNode = results.selectSingleNode('//Item[@id=\'' + schID + '\']');
if (!itmNode || grid.getRowIndex(schID) == -1) {
continue;
}
//old item
this.refreshItemsGrid(itmNode.getAttribute('type'), schID, itmNode);
}
}
}
catch (excep) { }
// Check if there are any other opened windows, that must be refreshed.
var doRefresh = false;
for (var winId in this.windowsByName) {
var win = null;
try {
if (this.windowsByName.hasOwnProperty(winId)) {
win = this.windowsByName[winId];
if (this.isWindowClosed(win)) {
this.deletePropertyFromObject(this.windowsByName, winId);
continue;
}
// Item doesn't updated if it was changed by action(Manual Release, Create New Revision)
/*if (win.top_ == top_) added "_" to "top" because we removed all the "top" in this file.
continue;*/
doRefresh = true;
break;
}
}
catch (excep) {
continue;
}
}
// Return if there are no windows to refresh.
if (!doRefresh) {
return;
}
// Get changed item ID (new Item) or new id=0 if item was deleted.
var itemNode = results.selectSingleNode('//Item');
var currentID = 0;
if (itemNode) {
currentID = itemNode.getAttribute('id');
}
var RefreshedRelatedItems = new Array();
var RefreshedItems = new Object();
var alreadyRefreshedWindows = new Object();
var self = this;
function refreshWindow(oldItemId, itemNd) {
if (alreadyRefreshedWindows[oldItemId]) {
return;
}
var win = self.uiFindWindowEx(oldItemId);
if (!win) {
return;
}
alreadyRefreshedWindows[oldItemId] = true;
alreadyRefreshedWindows[itemNd.getAttribute('id')] = true; //just fo a case item is versionable
self.uiReShowItemEx(oldItemId, itemNd);
}
var dependency = getTypeIdDependencyForRefreshing(IDsArray);
refreshVersionableItem(dependency);
function getTypeIdDependencyForRefreshing(IDsArray) {
var result = new Object();
for (var i in IDsArray) {
var itemID = IDsArray[i];
if (currentID == itemID) {
continue;
}
//not locked items with id=itemID *anywhere* in the cache
var nodes = self.itemsCache.getItemsByXPath('//Item[@id=\'' + itemID + '\' and string(locked_by_id)=\'\']');
for (var j = 0; j < nodes.length; j++) {
itemFromDom = nodes[j];
var type = itemFromDom.getAttribute('type');
//if type if LCM, Form, WFM, IT or RelshipType or id already refreshed skip adding it to array
if (type == 'Life Cycle Map' || type == 'Form' || type == 'Workflow Map' || type == 'ItemType' || type == 'RelationshipType' || RefreshedItems[itemID]) {
continue;
}
var cid = itemFromDom.selectSingleNode('config_id');
var value;
if (cid) {
value = {id: itemID, config_id: cid.text};
} else {
value = {id: itemID, config_id: undefined};
}
if (result[type]) {
//get structure: type = Array of {id, config_id}
result[type].push(value);
} else {
result[type] = new Array();
result[type].push(value);
}
}
}
return result;
}
function refreshVersionableItem(dependency) {
for (var e in dependency) {
var element = dependency[e];
//e - type. Type contains multiple ids
//create server request for data:
/*
-
id1, id2...
1
*/
var configIds = getConfigIdsForRequest(element);
if (configIds == '') {
continue;
}
var itemsToRefresh = self.loadItems(e, '' + configIds + ' ' + '1 ', 0);
for (var i = 0; i < itemsToRefresh.length; i++) {
var itemNd = itemsToRefresh[i];
var cid = itemNd.selectSingleNode('config_id').text;
var id = getOldIdForRefresh(element, cid);
refreshWindow(id, itemNd);
self.refreshItemsGrid(e, id, itemNd);
}
}
}
function getOldIdForRefresh(dependencyArray, configID) {
for (var i = 0; i < dependencyArray.length; i++) {
if (dependencyArray[i].config_id == configID) {
return dependencyArray[i].id;
}
}
}
function getConfigIdsForRequest(dependencyArray) {
var preResult = new Array(); //create array of ids for request in order to make request string in the end
var result = '';
for (var i = 0; i < dependencyArray.length; i++) {
if (dependencyArray[i].config_id) {
preResult.push('\'' + dependencyArray[i].config_id + '\'');
}
}
if (preResult.length > 0) {
while (preResult.length > 1) {
result += preResult.pop() + ',';
}
result += preResult.pop();
}
return result;
}
for (var i in IDsArray) {
var itemID = IDsArray[i];
//items with related_id=itemID
var nodes1 = this.itemsCache.getItemsByXPath('//Item[count(descendant::Item[@isTemp=\'1\'])=0 and string(@isDirty)!=\'1\' and Relationships/Item/related_id/Item[@id=\'' + itemID + '\']]');
nodes = nodes1;
// processing of items with related_id=itemID
for (var j = 0; j < nodes.length; j++) {
var itemNd = nodes[j];
var id = itemNd.getAttribute('id');
var type = itemNd.getAttribute('type');
var bAlreadyRefreshed = false;
for (var k = 0; k < RefreshedRelatedItems.length; k++) {
if (id == RefreshedRelatedItems[k]) {
bAlreadyRefreshed = true;
break;
}
}
if (bAlreadyRefreshed) {
continue;
} else {
RefreshedRelatedItems.push(id);
}
if (id == currentID) {
continue;
}
if (type == 'Life Cycle Map' || type == 'Form' || type == 'Workflow Map' || type == 'ItemType') {
continue;
}
//IR-006509
if (!this.isDirtyEx(itemNd)) {
var related_ids = itemNd.selectNodes('Relationships/Item/related_id[Item/@id="' + currentID + '"]'); //get related_id list with items with id=currentID
//update related_id nodes in cache
for (var i_r = 0, L = related_ids.length; i_r < L; i_r++) {
var relshipItem = related_ids[i_r].parentNode;
var relship_id = relshipItem.getAttribute('id');
var relship_type = relshipItem.getAttribute('type');
var res = this.soapSend('GetItem', ' ', undefined, false);
if (res.getFaultCode() == 0) {
var res_related_id = res.getResult().selectSingleNode('Item/related_id/Item[@id="' + currentID + '"]');
if (res_related_id == null) {
continue;
}
//update attributes and child nodes
var attr;
for (var i_att = 0; i_att < res_related_id.attributes.length; i_att++) {
attr = res_related_id.attributes[i_att];
related_ids[i_r].setAttribute(attr.nodeName, attr.nodeValue);
}
//it more safe than replace node. Because it is possible that there are places where reference to releated_id/Item node
//is chached in local variable. The replacement would just break the code.
//mergeItem does not merge attributes in its current implementation. Thus the attributes are copied with the legacy code above.
this.mergeItem(relshipItem.selectSingleNode('related_id/Item[@id="' + currentID + '"]'), res_related_id);
}
}
}
refreshWindow(id, itemNd);
} // ^^^ processing of items with related_id=itemID
}
};
Aras.prototype.refreshItemsGrid = function Aras_refreshItemsGrid(itemTypeName, itemID, updatedItem) {
var mainWindow = this.getMainWindow();
if (!updatedItem)
{
return false;
}
var updatedID = updatedItem.getAttribute('id');
try {
if (!mainWindow.work.isItemsGrid) {
return false;
}
}
catch (excep) { return false; }
if (itemTypeName == 'ItemType') {
if (itemID == mainWindow.work.itemTypeID) {
mainWindow.work.location.replace('../scripts/blank.html');
return true;
}
}
if (mainWindow.work.itemTypeName != itemTypeName) {
return false;
}
var grid = mainWindow.work.grid;
if (grid.getRowIndex(itemID) == -1) {
return true;
}
var wasSelected = (grid.getSelectedItemIds().indexOf(itemID) > -1);
if (updatedID != itemID)
{
//hack to prevent rewrite deleteRow to use typeName and Id instead of node
var oldItem = this.createXMLDocument();
oldItem.loadXML(' ');
oldItem = oldItem.documentElement;
mainWindow.work.deleteRow(oldItem);
}
mainWindow.work.updateRow(updatedItem);
if (wasSelected) {
if (updatedID == itemID)
{
mainWindow.work.onSelectItem(itemID);
}
else
{
var currSel = grid.getSelectedId();
//if (currSel)
mainWindow.work.onSelectItem(currSel);
}
} //if (wasSelected)
return true;
};
Aras.prototype.isDirtyItems = function Aras_isDirtyItems() {
if (this.getCommonPropertyValue('exitWithoutSavingInProgress')) {
return false;
}
var dirtyExist =
(
this.itemsCache.getItemsByXPath(
'/Innovator/Items/Item[@action!=\'\' and (@isTemp=\'1\' or (locked_by_id=\'' +
this.getUserID() +
'\' and (@isDirty=\'1\' or .//Item/@isDirty=\'1\' or .//Item/@isTemp=\'1\')))]').length > 0
);
return dirtyExist ? true : false;
};
Aras.prototype.dirtyItemsHandler = function Aras_dirtyItemsHandler(win, readOnly) {
if (this.isDirtyItems()) {
var param = new Object();
param.aras = this.getMostTopWindowWithAras(window).aras;
if (readOnly) {
param.mode = 'read_only';
}
if (!win) {
win = window;
}
var options = {
dialogWidth: 400,
dialogHeight: 500,
center: true
};
return this.modalDialogHelper.show('DefaultModal', win, param, options, 'dirtyItemsList.html');
}
};
Aras.prototype.getPreferenceItem = function Aras_getPreferenceItem(prefITName, specificITorRTId) {
if (!prefITName) {
return null;
}
var self = this;
var prefKey;
if (specificITorRTId) {
if (prefITName == 'Core_RelGridLayout') {
var relType = this.getRelationshipType(specificITorRTId).node;
var itID = specificITorRTId;
if (relType) {
itID = this.getItemProperty(relType, 'relationship_id');
}
prefKey = this.MetadataCache.CreateCacheKey('Preference', prefITName, specificITorRTId, itID, this.preferenceCategoryGuid);
} else {
prefKey = this.MetadataCache.CreateCacheKey('Preference', prefITName, specificITorRTId, this.preferenceCategoryGuid);
}
} else {
prefKey = this.MetadataCache.CreateCacheKey('Preference', prefITName, this.preferenceCategoryGuid);
}
var res = this.MetadataCache.GetItem(prefKey);
if (res) {
return res.content;
}
var findCriteriaPropNm = '';
var findCriteriaPropVal = specificITorRTId;
switch (prefITName) {
case 'Core_ItemGridLayout': {
findCriteriaPropNm = 'item_type_id';
break;
}
case 'Core_RelGridLayout': {
findCriteriaPropNm = 'rel_type_id';
break;
}
case 'cmf_ContentTypeGridLayout': {
findCriteriaPropNm = 'tabular_view_id';
break;
}
}
function getPrefQueryXml(prefCondition) {
var xml = '- ';
xml += prefCondition;
xml += '
';
xml += '- ';
if (findCriteriaPropNm) {
xml += '<' + findCriteriaPropNm + '>' + findCriteriaPropVal + '' + findCriteriaPropNm + '>';
}
xml += '
';
xml += ' ';
return xml;
}
var xml = getPrefQueryXml(inner_getConditionForUser());
var resDom = this.createXMLDocument();
var prefMainItemID = this.getVariable('PreferenceMainItemID');
var prefMainItemDom = this.createXMLDocument();
var res;
if (prefITName === 'Core_GlobalLayout') {
res = this.getMainWindow().arasMainWindowInfo.Core_GlobalLayout;
} else if (prefITName === 'SSVC_Preferences') {
res = this.getMainWindow().arasMainWindowInfo.SSVC_Preferences;
} else {
res = this.soapSend('ApplyItem', xml);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return null;
}
}
res = res.getResultsBody();
if (res && res.indexOf('Item') > -1) {
resDom.loadXML(res);
if (!prefMainItemID) {
prefMainItemDom.loadXML(res);
var tmpNd = prefMainItemDom.selectSingleNode('/*/Relationships');
if (tmpNd) {
tmpNd.parentNode.removeChild(tmpNd);
}
}
}
if (!resDom.selectSingleNode('//Item[@type=\'' + prefITName + '\']')) {
xml = getPrefQueryXml(inner_getConditionForSite());
res = this.soapSend('ApplyItem', xml);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return null;
}
var newPref = this.newItem(prefITName);
var tmp = newPref.cloneNode(true);
newPref = tmp;
res = res.getResultsBody();
if (res && res.indexOf('Item') > -1) {
resDom.loadXML(res);
var nds2Copy = resDom.selectNodes('//Item[@type=\'' + prefITName + '\']/*[local-name()!=\'source_id\' and local-name()!=\'permission_id\']');
for (var i = 0; i < nds2Copy.length; i++) {
var newNd = newPref.selectSingleNode(nds2Copy[i].nodeName);
if (!newNd) {
newNd = newPref.appendChild(newPref.ownerDocument.createElement(nds2Copy[i].nodeName));
}
newNd.text = nds2Copy[i].text;
}
}
if (findCriteriaPropNm) {
var tmpNd = newPref.appendChild(newPref.ownerDocument.createElement(findCriteriaPropNm));
tmpNd.text = findCriteriaPropVal;
}
resDom.loadXML(newPref.xml);
if (!prefMainItemID) {
var mainPref = this.newItem('Preference');
var tmp = mainPref.cloneNode(true);
mainPref = tmp;
var userNd = this.getLoggedUserItem();
identityNd = userNd.selectSingleNode('Relationships/Item[@type=\'Alias\']/related_id/Item[@type=\'Identity\']');
if (!identityNd) {
return null;
}
this.setItemProperty(mainPref, 'identity_id', identityNd.getAttribute('id'));
prefMainItemDom.loadXML(mainPref.xml);
}
}
if (!prefMainItemID) {
var mainPref = prefMainItemDom.documentElement;
var tmpKey = this.MetadataCache.CreateCacheKey('Preference', mainPref.getAttribute('id'));
var itm = aras.IomFactory.CreateCacheableContainer(mainPref, mainPref);
this.MetadataCache.SetItem(tmpKey, itm);
this.setVariable('PreferenceMainItemID', mainPref.getAttribute('id'));
}
var result = resDom.selectSingleNode('//Item[@type=\'' + prefITName + '\']');
var itm = aras.IomFactory.CreateCacheableContainer(result, result);
this.MetadataCache.SetItem(prefKey, itm);
return result;
function inner_getConditionForSite() {
var res =
'' +
'- ' +
'
World ' +
' ' +
' ';
return res;
}
function inner_getConditionForUser() {
var res;
var userNd = self.getLoggedUserItem();
var identityNd = userNd.selectSingleNode('Relationships/Item[@type=\'Alias\']/related_id/Item[@type=\'Identity\']');
if (!identityNd) {
return '';
}
res = '' + identityNd.getAttribute('id') + ' ';
return res;
}
};
Aras.prototype.getPreferenceItemProperty = function Aras_getPreferenceItemProperty(prefITName, specificITorRTId, propNm, defaultVal) {
var prefItm = this.getPreferenceItem(prefITName, specificITorRTId);
return this.getItemProperty(prefItm, propNm, defaultVal);
};
Aras.prototype.setPreferenceItemProperties = function Aras_setPreferenceItemProperties(prefITName, specificITorRTId, varsHash) {
if (!prefITName || !varsHash) {
return false;
}
var prefNode = this.getPreferenceItem(prefITName, specificITorRTId);
var varName;
for (varName in varsHash) {
var varValue = varsHash[varName];
var nd = prefNode.selectSingleNode(varName);
if (!nd) {
nd = prefNode.appendChild(prefNode.ownerDocument.createElement(varName));
}
if (nd.text != varValue) {
nd.text = varValue;
var params = new Object();
params.type = prefITName;
params.specificITorRTId = specificITorRTId;
params.propertyName = varName;
this.fireEvent('PreferenceValueChanged', params);
}
}
if (varName && !prefNode.getAttribute('action')) {
prefNode.setAttribute('action', 'update');
}
return true;
};
Aras.prototype.savePreferenceItems = function Aras_savePreferenceItems() {
var prefArr = this.MetadataCache.GetItemsById(this.preferenceCategoryGuid);
if (!prefArr || prefArr.length < 1) {
return;
}
var prefMainItemID = this.getVariable('PreferenceMainItemID');
var prefItem;
if (prefMainItemID) {
var tmpArr = this.MetadataCache.GetItemsById(prefMainItemID);
if (tmpArr.length > 0) {
prefItem = tmpArr[0].content;
}
}
if (!prefItem) {
return;
}
if (!prefItem.getAttribute('action')) {
prefItem.setAttribute('action', 'edit');
}
var rels = prefItem.selectSingleNode('Relationships');
if (!rels) {
rels = prefItem.appendChild(prefItem.ownerDocument.createElement('Relationships'));
}
var prefItemAction = prefItem.getAttribute('action');
var i = 0;
while (prefArr[i]) {
var nd = prefArr[i].content;
var ndAction = nd.getAttribute('action');
if (ndAction) {
nd = rels.appendChild(nd.cloneNode(true));
if (ndAction == 'add') {
var whereArr = new Array();
switch (nd.getAttribute('type')) {
case 'Core_GlobalLayout':
whereArr.push('[Core_GlobalLayout].source_id=\'' + prefItem.getAttribute('id') + '\'');
break;
case 'Core_ItemGridLayout':
whereArr.push('[Core_ItemGridLayout].source_id=\'' + prefItem.getAttribute('id') + '\'');
whereArr.push('[Core_ItemGridLayout].item_type_id=\'' + this.getItemProperty(nd, 'item_type_id') + '\'');
break;
case 'Core_RelGridLayout':
whereArr.push('[Core_RelGridLayout].source_id=\'' + prefItem.getAttribute('id') + '\'');
whereArr.push('[Core_RelGridLayout].rel_type_id=\'' + this.getItemProperty(nd, 'rel_type_id') + '\'');
break;
}
if (whereArr.length) {
nd.setAttribute('action', 'merge');
nd.setAttribute('where', whereArr.join(' AND '));
nd.removeAttribute('id');
}
}
}
i++;
}
if (prefItemAction == 'add') {
prefItem.setAttribute('action', 'merge');
prefItem.setAttribute('where', '[Preference].identity_id=\'' + this.getItemProperty(prefItem, 'identity_id') + '\'');
prefItem.removeAttribute('id');
}
prefItem.setAttribute('doGetItem', '0');
try { this.soapSend('ApplyItem', prefItem.xml); } catch (e) { return; }
return true;
};
Aras.prototype.mergeItemRelationships = function Aras_mergeItemRelationships(oldItem, newItem) {
//this method is for internal purposes only.
var newRelationships = newItem.selectSingleNode('Relationships');
if (newRelationships != null) {
var oldRelationships = oldItem.selectSingleNode('Relationships');
if (oldRelationships == null) {
oldRelationships = oldItem.appendChild(newRelationships.cloneNode(true));
} else if (oldRelationships.childNodes.length === 0) {
oldItem.replaceChild(newRelationships.cloneNode(true), oldRelationships);
} else {
this.mergeItemsSet(oldRelationships, newRelationships);
}
}
};
Aras.prototype.mergeItem = function Aras_mergeItem(oldItem, newItem) {
//this method is for internal purposes only.
var oldId = oldItem.getAttribute('id');
if (oldId) {
var newId = newItem.getAttribute('id');
if (newId && oldId !== newId) {
return; //do not merge Items with different ids.
}
}
var allPropsXpath = '*[local-name()!=\'Relationships\']';
var oldAction = oldItem.getAttribute('action');
if (!oldAction) {
oldAction = 'skip';
}
if (oldAction == 'delete') {
//do not merge newItem into oldSet
} else if (oldAction == 'add') {
//this should never happen because getItem results cannot return not saved Item. do nothing here.
} else if (oldAction == 'update' || oldAction == 'edit') {
//we can add only missing properties here and merge relationships
var newProps = newItem.selectNodes(allPropsXpath);
for (var i = 0; i < newProps.length; i++) {
var newProp = newProps[i];
var propNm = newProp.nodeName;
var oldProp = oldItem.selectSingleNode(propNm);
if (!oldProp) {
oldItem.appendChild(newProp.cloneNode(true));
} else {
var oldPropItem = oldProp.selectSingleNode('Item');
if (oldPropItem) {
var newPropItem = newProp.selectSingleNode('Item');
if (newPropItem) {
this.mergeItem(oldPropItem, newPropItem);
}
}
}
}
mergeSpecialAttributes(oldItem, newItem);
//merge relationships
this.mergeItemRelationships(oldItem, newItem);
} else if (oldAction == 'skip') {
//all properties not containing Items can be replaced here.
//process oldItem properies with * NO * Item inside
var oldProps = oldItem.selectNodes(allPropsXpath + '[not(Item)]');
for (var i = 0; i < oldProps.length; i++) {
var oldProp = oldProps[i];
var propNm = oldProp.nodeName;
var newProp = newItem.selectSingleNode(propNm);
if (newProp) {
oldItem.replaceChild(newProp.cloneNode(true), oldProp);
}
}
//process oldItem properies with Item inside
var oldItemProps = oldItem.selectNodes(allPropsXpath + '[Item]');
for (var i = 0; i < oldItemProps.length; i++) {
var oldProp = oldItemProps[i];
var propNm = oldProp.nodeName;
var newProp = newItem.selectSingleNode(propNm);
if (newProp) {
var oldPropItem = oldProp.selectSingleNode('Item');
var newPropItem = newProp.selectSingleNode('Item');
var oldPropItemId = oldPropItem.getAttribute('id');
if (newPropItem) {
var newPropItemId = newPropItem.getAttribute('id');
//id of item may be changed in case of versioning or when item is replaced with another item on server-side
if (oldPropItemId != newPropItemId) {
var oldItemHasUnsavedChanges = Boolean(oldPropItem.selectSingleNode('descendant-or-self::Item[@action!=\'skip\']'));
if (oldItemHasUnsavedChanges) {
//do nothing. mergeItem will do all it's best.
} else {
//set the new id on "old" Item tag
oldPropItem.setAttribute('id', newPropItemId);
//content of "old" Item tag is useless. Remove that.
var children = oldPropItem.selectNodes('*');
for (var j = 0, C_L = children.length; j < C_L; j++) {
oldPropItem.removeChild(children[j]);
}
}
}
this.mergeItem(oldPropItem, newPropItem);
} else {
var oldPropItemAction = oldPropItem.getAttribute('action');
if (!oldPropItemAction) {
oldPropItemAction = 'skip';
}
var newPropItemId = newProp.text;
if (oldPropItemAction == 'skip') {
if (newPropItemId != oldPropItemId) {
oldItem.replaceChild(newProp.cloneNode(true), oldProp);
}
}
}
}
}
//process all newItem properties which are missing in oldItem
var newProps = newItem.selectNodes(allPropsXpath);
for (var i = 0; i < newProps.length; i++) {
var newProp = newProps[i];
var propNm = newProp.nodeName;
var oldProp = oldItem.selectSingleNode(propNm);
if (!oldProp) {
oldItem.appendChild(newProp.cloneNode(true));
}
}
mergeSpecialAttributes(oldItem, newItem);
//merge relationships
this.mergeItemRelationships(oldItem, newItem);
}
function mergeSpecialAttributes(oldItem, newItem) {
var specialAttrNames = new Array('discover_only', 'type');
for (var i = 0; i < specialAttrNames.length; i++) {
if (newItem.getAttribute(specialAttrNames[i])) {
oldItem.setAttribute(specialAttrNames[i], newItem.getAttribute(specialAttrNames[i]));
}
}
}
};
Aras.prototype.mergeItemsSet = function Aras_mergeItemsSet(oldSet, newSet) {
//this method is for internal purposes only.
//both oldSet and newSet are nodes with Items inside. (oldSet and newSet normally are AML or Relationships nodes)
var oldDoc = oldSet.ownerDocument;
//we don't expect action attribute specified on Items from newSet
var newItems = newSet.selectNodes('Item[not(@action)]');
for (var i = 0; i < newItems.length; i++) {
var newItem = newItems[i];
var newId = newItem.getAttribute('id');
var newType = newItem.getAttribute('type');
var newTypeId = newItem.getAttribute('typeId');
var oldItem = oldSet.selectSingleNode('Item[@id="' + newId + '"][@type="' + newType + '"]');
if (!oldItem) {
//
oldItem = oldSet.appendChild(oldDoc.createElement('Item'));
oldItem.setAttribute('id', newId);
oldItem.setAttribute('type', newType);
oldItem.setAttribute('typeId', newTypeId);
}
this.mergeItem(oldItem, newItem);
}
};
// +++ Export to Office section +++
//this method is for internal purposes only.
Aras.prototype.export2Office = function Aras_export2Office(gridXmlCallback, toTool, itemNd, itemTypeName, tabName) {
var statusId = this.showStatusMessage('status', this.getResource('', 'aras_object.exporting'), system_progressbar1_gif);
var aras = this;
var contentCallback = function() {
if (toTool == 'export2Excel') {
return Export2Excel(typeof (gridXmlCallback) == 'function' ? gridXmlCallback() : gridXmlCallback, itemNd, itemTypeName, tabName);
}
return Export2Word(typeof (gridXmlCallback) == 'function' ? gridXmlCallback() : gridXmlCallback, itemNd);
};
this.clearStatusMessage(statusId);
this.saveString2File(contentCallback, toTool);
function Export2Excel(gridXml, itemNd, itemTypeName, tabName) {
var result;
var relatedResult;
var itemTypeNd;
var gridDoc = aras.createXMLDocument();
if (itemNd) {
itemTypeNd = aras.getItemTypeForClient(itemNd.getAttribute('type'), 'name').node;
}
if (!itemTypeName) {
if (itemTypeNd) {
itemTypeName = aras.getItemProperty(itemTypeNd, 'name');
} else {
itemTypeName = 'Innovator';
}
}
if (!tabName) {
tabName = 'RelationshipsTab';
}
if (gridXml != '') {
gridDoc.loadXML(gridXml);
result = generateXML(gridDoc, (itemNd && itemNd.xml) ? tabName : itemTypeName);
}
if (itemNd && itemNd.xml && itemTypeNd) {
var itemTypeID = itemTypeNd.getAttribute('id');
var resDom = aras.createXMLDocument();
resDom.loadXML('' + itemNd.xml + ' ');
var xpath = 'Relationships/Item[@type="Property"]';
var propNds = itemTypeNd.selectNodes(xpath);
aras.uiPrepareDOM4GridXSLT(resDom);
var grid_xml = aras.uiGenerateGridXML(resDom, propNds, null, itemTypeID, {mode: 'forExport2Html'}, true);
gridDoc.loadXML(grid_xml);
var tableNd = gridDoc.selectSingleNode('//table');
if (tableNd.selectSingleNode('thead').childNodes.length == 0) {
generateThs(gridDoc, propNds);
}
if (tableNd.selectSingleNode('columns').childNodes.length == 0) {
generateColumns(gridDoc, propNds);
}
relatedResult = generateXML(gridDoc, itemTypeName);
}
//form valid result xml for Excel export
if (result) {
if (relatedResult) {
var relatedDom = aras.createXMLDocument();
relatedDom.loadXML(relatedResult);
relatedStyles = relatedDom.documentElement.childNodes[0].childNodes;
var resultDom = aras.createXMLDocument();
resultDom.loadXML(result);
styles = resultDom.documentElement.childNodes[0].childNodes;
result = '';
//merge all styles from from and relationships grid
for (var i = 0; i < relatedStyles.length; i++) {
result += relatedStyles[i].xml;
}
for (var j = 0; j < styles.length; j++) {
result += styles[j].xml;
}
result += ' ';
//merge two worksheets
result += relatedDom.documentElement.childNodes[1].xml;
result += resultDom.documentElement.childNodes[1].xml;
result += ' ';
}
} else {
if (relatedResult) {
result = relatedResult;
} else {
result = generateXML(gridDoc);
}
}
return result;
function generateThs(dom, propNds) {
var parentNode = dom.selectSingleNode('//thead');
for (var i = 0; i < propNds.length; i++) {
var pNd = propNds[i];
var lbl = aras.getItemProperty(pNd, 'label');
var nm = aras.getItemProperty(pNd, 'name');
var newTh = parentNode.appendChild(dom.createElement('th'));
newTh.setAttribute('align', 'c');
newTh.text = (lbl ? lbl : nm);
}
return dom;
}
function generateColumns(dom, propNds) {
var parentNode = dom.selectSingleNode('//columns');
for (var i = 0; i < propNds.length; i++) {
var pNd = propNds[i];
var lbl = aras.getItemProperty(pNd, 'label');
var nm = aras.getItemProperty(pNd, 'name');
var type = aras.getItemProperty(pNd, 'data_type');
var widthAttr = (lbl ? lbl : nm).length * 8;
var newCol = parentNode.appendChild(dom.createElement('column'));
if (type == 'date') {
newCol.setAttribute('sort', 'DATE');
} else if (type == 'integer' || type == 'float' || type == 'decimal') {
newCol.setAttribute('sort', 'NUMERIC');
}
newCol.setAttribute('width', widthAttr);
newCol.setAttribute('order', i);
}
return dom;
}
}
function Export2Word(gridXml, itemNd) {
function generateThs(propNds) {
var res = ' ';
var tmpDom = aras.createXMLDocument();
tmpDom.loadXML(res);
for (var i = 0; i < propNds.length; i++) {
var pNd = propNds[i];
var lbl = aras.getItemProperty(pNd, 'label');
var nm = aras.getItemProperty(pNd, 'name');
var newTh = tmpDom.documentElement.appendChild(tmpDom.createElement('th'));
newTh.setAttribute('align', 'center');
newTh.setAttribute('style', 'background-color:#d4d0c8;');
newTh.text = (lbl ? lbl : nm);
}
res = tmpDom.xml;
return res;
}
var html = generateHtml(gridXml);
if (itemNd && itemNd.xml) {
var itemTypeNd = aras.getItemTypeForClient(itemNd.getAttribute('type'), 'name').node;
if (itemTypeNd) {
var itemTypeID = itemTypeNd.getAttribute('id');
var resDom = aras.createXMLDocument();
resDom.loadXML('' + itemNd.xml + ' ');
var xpath = 'Relationships/Item[@type="Property"]';
var propNds = itemTypeNd.selectNodes(xpath);
aras.convertFromNeutralAllValues(resDom.selectSingleNode('/Result/Item'));
aras.uiPrepareDOM4GridXSLT(resDom);
var grid_xml = aras.uiGenerateGridXML(resDom, propNds, null, itemTypeID, {mode: 'forExport2Html'}, true);
var tmpHtml = generateHtml(grid_xml);
if (tmpHtml.indexOf('');
if (i > 0) {
html = html.substr(0, i) + tmpHtml.substr(i2, i3 - i2 + 8) + ' ' + html.substr(i);
}
}
}
return html;
}
function generateHtml(gridXml) {
var res = '';
var gridDom = aras.createXMLDocument();
if (!gridXml) {
gridXml = '';
}
gridDom.loadXML(gridXml);
if (gridDom.parseError.errorCode == 0) {
var tblNd = gridDom.selectSingleNode('//table');
if (tblNd) {
tblNd.setAttribute('base_href', aras.getScriptsURL());
}
res = aras.applyXsltFile(gridDom, aras.getScriptsURL() + '../styles/printGrid4Export.xsl');
}
return res;
}
function generateXML(gridDom, workSheetName) {
var res = '';
var tblNd = gridDom.selectSingleNode('//table');
if (tblNd) {
tblNd.setAttribute('base_href', aras.getScriptsURL());
if (workSheetName) {
tblNd.setAttribute('workSheet', workSheetName);
}
}
var xml = ArasModules.xml;
var xslt = xml.parseFile(aras.getScriptsURL() + '../styles/printGrid4ExportToExcel.xsl');
return xml.transform(gridDom, xslt);
}
};
//this method is for internal purposes only.
Aras.prototype.saveString2File = function ArasSaveString2File(contentCallback, extension, fileName) {
var ext = extension ? extension.toLowerCase() : 'unk';
var fileNamePrefix = fileName || 'export2unknown_type';
var mimeType = '';
if (ext.indexOf('excel') !== -1) {
ext = 'xls';
mimeType = 'application/excel';
fileNamePrefix = this.getResource('', 'aras_object.export2excel_file_prefix');
} else if (ext.indexOf('word') !== -1) {
ext = 'doc';
mimeType = 'application/msword';
fileNamePrefix = this.getResource('', 'aras_object.export2word_file_prefix');
}
var blob = new Blob([contentCallback()], {type: mimeType});
if ('msSaveBlob' in window.navigator) {
window.navigator.msSaveBlob(blob, fileNamePrefix + '.' + ext);
return;
}
var link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileNamePrefix + '.' + ext;
link.setAttribute('type', mimeType);
var e = document.createEvent('MouseEvents');
e.initEvent('click' ,true ,true);
link.dispatchEvent(e);
};
// --- Export to Office section ---
Aras.prototype.EscapeSpecialChars = function Aras_EscapeSpecialChars(str) {
if (!this.utilDoc) {
this.utilDoc = this.createXMLDocument();
}
var element_t = this.utilDoc.createElement('t');
element_t.text = str;
var result = element_t.xml;
return result.substr(3, result.length - 7);
};
// value returned as xpath function concat(), ie addition quotes aren't needed
Aras.prototype.EscapeXPathStringCriteria = function Aras_EscapeXPathStringCriteria(str) {
var res = str.replace(/'/g, '\',"\'",\'');
if (res != str) {
return 'concat(\'' + res + '\')';
} else {
return '\'' + res + '\'';
}
};
/*
//unit tests for Aras_isPropertyValueValid function
Boolean ? value is 0 or 1. (*)
Color ? must satisfy regexp /^#[a-f0-9]{6}$|^btnface$/i. (*)
Color List ? must satisfy regexp /^#[a-f0-9]{6}$|^btnface$/i. (*)
Date ? input string must represent a date in a supported format. (*)
Decimal ? must be a number. (*)
Federated ? read-only. No check.
Filter List ? string length must be not greater than 64. (*)
Float ? must be a number. (*)
Foreign ? read-only. No check.
Formatted Text ? No check.
Image ? string length must be not greater than 128. (*)
Qrcode ? string length must be not greater than 128. (*)
Integer ? must be an integer number. (*)
Item ? must be an item id (32 characters from [0-9A-F] set). (*)
List ? string length must be not greater than 64. (*)
MD5 ? 32 characters from [0-9A-F] set. (*)
Sequence ? read-only. No check.
String ? check if length of inputted string is not greater than maximum permissible string length.
Verify against property pattern if specified. (*)
Text ? No check.
Where (*) means: Empty value is not permissible if property is marked as required.
Property definition:
data_type - string
pattern - string
is_required - boolean
stored_length - integer
*/
/*common tests part* /
var allDataTypes = new Array("boolean", "color", "color list", "date", "decimal", "federated", "filter list", "float", "foreign", "formatted text", "image", "integer", "item", "list", "md5", "sequence", "string", "text");
function RunTest(testDescription, testDataArr, expectedResults)
{
var failedTests = new Array();
for (var i=0; i 0);
};
Aras.prototype.isNegativeInteger = function Aras_isPositiveInteger(propertyValue) {
return (this.isInteger(propertyValue) && parseInt(propertyValue) < 0);
};
Aras.prototype.isPropertyValueValid = function Aras_isPropertyValueValid(propertyDef, propertyValue, inputLocale) {
this.ValidationMsg = '';
var data_type = propertyDef.data_type;
if (propertyValue !== '') {
switch (data_type) {
case 'boolean':
if (!propertyValue == '0' && !propertyValue == '1') {
this.ValidationMsg = this.getResource('', 'aras_object.value_property _must_be _boolean');
}
break;
case 'color':
case 'color list':
if (!/^#[a-f0-9]{6}$|^btnface$/i.test(propertyValue)) {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_contains_incorrect_symbols');
}
break;
case 'date':
var dateFormat = this.getDateFormatByPattern(propertyDef.pattern || 'short_date'),
lessStrictFormat = dateFormat,
neutralDate, dotNetPattern;
propertyValue = typeof (propertyValue) === 'string' ? propertyValue.trim() : propertyValue;
while (lessStrictFormat && !neutralDate) {
dotNetPattern = this.getClippedDateFormat(lessStrictFormat) || this.getDotNetDatePattern(lessStrictFormat);
neutralDate = this.getIomSessionContext().ConvertToNeutral(propertyValue, data_type, dotNetPattern);
lessStrictFormat = this.getLessStrictDateFormat(lessStrictFormat);
}
if (typeof neutralDate !== 'string') {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_date');
}
break;
case 'decimal':
var decimalNumber = this.getIomSessionContext().ConvertToNeutral(propertyValue, data_type);
if (isNaN(parseFloat(decimalNumber))) {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_decimal');
}
break;
case 'federated':
break;
case 'float':
var floatNumber = this.getIomSessionContext().ConvertToNeutral(propertyValue, data_type);
if (isNaN(parseFloat(floatNumber))) {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_float');
}
break;
case 'foreign':
case 'formatted text':
break;
case 'image':
if (propertyValue.length > 128) {
this.ValidationMsg = this.getResource('', 'aras_object.length_image_property_cannot_be_larger_128_symbols');
}
break;
case 'qrcode':
if (propertyValue.length > 128) {
this.ValidationMsg = this.getResource('', 'aras_object.length_qrcode_property_cannot_be_larger_128_symbols');
}
break;
case 'integer':
if (!this.isInteger(propertyValue)) {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_integer');
}
break;
case 'item':
if (typeof (propertyValue) == 'string' && !/^[0-9a-f]{32}$/i.test(propertyValue)) {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_item_id');
}
break;
case 'md5':
if (propertyDef.stored_length) {
var pattern = new RegExp("^[0-9a-f]{" + propertyDef.stored_length + "}$", "i");
if (!pattern.test(propertyValue)) {
this.ValidationMsg = this.getResource('', 'aras_object.length_properties_value_canot_be_larger', propertyDef.stored_length);
}
} else if (!/^[0-9a-f]{32}$/i.test(propertyValue)) {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_be_md5');
}
break;
case 'sequence':
break;
case 'filter list':
case 'list':
case 'ml_string':
case 'mv_list':
case 'string':
if (propertyDef.stored_length < propertyValue.length) {
this.ValidationMsg = this.getResource('', 'aras_object.length_properties_value_canot_be_larger', propertyDef.stored_length);
break;
}
if (data_type == 'string' && propertyDef.pattern) {
var re = new RegExp(propertyDef.pattern);
if (!re.test(propertyValue)) {
this.ValidationMsg = this.getResource('', 'aras_object.value_property_invalid_must_correspond_with_pattern', propertyDef.pattern);
break;
}
}
break;
case 'text':
break;
default:
throw new Error(5, this.getResource('', 'aras_object.invalid_parameter_propertydef_data_type'));
break;
}
}
if (this.ValidationMsg != '') {
this.ValidationMsg += ' ' + this.getResource('', 'aras_object.edit_again');
}
return this.ValidationMsg == '';
};
Aras.prototype.ValidationMsg = '';
Aras.prototype.showValidationMsg = function Aras_showValidationMsg(ownerWindow) {
return this.confirm(this.ValidationMsg, ownerWindow);
};
/**
* Indicate whether window is closed.
* Supposition: sometimes invoking of property window.closed launch exception "Permission denied". (After applying patch KB918899)
*/
Aras.prototype.isWindowClosed = function Aras_isWindowClosed(window) {
return this.browserHelper && this.browserHelper.isWindowClosed(window);
};
//+++ some api for classification +++
Aras.prototype.isClassPathRoot = function Aras_isClassPathRoot(class_path) {
return '' == class_path || !class_path;
};
Aras.prototype.areClassPathsEqual = function Aras_areClassPathsEqual(class_path1, class_path2) {
//return this.doesClassPath1StartWithClassPath2(class_path1, class_path2, true);
return class_path1 == class_path2;
};
Aras.prototype.doesClassPath1StartWithClassPath2 = function Aras_doesClassPath1StartWithClassPath2(class_path1, class_path2) {
if (class_path2.length > class_path1.length) {
return false;
}
var class_path1Elements = class_path1.split('\/');
var class_path2Elements = class_path2.split('\/');
if (class_path2Elements.length > class_path1Elements.length) {
return false;
}
for (var i = 0; i < class_path2Elements.length; i++) {
if (class_path2Elements[i] != class_path1Elements[i]) {
return false;
}
}
return true;
};
/*
Aras.prototype.fireUnitTestsForSelectPropNdsByClassPath = function Aras_fireUnitTestsForSelectPropNdsByClassPath()
{
var pNms = new Array("simple classpath", "with chars to escape", "root1", "root2", "root3", "child class path", "wrong root");
//!!!before testing remove // and the second occurence of /* in the next code line
//var cps = new Array("/test/simple Classpath", "/*/
/*with \\chars\\ \" to escape<<>>[[[[]:-))))B!!!!", "", "/*", "/test", "/test/simple Classpath/its child", "/WRONG ROOT/simple Classpath");
var checkSums = new Array(4, 4, 3, 3, 3, 5, 5);//numbers of nodes returned according to class paths stored in cps array.
if (pNms.length!=cps.length || pNms.length!=checkSums.length)
{
alert("test setup is incorrect");
return;
}
var xml = "test "+
""+
"- "+
"
"+pNms[0]+" "+
""+cps[0]+" "+
" "+
"- "+
"
"+pNms[1]+" "+
" "+
" "+
"- "+
"
"+pNms[2]+" "+
""+cps[2]+" "+
" "+
"- "+
"
"+pNms[3]+" "+
""+cps[3]+" "+
" "+
"- "+
"
"+pNms[4]+" "+
""+cps[4]+" "+
" "+
"- "+
"
"+pNms[5]+" "+
""+cps[5]+" "+
" "+
"- "+
"
"+pNms[6]+" "+
""+cps[6]+" "+
" "+
" "
var d = this.createXMLDocument();
d.loadXML(xml);
var itemTypeNd = d.documentElement;
var propNds;
var res = "Result:\n";
var class_path;
for (var i=0; i ';
soapSendCaller(xmlBody, resultHanlder);
};
Aras.prototype.arrayToMVListPropertyValue = function Aras_arrayToMVListPropertyValue(arr) {
var tmpArr = new Array();
for (var i = 0; i < arr.length; i++) {
tmpArr.push(arr[i].replace(/,/g, '\\,'));
}
return tmpArr.join(',');
};
Aras.prototype.mvListPropertyValueToArray = function Aras_mvListPropertyValueToArray(val) {
var Delimiter = ',';
var EscapeString = '\\';
var tmpDelim = '#';
val = val.replace(/#/g, EscapeString + Delimiter);
val = val.replace(/\\,/g, tmpDelim + tmpDelim);
var tmpArr = val.split(Delimiter);
var retArr = new Array();
for (var i = 0; i < tmpArr.length; i++) {
retArr.push(tmpArr[i].replace(/##/g, Delimiter).replace(/\\#/g, tmpDelim));
}
return retArr;
};
Aras.prototype.ShowContextHelp = function Aras_ShowContextHelp(itemTypeName) {
var tophelpurl = this.getTopHelpUrl();
if (tophelpurl) {
if (tophelpurl.charAt(tophelpurl.length - 1) != '/') {
tophelpurl += '/';
}
var currItemType = this.getItemFromServerByName('ItemType', itemTypeName, 'help_item,help_url');
var tmpurl = tophelpurl + this.getSessionContextLanguageCode() + '/index.htm';
tophelpurl = WebFile.Exists(tmpurl) ? tmpurl : tophelpurl + 'en/index.htm';
var urlstring = tophelpurl;
if (currItemType) {
var thisHelpId = currItemType.getProperty('help_item');
var thisHelpURL = currItemType.getProperty('help_url');
var thisHelp = this.getItemById('Help', thisHelpId, 0);
if (thisHelpURL != undefined && thisHelpURL != '') {
urlstring += '#' + thisHelpURL;
} else {
if (thisHelpId != undefined && thisHelpId != '') {
this.uiShowItemEx(thisHelp, undefined);
return;
} else {
urlstring = tophelpurl;
}
}
}
window.open(urlstring);
}
};
Aras.prototype.UpdateFeatureTreeIfNeed = function Aras_UpdateFeatureTreeIfNeed() {
if (this.isAdminUser()) {
if (this.getMainWindow().arasMainWindowInfo.isFeatureTreeExpiredResult === 'True') {
var license = new Licensing(this);
license.UpdateFeatureTree(function(isSuccess) {
if (isSuccess) {
license.showState();
} else {
license._showErrorPage();
}
});
}
}
};
/**
* This function is a wrapper for IomInnovator.ConsumeLicense to handle exсeptions in case when LicenseService has returned "500" http response.
* Our IOM controls are hosted in the main window and are shared between other windows. So, if tearoff window calls IomInnovator.ConsumeLicense inside of try catch block and exception is occured then it appears in the main window as script error and only after that will be handled by "catch" block of tearoff window.
*/
Aras.prototype.ConsumeLicense = function Aras_ConsumeLicense(featureName) {
var consumeLicenseResult = {
isError: false,
errorMessage: undefined,
result: undefined
};
try {
consumeLicenseResult.result = this.IomInnovator.ConsumeLicense(featureName);
} catch (e) {
consumeLicenseResult.isError = true;
consumeLicenseResult.errorMessage = e.message;
}
return consumeLicenseResult;
};
/**
* @deprecated Use this.MetadataCache.CreateCacheKey()
* @returns {array}
*/
Aras.prototype.CreateCacheKey = function Aras_CreateCacheKey() {
var key = this.IomFactory.CreateArrayList();
for (var i = 0; i < arguments.length; i++) {
key.push(arguments[i]);
}
return key;
};
Aras.prototype.ValidateXml = function Aras_ValidateXml(schemas, xml) {
var xmlBody = shapeXmlBody(schemas, xml);
var url = this.getBaseURL() + '/HttpHandlers/XmlValidatorHandler.ashx';
var xmlhttp = this.XmlHttpRequestManager.CreateRequest();
// search in cache
var responseInCache = this.commonProperties.validateXmlCache.filter(function(obj) {
return obj.key === xmlBody;
});
if (responseInCache.length === 1) {
return responseInCache[0].value;
} else {
xmlhttp.open('POST', url, false);
xmlhttp.send(xmlBody);
var resText = xmlhttp.responseText;
var resDom = this.createXMLDocument();
resDom.loadXML(resText);
// we limit the size of the cache by 100
if (this.commonProperties.validateXmlCache.length > 100) {
this.commonProperties.validateXmlCache.shift();
}
var cacheObject = this.newObject();
cacheObject.key = xmlBody;
cacheObject.value = resDom;
this.commonProperties.validateXmlCache.push(cacheObject);
return resDom;
}
function shapeXmlBody(schemas, targetXml) {
var xmlBody = [];
xmlBody.push('');
for (var i = 0; i < schemas.length; i++) {
var schema = schemas[i];
xmlBody.push('');
xmlBody.push('');
xmlBody.push(' ');
}
xmlBody.push('');
xmlBody.push('');
xmlBody.push(' ');
xmlBody.push(' ');
return xmlBody.join('');
}
};
Aras.prototype.getMostTopWindowWithAras = function Aras_getMostTopWindowWithAras(windowObj) {
return TopWindowHelper.getMostTopWindowWithAras(windowObj);
};
Aras.prototype.SsrEditorWindowId = 'BB91CEC07FF24BE5945F2E5412752E8B';
/** path.js **/
function Path() {}
Path.lastException = '';
Path.combinePath = function(dirPath, fileName) {
var result = '';
if (this.isMac()) {
if (this.isValidFileName(fileName)) {
result = dirPath + '/' + fileName;
} else {
throw this.lastException;
}
} else if (this.isWindows()) {
if (this.isValidFileName(fileName)) {
result = dirPath + '\\' + fileName;
} else {
throw this.lastException;
}
}
return result;
};
Path.isValidFileName = function(filename) {
if (this.isWindows()) {
var cannotStartWithDotRegEx = /^\./;
if (cannotStartWithDotRegEx.test(filename)) {
this.lastException = 'File name cannot start with dot: ' + filename;
return false;
}
var winReservedNamesRegEx = /^(con|prn|aux|nul|com[0-9]|lpt[0-9]|)(\.|$)/i;
if (winReservedNamesRegEx.test(filename)) {
this.lastException = 'File name is reserved by OS: ' + filename;
return false;
}
/*
The following reserved characters:
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
*/
var reservedCharactersRegEx = /^[^\\/:\*\?"<>\|]{0,255}$/;
if (!reservedCharactersRegEx.test(filename)) {
this.lastException = 'Invalid file name for ' + navigator.platform + ' OS: ' + filename;
return false;
}
return true;
} else if (this.isMac()) {
var fileExp = /^([^:]){1,255}$/;
if (fileExp.test(filename)) {
return true;
} else {
this.lastException = 'invalid file name for ' + navigator.platform + ' OS: ' + filename;
return false;
}
}
};
Path.isMac = function() {
/*
Mac - Macintosh
Win -Windows
X11 -Unix
*/
var regExp = /^Mac/;
if (regExp.test(navigator.platform)) {
return true;
} else {
return false;
}
};
Path.isWindows = function() {
var regExp = /^Win/;
if (regExp.test(navigator.platform)) {
return true;
} else {
return false;
}
};
Path.isMacPath = function(path) {
var pathExp = /^(\/{1}[^:]{0,255}[^\:\/]{1})$/;
if (pathExp.test(path)) {
return true;
} else {
return false;
}
};
Path.isWinPath = function(path) {
var pathExp = /^[a-zA-Z]{1}:((\\[^:<>\\\/\?\*\|\"\^\s]){1}[^:<>\\\/\?\*\|\"\^]{0,255})*$/;
if (pathExp.test(path)) {
return true;
} else {
return false;
}
};
Path.isValidFilePath = function(path) {
if (this.isMac()) {
if (this.isMacPath(path)) {
return true;
} else {
return false;
}
} else if (this.isWindows()) {
if (this.isWinPath(path)) {
return true;
} else {
return false;
}
} else {
return false;
}
};
Path.getInvalidFileNameChars = function() {
var result = [];
if (this.isMac()) {
result.push(':');
} else if (this.isWindows()) {
result.push(':');
result.push('\\');
result.push('\/');
result.push('?');
result.push('^');
result.push('"');
result.push('*');
result.push('>');
result.push('<');
result.push('|');
}
return result;
};
Path.getFileName = function(filePath) {
if (filePath) {
var pathSeparator = Path.isWindows() ? '\\' : '\/';
return filePath.substring(filePath.lastIndexOf(pathSeparator) + 1, filePath.length);
}
};
Path.getDirectoryName = function(filePath) {
if (filePath) {
var pathSeparator = Path.isWindows() ? '\\' : '\/';
return filePath.substring(0, filePath.lastIndexOf(pathSeparator) + 1);
}
};
/** MetadataCache.js **/
function MetadataCache(aras) {
var scopeVariable = {};
scopeVariable.aras = aras;
scopeVariable.cache = aras.IomFactory.CreateItemCache();
scopeVariable.cacheVariable = null;
scopeVariable.preloadDates = {};
scopeVariable.typeInfo = {
ItemType: {
typeKey: '3EC33FE3B3C333333E33CF3D33AC33C3',
getDatesMethod: 'GetItemTypesMetadata',
getMethod: 'GetItemType'
},
RelationshipType: {
typeKey: '76381576909211E296CE0B586188709B',
getDatesMethod: 'GetRelationshipTypesMetadata',
getMethod: 'GetRelationshipType'
},
Form: {
typeKey: '2EC22FE2B2C222222E22CF2D22AC22C2',
getDatesMethod: 'GetFormsMetadata',
getMethod: 'GetForm'
},
Method: {
typeKey: '6E02B71E7A6E4FF38A9866C27837906D',
getDatesMethod: 'GetClientMethodsMetadata',
getMethod: 'GetClientMethod'
},
GetAllClientMethodsMetadata: {
typeKey: 'F29AC97834104075AA42EE4984AEDC68',
getDatesMethod: 'GetAllClientMethodsMetadata',
getMethod: 'GetAllClientMethods'
},
List: {
typeKey: '4EC44FE4B4C444444E44CF4D44AC44C4',
getDatesMethod: 'GetListsMetadata',
getMethod: 'GetList'
},
Identity: {
typeKey: '36F92EC1A0CF43C1801F50510D86FEAD',
getDatesMethod: 'GetIdentitiesMetadata',
getMethod: 'GetIdentity'
},
GetLastModifiedSearchModeDate: {
typeKey: 'BAD4F21DBF1C41B8B14BD3060FF5E8F5',
getDatesMethod: 'GetLastModifiedSearchModeDate',
getMethod: 'GetSearchModes'
},
ConfigurableUI: {
typeKey: '64494CAB13F846A0AD19216DBC3E1980',
getDatesMethod: 'GetConfigurableUiMetadata',
getMethod: 'GetConfigurableUi'
},
PresentationConfiguration: {
typeKey: 'BDE98AE974C24A759AF406C526EFD1A7',
getDatesMethod: 'GetPresentationConfigurationMetadata',
getMethod: 'GetPresentationConfiguration'
},
CommandBarSection: {
typeKey: '7962E50B66E44BCC9BEDC3ECAE899455',
getDatesMethod: 'GetCommandBarSectionMetadata',
getMethod: 'GetCommandBarSection'
},
// note that it returns zero-filled (GU)ID if there's no cmf_ContentType for given linked_document_type
ContentTypeByDocumentItemType: {
typeKey: 'E76EC697E76248CC8D08FE56C1DB880B',
getDatesMethod: 'GetContentTypeByDocumentItemTypeMetadata',
getMethod: 'GetContentTypeByDocumentItemType'
}
};
scopeVariable.findTypeInfoNameById = function(id) {
var res;
for (var prop in this.typeInfo) {
if (this.typeInfo.hasOwnProperty(prop)) {
if (this.typeInfo[prop].typeKey === id) {
res = prop;
break;
}
}
}
return res;
};
scopeVariable.getPreloadDate = function(name) {
if (!this.preloadDates[name]) {
this.updatePreloadDates();
}
return this.preloadDates[name];
};
scopeVariable._getMostTopWindowWithAras = function() {
return window;
};
scopeVariable.extractDateFromCache = function(criteriaValue, criteriaType, itemType) {
var id = criteriaType == 'id' ? criteriaValue : this.extractIdByName(criteriaValue, itemType);
return this.extractDateById(id, itemType);
};
scopeVariable.extractIdByName = function(name, itemType) {
var key = this.createCacheKey('MetadataIdsByNameInLowerCase', this.typeInfo[itemType].typeKey);
var container = this.getItem(key);
if (!container) {
this.refreshMetadata(itemType);
container = this.getItem(key);
}
return container ? container.content[name.toLowerCase()] : '';
};
scopeVariable.extractNameById = function(id, itemType) {
var key = this.createCacheKey('MetadataNamesById', this.typeInfo[itemType].typeKey);
var container = this.getItem(key);
if (!container) {
this.refreshMetadata(itemType);
container = this.getItem(key);
}
return container ? container.content[id] : '';
};
scopeVariable.extractDateById = function(id, itemType) {
var key = this.createCacheKey('MetadataDatesById', this.typeInfo[itemType].typeKey);
var container = this.getItem(key);
if (!container) {
this.refreshMetadata(itemType);
container = this.getItem(key);
}
var date = container ? container.content[id] : '';
if (!date) {
var currentTime = new Date();
date = currentTime.getFullYear() + '-' + currentTime.getMonth() + '-' + currentTime.getDate() +
'T' + currentTime.getHours() + ':' + currentTime.getMinutes() + ':' + currentTime.getSeconds() + '.00';
}
return date;
};
scopeVariable.refreshMetadata = function(itemType, async, callback) {
var methodName = this.typeInfo[itemType].getDatesMethod;
var typeKey = this.typeInfo[itemType].typeKey;
this.removeById(typeKey, true);
var self = this;
var requestURL = this.generateRequestURL(methodName, '', this.getPreloadDate(itemType));
this.sendSoapInternal(methodName, requestURL, async ? true : false).then(function(res) {
var finalRetVal = res;
self.refreshMetadataInternal(finalRetVal, typeKey);
if (callback) {
callback();
}
});
};
scopeVariable.refreshMetadataInternal = function(res, typeKey) {
if (res.getFaultCode() !== 0) {
this.aras.AlertError(res);
return;
}
var evalString = 'var metadataItems=' + res.getResult().text;
eval(evalString); // jshint ignore: line
var idsByName = {};
var namesById = {};
var datesById = {};
for (var i = 0; i < metadataItems.length; i++) {
var m = metadataItems[i];
idsByName[m.name.toLowerCase()] = m.id;
namesById[m.id] = m.name;
datesById[m.id] = m.modified_on;
}
var key;
var container;
key = this.createCacheKey('MetadataIdsByNameInLowerCase', typeKey);
container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(idsByName, idsByName);
this.setItem(key, container);
key = this.createCacheKey('MetadataNamesById', typeKey);
container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(namesById, namesById);
this.setItem(key, container);
key = this.createCacheKey('MetadataDatesById', typeKey);
container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(datesById, datesById);
this.setItem(key, container);
};
scopeVariable.getSoapFromServerOrFromCache = function(methodName, queryParameters) {
var requestURL = this.generateRequestURL(methodName, queryParameters);
var res = this.getSoapFromCache(methodName, requestURL);
if (!res) {
res = this.sendSoap(methodName, requestURL);
if (res.getFaultCode() === 0) {
this.putSoapToCache(methodName, requestURL, res);
}
}
return res;
};
scopeVariable.getSoapFromCache = function(methodName, requestURL) {
var key = this.createCacheKey('MetadataServiceCache', requestURL);
var container = this.getItem(key);
return container ? container.content : undefined;
};
scopeVariable.putSoapToCache = function(methodName, requestURL, content) {
var key = this.createCacheKey('MetadataServiceCache', requestURL);
var container = this._getMostTopWindowWithAras().aras.IomFactory.CreateCacheableContainer(content, content);
this.setItem(key, container);
};
scopeVariable.generateRequestURL = function(methodName, queryParameters, cacheKey) {
function appendParameter(param, value) {
if (param !== '') {
param += '&';
}
param += value;
return param;
}
var soapHeaders = this.aras.getHttpHeadersForSoapMessage();
queryParameters = appendParameter(queryParameters, 'database=' + soapHeaders.DATABASE);
queryParameters = appendParameter(queryParameters, 'user=' + soapHeaders.AUTHUSER);
//Language Code (not Locale!!!) is only necessary value for I18N
queryParameters = appendParameter(queryParameters, 'lang=' + this.aras.getSessionContextLanguageCode());
queryParameters = appendParameter(queryParameters, 'cache=' + (cacheKey ? cacheKey : '0'));
return this._getMostTopWindowWithAras().aras.getServerBaseURL() + 'MetaData.asmx/' + methodName + (queryParameters ? '?' + queryParameters : '');
};
scopeVariable.sendSoap = function(methodName, requestURL) {
var finalRetVal;
this.sendSoapInternal(methodName, requestURL, false).then(function(res) {
finalRetVal = res;
});
return finalRetVal;
};
scopeVariable.sendSoapAsync = function(methodName, requestURL) {
return this.sendSoapInternal(methodName, requestURL, true);
};
scopeVariable.sendSoapInternal = function(methodName, requestURL, async) {
var aras = this.aras;
var promiseFunction = function(resolve) {
var finalRetVal;
ArasModules.soap('', {
url: requestURL,
method: methodName,
restMethod: 'GET',
async: async
}).then(function(resultNode) {
var text;
if (resultNode.ownerDocument) {
var doc = resultNode.ownerDocument;
text = doc.xml || (new XMLSerializer()).serializeToString(doc);
} else {
text = resultNode;
}
finalRetVal = new SOAPResults(aras, text, false);
resolve(finalRetVal);
}, function(xhr) {
finalRetVal = new SOAPResults(aras, xhr.responseText, false);
resolve(finalRetVal);
});
};
var promise;
if (!async) {
promise = new ArasModules.SyncPromise(promiseFunction);
} else {
promise = new Promise(promiseFunction);
}
return promise;
};
scopeVariable.getItemType = function(criteriaValue, criteriaName) {
var itemType = 'ItemType';
var id = criteriaName == 'id' ? criteriaValue : this.extractIdByName(criteriaValue, itemType);
var date = this.extractDateById(id, itemType);
var queryParameters = 'id=' + id + '&date=' + date;
var methodName = this.typeInfo.ItemType.getMethod;
var requestURL = this.generateRequestURL(methodName, queryParameters);
var res = this.getSoapFromCache(methodName, requestURL);
if (!res) {
res = this.sendSoap(methodName, requestURL);
if (res.getFaultCode() === 0) {
this.putSoapToCache(methodName, requestURL, res);
var rels = res.results.selectNodes(this.aras.XPathResult() + '/Item/Relationships/Item[@type="RelationshipType"]');
for (var i = 0; i < rels.length; i++) {
var rel = rels[i];
var relId = this.aras.getItemProperty(rel, 'id');
var relDate = this.extractDateById(relId, 'RelationshipType');
var relQueryParameters = 'id=' + relId + '&date=' + relDate;
var relRequestURL = this.generateRequestURL(this.typeInfo.RelationshipType.getMethod, relQueryParameters);
var relRes = new SOAPResults(this.aras, '' + rel.xml + ' ');
this.putSoapToCache(this.typeInfo.RelationshipType.getMethod, relRequestURL, relRes);
}
}
}
return res;
};
scopeVariable.stdGet = function(typeInfo, itemType, criteriaValue, criteriaName) {
var id = criteriaName == 'id' ? criteriaValue : this.extractIdByName(criteriaValue, itemType);
var date = this.extractDateById(id, itemType);
var queryParameters = 'id=' + id + '&date=' + date;
return this.getSoapFromServerOrFromCache(typeInfo.getMethod, queryParameters);
};
scopeVariable.getRelationshipType = function(criteriaValue, criteriaName) {
return this.stdGet(this.typeInfo.RelationshipType, 'RelationshipType', criteriaValue, criteriaName);
};
scopeVariable.getForm = function(criteriaValue, criteriaName) {
return this.stdGet(this.typeInfo.Form, 'Form', criteriaValue, criteriaName);
};
scopeVariable.getClientMethod = function(criteriaValue, criteriaName) {
var methodNd = this.getClientMethodNd(criteriaValue, criteriaName);
if (methodNd) {
return new SOAPResults(this.aras,'' + methodNd.xml + ' ');
}
return this.stdGet(this.typeInfo.Method, 'Method', criteriaValue, criteriaName);
};
scopeVariable.getClientMethodNd = function(criteriaValue, criteriaName) {
var allMethods = this.getAllClientMethods();
var methodId;
if (criteriaName != 'id') {
var idsByNames = this.getItem(this.createCacheKey('MetadataClientMethodsIdsByNames', '307C85932F514F70A81B7A09376A8D6C'));
if (!idsByNames) {
return;
}
methodId = idsByNames[criteriaValue.toLowerCase()];
} else {
methodId = criteriaValue;
}
return allMethods[methodId];
};
scopeVariable.getAllClientMethods = function() {
var typeKey = this.typeInfo.GetAllClientMethodsMetadata.typeKey;
var dateMethodName = this.typeInfo.GetAllClientMethodsMetadata.getDatesMethod;
var methodName = this.typeInfo.GetAllClientMethodsMetadata.getMethod;
var date = this.getLastModifiedItemDateFromCache('MetadataLastModifiedClientMethodsDate', typeKey, dateMethodName);
var requestURL = this.generateRequestURL(methodName, 'date=' + date);
var res = this.getSoapFromCache(methodName, requestURL);
if (!res) {
res = this.sendSoap(methodName, requestURL);
var methodDict = {};
if (res.getFaultCode() === 0) {
var nodes = res.getResult().selectNodes(this.aras.XPathResult('/Item[@type=\'Method\']'));
if (nodes.length > 0) {
var idsByNames = {};
for (var i = 0; i < nodes.length; i++) {
var id = nodes[i].getAttribute('id');
idsByNames[nodes[i].selectSingleNode('name').text.toLowerCase()] = id;
methodDict[id] = nodes[i];
}
this.putSoapToCache(methodName, requestURL, methodDict);
var cacheKey = this.createCacheKey('MetadataClientMethodsIdsByNames', '307C85932F514F70A81B7A09376A8D6C');
this.setItem(cacheKey, idsByNames);
}
}
res = methodDict;
}
return res;
};
scopeVariable.getQueryParametersForGetCUI = function(context) {
// date is single maximal for all CUI config, no any per id/context division
var date = this.extractDateById('83F725B93D9840E7A4B139E40DCDA8C4', 'ConfigurableUI');
var complexId = 'item_type_id=' + context.item_type_id + '&location_name=' + context.location_name + '&item_classification=' + context.item_classification;
var queryParameters = 'id=' + escape(complexId) + '&date=' + date;
return queryParameters;
};
scopeVariable.getConfigurableUi = function(context) {
var queryParameters = this.getQueryParametersForGetCUI(context);
return this.getSoapFromServerOrFromCache(this.typeInfo.ConfigurableUI.getMethod, queryParameters);
};
scopeVariable.getConfigurableUiAsync = function(context) {
var queryParameters = this.getQueryParametersForGetCUI(context);
var methodName = this.typeInfo.ConfigurableUI.getMethod;
var requestURL = this.generateRequestURL(methodName, queryParameters);
var res = this.getSoapFromCache(methodName, requestURL);
if (!res) {
return this.sendSoapAsync(methodName, requestURL).then(function(result) {
if (result.getFaultCode() === 0) {
this.putSoapToCache(methodName, requestURL, result);
}
return result;
}.bind(this));
}
return Promise.resolve(res);
};
scopeVariable.stdGetById = function(typeInfo, itemType, id) {
var date = this.extractDateById(id, itemType);
return this.getSoapFromServerOrFromCache(typeInfo.getMethod, 'id=' + id + '&date=' + date);
};
scopeVariable.getPresentationConfiguration = function(id) {
return this.stdGetById(this.typeInfo.PresentationConfiguration, 'PresentationConfiguration', id);
};
scopeVariable.getCommandBarSection = function(id) {
return this.stdGetById(this.typeInfo.CommandBarSection, 'CommandBarSection', id);
};
scopeVariable.getContentTypeByDocumentItemType = function(id) {
return this.stdGetById(this.typeInfo.ContentTypeByDocumentItemType, 'ContentTypeByDocumentItemType', id);
};
scopeVariable.getList = function(listIds, filterListIds) {
//listIds - list of ids for which Value type is needed
//filterListIds - list of ids for which Filter Value type is needed
var queryParameters; //variable for request params
var response; //variable with response to check content
var methodName = this.typeInfo.List.getMethod;
var result = '';
var i;
//check if list isn't empty
if (listIds.length !== 0) {
//for each single element in collection request for metadata to service
for (i = 0; i < listIds.length; i++) {
queryParameters = 'id=' + listIds[i] + '&valType=value&date=' + this.extractDateById(listIds[i], 'List');
response = this.getSoapFromServerOrFromCache(methodName, queryParameters);
//if fault code was returned we return object with this fault
if (response.getFaultCode() !== 0) {
return response;
}
result += response.getResultsBody();
}
}
if (filterListIds.length !== 0) {
//for each single element in collection request for metadata to service
for (i = 0; i < filterListIds.length; i++) {
queryParameters = 'id=' + filterListIds[i] + '&valType=filtervalue&date=' + this.extractDateById(filterListIds[i], 'List');
response = this.getSoapFromServerOrFromCache(methodName, queryParameters);
//if fault code was returned we return object with this fault
if (response.getFaultCode() !== 0) {
return response;
}
result += response.getResultsBody();
}
}
result += ' ';
result = new SOAPResults(this.aras, result);
return result;
};
scopeVariable.getIdentity = function(criteriaValue, criteriaName) {
return this.stdGet(this.typeInfo.Identity, 'Identity', criteriaValue, criteriaName);
};
scopeVariable.getSearchModes = function() {
var typeKey = this.typeInfo.GetLastModifiedSearchModeDate.typeKey;
var dateMethodName = this.typeInfo.GetLastModifiedSearchModeDate.getDatesMethod;
var methodName = this.typeInfo.GetLastModifiedSearchModeDate.getMethod;
var date = this.getLastModifiedItemDateFromCache('MetadataLastModifiedSearchModeDate', typeKey, dateMethodName);
var queryParameters = 'date=' + date;
var res = this.getSoapFromServerOrFromCache(methodName, queryParameters);
if (res.getFaultCode() !== 0) {
this.aras.AlertError(res);
var resIOMError = this.aras.newIOMInnovator().newError(res.getFaultString());
return resIOMError;
}
return res.getResult();
};
scopeVariable.getLastModifiedItemDateFromCache = function(cacheKey, typeKey, dateMethodName) {
var keyDateItems = this.createCacheKey(cacheKey, typeKey);
var date = this.getItem(keyDateItems);
if (!date) {
date = this.getLastModifiedItemDateFromServer(dateMethodName);
this.removeItemById(typeKey, true);
this.setItem(keyDateItems, date);
}
return date;
};
scopeVariable.getLastModifiedItemDateFromServer = function(dateMethodName) {
return this.getPreloadDate(dateMethodName);
};
scopeVariable.updatePreloadDates = function(metadataDates) {
if (!metadataDates) {
metadataDates = aras.getMainWindow().arasMainWindowInfo.GetAllMetadataDates;
}
for (var i = 0; i < metadataDates.childNodes.length; i++) {
this.preloadDates[metadataDates.childNodes[i].nodeName] = metadataDates.childNodes[i].text;
}
};
scopeVariable.deleteListDatesFromCache = function() {
this.removeItemById(this.typeInfo.List.typeKey);
};
scopeVariable.deleteFormDatesFromCache = function() {
this.removeItemById(this.typeInfo.Form.typeKey);
};
scopeVariable.deleteClientMethodDatesFromCache = function() {
this.removeItemById(this.typeInfo.Method.typeKey);
};
scopeVariable.deleteAllClientMethodsDatesFromCache = function() {
this.removeItemById(this.typeInfo.GetAllClientMethodsMetadata.typeKey);
};
scopeVariable.deleteITDatesFromCache = function() {
this.removeItemById(this.typeInfo.ItemType.typeKey);
};
scopeVariable.deleteRTDatesFromCache = function() {
this.removeItemById(this.typeInfo.RelationshipType.typeKey);
};
scopeVariable.deleteIdentityDatesFromCache = function() {
this.removeItemById(this.typeInfo.Identity.typeKey);
};
scopeVariable.deleteConfigurableUiDatesFromCache = function() {
this.removeItemById(this.typeInfo.ConfigurableUI.typeKey);
};
scopeVariable.deletePresentationConfigurationDatesFromCache = function() {
this.removeItemById(this.typeInfo.PresentationConfiguration.typeKey);
};
scopeVariable.deleteCommandBarSectionDatesFromCache = function() {
this.removeItemById(this.typeInfo.CommandBarSection.typeKey);
};
scopeVariable.deleteContentTypeByDocumentItemTypeDatesFromCache = function() {
this.removeItemById(this.typeInfo.ContentTypeByDocumentItemType.typeKey);
};
scopeVariable.deleteSearchModeDatesFromCache = function() {
this.removeItemById(this.typeInfo.GetLastModifiedSearchModeDate.typeKey);
};
scopeVariable.getItem = function(key) {
return this.cache.GetItem(key);
};
scopeVariable.removeById = function(id, doNotClearDate) {
this.cache.RemoveById(id);
if (!doNotClearDate) {
var typeInfoName = this.findTypeInfoNameById(id);
delete this.preloadDates[typeInfoName];
}
};
scopeVariable.setItem = function(key, item) {
this.cache.SetItem(key, item);
};
scopeVariable.getItemsById = function(key) {
return this.cache.GetItemsById(key);
};
scopeVariable.clearCache = function() {
this.cache.ClearCache();
this.preloadDates = {};
this.updatePreloadDates();
};
//This function accepts any number of parameters
scopeVariable.createCacheKey = function() {
var key = aras.IomFactory.CreateArrayList();
for (var i = 0; i < arguments.length; i++) {
key.add(arguments[i]);
}
return key;
};
scopeVariable.removeItemById = function(id) {
var mainArasObj = aras.getMainArasObject();
if (mainArasObj && mainArasObj != aras) {
mainArasObj.MetadataCache.RemoveItemById(id);
} else {
this.removeById(id);
}
};
return {
GetItemType: function(criteriaValue, criteriaName) {
return scopeVariable.getItemType(criteriaValue, criteriaName);
},
GetRelationshipType: function(criteriaValue, criteriaName) {
return scopeVariable.getRelationshipType(criteriaValue, criteriaName);
},
GetForm: function(criteriaValue, criteriaName) {
return scopeVariable.getForm(criteriaValue, criteriaName);
},
GetClientMethod: function(criteriaValue, criteriaName) {
return scopeVariable.getClientMethod(criteriaValue, criteriaName);
},
GetClientMethodNd: function(criteriaValue, criteriaName) {
return scopeVariable.getClientMethodNd(criteriaValue, criteriaName);
},
GetAllClientMethods: function() {
return scopeVariable.getAllClientMethods();
},
GetList: function(listIds, filterListIds) {
return scopeVariable.getList(listIds, filterListIds);
},
GetApplicationVersion: function() {
var requestUrl = scopeVariable.generateRequestURL('GetApplicationVersion', '');
return scopeVariable.sendSoap('GetApplicationVersion', requestUrl);
},
GetIdentity: function(criteriaValue, criteriaName) {
return scopeVariable.getIdentity(criteriaValue, criteriaName);
},
GetSearchModes: function() {
return scopeVariable.getSearchModes();
},
GetItemTypeName: function(id) {
return scopeVariable.extractNameById(id, 'ItemType');
},
GetRelationshipTypeName: function(id) {
return scopeVariable.extractNameById(id, 'RelationshipType');
},
GetFormName: function(id) {
return scopeVariable.extractNameById(id, 'Form');
},
GetItemTypeId: function(name) {
return scopeVariable.extractIdByName(name, 'ItemType');
},
GetRelationshipTypeId: function(name) {
return scopeVariable.extractIdByName(name, 'RelationshipType');
},
GetFormId: function(name) {
return scopeVariable.extractIdByName(name, 'Form');
},
ExtractDateFromCache: function(criteriaValue, criteriaType, itemType) {
return scopeVariable.extractDateFromCache(criteriaValue, criteriaType, itemType);
},
DeleteListDatesFromCache: function() {
return scopeVariable.deleteListDatesFromCache();
},
DeleteFormDatesFromCache: function() {
return scopeVariable.deleteFormDatesFromCache();
},
DeleteClientMethodDatesFromCache: function() {
return scopeVariable.deleteClientMethodDatesFromCache();
},
DeleteAllClientMethodsDatesFromCache: function() {
return scopeVariable.deleteAllClientMethodsDatesFromCache();
},
DeleteITDatesFromCache: function() {
return scopeVariable.deleteITDatesFromCache();
},
DeleteRTDatesFromCache: function() {
return scopeVariable.deleteRTDatesFromCache();
},
DeleteIdentityDatesFromCache: function() {
return scopeVariable.deleteIdentityDatesFromCache();
},
DeleteConfigurableUiDatesFromCache: function() {
return scopeVariable.deleteConfigurableUiDatesFromCache();
},
DeletePresentationConfigurationDatesFromCache: function() {
return scopeVariable.deletePresentationConfigurationDatesFromCache();
},
DeleteCommandBarSectionDatesFromCache: function() {
return scopeVariable.deleteCommandBarSectionDatesFromCache();
},
DeleteContentTypeByDocumentItemTypeDatesFromCache: function() {
return scopeVariable.deleteContentTypeByDocumentItemTypeDatesFromCache();
},
DeleteSearchModeDatesFromCache: function() {
return scopeVariable.deleteSearchModeDatesFromCache();
},
GetItem: function(key) {
return scopeVariable.getItem(key);
},
RemoveById: function(id) {
return scopeVariable.removeById(id);
},
SetItem: function(key, item) {
return scopeVariable.setItem(key, item);
},
GetItemsById: function(key) {
return scopeVariable.getItemsById(key);
},
ClearCache: function() {
return scopeVariable.clearCache();
},
CreateCacheKey: function() {
return scopeVariable.createCacheKey.apply(null, arguments);
},
RemoveItemById: function(id) {
return scopeVariable.removeItemById(id);
},
GetConfigurableUi: function(context) {
return scopeVariable.getConfigurableUi(context);
},
GetConfigurableUiAsync: function(context) {
return scopeVariable.getConfigurableUiAsync(context);
},
GetPresentationConfiguration: function(id) {
return scopeVariable.getPresentationConfiguration(id);
},
GetCommandBarSection: function(id) {
return scopeVariable.getCommandBarSection(id);
},
GetContentTypeByDocumentItemType: function(id) {
///Zero-filled (GU)ID if there's no cmf_ContentType for given linked_document_type
return scopeVariable.getContentTypeByDocumentItemType(id);
},
RefreshMetadata: function(itemTypeName, async, callback) {
return scopeVariable.refreshMetadata(itemTypeName, async, callback);
},
UpdatePreloadDates: function(metadataDates) {
return scopeVariable.updatePreloadDates(metadataDates);
}
};
}
/** iom.js **/
function IOMCache(parentArasObj) {
this.arasObj = parentArasObj;
}
IOMCache.prototype.apply = function IOMCacheApply(itemNd) {
if (!itemNd) {
return null;
}
var itemID = itemNd.getAttribute('id');
var itemTypeName = itemNd.getAttribute('type');
var itemAction = itemNd.getAttribute('action');
if (itemAction === null) {
itemAction = '';
}
var win = this.arasObj.uiFindWindowEx2(itemNd);
//special checks for the item of ItemType type
// tag in itemNd required for next call
var res;
if (itemTypeName == 'ItemType') {
res = this.arasObj.checkItemType(itemNd, win);
} else {
res = true;
}
if (!res) {
return null;
}
if (itemTypeName) {
if (itemAction == 'delete') {
this.arasObj.deleteItem(itemTypeName, itemID, true);
return null;
} else if (itemAction == 'purge') {
this.arasObj.purgeItem(itemTypeName, itemID, true);
return null;
}
}
//general checks for the item to be saved: all required parameters should be set
if (itemTypeName) {
res = this.arasObj.checkItem(itemNd, win);
} else {
res = true;
}
if (!res) {
return null;
}
res = null;
var backupCopy = itemNd;
var oldParent = backupCopy.parentNode;
itemNd = itemNd.cloneNode(true);
this.arasObj.prepareItem4Save(itemNd);
var isTemp = this.arasObj.isTempEx(itemNd);
if (itemNd.getAttribute('action') == 'add') {
if (itemTypeName == 'RelationshipType') {
if (!itemNd.selectSingleNode('relationship_id/Item')) {
var rsItemNode = itemNd.selectSingleNode('relationship_id');
if (rsItemNode) {
var rs = this.arasObj.getItemById('', rsItemNode.text, 0);
if (rs) {
rsItemNode.text = '';
rsItemNode.appendChild(rs.cloneNode(true));
}
}
}
var tmp001 = itemNd.selectSingleNode('relationship_id/Item');
if (tmp001 && this.arasObj.getItemProperty(tmp001, 'name') === '') {
this.arasObj.setItemProperty(tmp001, 'name', this.arasObj.getItemProperty(itemNd, 'name'));
}
}
}
var files = itemNd.selectNodes('descendant-or-self::Item[@type="File" and (@action="add" or @action="update")]');
if (files.length === 0) {
res = this.arasObj.soapSend('ApplyItem', itemNd.xml);
if (res.getFaultCode() !== 0) {
return null;
}
res = res.results.selectSingleNode(this.arasObj.XPathResult('/Item'));
} else {
res = this.arasObj.sendFilesWithVaultApplet(itemNd, 'Sending of File to Vault...');
}//else if (files.length==0)
if (!res) {
return null;
}
res.setAttribute('levels', '0');
var newID = res.getAttribute('id');
this.arasObj.updateInCacheEx(backupCopy, res);
if (itemTypeName == 'RelationshipType') {
var relationshipId = this.arasObj.getItemProperty(itemNd, 'relationship_id');
if (relationshipId) {
this.arasObj.removeFromCache(relationshipId);
}
this.arasObj.commonProperties.formsCacheById = this.arasObj.newObject();
} else if (itemTypeName == 'ItemType') {
var itemName = this.arasObj.getItemProperty(itemNd, 'name');
this.arasObj.deletePropertyFromObject(this.arasObj.sGridsSetups, itemName);
this.arasObj.commonProperties.formsCacheById = this.arasObj.newObject();
}
if (oldParent) {
res = oldParent.selectSingleNode('Item[@id="' + newID + '"]');
} else {
res = this.arasObj.getFromCache(newID);
}
if (!res) {
return null;
}
if (newID != itemID) {
var itms = this.arasObj.getAffectedItems(itemNd.getAttribute('type'), newID);
if (itms) {
for (var i = 0; i < itms.length; i++) {
var itm = itms[i];
var itmID = itm.getAttribute('id');
var affectedItm = this.arasObj.getItemById('', itmID, 0);
if (affectedItm) {
if (affectedItm.getAttribute('levels') === null) {
affectedItm.setAttribute('levels', 1);
}
var tmpRes = this.arasObj.loadItems(itm.getAttribute('type'), 'id="' + itmID + '"', affectedItm.getAttribute('levels'));
if (!tmpRes) {
continue;
}
if (this.arasObj.uiFindWindowEx[itmID]) {
setTimeout('TopWindowHelper.getMostTopWindowWithAras(window).aras.uiReShowItem(\'' + itmID + '\',\'' + itmID + '\');', 100);
}
}
}
}
}
return res;
};
function Innovator()
{
return top.aras.newIOMInnovator();
}
function Item(itemTypeName, action, mode)
{
return top.aras.IomInnovator.newItem(itemTypeName, action);
}
function AuthenticationBrokerClient() { }
AuthenticationBrokerClient.prototype.GetFileDownloadToken = function AuthenticationBrokerClientGetFileDownloadToken(fileId) {
var innovatorUrl = TopWindowHelper.getMostTopWindowWithAras(window).aras.getServerBaseURL();
var result = GetSynchronousJSONResponse(innovatorUrl + 'AuthenticationBroker.asmx/GetFileDownloadToken', '{"param":{"fileId":"' + fileId + '"}}');
var evalMethod = window.eval;
result = evalMethod('(' + result + ')');
return result.d;
};
AuthenticationBrokerClient.prototype.GetFilesDownloadTokens = function AuthenticationBrokerClientGetFilesDownloadTokens(fileIds) {
var body = '{"parameters":[';
for (var i = 0; i < fileIds.count; i++) {
body += '{"__type":"FileDownloadParameters","fileId":"' + fileIds(i) + '"},';
}
body = body.slice(0, body.length - 1) + ']}';
var innovatorUrl = TopWindowHelper.getMostTopWindowWithAras(window).aras.getServerBaseURL();
var result = GetSynchronousJSONResponse(innovatorUrl + 'AuthenticationBroker.asmx/GetFilesDownloadTokens', body);
var evalMethod = window.eval;
result = evalMethod('(' + result + ')');
result = result.d;
var list = TopWindowHelper.getMostTopWindowWithAras(window).aras.IomFactory.CreateArrayList();
for (var j = 0, count = result.length - 1; j < count; j++) {
list.Add(result[j]);
}
return list;
};
function LicenseManagerWebServiceClient() {
this.aras = TopWindowHelper.getMostTopWindowWithAras(window).aras;
this.actionNamespace = this.aras.arasService.actionNamespace;
this.iServiceName = this.aras.arasService.serviceName;
this.licenseServiceUrl = this.aras.getServerBaseURL() + 'Licensing.asmx/';
}
LicenseManagerWebServiceClient.prototype.ConsumeLicense = function(featureName) {
// don't used soap because request body isn't XML
var xhr = new XMLHttpRequest();
var methodName = 'ConsumeLicense';
var url = this.licenseServiceUrl + methodName;
xhr.open('POST', url, false);
var additionalHeaders = this.aras.getHttpHeadersForSoapMessage(methodName);
Object.keys(additionalHeaders).forEach(function(header) {
xhr.setRequestHeader(header, additionalHeaders[header]);
});
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
xhr.send('featureName=' + encodeURIComponent(featureName));
if (xhr.status !== 200) {
throw new Error(xhr.responseText);
}
var doc = this.aras.createXMLDocument();
doc.loadXML(xhr.responseText);
return doc.documentElement.text;
};
function GetSynchronousJSONResponse(url, postData) {
var xmlhttp = new XMLHttpRequest();
url = url + '?rnd=' + Math.random(); // to be ensure non-cached version
xmlhttp.open('POST', url, false);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
var headers = TopWindowHelper.getMostTopWindowWithAras(window).aras.getHttpHeadersForSoapMessage('GetFileDownloadToken');
for (var hName in headers) {
xmlhttp.setRequestHeader(hName, headers[hName]);
}
xmlhttp.send(postData);
return xmlhttp.responseText;
}
/** vars_storage.js **/
function VarsStorageClass() {
this.unknownStorage = {};
}
VarsStorageClass.prototype.getVariable = function VarsStorageClassGetVariable(varName) {
var res = this.unknownStorage[varName];
return res;
};
VarsStorageClass.prototype.setVariable = function VarsStorageClassSetVariable(varName, varValue) {
if (typeof (varValue) != 'string' && varValue !== null) {
varValue = varValue.toString();
}
this.unknownStorage[varName] = varValue;
};
/** user_notifications.js **/
function UserNotificationContainer(notification_control) {
if (!notification_control) {
throw new Error(1, 'ArgumentException: notification_control can\'t be undefined');
}
this.NotificationControl = notification_control;
this.CheckInterval = null;
this.CheckTimeout = null;
this.constAcknowledge = 'Acknowledge';
this.constClose = 'Close';
this.url = parent.aras.getInnovatorUrl() + 'NotificationServer/UserNotifications/ProxyPage.aspx';
this.UpdateInfoDom = null;
this.PopupParametersArray = [];
var variable = parent.aras.commonProperties.MessageCheckInterval;
if (variable) {
this.CheckInterval = variable;
}
if (!this.CheckInterval) {
parent.aras.AlertError(parent.aras.getResource('', 'user_notifications.failed_get_interval_variable'), '', '');
return;
}
this.CheckTimeout = setTimeout(function() { parent.aras.UserNotification.StartIterativeUpdateMessageCollection(); }, this.CheckInterval);
}
UserNotificationContainer.prototype.AddMessage = function UserNotificationContainer_AddMessage(id, text, image, messageItem) {
this.NotificationControl.AddOrUpdate(id, text, image, messageItem);
};
UserNotificationContainer.prototype.RemoveMessage = function UserNotificationContainer_RemoveMessage(id) {
return this.NotificationControl.Remove(id);
};
UserNotificationContainer.prototype.ClearCollection = function UserNotificationContainer_ClearCollection() {
this.NotificationControl.Clear();
};
UserNotificationContainer.prototype.MakeAllMessagesOld = function UserNotificationContainer_MakeAllMessagesOld() {
this.NotificationControl.MakeOld();
};
UserNotificationContainer.prototype.ClearOldMessages = function UserNotificationContainer_ClearOldMessages() {
this.NotificationControl.ClearOld();
};
UserNotificationContainer.prototype.GetMessageQuery = function UserNotificationContainer_GetMessageQuery() {
var query_dom = parent.aras.createXMLDocument();
var dtObj = new Date();
var yyyy = String(dtObj.getFullYear());
var h = {
MM: String('0' + (dtObj.getMonth() + 1)),
dd: String('0' + dtObj.getDate()),
hh: String('0' + dtObj.getHours()),
mm: String('0' + dtObj.getMinutes()),
ss: String('0' + dtObj.getSeconds())
};
for (var k in h) {
h[k] = h[k].substr(h[k].length - 2);
}
var r = yyyy + '-' + h.MM + '-' + h.dd + 'T' + h.hh + ':' + h.mm + ':' + h.ss;
query_dom.loadXML(' ');
var currentUserIDNode = query_dom.createElement('CurrentUserID');
var dateTimeNode = query_dom.createElement('DateTime');
currentUserIDNode.text = parent.aras.getCurrentUserID();
dateTimeNode.text = r;
query_dom.documentElement.appendChild(currentUserIDNode);
query_dom.documentElement.appendChild(dateTimeNode);
return query_dom.documentElement.xml;
};
UserNotificationContainer.prototype.AsyncCheckNewMessages = function UserNotificationContainer_AsyncCheckNewMessages(getCollectionCallback) {
var soapController = new SoapController(resultCallbackHandler);
soapController.NotificationContainer = this;
var query = this.GetMessageQuery();
var soap_res = parent.aras.soapSend('GetNotifications', query, this.url, null, soapController);
function resultCallbackHandler(soap_res) {
if (this.NotificationContainer) {
var message_collection = this.NotificationContainer.ProcessSoapResult(soap_res);
getCollectionCallback(this.NotificationContainer, message_collection);
}
}
};
UserNotificationContainer.prototype.SyncGetMessageCollection = function UserNotificationContainer_SyncGetMessageCollection() {
var query = this.GetMessageQuery();
var soap_res = parent.aras.soapSend('GetNotifications', query, this.url);
return this.ProcessSoapResult(soap_res);
};
UserNotificationContainer.prototype.ProcessSoapResult = function UserNotificationContainer_ProcessSoapResult(soap_res) {
if (soap_res.getFaultCode() !== 0) {
parent.aras.AlertError(soap_res);
return null;
}
var result_dom;
if (soap_res.isFault()) {
return null;
} else {
result_dom = soap_res.getResult();
}
return result_dom;
};
UserNotificationContainer.prototype.RefreshUpdateDom = function UserNotificationContainer_RefreshUpdateDom(result_dom) {
if (!result_dom) {
return;
}
this.UpdateInfoDom = result_dom.selectSingleNode('Item[@id=\'UpdateInfoMessage\']');
};
UserNotificationContainer.prototype.FillStandardMessageCollection = function UserNotificationContainer_FillStandardMessageCollection(result_dom, clear_before) {
if (clear_before) {
this.ClearCollection();
} else {
this.MakeAllMessagesOld();
}
if (!result_dom) {
this.ClearCollection();
return;
}
var standard_collection = result_dom.selectNodes('Item[type/text()=\'Standard\']')
for (var i = 0; i < standard_collection.length; i++) {
var messageItem = standard_collection[i];
var message_id = messageItem.getAttribute('id');
var title = parent.aras.getItemProperty(messageItem, 'title');
var image_url = parent.aras.getItemProperty(messageItem, 'icon');
this.AddMessage(message_id, title, image_url, messageItem);
}
this.ClearOldMessages();
};
UserNotificationContainer.prototype.ShowPopupCollection = function UserNotificationContainer_ShowPopupCollection(result_dom, showAsModeless) {
if (!result_dom) {
return;
}
var popup_collection = result_dom.selectNodes('Item[type/text()=\'Popup\']');
var sorted_list = this.SortMessagesByPriority(popup_collection);
var i = 0;
var nextSortedList = function() {
if (i >= sorted_list.length) {
return;
}
var index = showAsModeless ? i : sorted_list.length - i - 1;
if (!sorted_list[index]) {
i++;
nextSortedList();
} else {
nextMsgIndex(index, 0);
}
}.bind(this);
var nextMsgIndex = function(index, msg_index) {
if (msg_index >= sorted_list[index].length) {
i++;
nextSortedList();
} else {
this.DisplayMessageDialog(sorted_list[index][msg_index], showAsModeless, function() {
window.setTimeout(function() {
msg_index++;
nextMsgIndex(index, msg_index);
}, 0);
});
}
}.bind(this);
nextSortedList();
};
UserNotificationContainer.prototype.SortMessagesByPriority = function UserNotificationContainer_SortMessagesByPriority(message_collection) {
var sorted_list = [];
for (var i = 0; i < message_collection.length; i++) {
var priority = parent.aras.getItemProperty(message_collection[i], 'priority');
if (!sorted_list[priority]) {
sorted_list[priority] = [];
}
sorted_list[priority][sorted_list[priority].length] = message_collection[i];
}
return sorted_list;
};
UserNotificationContainer.prototype.UpdateMessageCollection = function UserNotificationContainer_UpdateMessageCollection(doAsync, callback) {
if (!doAsync) {
doAsync = false;
}
if (doAsync) {
var fn = function getCollectionCallback(container, message_collection) {
container.RefreshUpdateDom(message_collection);
container.FillStandardMessageCollection(message_collection);
container.ShowPopupCollection(message_collection, true);
callback();
};
this.AsyncCheckNewMessages(fn);
} else {
var message_collection = this.SyncGetMessageCollection();
this.RefreshUpdateDom(message_collection);
this.FillStandardMessageCollection(message_collection);
this.ShowPopupCollection(message_collection, false);
}
};
UserNotificationContainer.prototype.StartIterativeUpdateMessageCollection = function UserNotificationContainer_StartIterativeUpdateMessageCollection() {
this.UpdateMessageCollection(true, callback);
function callback() {
this.CheckTimeout = setTimeout(function() { parent.aras.UserNotification.StartIterativeUpdateMessageCollection(); }, parent.aras.UserNotification.CheckInterval);
}
};
UserNotificationContainer.prototype.DisplayMessageDialogById = function UserNotificationContainer_DisplayMessageDialogById(message_id, showAsModeless) {
if ('UpdateInfoMessage' == message_id) {
this.DisplayMessageDialog(this.UpdateInfoDom, showAsModeless);
} else {
var message_item = parent.aras.getItemById('Message', message_id);
if (message_item) {
this.DisplayMessageDialog(message_item, showAsModeless);
} else {
parent.aras.AlertError(parent.aras.getResource('', 'user_notifications.message_no_more_available'), '', '');
this.RemoveMessage(message_id);
}
}
};
UserNotificationContainer.prototype.DisplayMessageDialog = function UserNotificationContainer_DisplayMessageDialog(message_item, showAsModeless, callback)
{
if (message_item == null) {
return;
}
var template_url = parent.aras.getI18NXMLResource('notification_popup_template.xml', parent.aras.getBaseURL());
var template_dom = parent.aras.createXMLDocument();
template_dom.load(template_url);
var parameters = this.PopupParametersArray[parent.aras.getItemProperty(message_item, 'id')];
if (!parameters) {
parameters = {};
}
var opened_message_window = parameters.window;
parameters.id = parent.aras.getItemProperty(message_item, 'id');
parameters.default_template = template_dom.selectSingleNode('template/html').text;
parameters.custom_html = parent.aras.getItemProperty(message_item, 'custom_html');
parameters.dialogWidth = parent.aras.getItemProperty(message_item, 'width');
parameters.dialogHeight = parent.aras.getItemProperty(message_item, 'height');
parameters.css = parent.aras.getItemProperty(message_item, 'css');
parameters.is_standard_template = parent.aras.getItemProperty(message_item, 'is_standard_template') == '1';
if (!parameters.dialogWidth || parameters.is_standard_template) {
parameters.dialogWidth = template_dom.selectSingleNode('template/dialog_width').text;
}
if (!parameters.dialogHeight || parameters.is_standard_template) {
parameters.dialogHeight = template_dom.selectSingleNode('template/dialog_height').text;
}
parameters.title = parent.aras.getItemProperty(message_item, 'title');
parameters.text = parent.aras.getItemProperty(message_item, 'text');
parameters.url = parent.aras.getItemProperty(message_item, 'url');
parameters.icon = parent.aras.getItemProperty(message_item, 'icon');
parameters.OK_IsVisible = ('1' == parent.aras.getItemProperty(message_item, 'show_ok_button'));
parameters.Exit_IsVisible = ('1' == parent.aras.getItemProperty(message_item, 'show_exit_button'));
parameters.OK_Label = parent.aras.getItemProperty(message_item, 'ok_button_label');
parameters.Exit_Label = parent.aras.getItemProperty(message_item, 'exit_button_label');
parameters.container = this;
parameters.opener = window;
parameters.writeContent = writeContent;
parameters.aras = parent.aras;
this.PopupParametersArray[parameters.id] = parameters;
if (!showAsModeless) {
parameters.dialogWidth = parameters.dialogWidth;
parameters.dialogHeight = parameters.dialogHeight;
parameters.content = 'modalDialog.html';
window.ArasModules.Dialog.show('iframe', parameters).promise.then(
function(res) {
if (res == this.constAcknowledge) {
this.AcknowledgeMessage(message_item);
}
if (callback) {
callback();
}
}.bind(this)
);
} else {
var sFeatures = '';
sFeatures += 'height=' + parameters.dialogHeight + ', ';
sFeatures += 'width=' + parameters.dialogWidth + '';
if (opened_message_window) {
opened_message_window.close();
}
var fn = function OnBeforeUnloadHandler() {
if (parameters.window.returnValue == parameters.window.parameters.container.constAcknowledge) {
parameters.window.parameters.container.AcknowledgeMessage(message_item);
}
parameters.window = null;
};
parameters.window = window.open(parent.aras.getScriptsURL() + 'blank.html', '', sFeatures);
parameters.window.focus();
writeContent(parameters.window);
parameters.window.parameters = parameters;
parameters.window.addEventListener('beforeunload', fn);
if (callback) {
callback();
}
}
//////////////////////////////////////////
function writeContent(w) {
var doc = w.document,
template,
title_expr = new RegExp('{TITLE}', 'g'),
url_expr = new RegExp('{URL}', 'g'),
text_expr = new RegExp('{TEXT}', 'g'),
icon_expr = new RegExp('{ICON}', 'g');
if (!parameters.is_standard_template) {
template = parameters.custom_html.replace(title_expr, parameters.title);
template = template.replace(url_expr, parameters.url);
template = template.replace(text_expr, parameters.text);
template = template.replace(icon_expr, parameters.icon);
doc.write(template);
} else {
template = parameters.default_template.replace(title_expr, parameters.title);
template = template.replace(url_expr, parameters.url);
template = template.replace(text_expr, parameters.text);
template = template.replace(icon_expr, parameters.icon);
doc.write(template);
if (parameters.css) {
var style = doc.createElement('style');
style.innerHTML = parameters.css;
doc.head.appendChild(style);
}
var notificationTitle = doc.getElementById('notification_title');
var titleElement = notificationTitle.appendChild(doc.createElement('h2'));
titleElement.setAttribute('class', 'title');
if (parameters.url) {
var urlElement = titleElement.appendChild(doc.createElement('a'));
urlElement.setAttribute('href', parameters.url);
urlElement.setAttribute('target', '_about');
urlElement.setAttribute('class', 'sys_item_link');
urlElement.textContent = parameters.title;
} else {
titleElement.textContent = parameters.title;
}
if (!parameters.icon) {
doc.getElementById('message_icon').style.display = 'none';
}
}
w.returnValue = parameters.container.constClose;
w.closeWindow = function(value) {
if (w.dialogArguments && w.dialogArguments.dialog) {
w.dialogArguments.dialog.close(value);
} else {
w.returnValue = value || w.returnValue;
w.close();
}
};
doc.close();
var innerHTML = '';
if (parameters.OK_IsVisible) {
innerHTML += parameters.container.uiDrawInputButton('OK_button', parameters.OK_Label, ' window.closeWindow(\'' + parameters.container.constAcknowledge + '\');', 'notification_ok_btn');
}
if (parameters.Exit_IsVisible) {
innerHTML += parameters.container.uiDrawInputButton('Exit_button', parameters.Exit_Label, ' window.closeWindow(\'' + parameters.container.constClose + '\');', 'cancel_button notification_exit_btn');
}
if (innerHTML) {
var el = doc.createElement('center');
el.innerHTML = innerHTML;
var source = doc.getElementById('btns') || doc.getElementsByTagName('body')[0];
if (source) {
source.appendChild(el);
}
}
}
};
UserNotificationContainer.prototype.uiDrawInputButton = function UserNotificationContainer_uiDrawInputButton(name, value, handler_code, class_name) {
return ' ';
};
UserNotificationContainer.prototype.AcknowledgeMessage = function UserNotificationContainer_AcknowledgeMessage(message_item) {
if (!message_item) {
return;
}
var acknowledge_dom = message_item.selectSingleNode('acknowledge');
if (acknowledge_dom.text == 'Once') {
var message_id = message_item.getAttribute('id');
var relsh = '' +
'- ' +
'
' + parent.aras.getCurrentUserID() + ' ' +
' ' + message_item.getAttribute('id') + ' ' +
' ';
var soap_res = parent.aras.soapSend('ApplyItem', relsh);
if (soap_res.getFaultCode() !== 0) {
parent.aras.AlertError(soap_res);
return null;
}
if (soap_res.isFault()) {
return null;
}
this.RemoveMessage(message_id);
}
};
UserNotificationContainer.prototype.Dispose = function UserNotificationContainer_Dispose() {
if (this.CheckTimeout) {
clearTimeout(this.CheckTimeout);
}
};
/** Licensing.js **/
// © Copyright by Aras Corporation, 2013.
Licensing.ActionType = {
Activate: 0,
Update: 1,
Deactivate: 2
};
function Licensing(aras) {
this.arasObject = aras;
this.actionNamespace = aras.arasService.actionNamespace;
this.iServiceName = aras.arasService.serviceName;
this.url = aras.arasService.serviceUrl;
this.propgressBarImage = '../images/Progress.gif';
this.wnd = window;
this.error = {};
this.state = '';
this._getFeatureLicenseSecureId = function(featureLicenseId) {
if (featureLicenseId) {
var qry = this.arasObject.newIOMItem('Feature License', 'get');
qry.setID(featureLicenseId);
qry.setAttribute('select', 'secure_id');
qry = qry.apply();
if (!qry.isError() && qry.getItemCount() === 1) {
return qry.getProperty('secure_id');
}
}
return '';
};
this._validateActivationKey = function(activationKey) {
if (!activationKey) {
this.arasObject.AlertError(this.arasObject.getResource('', 'licensing.activation_key_is_empty'), '', '', this.wnd);
return false;
}
return true;
};
this._getNonFailedDoc = function(arasObject, result) {
if (!result) {
this.error = {
details: arasObject.getResource('', 'licensing.service_not_available'),
title: arasObject.getResource('', 'licensing.service_not_available_title')
};
return false;
} else if (result.search(/ ');
var envelopeNd = query.dom.selectSingleNode('//*[local-name()=\'Envelope\']');
if (envelopeNd) {
query.loadAML(envelopeNd.xml);
}
if (query.isError()) {
this.error = {alert: true, query: query};
return false;
}
return query;
};
this._showErrorPage = function(win, activationKey) {
var error = this.error;
var params;
this.error = null;
var mainWindow = this.arasObject.getMainWindow();
if (error && error.customError) {
params = {
aras: this.arasObject,
subjectHide: error.subjectHide,
errorDetails: error.details,
title: error.title,
dialogWidth: 365,
dialogHeight: 140,
content: 'Licensing/ActivateError.html'
};
mainWindow.ArasModules.Dialog.show('iframe', params);
} else if (error && error.alert) {
this.arasObject.AlertError(error.query, '', '', this.wnd);
} else if (error) {
var result = this._getRequiredServerInfo();
if (activationKey) {
result += '' + activationKey + ' ';
}
params = {
title: error.title,
aras: this.arasObject,
result: result,
errorDetails: error.details,
dialogWidth: 400,
dialogHeight: 295,
content: 'Licensing/ServiceError.html'
};
mainWindow.ArasModules.Dialog.show('iframe', params);
} else {
return;
}
if (win) {
win.close();
}
};
this._callMethodOnLicensingService = function(methodName, paramName, paramValue) {
// don't used soap because request body isn't XML
var xhr = new XMLHttpRequest();
var url = this.arasObject.getServerBaseURL() + 'Licensing.asmx/' + methodName;
xhr.open('POST', url, false);
var additionalHeaders = this.arasObject.getHttpHeadersForSoapMessage(methodName);
Object.keys(additionalHeaders).forEach(function(header) {
xhr.setRequestHeader(header, additionalHeaders[header]);
});
var body = paramName + '=' + encodeURIComponent(paramValue);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
xhr.send(body);
if (xhr.status !== 200) {
this._errorCallback(xhr.statusText, xhr.responseText);
return false;
}
return true;
};
this._getFrameworkLicenseKey = function() {
var serverInfo = this._getRequiredServerInfo();
if (serverInfo) {
frameworkLicenseKey = serverInfo.match(/]*>([^<]+)<\/framework_license_key>/)[1];
return frameworkLicenseKey ? frameworkLicenseKey : '';
}
return '';
};
this._getRequiredServerInfo = function() {
var result;
var self = this;
ArasModules.soap('',
{
url: this.arasObject.getServerBaseURL() + 'Licensing.asmx/',
appendMethodToURL: true,
async: false,
method: 'GetServerInfo',
methodNm: this.actionNamespace,
restMethod: 'POST'
})
.then(function(responseText) {
result = responseText;
}, function(rq) {
result = self._errorCallback(rq.statusText, rq.responseText);
});
if (!result) { return ''; }
var doc = this.arasObject.createXMLDocument();
doc.loadXML(result);
return doc.documentElement ? doc.documentElement.text : '';
};
this._displayFeatureRequirementsForms = function(getMetaInfoResult, activationKey, featureLicenseId, action) {
var self = this;
function showFeatureRequirementDialog(params) {
var aras = params.aras;
var container = getLicenseActionContainer(self, activationKey);
if (container) {
var postData = container;
var queryParameters = '';
queryParameters = appendParameter(queryParameters, 'actionName=' + params.action);
queryParameters = appendParameter(queryParameters, 'activationKey=' + params.activationKey);
var topWndAras = aras.getMostTopWindowWithAras(window).aras;
var formUrl = 'VirtualGetLicenseForm' + (queryParameters ? '?' + queryParameters : '');
var postUrl = topWndAras.getBaseURL() + '/Modules/aras.innovator.core.License/PostLicenseForm' + (queryParameters ? '?' + queryParameters : '');
var xmlhttp = topWndAras.XmlHttpRequestManager.CreateRequest();
xmlhttp.open('POST', postUrl, false);
xmlhttp.send(postData);
return formUrl;
} else {
//false
return container;
}
function getLicenseActionContainer(context)
{
var result = false;
var requestBody = '' +
'' +
'' +
'' + aras.commonProperties.clientRevision + ' ' +
' ' +
' ';
try {
var method = 'GetLicenseActionContainer';
var methodNm = context.actionNamespace;
var requestResponse;
ArasModules.soap(requestBody, {
url: context.url,
async: false,
method: method,
methodNm: methodNm,
SOAPAction: methodNm + context.iServiceName + '/' + method,
headers: {}
})
.then(function(responseText) {
requestResponse = responseText;
}, function(req) {
var dialogErrorCallback = context._GenerateActivateErrorCallback(
context.arasObject.getResource('', 'licensing.could_not_load_feature_requirements'),
activationKey
);
dialogErrorCallback(req.statusText, req.responseText, req.status);
});
var doc = aras.createXMLDocument();
doc.loadXML(requestResponse);
var envelope = doc.selectSingleNode('//*[local-name()=\'Envelope\']');
if (envelope) {
result = envelope.text;
}
}
finally {
return result;
}
}
function appendParameter(param, value) {
if (param !== '') {
param += '&';
}
param += value;
return param;
}
}
var query = this._checkErrors(this.arasObject, getMetaInfoResult);
if (!query) {
this._showErrorPage(null, activationKey);
return false;
}
var params = this.arasObject.newObject();
params.aras = this.arasObject;
var formArray = [];
var itemTypeArray = [];
var instanceArray = [];
var listArray = [];
var width = 350;
var height = 150;
var forms = query.getItemsByXPath('/AML/Item[@type=\'Form\']');
var formsCount = forms.getItemCount();
if (formsCount === 0) {
if (action !== Licensing.ActionType.Deactivate) {
return featureLicenseId ? this.Update(featureLicenseId) : this.Activate(activationKey);
}
return this.Deactivate(featureLicenseId);
} else {
for (var i = 0; i < formsCount; i++) {
var formItem = forms.getItemByIndex(i);
var w = parseInt(formItem.getProperty('width'));
var h = parseInt(formItem.getProperty('height'));
width = w > width ? w : width;
height = h > height ? h : height;
formArray.push(formItem);
listArray.push(query.getItemsByXPath('/AML/Item[@type=\'List\']'));
itemTypeArray.push(query.getItemsByXPath('/AML/Item[@type=\'ItemType\' and name=\'' + formItem.getProperty('name') + '\']'));
instanceArray[i] = query.getItemsByXPath('/AML/Item[@type=\'' + formItem.getProperty('name') + '\']');
}
height = parseInt(height) + 66;
params.licensingObject = this;
params.forms = formArray;
params.itemTypes = itemTypeArray;
params.listArray = listArray;
params.instances = instanceArray;
params.activationKey = activationKey;
params.featureLicenseId = featureLicenseId;
params.action = action;
self = this;
params.dialogWidth = width;
params.dialogHeight = height;
var formUrl = showFeatureRequirementDialog(params);
if (formUrl) {
params.content = formUrl;
var mainWindow = this.arasObject.getMainWindow();
mainWindow.ArasModules.Dialog.show('iframe', params);
} else {
return false;
}
}
return true;
};
this._getMetaInfoFromArasService = function(action, activationKey, featureLicenseId) {
var methodName;
var callbackMethod;
var parameterName = 'featureLicenseSecureId';
var parameterValue = this._getFeatureLicenseSecureId(featureLicenseId);
if (Licensing.ActionType.Activate === action) {
parameterName = 'activationKey';
parameterValue = activationKey;
methodName = 'GetMetaInfoForActivate';
callbackMethod = this._GenerateActivateErrorCallback(null, activationKey);
} else if (Licensing.ActionType.Update === action) {
methodName = 'GetMetaInfoForUpdate';
} else if (Licensing.ActionType.Deactivate === action) {
methodName = 'GetMetaInfoForDeactivate';
}
var metaInfoResult;
var statusId;
try {
statusId = this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage);
var methodNamespace = this.actionNamespace;
var requestBody = '<' + parameterName + '>' + parameterValue + '' + parameterName + '>';
ArasModules.soap(requestBody, {
url: this.url,
async: false,
method: methodName,
methodNm: methodNamespace,
SOAPAction: methodNamespace + this.iServiceName + '/' + methodName,
headers: {}
})
.then(function(responseText) {
metaInfoResult = responseText;
}, function(req) {
callbackMethod(req.statusText, req.responseText, req.status);
});
} finally {
this.arasObject.clearStatusMessage(statusId);
}
this._displayFeatureRequirementsForms(metaInfoResult, activationKey, featureLicenseId, action);
};
this._showInformationAboutImportedFeatureLicense = function(result, title) {
var self = this;
var mainWindow = this.arasObject.getMainWindow();
mainWindow.ArasModules.Dialog.show('iframe', {
aras: this.arasObject,
result: result,
title: this.arasObject.getResource('', 'licensing.success_import_title'),
dialogWidth: 600,
dialogHeight: 270,
center: true,
content: 'Licensing/SuccessMessage.html'
});
};
this._showActivateFeatureDialog = function LicensingShowActivateFeatureDialog(activationKey, action, featureLicenseId) {
var aras = this.arasObject;
var params = this.arasObject.newObject();
params.aras = aras;
params.licensingObject = this;
params.action = action;
params.activationKey = activationKey;
params.featureLicenseId = featureLicenseId;
params.dialogWidth = 350;
params.dialogHeight = 140;
params.center = true;
params.content = 'Licensing/ActivateFeature.html';
switch (action || Licensing.ActionType.Activate) {
case 0:
params.title = aras.getResource('', 'licensing.action_type_activate');
break;
case 1:
params.title = aras.getResource('', 'licensing.action_type_update');
break;
case 2:
params.title = aras.getResource('', 'licensing.action_type_deactivate');
break;
}
var mainWindow = aras.getMainWindow();
mainWindow.ArasModules.Dialog.show('iframe', params);
};
this._getFeatureLicenseByLicenseData = function(encryptedFeatureLicense) {
var qry = this.arasObject.newIOMItem('Feature License', 'get');
qry.setProperty('license_data', encryptedFeatureLicense);
return qry.apply();
};
this._prepareLicenseRequestBody = function(propertyName, propertyValue, additionalData) {
var serverInfo = this._getRequiredServerInfo();
additionalData = additionalData ? additionalData : ' ';
var result = '' +
'<' + propertyName + '>' + propertyValue + '' + propertyName + '>' +
'' +
' ' +
serverInfo +
additionalData +
' ' +
' ';
return result;
};
this._getFeatureTreeFromInnovatorServer = function() {
var method = 'GetFeatureTree';
var methodNm = this.actionNamespace;
var self = this;
var res;
ArasModules.soap('', {
url: this.arasObject.getServerBaseURL() + 'Licensing.asmx/GetFeatureTree',
async: false,
method: method,
methodNm: methodNm,
SOAPAction: methodNm + this.iServiceName + '/' + method,
headers: this.arasObject.getHttpHeadersForSoapMessage()
})
.then(function(result) {
res = result;
}, function(req) {
self._errorCallback(req.statusText, req.responseText, req.status);
});
return res;
};
this._errorCallback = function(errorMessage, technicalMessage, stackTrace) {
technicalMessage = !technicalMessage ? '' : technicalMessage;
stackTrace = !stackTrace ? technicalMessage : stackTrace;
this.arasObject.AlertError(errorMessage, technicalMessage, stackTrace);
return false;
};
this._GetResponseFaultstring = function(responseText) {
var doc = this.arasObject.createXMLDocument();
doc.loadXML(responseText);
var errorDetails = '';
if (doc.selectSingleNode('//faultstring')) {
errorDetails = doc.selectSingleNode('//faultstring').text;
}
return errorDetails;
};
this._GenerateActivateErrorCallback = function(messagePrefix, activationKey) {
var prefix = messagePrefix;
if (!prefix) {
prefix = '';
}
return function(statusText, responseText, status) {
if (status !== 404) {
var errorDetails = this._GetResponseFaultstring(responseText);
this._ShowActivateErrorDialog(prefix + errorDetails);
}
}.bind(this);
};
this._ShowActivateErrorDialog = function(errorDetails) {
var params = this.arasObject.newObject();
params.aras = this.arasObject;
params.errorDetails = errorDetails;
params.title = this.arasObject.getResource('', 'licensing.activation_error_tilte');
params.dialogWidth = 365;
params.dialogHeight = 160;
params.content = 'Licensing/ActivateError.html';
var mainWindow = this.arasObject.getMainWindow();
mainWindow.ArasModules.Dialog.show('iframe', params);
return false;
};
}
Licensing.prototype.GetLicenseAgreement = function LicensingGetLicenseAgreement(activationKey) {
var requestBody = this._prepareLicenseRequestBody('activationKey', activationKey);
var query = false;
var statusId = '';
try {
statusId = this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage);
var method = 'GetLicenseAgreement';
var methodNm = this.actionNamespace;
var self = this;
var requestResponse;
ArasModules.soap(requestBody, {
url: this.url,
async: false,
method: method,
methodNm: methodNm,
SOAPAction: methodNm + this.iServiceName + '/' + method,
headers: {}
})
.then(function(responseText) {
requestResponse = responseText;
}, function(req) {
self._GenerateActivateErrorCallback(null, activationKey)(req.statusText, req.responseText, req.status);
});
query = this._checkErrors(this.arasObject, requestResponse);
} finally {
this.arasObject.clearStatusMessage(statusId);
}
return query;
};
Licensing.prototype.Activate = function LicensingActivate(activationKey, additionalData, additionalOptions) {
if (!this._validateActivationKey(activationKey)) {
return false;
}
var requestBody = this._prepareLicenseRequestBody('activationKey', activationKey, additionalData);
var statusId = '';
try {
statusId = additionalOptions ? additionalOptions.statusId : this.arasObject.showStatusMessage('status',
this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage);
var method = 'Activate';
var methodNm = this.actionNamespace;
var self = this;
var requestResponse;
ArasModules.soap(requestBody, {
url: this.url,
async: false,
method: method,
methodNm: methodNm,
SOAPAction: methodNm + this.iServiceName + '/' + method,
headers: {}
})
.then(function(responseText) {
requestResponse = responseText;
}, function(req) {
self._GenerateActivateErrorCallback(null, activationKey)(req.statusText, req.responseText, req.status);
});
if (!requestResponse) {
return false;
}
var query = this._checkErrors(this.arasObject, requestResponse);
if (!query) {
this._showErrorPage(additionalOptions ? additionalOptions.win : null);
return false;
}
if (additionalOptions) {
additionalOptions.featureAction = 'activate';
}
return this.ImportFeatureLicense(query.getResult(), additionalOptions);
} finally {
this.arasObject.clearStatusMessage(statusId);
}
};
Licensing.prototype.Update = function LicensingUpdate(featureLicenseId, additionalData, additionalOptions) {
var featureLicenseSecureId = this._getFeatureLicenseSecureId(featureLicenseId);
var requestBody = this._prepareLicenseRequestBody('featureLicenseSecureId', featureLicenseSecureId, additionalData);
var statusId = '';
try {
statusId = additionalOptions ? additionalOptions.statusId : this.arasObject.showStatusMessage('status',
this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage);
var method = 'Update';
var methodNm = this.actionNamespace;
var requestResponse;
ArasModules.soap(requestBody, {
url: this.url,
async: false,
method: method,
methodNm: methodNm,
SOAPAction: methodNm + this.iServiceName + '/' + method,
headers: {}
})
.then(function(responseText) {
requestResponse = responseText;
});
var query = this._checkErrors(this.arasObject, requestResponse);
if (!query) {
this._showErrorPage(additionalOptions ? additionalOptions.win : null);
return false;
}
if (additionalOptions) {
additionalOptions.win.close();
}
var mainWindow = this.arasObject.getMainWindow();
var self = this;
mainWindow.ArasModules.Dialog.show('iframe', {
aras: this.arasObject,
featureAction: 'update',
title: arasObject.getResource('', 'licensing.success_update_title'),
dialogWidth: 350,
dialogHeight: 120,
center: true,
content: 'Licensing/SuccessMessage.html'
});
return true;
} finally {
this.arasObject.clearStatusMessage(statusId);
}
};
Licensing.prototype.Deactivate = function LicensingDeactivate(featureLicenseId, additionalData, additionalOptions) {
var featureLicenseSecureId = this._getFeatureLicenseSecureId(featureLicenseId);
var requestBody = this._prepareLicenseRequestBody('featureLicenseSecureId', featureLicenseSecureId, additionalData);
var statusId = '';
try {
statusId = additionalOptions ? additionalOptions.statusId : this.arasObject.showStatusMessage('status',
this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage);
var method = 'Deactivate';
var methodNm = this.actionNamespace;
var requestResponse;
ArasModules.soap(requestBody, {
url: this.url,
async: false,
method: method,
methodNm: methodNm,
SOAPAction: methodNm + this.iServiceName + '/' + method,
headers: {}
})
.then(function(responseText) {
requestResponse = responseText;
});
var query = this._checkErrors(this.arasObject, requestResponse);
if (!query) {
this._showErrorPage(additionalOptions ? additionalOptions.win : null);
return false;
}
this.arasObject.deleteItem('Feature License', featureLicenseId, true);
} finally {
this.arasObject.clearStatusMessage(statusId);
}
return true;
};
Licensing.prototype.showState = function LicensingShowState() {
if (this.state) {
this.arasObject.AlertSuccess(this.state, window);
this.state = null;
}
};
Licensing.prototype.UpdateFeatureTreeUI = function LicensingUpdateFeatureTreeUI() {
var statusId = '';
try {
statusId = this.arasObject.showStatusMessage('status', this.arasObject.getResource('', 'licensing.request_aras'), this.propgressBarImage);
if (!this.UpdateFeatureTree()) {
this._showErrorPage();
return false;
}
} finally {
this.showState();
this.arasObject.clearStatusMessage(statusId);
}
return true;
};
Licensing.prototype.UpdateFeatureTree = function LicensingUpdateFeatureTree(callback) {
var self = this;
var getResponse = function(responseText) {
var arasObject = self.arasObject;
if (!responseText) {
self.error = {
customError: true,
subjectHide: true,
details: arasObject.getResource('', 'licensing.update_feature_tree_service_not_available'),
title: arasObject.getResource('', 'licensing.update_feature_tree_service_not_available_title')
};
if (callback) {
callback();
}
return false;
} else if (!self._getNonFailedDoc(arasObject, responseText)) {
self.state = arasObject.getResource('', 'licensing.feature_tree_failed_updated_featureTree');
if (callback) {
callback();
}
return false;
}
var doc = arasObject.createXMLDocument();
doc.loadXML(responseText);
var featureTreeText = doc.documentElement ? doc.documentElement.text : '';
var bResult = self._callMethodOnLicensingService('UpdateFeatureTree', 'encryptedFeatureTree', featureTreeText);
bResult = !!bResult;
self.state = bResult ? arasObject.getResource('', 'licensing.feature_tree_successfully_updated') :
arasObject.getResource('', 'licensing.feature_tree_failed_updated_featureTree');
if (callback) {
callback(bResult);
}
return bResult;
};
var data = '' + this._getFrameworkLicenseKey() + ' ';
var method = 'GetFeatureTree';
var methodNm = this.actionNamespace;
var getFeatureTreeResult;
ArasModules.soap(data, {
async: !!callback,
url: this.url,
method: method,
methodNm: methodNm,
SOAPAction: methodNm + this.iServiceName + '/' + method,
headers: {}
})
.then(function(result) {
if (callback) {
getResponse(result);
} else {
getFeatureTreeResult = result;
}
}, function() {
self.state = self.arasObject.getResource('', 'licensing.feature_tree_failed_updated_featureTree');
if (callback) {
callback();
}
});
if (!callback) {
return getResponse(getFeatureTreeResult);
}
};
Licensing.prototype.ShowLicenseManagerDialog = function LicensingShowLicenseManagerDialog() {
var params = {
aras: this.arasObject,
title: this.arasObject.getResource('', 'licmanager.title'),
dialogWidth: 1000,
dialogHeight: 420,
resizable: true,
center: true,
content: 'Licensing/LicManager.html'
};
var mainWindow = this.arasObject.getMainWindow();
mainWindow.ArasModules.Dialog.show('iframe', params);
};
Licensing.prototype.ActivateFeature = function LicensingActivateFeature(activationKey) {
return this._showActivateFeatureDialog(activationKey);
};
Licensing.prototype.DeactivateFeature = function LicensingDeactivateFeature(activationKey, featureLicenseId) {
return this._showActivateFeatureDialog(activationKey, Licensing.ActionType.Deactivate, featureLicenseId);
};
Licensing.prototype.ImportFeatureLicense = function LicensingImportFeatureLicense(featureLicenseText, additionalOptions) {
var importFeature = function(featureLicenseText) {
var bResult = this._callMethodOnLicensingService('ImportFeatureLicense', 'encryptedFeatureLicense', featureLicenseText);
if (bResult) {
if (additionalOptions) {
additionalOptions.win.close();
}
var featureLicense = this._getFeatureLicenseByLicenseData(featureLicenseText);
if (featureLicense.isError()) {
this.arasObject.AlertError(featureLicense, this.wnd);
return false;
}
var self = this;
var params = {
aras: this.arasObject,
result: featureLicense,
featureAction: additionalOptions ? additionalOptions.featureAction : '',
dialogWidth: 350,
dialogHeight: 190,
center: true,
content: 'Licensing/SuccessMessage.html'
};
params.title = this.arasObject.getResource('', (params.featureAction === 'update') ? 'licensing.success_update_title' : 'licensing.success_import_title');
var mainWindow = this.arasObject.getMainWindow();
window.setTimeout(function() {
mainWindow.ArasModules.Dialog.show('iframe', params).promise.then();
}.bind(this), 0);
}
};
if (!featureLicenseText) {
var mainWindow = this.arasObject.getMainWindow();
mainWindow.ArasModules.Dialog.show('iframe', {
aras: this.arasObject,
title: this.arasObject.getResource('', 'licensing.import_feature_license'),
dialogWidth: 350,
dialogHeight: 140,
center: true,
content: 'Licensing/ImportLicense.html'
}).promise.then(
function(res) {
if (res) {
importFeature.bind(this)(res);
}
}.bind(this)
);
} else {
importFeature.call(this, featureLicenseText);
}
};
Licensing.prototype.PerformActionOverFeature = function LicensingPerformActionOverFeature(action, activationKey, featureLicenseId) {
if (!this._validateActivationKey(activationKey)) {
return false;
}
this._getMetaInfoFromArasService(action, activationKey, featureLicenseId);
};
Licensing.prototype.ViewFeatureTree = function LicensingViewFeatureTree() {
var featureTreeXml = this._getFeatureTreeFromInnovatorServer();
if (!featureTreeXml) {
return;
}
var doc = this.arasObject.createXMLDocument();
doc.loadXML(featureTreeXml);
var xmlDocument = this.arasObject.createXMLDocument();
xmlDocument.validateOnParse = true;
xmlDocument.loadXML(doc.childNodes[doc.childNodes.length - 1].text);
var xslt = this.arasObject.createXMLDocument();
xslt.load(this.arasObject.getScriptsURL() + 'Licensing/FeatureTree.xsl');
featureTreeXml = xmlDocument.transformNode(xslt);
var params = {
aras: this.arasObject,
featureTreeXml: featureTreeXml,
title: 'Aras Feature Tree',
dialogHeight: 620,
dialogWidth: 500,
resizable: true,
center: true,
scroll: true,
content: 'Licensing/FeatureTree.html'
};
var mainWindow = this.arasObject.getMainWindow();
mainWindow.ArasModules.Dialog.show('iframe', params);
};
/** ..\BrowserCode\common\javascript\FileSystemAccess.js **/
var fileSystemAccess = {
init: function(parentAras) {
this.fileList = {};
this.clientData = {};
this.lastError = '';
if (parentAras.vault) {
this.associatedFileList = parentAras.vault.vault.associatedFileList;
this.fileToMd5 = parentAras.vault.vault.fileToMd5;
} else {
this.associatedFileList = {};
this.fileToMd5 = {};
}
},
getFileChecksum: function(file) {
if (typeof file === 'string') {
var parts = file.split(/[\\\/]/);
var fileID = parts[0];
return fileSystemAccess.fileToMd5[this.associatedFileList[fileID] || this.fileList[fileID]];
} else {
return fileSystemAccess.fileToMd5[file.size + '.' + file.name + '.' + file.lastModified] || '';
}
},
getFileSize: function(file) {
if (typeof file === 'string') {
var parts = file.split(/[\\\/]/);
var fileID = parts[0];
return this.associatedFileList[fileID].size;
} else {
return file.size;
}
},
sendFiles: function(strUrl) {
var fileId;
var i;
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', strUrl, false);
var form = new FormData();
var keys = Object.keys(this.clientData);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
form.append(key, this.clientData[key]);
}
var fileIds = Object.keys(this.fileList);
for (i = 0; i < fileIds.length; i++) {
fileId = fileIds[i];
form.append(fileId, this.fileList[fileId]);
}
httpRequest.send(form);
if (httpRequest.status !== 200) {
Object.assign(this.associatedFileList, this.fileList);
this.lastError = 'Cannot upload file. Exception name: "WebException"; Exception message: "The remote server returned an error: ' +
httpRequest.status + '"';
return false;
}
var xml = httpRequest.responseXML;
if (xml && xml.firstChild && xml.firstChild.firstChild) {
var result = xml.firstChild.firstChild.firstChild;
var isFault = (result && result.nodeName.toLowerCase() === 'soap-env:fault');
if (isFault) {
Object.assign(this.associatedFileList, this.fileList);
}
}
this.response = httpRequest.responseText;
return true;
},
sendFilesAsync: function(serverUrl) {
var clientData = this.clientData;
var res = [];
var keys = Object.keys(aras.vault.vault.fileList);
for (var i = 0; i < keys.length; i++) {
res.push(aras.vault.vault.fileList[keys[i]]);
}
keys = Object.keys(clientData);
var credentials = {};
for (i = 0; i < keys.length; i++) {
var key = keys[i];
if (key != 'XMLdata' && key != 'SOAPACTION') {
credentials[key] = clientData[key];
}
}
var vaultModule;
var mainWnd;
if (window.itemTypeName === 'File' && !window.frameElement) {
mainWnd = aras.getMainWindow();
vaultModule = mainWnd.ArasModules.vault;
} else {
vaultModule = ArasModules.vault;
}
vaultModule.options.serverUrl = serverUrl;
vaultModule.options.credentials = credentials;
var finallyCallback = function(res) {
this.response = res.xml || res.parentNode.xml;
return true;
}.bind(this);
return vaultModule.send(res, clientData.XMLdata).then(finallyCallback, finallyCallback);
},
clearClientData: function() {
this.clientData = {};
},
addFileToList: function(fileID, filepath) {
if (!filepath) {
this.lastError = 'Filename is empty';
return false;
}
if (this.associatedFileList[fileID]) {
this.fileList[fileID] = this.associatedFileList[fileID];
} else if (typeof filepath !== 'string') {
if (aras.Browser.isIe()) {
filepath.Xhr = XMLHttpRequest;
}
this.fileList[fileID] = filepath;
this.associatedFileList[fileID] = filepath;
}
return true;
},
removeFileFromList: function(fileId) {
if (this.associatedFileList[fileId]) {
delete this.associatedFileList[fileId];
}
if (this.fileList[fileId]) {
delete this.fileList[fileId];
}
},
selectFile: function() {
return ArasModules.vault.selectFile().then(function(file) {
//aras.browserHelper.toggleSpinner(document, true, 'dimmer_spinner_whole_window');
return file;
}).then(this.calculateMd5).then(function(file) {
//aras.browserHelper.toggleSpinner(document, false, 'dimmer_spinner_whole_window');
return file;
});
},
clearFileList: function() {
this.fileList = {};
},
setClientData: function(name, valueRenamed) {
this.clientData[name] = valueRenamed;
},
getClientData: function(name) {
return this.clientData[name];
},
getResponse: function() {
return this.response || '';
},
setLocalFileName: function(filename) {
this.localFileName = filename;
},
downloadFile: function(strUrl) {
var fileId = /fileID=([^&]+)/ig.exec(strUrl);
if (!fileId) {
return false;
}
fileId = fileId[1];
strUrl = aras.IomInnovator.getFileUrl(fileId, aras.Enums.UrlType.SecurityToken);
if (this.localFileName) {
strUrl = strUrl.replace(/fileName=.*?(?=&|$)/, 'fileName=' + this.localFileName);
}
strUrl += '&contentDispositionAttachment=1';
window.ArasModules.vault.downloadFile(strUrl)
.catch(function(err) {
var win = aras.getMostTopWindowWithAras(window);
win.aras.AlertError('Server status: ' + err.status + '. ' + err.message);
});
return true;
},
calculateMd5: function(file) {
var md5Promise = new Promise(function(resolve, reject) {
require(['../browsercode/common/javascript/spark-md5.js'], function(SparkMD5) {
var fileReader = new FileReader();
var frOnload = function(e) {
spark.append(e.target.result);
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
var md5 = spark.end();
fileSystemAccess.fileToMd5[file.size + '.' + file.name + '.' + file.lastModified] = md5;
resolve(file);
}
};
var chunkSize = 2097152; // read in chunks of 2MB
var chunks = Math.ceil(file.size / chunkSize);
var currentChunk = 0;
var spark = new SparkMD5.ArrayBuffer();
function loadNext() {
fileReader.onload = frOnload;
fileReader.onerror = reject;
var start = currentChunk * chunkSize;
var end = Math.min(file.size,start + chunkSize);
fileReader.readAsArrayBuffer(file.slice(start, end));
}
loadNext();
});
});
return md5Promise;
},
getLastError: function() {
return this.lastError;
},
readText: function(file, encoding) {
var fileReader = new FileReader();
return new Promise(function(resolve, reject) {
fileReader.onload = function() {
resolve(this.result);
};
fileReader.onerror = reject;
fileReader.readAsText(file, encoding);
});
},
readBase64: function(file, start, count) {
return new Promise(function(resolve, reject) {
var fileReader = new FileReader();
fileReader.onload = function() {
resolve(this.result);
};
fileReader.onerror = reject;
fileReader.readAsDataURL(file.slice(start, start + count));
});
}
};
/** ..\BrowserCode\common\javascript\BrowserHelper.js **/
function BrowserHelper(aras, aWindow) {
'use strict';
this.window = aWindow;
this.aras = aras;
}
BrowserHelper.prototype.initComponents = function() {
var winInetCredentialsCol = {AddFromWinInet: function() { }};
var timeZoneInfo = null;
Object.defineProperty(this, 'winInetCredentialsCollection', {
get: function() {
return winInetCredentialsCol;
}
});
Object.defineProperty(this, 'tzInfo', {
get: function() {
if (!timeZoneInfo) {
timeZoneInfo = new this.window.TimeZonesInformation();
}
return timeZoneInfo;
}
});
};
BrowserHelper.prototype.adjustHeightTexAreaWithNullableRows = function(textArea) {
return this.aras.Browser.isIe() ?
textArea.offsetHeight :
((textArea.offsetHeight - 2) / 3 + 2); // There is 3 lines in case of rows == 0
};
BrowserHelper.prototype.getNodeTranslationElement = function(srcNode, nodeName, translationXMLNsURI, lang) {
if (this.aras.Browser.isIe()) {
return srcNode.selectSingleNode('*[local-name()=\'' + nodeName + '\' and namespace-uri()=\'' + translationXMLNsURI + '\' and @xml:lang=\'' + lang + '\']');
}
var nds = srcNode.getElementsByTagNameNS(translationXMLNsURI, nodeName);
var i;
var resNd;
for (i = 0; i < nds.length; i++) {
if (nds[i].parentNode == srcNode && nds[i].getAttribute('xml:lang') === lang) {
resNd = nds[i];
break;
}
}
return resNd;
};
BrowserHelper.prototype.createTranslationNode = function(srcNode, nodeName, translationXMLNsURI, translationXMLNdPrefix) {
if (srcNode.ownerDocument.createElementNS) {
return srcNode.ownerDocument.createElementNS(translationXMLNsURI, translationXMLNdPrefix + ':' + nodeName);
}
var resNd = srcNode.ownerDocument.createNode(1, translationXMLNdPrefix + ':' + nodeName, translationXMLNsURI);
resNd.setAttribute('xmlns:' + translationXMLNdPrefix, translationXMLNsURI);
return resNd;
};
BrowserHelper.prototype.getTextContentPropertyName = function() {
return 'textContent';
};
BrowserHelper.prototype.getHeightDiffBetweenTearOffAndMainWindow = function() {
//Height of Title Bar in Main window is less than in Tear-Off window
return this.aras.Browser.isIe() ? 0 : 8;
};
BrowserHelper.prototype.isWindowClosed = function(window) {
var res = false;
try {
res = window.closed;
}
catch (e) {
//"Permission denied."
// "-2146823281" - "Object expected" - this error sometimes generates by MS edge, when window is closed and reference is corrupted
if (e.number != -2146828218 && e.number != -2146823281) {
throw e;
} else {
res = true;
}
}
return res;
};
BrowserHelper.prototype.getUserPasswordViaWinAuth = function ()
{
if (document.queryCommandSupported('ClearAuthenticationCache')) {
document.execCommand('ClearAuthenticationCache', 'false');
}
var urlIOMLogin = this.aras.getScriptsURL() + 'IOMLogin.aspx?redirect_me_to401=1';
var doc = this.aras.createXMLDocument();
var xmlhttp = this.aras.XmlHttpRequestManager.CreateRequest();
xmlhttp.open('GET', urlIOMLogin, false);
try {
xmlhttp.send();
}
catch (e)
{
//create URL like 'http://123123blablablasalt@namedomain.com/...'
//for reset Google Chrome credentials when entered login like 'DOMAIN\username'
var urlReset = this.aras.getScriptsURL();
urlReset = urlReset.replace(location.host, Date.now() + 'cache@' + location.host);
urlReset = urlReset.replace(/X-cache[a-z0-9_\-\.=]{1,40}\//i, '');
urlReset += 'IOMLogin.aspx';
var xmlhttpReset = this.aras.XmlHttpRequestManager.CreateRequest();
xmlhttp.open('GET', urlReset, false);
xmlhttp.send();
return;
}
var txt = xmlhttp.responseText;
//if not xml
if (!txt || txt.indexOf('<') < 0) {
return;
}
doc.loadXML(txt);
if (!doc.xml) {
return;
}
//+++ the logic below is actually copied from GetMD5PasswordForInnovator function
var nd;
var pwd;
var rNode = doc.selectSingleNode('//Result');
if (!rNode) {
return;
}
nd = rNode.selectSingleNode('password');
if (!nd || !nd.text) {
return;
}
pwd = nd.text;
nd = rNode.selectSingleNode('hash');
if (nd.text.toUpperCase() != 'FALSE') {
if (this.aras.getVariable('fips_mode')) {
pwd = ArasModules.cryptohash.SHA256(pwd);
} else {
pwd = this.aras.calcMD5(pwd);
}
}
return pwd;
};
/***
* Move window to specified coordinates
* @param aWindow target window to move
* @param x
* @param y
*/
BrowserHelper.prototype.moveWindowTo = function(aWindow, x, y) {
if (!this.aras.Browser.isEdge()) {
aWindow.moveTo(x, y);
}
};
/***
* Resize window to specified measurements
* @param aWindow window to resize
* @param width
* @param height
*/
BrowserHelper.prototype.resizeWindowTo = function(aWindow, width, height) {
if (this.aras.Browser.isIe() && aWindow.dialogArguments) {
//some dialog shown with a call to showModalDialog or showModelessDialog method
//window.resizeTo still doesn't work for dialogs in IE. Tested in IE 9 - IE 11.
var frameWidth = aWindow.outerWidth - aWindow.innerWidth;
var frameHeight = aWindow.outerHeight - aWindow.innerHeight;
//according to MSDN dialogHeight property returns the height of the content area and doesn't include the height of the frame.
//http://msdn.microsoft.com/en-us/library/ie/ms533724%28v=vs.85%29.aspx
aWindow.dialogHeight = (height - frameHeight) + 'px';
aWindow.dialogWidth = (width - frameWidth) + 'px';
} else if (!this.aras.Browser.isEdge()) {
//regular window
aWindow.resizeTo(width, height);
}
};
/***
* Set focus to specified window
* @param aWindow Window to focus
*/
BrowserHelper.prototype.setFocus = function(aWindow) {
// window.focus is not working in chrome for parent window.
// We need use window.open with empty url as 1-st argument and name of exits window as 2-nd argument.
if (aras.Browser.isCh() && aWindow.opener && !aWindow.frameElement) {
aWindow.opener.open('', aWindow.name);
}
//setTimeout to fix window.focus in Mozilla Firefox
setTimeout(function() { aWindow.focus(); }, 0);
};
/***
* Close specified window
* @param aWindow window to close
*/
BrowserHelper.prototype.closeWindow = function(topWindow) {
if (this.aras.Browser.isIe()) {
// the "open" method is workaround for IE
// proof: https://jeffclayton.wordpress.com/2015/02/13/javascript-window-close-method-that-still-works/
topWindow.open('blank.html', '_top');
}
topWindow.close();
};
BrowserHelper.prototype.lockNewWindowOpen = function(aras, lockFlag) {
if (this.aras.Browser.isIe()) {
aras.commonProperties.lockNewWindowOpen = lockFlag;
}
};
BrowserHelper.prototype.newWindowCanBeOpened = function(aras) {
return !aras.commonProperties.lockNewWindowOpen;
};
BrowserHelper.prototype.fixSizeOnModalDialogResize = function(modalDialogWin, idsToResizeWidth, idsToResizeHeight, fixBody, cb) {
if (this.aras.Browser.isIe()) {
modalDialogWin.addEventListener('resize', function() {
var i;
var doc = modalDialogWin.document;
var w = doc.documentElement.clientWidth;
var h = doc.documentElement.clientHeight;
var oldw = modalDialogWin['BrowserHelper_oldClientWidth'];
var oldh = modalDialogWin['BrowserHelper_oldClientHeight'];
if (w != oldw) {
if (idsToResizeWidth) {
idsToResizeWidth = typeof idsToResizeWidth === 'string' ? [idsToResizeWidth] : idsToResizeWidth;
for (i = 0; i < idsToResizeWidth.length; i++) {
doc.getElementById(idsToResizeWidth[i]).style.width = w + 'px';
}
}
if (fixBody) {
doc.body.width = w + 'px';
}
modalDialogWin['BrowserHelper_oldClientWidth'] = w;
}
if (idsToResizeHeight && h != oldh) {
if (idsToResizeHeight) {
idsToResizeHeight = typeof idsToResizeHeight === 'string' ? [idsToResizeHeight] : idsToResizeHeight;
for (i = 0; i < idsToResizeHeight.length; i++) {
doc.getElementById(idsToResizeHeight[i]).style.height = h + 'px';
}
}
if (fixBody) {
doc.body.height = h + 'px';
}
modalDialogWin['BrowserHelper_oldClientHeight'] = h;
}
if (cb) {
cb({'old': {w: oldw, h: oldh}, 'new': {w: w, h: h}});
}
});
}
};
BrowserHelper.prototype.adjustGridSize = function(aWindow, handler, asFunc) {
if (this.aras.Browser.isIe()) {
if (asFunc) {
aWindow.onresize = handler;
} else {
aWindow.addEventListener('resize', handler, false);
}
handler();
}
};
/**
* Turning on/off class in "spinner" element (classList is required)
*
* @param {HTMLElement|Document} context - current container object
* @param {string} state - turn on/off spinner
* @param {string} [spinnerId] - id attribute of spinner element
* @return {boolean} spinner found or no
*/
BrowserHelper.prototype.toggleSpinner = function(context, state, spinnerId) {
spinnerId = spinnerId || 'dimmer_spinner';
var spinnerEl = (context.ownerDocument || context).getElementById(spinnerId);
if (!spinnerEl) {
return false;
}
spinnerEl.classList.toggle('disabled-spinner', !state);
return true;
};
// +++++++ Methods for generating XSLT stylesheets for Grids
BrowserHelper.prototype.addXSLTCssFunctions = function(container) {
container.push('\n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push('\n');
container.push(' \n');
container.push(' \n');
container.push(' ; \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' ; \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
};
BrowserHelper.prototype.addXSLTSpecialNamespaces = function(container) {};
BrowserHelper.prototype.addXSLTInitItemCSSCall = function(container, cssValue, fedCssValue) {
container.push('\n');
container.push(' \n');
container.push(' \n');
container.push(' \n');
};
BrowserHelper.prototype.addXSLTGetPropertyStyleExCall = function(container, nameCSS, cellCSSVariableName1, name) {
container.push('\n');
container.push(' \n');
container.push(' \n');
container.push(' ' + name + ' \n');
container.push(' \n');
container.push(' \n');
};
// ------- Methods for generating XSLT stylesheets for Grids
BrowserHelper.prototype.escapeUrl = function(url) {
//after xslt transformation of the data for grid in FF need to escape the url on the pictures src
if (this.aras.Browser.isFf()) {
return url.replace(/&/g, '&');
} else {
return url;
}
};
//IE does not properly set the focus in input fields in the new iframes
//We programmatically set the focus on the input field, and then remove the focus
//then IE will be able to operate normally with all input fields.
BrowserHelper.prototype.restoreFocusForIE = function(window) {
if (this.aras.Browser.isIe()) {
var document = window.document;
var inputTMP = document.createElement('INPUT');
inputTMP.setAttribute('type', 'text');
inputTMP.style.position = 'absolute';
inputTMP.style.top = '-1000px';
document.body.appendChild(inputTMP);
inputTMP.focus();
document.body.focus();
document.body.removeChild(inputTMP);
}
};
/** TimeZonesInformation.js **/
function TimeZonesInformation() {
}
/***
* @param date Date with respect to which is calculated offset
* @param winTzName Name of windows time zone
* @returns {*} Time zone offset using olson time zone database
*/
TimeZonesInformation.prototype.getTimeZoneOffset = function TimeZonesInformationGetTimeZoneOffset(date, winTzName) {
var xmlHttp = new XmlHttpRequestManager().CreateRequest();
xmlHttp.open('GET', aras.getBaseURL() + '/TimeZone/GetOlsonTimeZoneName?windowsTimeZoneName=' + winTzName, false);
xmlHttp.send();
if (xmlHttp.status == 404) {
aras.AlertError('Could not found timeZone: ' + winTzName);
return;
}
// Get olson time zone name by windows time zone name
var olsonTzName = xmlHttp.responseText;
dojo.require('Aras.Client.Controls.Experimental.TimeZoneInfo');
var tzInfo = Aras.Client.Controls.Experimental.TimeZoneInfo.getTzInfo(date, olsonTzName);
return tzInfo.tzOffset;
};
/***
* @returns {*} Timezone name in windows format
*/
TimeZonesInformation.prototype.getTimeZoneLabel = function() {
var getZoneNameFromDateString = function(str) {
if (!str || (str && (str.indexOf('(') === -1 || str.indexOf(')') === -1))) {
return;
}
var regexp1 = /.*?\((.*).*/;
str = regexp1.exec(str)[1];
if (!str) {
return;
}
var regexp2 = /(.*)\)/;
str = regexp2.exec(str)[1];
if (str) {
return str;
}
};
var timeZoneName;
if ((aras.Browser.isIe() || aras.Browser.isFf()) && aras.Browser.OSName === 'Windows') {
var dateString = (new Date()).toString();
timeZoneName = getZoneNameFromDateString(dateString);
}
if (!timeZoneName) {
timeZoneName = jstz.determine().name();
}
return timeZoneName || '';
};
/***
* @returns {*} Timezone name in windows format
*/
TimeZonesInformation.prototype.getWindowsTimeZoneName = function TimeZonesInformation_getWindowsTimeZoneName() {
dojo.require("Aras.Client.Controls.Experimental.TimeZoneInfo");
var timeZoneName = aras.utils.systemInfo.currentTimeZoneName;
if (timeZoneName.indexOf("/") > 0) { // Olson timezone has {country}/{city} format
var xmlHttp = new XmlHttpRequestManager().CreateRequest();
xmlHttp.open("GET", aras.getBaseURL() + "/TimeZone/GetWindowTimeZoneName?olsonTimeZoneName=" + timeZoneName, false);
xmlHttp.send();
if (xmlHttp.status == 404) {
aras.AlertError("Could not found timeZone: " + timeZoneName);
return;
}
return xmlHttp.responseText;
}
return timeZoneName;
};
TimeZonesInformation.prototype.getWindowsTimeZoneNames = function(tzLabel) {
var inputType = tzLabel.indexOf('/') > 0 ? 'iana' : 'windows';
var localTime = (new Date()).toISOString();
var localTimeOffset = (-1 * (new Date()).getTimezoneOffset()).toString();
var url = aras.getBaseURL() + '/TimeZone/GetTimezoneNames?tzlabel=' +
encodeURIComponent(tzLabel) + '&inputType=' + encodeURIComponent(inputType) +
'&localTime=' + encodeURIComponent(localTime) +
'&offsetBetweenLocalTimeAndUTCTime=' + encodeURIComponent(localTimeOffset);
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', url, false);
xmlHttp.send();
if (xmlHttp.status !== 200) {
aras.AlertError('Could not found timeZone: ' + tzLabel);
return [];
}
return JSON.parse(xmlHttp.responseText).map(function(tz) {return tz.id;});
};
TimeZonesInformation.prototype.setTimeZoneNameInLocalStorage = function(tzLabel, tzName) {
var tzOffset = -1 * (new Date()).getTimezoneOffset();
var timeZones = {};
timeZones[tzOffset + tzLabel] = tzName;
localStorage.setItem('timeZone', JSON.stringify(timeZones));
};
TimeZonesInformation.prototype.getTimeZoneNameFromLocalStorage = function(tzLabel) {
var tzOffset = -1 * (new Date()).getTimezoneOffset();
var timeZones = JSON.parse(localStorage.getItem('timeZone'));
if (timeZones && timeZones.hasOwnProperty(tzOffset + tzLabel)) {
return timeZones[tzOffset + tzLabel];
}
};
/** md5.js **/
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ''; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hexMd5(s) { return binl2hex(coreMd5(str2binl(s), s.length * chrsz)); }
function b64Md5(s) { return binl2b64(coreMd5(str2binl(s), s.length * chrsz)); }
function strMd5(s) { return binl2str(coreMd5(str2binl(s), s.length * chrsz)); }
function hexHmacMd5(key, data) { return binl2hex(coreHmacMd5(key, data)); }
function b64HmacMd5(key, data) { return binl2b64(coreHmacMd5(key, data)); }
function strHmacMd5(key, data) { return binl2str(coreHmacMd5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5VmTest() {
return hexMd5('abc') == '900150983cd24fb0d6963f7d28e17f72';
}
/*
* Call hexMd5, adding new param (compatibility with older version)
*/
function calcMD5(str) {
if (!str) {
return '';
}
return hexMd5(str);
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function coreMd5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5ff(a, b, c, d, x[i + 0], 7, -680876936);
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5gg(b, c, d, a, x[i + 0], 20, -373897302);
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5hh(d, a, b, c, x[i + 0], 11, -358537222);
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5ii(a, b, c, d, x[i + 0], 6, -198630844);
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safeAdd(a, olda);
b = safeAdd(b, oldb);
c = safeAdd(c, oldc);
d = safeAdd(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRol(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
function md5ff(a, b, c, d, x, s, t) {
return md5cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5gg(a, b, c, d, x, s, t) {
return md5cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function coreHmacMd5(key, data) {
var bkey = str2binl(key);
if (bkey.length > 16) {
bkey = coreMd5(bkey, key.length * chrsz);
}
var ipad = Array(16);
var opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = coreMd5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return coreMd5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safeAdd(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bitRol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for (var i = 0; i < str.length * chrsz; i += chrsz) {
bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
}
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin) {
var str = '';
var mask = (1 << chrsz) - 1;
for (var i = 0; i < bin.length * 32; i += chrsz) {
str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);
}
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray) {
var hexTab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef';
var str = '';
for (var i = 0; i < binarray.length * 4; i++) {
str += hexTab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
hexTab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray) {
var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var str = '';
for (var i = 0; i < binarray.length * 4; i += 3) {
var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) |
(((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) |
((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
for (var j = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) {
str += b64pad;
} else {
str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
}
}
}
return str;
}
/** cookie.js **/
//
// Cookie Functions -- "Night of the Living Cookie" Version (25-Jul-96)
//
// Written by: Bill Dortch, hIdaho Design
// The following functions are released to the public domain.
//
// This version takes a more aggressive approach to deleting
// cookies. Previous versions set the expiration date to one
// millisecond prior to the current time; however, this method
// did not work in Netscape 2.02 (though it does in earlier and
// later versions), resulting in "zombie" cookies that would not
// die. DeleteCookie now sets the expiration date to the earliest
// usable date (one second into 1970), and sets the cookie's value
// to null for good measure.
//
// Also, this version adds optional path and domain parameters to
// the DeleteCookie function. If you specify a path and/or domain
// when creating (setting) a cookie**, you must specify the same
// path/domain when deleting it, or deletion will not occur.
//
// The FixCookieDate function must now be called explicitly to
// correct for the 2.x Mac date bug. This function should be
// called *once* after a Date object is created and before it
// is passed (as an expiration date) to SetCookie. Because the
// Mac date bug affects all dates, not just those passed to
// SetCookie, you might want to make it a habit to call
// FixCookieDate any time you create a new Date object:
//
// var theDate = new Date();
// FixCookieDate (theDate);
//
// Calling FixCookieDate has no effect on platforms other than
// the Mac, so there is no need to determine the user's platform
// prior to calling it.
//
// This version also incorporates several minor coding improvements.
//
// **Note that it is possible to set multiple cookies with the same
// name but different (nested) paths. For example:
//
// SetCookie ("color","red",null,"/outer");
// SetCookie ("color","blue",null,"/outer/inner");
//
// However, GetCookie cannot distinguish between these and will return
// the first cookie that matches a given name. It is therefore
// recommended that you *not* use the same name for cookies with
// different paths. (Bear in mind that there is *always* a path
// associated with a cookie; if you don't explicitly specify one,
// the path of the setting document is used.)
//
// Revision History:
//
// "Toss Your Cookies" Version (22-Mar-96)
// - Added FixCookieDate() function to correct for Mac date bug
//
// "Second Helping" Version (21-Jan-96)
// - Added path, domain and secure parameters to SetCookie
// - Replaced home-rolled encode/decode functions with Netscape's
// new (then) escape and unescape functions
//
// "Free Cookies" Version (December 95)
//
//
// For information on the significance of cookie parameters, and
// and on cookies in general, please refer to the official cookie
// spec, at:
//
// http://www.netscape.com/newsref/std/cookie_spec.html
//
//******************************************************************
//
// "Internal" function to return the decoded value of a cookie
//
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(';', offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
//
// Function to correct for 2.x Mac date bug. Call this function to
// fix a date object prior to passing it to SetCookie.
// IMPORTANT: This function should only be called *once* for
// any given date object! See example at the end of this document.
//
function FixCookieDate(date) {
var base = new Date(0);
var skew = base.getTime(); // dawn of (Unix) time - should be 0
if (skew > 0) { // Except on the Mac - ahead of its time
date.setTime(date.getTime() - skew);
}
}
//
// Function to return the value of the cookie specified by "name".
// name - String object containing the cookie name.
// returns - String object containing the cookie value, or null if
// the cookie does not exist.
//
function GetCookie(name) {
var arg = name + '=';
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = document.cookie.indexOf(' ', i) + 1;
if (i === 0) {
break;
}
}
return null;
}
//
// Function to create or update a cookie.
// name - String object containing the cookie name.
// value - String object containing the cookie value. May contain
// any valid string characters.
// [expires] - Date object containing the expiration data of the cookie. If
// omitted or null, expires the cookie at the end of the current session.
// [path] - String object indicating the path for which the cookie is valid.
// If omitted or null, uses the path of the calling document.
// [domain] - String object indicating the domain for which the cookie is
// valid. If omitted or null, uses the domain of the calling document.
// [secure] - Boolean (true/false) value indicating whether cookie transmission
// requires a secure channel (HTTPS).
//
// The first two parameters are required. The others, if supplied, must
// be passed in the order listed above. To omit an unused optional field,
// use null as a place holder. For example, to call SetCookie using name,
// value and path, you would code:
//
// SetCookie ("myCookieName", "myCookieValue", null, "/");
//
// Note that trailing omitted parameters do not require a placeholder.
//
// To set a secure cookie for path "/myPath", that expires after the
// current session, you might code:
//
// SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function SetCookie(name, value, expires, path, domain, secure) {
document.cookie = name + '=' + escape(value) +
((expires) ? '; expires=' + expires.toUTCString() : '') +
((path) ? '; path=' + path : '') +
((domain) ? '; domain=' + domain : '') +
((secure) ? '; secure' : '');
}
// Function to delete a cookie. (Sets expiration date to start of epoch)
// name - String object containing the cookie name
// path - String object containing the path of the cookie to delete. This MUST
// be the same as the path used to create the cookie, or null/omitted if
// no path was specified when creating the cookie.
// domain - String object containing the domain of the cookie to delete. This MUST
// be the same as the domain used to create the cookie, or null/omitted if
// no domain was specified when creating the cookie.
//
function DeleteCookie(name, path, domain) {
if (GetCookie(name)) {
document.cookie = name + '=' +
((path) ? '; path=' + path : '') +
((domain) ? '; domain=' + domain : '') +
'; expires=Thu, 01-Jan-70 00:00:01 GMT';
}
}
/** soap_object.js **/
// (c) Copyright by Aras Corporation, 2004-2009.
/*----------------------------------------
* FileName: soap_object.js
*
* Purpose:
* Provide a way to comminucate with InnovatorServer using SOAP messages
*
*/
///
/// For internal use only.
/// Stores a set of Soap related constants.
///
///
///
///
///
var SoapConstants = {};
///
/// URI to SOAP 1.1 schema
///
///
///
///
///
SoapConstants.SoapEnvUri = 'http://schemas.xmlsoap.org/soap/envelope/';
///
/// Namespace used to return SOAP messages.
///
///
///
///
///
SoapConstants.SoapNamespace = 'SOAP-ENV';
///
/// Opening tags Envelope, Body
///
///
///
///
///
SoapConstants.EnvelopeBodyStart = '<' + SoapConstants.SoapNamespace + ':Envelope xmlns:' + SoapConstants.SoapNamespace + '="' + SoapConstants.SoapEnvUri + '"><' + SoapConstants.SoapNamespace + ':Body>';
///
///
///
///
///
///
///
SoapConstants.EnvelopeBodyEnd = '' + SoapConstants.SoapNamespace + ':Body>' + SoapConstants.SoapNamespace + ':Envelope>';
///
/// Opening tags Envelope, Body, Fault
///
///
///
///
///
SoapConstants.EnvelopeBodyFaultStart = SoapConstants.EnvelopeBodyStart + '<' + SoapConstants.SoapNamespace + ':Fault>';
///
///
///
///
///
///
///
SoapConstants.EnvelopeBodyFaultEnd = '' + SoapConstants.SoapNamespace + ':Fault>' + SoapConstants.EnvelopeBodyEnd;
///
/// Check of namespace to be used in XPath
///
///
///
///
///
SoapConstants.SoapNamespaceCheck = 'namespace-uri()=\'' + SoapConstants.SoapEnvUri + '\' or namespace-uri()=\'\'';
///
/// XPath for Envelope
///
///
///
///
///
SoapConstants.EnvelopeXPath = '*[local-name()=\'Envelope\' and (' + SoapConstants.SoapNamespaceCheck + ')]';
///
/// XPath for Body
///
///
///
///
///
SoapConstants.BodyXPath = '*[local-name()=\'Body\' and (' + SoapConstants.SoapNamespaceCheck + ')]';
///
/// XPath for Fault
///
///
///
///
///
SoapConstants.FaultXPath = '*[local-name()=\'Fault\' and (' + SoapConstants.SoapNamespaceCheck + ')]';
///
/// XPath for Envelope/Body
///
///
///
///
///
SoapConstants.EnvelopeBodyXPath = SoapConstants.EnvelopeXPath + '/' + SoapConstants.BodyXPath;
///
/// XPath for Envelope/Body/Fault
///
///
///
///
///
SoapConstants.EnvelopeBodyFaultXPath = SoapConstants.EnvelopeBodyXPath + '/' + SoapConstants.FaultXPath;
/*
SoapController is designed to manage asynchronous soap requests.
Contains:
callback - function which is called when request is finished
The parameter is passed to constructor.
stop - readonly parameter. Function which can be used to abort request
*/
function SoapController(callback) {
this.isInvalid = false;
this.callback = callback;
this.stop = null;
}
//marks soap controller instance as invalid. For example when callback is no longer valid (for example when window is closed)
//this will prevent script errors.
SoapController.prototype.markInvalid = function SoapController_markInvalid() {
this.isInvalid = true;
};
function SOAP(parent)
{
this.parent = parent; //parent aras object
if (parent.getCurrentLoginName()) {
ArasModules.soap(null, {
url: parent.getServerURL(),
method: 'ApplyItem',
headers: {
'AUTHUSER': encodeURIComponent(parent.getCurrentLoginName()),
'AUTHPASSWORD': parent.getCurrentPassword(),
'DATABASE': encodeURIComponent(parent.getDatabase()),
'LOCALE': parent.getCommonPropertyValue('systemInfo_CurrentLocale'),
'TIMEZONE_NAME': parent.getCommonPropertyValue('systemInfo_CurrentTimeZoneName')
}
});
}
}
SOAP.prototype.send = function SOAP_send(methodName, bodyStr, url, saveChanges, soapController, is_bgrequest, authController, skip_empty_pwd) {
/*----------------------------------------
* send
*
* Purpose:
* send xml to InovatorServer and return result.
* returns SOAPResults object
*
* Arguments:
* methodName - string with Innovator Server method name (ApplyItem, GetItem, ...)
* bodyStr - xml string to send
* url - url of Innovator Server (by default url is built from this.parent.baseURL)
*
* soapController - an instance of SoapController
*/
var self = this;
var arasableObj = this.parent;
if (!arasableObj || methodName === undefined) {
return null;
}
if (!arasableObj.getCommonPropertyValue('ignoreSessionTimeoutInSoapSend') && arasableObj.getCommonPropertyValue('exitWithoutSavingInProgress')) {
return new SOAPResults(arasableObj, getFaultXml('The session is closed.'), saveChanges);
}
var options = {method: methodName};
if (url) {
options.url = url;
}
var methodXmlns = '';
if (methodName.indexOf('/') !== -1) {
methodXmlns = methodName.substring(0, methodName.lastIndexOf('/'));
methodName = methodName.substring(methodName.lastIndexOf('/') + 1, methodName.length);
}
if (methodXmlns) {
options.methodNm = methodXmlns;
}
var soapStr = removeUnchangedPermission(bodyStr || '');
if (soapStr && arasableObj.Browser.isIe()) {
soapStr = soapStr.replace(/\r\n/g, '\n');
}
SaveRequestToLog(soapStr);
var pwd = arasableObj.getCurrentPassword();
var resStr = '';
if (!pwd && !skip_empty_pwd)
{
var errDescription = arasableObj.getResource('', 'soap_object.pwd_cannot_be_empty');
resStr = getFaultXml(errDescription);
return new SOAPResults(arasableObj, resStr, saveChanges);
}
var async = !!(soapController && soapController.callback);
options.async = async;
var promise = ArasModules.soap(soapStr, options);
if (async) {
soapController.stop = promise.abort;
}
var result;
promise.then(function(resultNode) {
var text;
if (resultNode.ownerDocument)
{
var doc = resultNode.ownerDocument;
text = doc.xml || (new XMLSerializer()).serializeToString(doc);
}
else
{
text = resultNode;
}
var finalRetVal = new SOAPResults(arasableObj, text, saveChanges);
if (methodName && methodName.toLowerCase() === 'validateuser') {
arasableObj.setCommonPropertyValue('ValidateUserXmlResult', text);
}
if (async)
{
if (!soapController.isInvalid)
{
soapController.callback(finalRetVal);
}
return;
}
result = finalRetVal;
}).catch(function (xhr)
{
var res = new SOAPResults(arasableObj, xhr.responseText, saveChanges);
if (async)
{
if (!soapController.isInvalid) {
soapController.callback(res);
}
return;
}
result = res;
});
return result;
//function region >>>>>>>>>>>>>>>>>>
function removeUnchangedPermission(bodyStr) {
//select all permission_id nodes with attribute origPermission where origPermission
if (!bodyStr)
{
return bodyStr;
}
var workDom = new XmlDocument();
workDom.loadXML(bodyStr);
var permissionNodes = workDom.selectNodes('//descendant-or-self::node()[local-name(.) = \'permission_id\' and not(child::Item) and @origPermission]');
if (permissionNodes && permissionNodes.length > 0) {
for (var i = 0; i < permissionNodes.length; i++) {
if (permissionNodes[i].getAttribute('origPermission') == permissionNodes[i].text) {
var parent = permissionNodes[i].parentNode;
parent.removeChild(permissionNodes[i]);
}
else
{
permissionNodes[i].removeAttribute('origPermission');
}
}
}
return workDom.xml;
}
function getFaultXml(descr) {
var faultRetVal = SoapConstants.EnvelopeBodyFaultStart + '' + SoapConstants.SoapNamespace + ':Server ' + descr + ' ' + SoapConstants.EnvelopeBodyFaultEnd;
return faultRetVal;
}
function SaveRequestToLog(soapStr) {
// save soap message to local file system
if ('true' === arasableObj.getVariable('SaveRequest')) {
arasableObj.saveString2File(function() { return soapStr; }, 'xml', methodName + '_' + self.getDateStamp().replace(/:/g, '_'));
}
}
};
SOAP.showExitExcuse = function(arasableObj) {
var p = {};
var mainWnd = arasableObj.getMainWindow();
p.buttons = {};
p.buttons.btnExit = arasableObj.getResource('', 'soap_object.exit_innovator');
p.defaultButton = 'btnExit';
p.btnstyles = {btnExit: ''};
p.message = arasableObj.getResource('', 'soap_object.session_has_expired');
p.message += arasableObj.getResource('', 'soap_object.changes_will_be_lost_warning');
p.aras = arasableObj;
mainWnd.focus();
mainWnd.showModalDialog(arasableObj.getScriptsURL() + 'groupChgsDialog.html', p, 'dialogHeight:150px;dialogWidth:300px;center:yes;resizable:no;status:no;help:no;');
};
SOAP.checkIsSessionTimeOut = function(responseText) {
var aras = TopWindowHelper.getMostTopWindowWithAras(window).aras || window.opener.aras;
var mainWnd = aras.getMainWindow();
if (!mainWnd) {
return false;
}
if (sessionStorage.getItem('ArasSessionCheck')) {
mainWnd.DoFocusAfterAlert = true;
return false;
}
sessionStorage.setItem('ArasSessionCheck', true);
var data = {
title: aras.getResource('', 'soap_object.confirm_password'),
md5: aras.getPassword(),
fieldName2ReturnMD5: 'oldhash',
oldMsg: aras.getResource('', 'soap_object.confirm_password2'),
oldPwdOnly: true,
aras: aras,
dialogWidth: 300,
dialogHeight: 120,
center: true,
content: 'changeMD5Dialog.html'
};
var win = TopWindowHelper.getMostTopWindowWithAras(window);
var argwin = (win.main || win);
mainWnd.focus();
var process = function (password) {
if (password === undefined) {
var style = 'style="width: 100px; margin: 5px;"';
var dialogParams = {
buttons: {
btnReturn: aras.getResource('', 'soap_object.return_to_login'),
btnExit: aras.getResource('', 'soap_object.exit_innovator')
},
defaultButton: 'btnReturn',
btnstyles: {btnReturn: style, btnExit: style},
btnclasses: {btnReturn: '', btnExit: 'cancel_button'},
message: aras.getResource('', 'soap_object.changes_will_be_lost_warning'),
aras: aras,
dialogHeight: 150,
content: 'groupChgsDialog.html',
dialogWidth: 300,
dialogHeight: 120,
center: true
};
argwin.ArasModules.Dialog.show('iframe', dialogParams).promise.then(function (tmpRes) {
if (tmpRes !== 'btnReturn') {
aras.setCommonPropertyValue('exitWithoutSavingInProgress', true);
if (mainWnd && aras.browserHelper) {
aras.browserHelper.closeWindow(mainWnd);
}
return false;
}
argwin.ArasModules.Dialog.show('iframe', data).promise.then(process);
});
} else if (password !== aras.getPassword()) {
mainWnd.DoFocusAfterAlert = true;
return aras.AlertError(aras.getResource('', 'soap_object.pwd_is_wrong')).then(function () {
return argwin.ArasModules.Dialog.show('iframe', data).promise.then(process);
});
} else {
var valid = false;
return ArasModules.nativSoap(' ', {
method: 'ValidateUser'
}).then(function() {
return true;
}, function(xhr) {
return aras.AlertError(new SOAPResults(aras, xhr.responseText, false));
});
}
};
var dialog = argwin.ArasModules.Dialog.show('iframe', data).promise.then(process);
return dialog;
};
SOAP.prototype.parseResponseHeaders = function SOAP_parseResponseHeaders(xmlhttp, arasableObj) { };
SOAP.prototype.getDateStamp = function SOAP_getDateStamp() {
var date = new Date();
var now = date.getFullYear() + '-';
if (date.getMonth() < 10) {
now += '0';
}
now += date.getMonth() + '-';
if (date.getDate() < 10) {
now += '0';
}
now += date.getDate() + ' ' +
date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds();
return now;
};
///////////////////////////////////////////////////////////////////////////////////////////
// SOAPResults
function SOAPResults(arasableObj, resultsXML, saveChanges) {
this.arasableObj = arasableObj; //parent aras object
var xmlWithPermissions;
if (resultsXML) {
xmlWithPermissions = setOriginalPermissionID(resultsXML);
this.results = xmlWithPermissions;
} else {
this.results = arasableObj.createXMLDocument();
}
//lazy "xmlWithPermissions.xml" calculating to consume memory (mainly) and cpu only when resultsXML is called
Object.defineProperty(this, 'resultsXML', {
get: function() {
return !xmlWithPermissions ? '' : xmlWithPermissions.xml;
}
});
var message = this.getMessage();
arasableObj.refreshWindows(message, this.results, saveChanges);
function setOriginalPermissionID(resultsXML) {
var workDom = arasableObj.createXMLDocument();
workDom.loadXML(resultsXML);
//select all nodes "permission_id"
var permissionNodes = workDom.selectNodes('//permission_id');
if (permissionNodes && permissionNodes.length > 0) {
for (var i = 0; i < permissionNodes.length; i++) {
if (permissionNodes[i].selectSingleNode('./Item') === null) {
//if it doesn't contain any child nodes - set attribute origPermission = innerText
permissionNodes[i].setAttribute('origPermission', permissionNodes[i].text);
} else {
//else select id of child Item node and set attribute origPermission = id
permissionNodes[i].setAttribute('origPermission', permissionNodes[i].selectSingleNode('./Item/@id').value);
}
}
}
return workDom;
}
}
SOAPResults.prototype.getResponseText = function() {
return this.resultsXML;
};
SOAPResults.prototype.getParseError = function() {
var res;
if (this.results.parseError.errorCode !== 0) {
res = '*** Wrong SOAP message! *** ' + '\n\n' +
'Error: ' + this.results.parseError.srcText.replace('H1', 'H3') + '\n' +
'ErrorCode: ' + this.results.parseError.errorCode + '\n' +
'Reason: ' + this.results.parseError.reason;
} else {
res = undefined;
}
return res;
};
SOAPResults.prototype.isFault = function SOAPResults_isFault() {
if (this.results.parseError.errorCode !== 0) {
return this.getParseError();
}
var fault = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault());
if (fault) {
return true;
} else {
return false;
}
};
SOAPResults.prototype.getFaultCode = function() {
if (this.results.parseError.errorCode !== 0) {
return this.getParseError();
}
var faultcode = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/faultcode'));
if (faultcode) {
return faultcode.text;
} else {
return 0;
}
};
SOAPResults.prototype.getFaultString = function() {
if (this.results.parseError.errorCode !== 0) {
return this.getParseError();
}
var faultstring = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/faultstring'));
if (faultstring) {
return faultstring.text;
} else {
return '';
}
};
SOAPResults.prototype.getFaultActor = function() {
if (this.results.parseError.errorCode !== 0) {
return this.getParseError();
}
var faultactor = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/detail/legacy_faultactor'));
if (faultactor) {
return faultactor.text;
} else {
return '';
}
};
SOAPResults.prototype.getFaultDetails = function() {
if (this.results.parseError.errorCode !== 0) {
return this.getParseError();
}
var detail = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/detail'));
var msg = '';
if (detail) {
msg = detail.text; //.replace(/^.+\]/,'');
// msg = msg.replace(/,.+$/,'');
}
return msg;
};
SOAPResults.prototype.getServerMessage = function SOAPResults_getServerMessage() {
var faultNd = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault());
if (faultNd && faultNd.parentNode) {
var serverMessageNd = faultNd.parentNode.selectSingleNode('server_message');
if (serverMessageNd) {
return serverMessageNd.xml;
}
}
};
SOAPResults.prototype.getResultsBody = function() {
var res = this.getResult();
var items = res.selectNodes('Item');
return items.length == 1 ? items[0].xml : res.xml;
};
SOAPResults.prototype.getResult = function() {
var res = null;
if (this.results && this.results.documentElement) {
res = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathResult());
}
if (!res) {
var subst = this.arasableObj.createXMLDocument();
subst.loadXML(SoapConstants.EnvelopeBodyStart + ' ' + SoapConstants.EnvelopeBodyEnd);
res = subst.documentElement.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathResult());
}
return res;
};
SOAPResults.prototype.getMessage = function() {
var res = null;
if (this.results && this.results.documentElement) {
res = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathMessage());
}
if (!res) {
var subst = new XmlDocument();
subst.loadXML(SoapConstants.EnvelopeBodyStart + ' ' + SoapConstants.EnvelopeBodyEnd);
res = subst.documentElement.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathMessage());
}
return res;
};
SOAPResults.prototype.getMessageValue = function SOAPResults_getMessageValue(key) {
var msg;
if (this.isFault()) {
msg = this.results.selectSingleNode(TopWindowHelper.getMostTopWindowWithAras(window).aras.XPathFault('/detail/message[@key=\'' + key + '\']'));
} else {
var nd = this.getMessage();
if (nd) {
msg = nd.selectSingleNode('event[@name=\'' + key + '\']');
}
}
return (msg ? msg.getAttribute('value') : undefined);
};
/** item_methods.js **/
// © Copyright by Aras Corporation, 2004-2011.
/*
* The item methods extension for the Aras Object.
* most of methods in this file use itemID and itemTypeName as parameters
*/
/*-- newFileItem
*
* Method to create a new item of ItemType File
* fileNameOrObject = the name of the file or FileObject
*
*/
Aras.prototype.newFileItem = function Aras_newFileItem(fileNameOrObject) {
var brief_fileName = "";
if (typeof fileNameOrObject === "string") {
var parts = fileNameOrObject.split(/[\\\/]/);
brief_fileName = parts[parts.length - 1];
} else {
brief_fileName = fileNameOrObject.name;
}
with (this) {
var item = createXmlElement('Item');
item.setAttribute('type', 'File');
item.setAttribute('id', generateNewGUID());
item.setAttribute('action', 'add');
item.setAttribute('loaded', '1');
item.setAttribute('levels', '1');
item.setAttribute('isTemp', '1');
setItemProperty(item, 'filename', brief_fileName);
if (typeof fileNameOrObject === "string") {
setItemProperty(item, 'checkedout_path', fileNameOrObject.substring(0, fileNameOrObject.length - brief_fileName.length - 1));
} else {
setItemProperty(item, 'checkedout_path', '');
aras.vault.addFileToList(item.getAttribute('id'), fileNameOrObject);
}
var fileSize = aras.vault.getFileSize(fileNameOrObject);
setItemProperty(item, 'file_size', fileSize);
var locatedItemId = getRelationshipTypeId('Located');
if (!locatedItemId) {
AlertError(getResource('', 'item_methods.located_item_type_not_exist'));
return null;
}
var locatedItem = newRelationship(locatedItemId, item, false, null, null);
var vaultServerID = getVaultServerID();
if (vaultServerID == '') {
AlertError(getResource('', 'item_methods.no_defualt_vault_sever'), window);
return null;
}
setItemProperty(locatedItem, 'related_id', vaultServerID);
return item;
}
};
/*-- newItem
*
* Method to create a new item
* itemTypeName = the name of the ItemType
*
*/
Aras.prototype.newItem = function Aras_newItem(itemTypeName, itemTypeNdOrSpecialArg) {
var self = this;
function newItem_internal(arasObj, filePath) {
var item = null;
var typeId = itemType.getAttribute('id');
if (itemTypeName == 'Workflow Map') {
item = arasObj.newWorkflowMap();
item.setAttribute('typeId', typeId);
return item;
}
if (itemTypeName === 'File') {
var fileName = null;
var isFileNameSpecified = itemTypeNdOrSpecialArg;
if (isFileNameSpecified) {
fileName = itemTypeNdOrSpecialArg;
} else {
var vault = arasObj.vault;
fileName = vault.selectFile();
}
if (fileName) {
item = arasObj.newFileItem(fileName);
item.setAttribute('typeId', typeId);
}
return item;
}
item = self.createXmlElement('Item');
item.setAttribute('type', itemTypeName);
item.setAttribute('id', arasObj.GUIDManager.GetGUID());
item.setAttribute('action', 'add');
item.setAttribute('loaded', '1');
item.setAttribute('levels', '1');
item.setAttribute('isTemp', '1');
item.setAttribute('typeId', typeId);
var properties = itemType.selectNodes('Relationships/Item[@type="Property" and default_value and not(default_value[@is_null="1"])]');
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
var propertyName = arasObj.getItemProperty(property, 'name');
var dataType = arasObj.getItemProperty(property, 'data_type');
var defaultValue = arasObj.getItemProperty(property, 'default_value');
if (dataType == 'item') {
var dataSource = property.selectSingleNode('data_source');
if (dataSource) {
dataSource = dataSource.getAttribute('name');
}
if (dataSource) {
defaultValue = arasObj.getItemById(dataSource, defaultValue, 0);
}
}
arasObj.setItemProperty(item, propertyName, defaultValue, undefined, itemType);
}
if (itemTypeName == 'Life Cycle Map') {
var stateTypeID = arasObj.getRelationshipTypeId('Life Cycle State');
var newState = arasObj.newRelationship(stateTypeID, item);
arasObj.setItemProperty(newState, 'name', 'Start');
arasObj.setItemProperty(newState, 'image', '../images/LifeCycleState.svg');
arasObj.setItemProperty(item, 'start_state', newState.getAttribute('id'));
} else if (itemTypeName == 'Form') {
arasObj.setItemProperty(item, 'stylesheet', '../styles/default.css');
var relTypeID = arasObj.getRelationshipTypeId('Body');
var bodyRel = arasObj.newRelationship(relTypeID, item);
}
return item;
}
var isItemTypeSpecified = itemTypeNdOrSpecialArg && itemTypeNdOrSpecialArg.xml;
var itemType = isItemTypeSpecified ? itemTypeNdOrSpecialArg : this.getItemTypeForClient(itemTypeName).node;
if (!itemType) {
this.AlertError(this.getResource('', 'ui_methods_ex.item_type_not_found', itemTypeName));
return false;
}
function handleNewItemType(newTypeName) {
if (newTypeName) {
var new_itemNd = self.newItem(newTypeName);
self.itemsCache.addItem(new_itemNd);
return new_itemNd;
} else {
return null;
}
}
if (this.isPolymorphic(itemType)) {
var itemTypesList = this.getMorphaeList(itemType);
var selectionDialog = this.uiItemTypeSelectionDialog(itemTypesList, arguments[3]);
if (selectionDialog && selectionDialog.then) {
return selectionDialog.then(handleNewItemType);
} else {
return handleNewItemType(selectionDialog)
}
}
var onBeforeNewEv = itemType.selectNodes('//Item[client_event="OnBeforeNew"]/related_id/Item');
var onAfterNewEv = itemType.selectNodes('//Item[client_event="OnAfterNew"]/related_id/Item');
var onNewEv = itemType.selectSingleNode('//Item[client_event="OnNew"]/related_id/Item');
var res;
var xml = ' ';
if (onBeforeNewEv.length) {
for (var i = 0; i < onBeforeNewEv.length; i++) {
try {
res = this.evalMethod(this.getItemProperty(onBeforeNewEv[i], 'name'), xml);
} catch (exp) {
this.AlertError(this.getResource('', 'item_methods.event_handler_failed'), this.getResource('', 'item_methods.event_handler_failed_with_message', exp.description), this.getResource('', 'common.client_side_err'));
return null;
}
if (res === false) {
return null;
}
}
}
if (onNewEv) {
res = this.evalMethod(this.getItemProperty(onNewEv, 'name'), xml);
if (res) {
res = res.node;
}
if (!res) {
return null;
}
} else {
res = newItem_internal(this);
}
if (onAfterNewEv.length && res) {
for (var i = 0; i < onAfterNewEv.length; i++) {
try {
res = this.evalMethod(this.getItemProperty(onAfterNewEv[i], 'name'), res.xml);
} catch (exp) {
this.AlertError(this.getResource('', 'item_methods.event_handler_failed'), this.getResource('', 'item_methods.event_handler_failed_with_message', exp.description), this.getResource('', 'common.client_side_err'));
return null;
}
if (res) {
res = res.node;
}
if (!res) {
return null;
}
}
}
if (onNewEv) {
for (var name in this.windowsByName) {
try {
var win = this.windowsByName[name];
if (win && win.onRefresh) {
win.onRefresh();
}
} catch (excep) {}
}
res = null;
}
return res;
};
/*
* this function add item to packageDefinition
*/
Aras.prototype.addItemToPackageDef = function(strArrOfId, itemTypeName) {
//check if items selected in grid
if (strArrOfId.length < 1) {
return;
}
var ArasObj = this;
var packArray = null;
var countOfPacks = 0;
var htmlContent = '';
var params = new Object();
var itemTypeLabel = '';
var itemTypeId = this.getItemTypeId(itemTypeName);
params.writeContent = writeContent;
params.aras = ArasObj;
// We need to replace id with config_id.
var copyOfIds = new Array();
for (var i = 0; i < strArrOfId.length; i++) {
copyOfIds.push('\'' + strArrOfId[i] + '\'');
}
var aml = '' + copyOfIds.join(',') + ' ';
var res = this.soapSend('ApplyItem', aml);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return;
}
res = res.getResultsBody();
var result = this.createXMLDocument();
result.loadXML(res);
for (var i = 0; i < result.selectNodes('./Item').length; i++) {
strArrOfId[i] = result.selectSingleNode('./Item[id=\'' + strArrOfId[i] + '\']/config_id').text;
}
//check if PackageDefinition exist
var packageDefId = this.getItemTypeId('PackageDefinition');
if (!packageDefId) {
ArasObj.AlertError(this.getResource('', 'item_methods.unable_get_package_definition_item_type'));
return;
}
//getting the label of ItemType
var itemType = this.getItemTypeForClient(itemTypeName);
if (itemType) {
//IR-014145 'Problem report with 'Add To Package Definition'' fix: we need only "en" label.
var qyItemWithEnLbl = new this.getMostTopWindowWithAras(window).Item();
qyItemWithEnLbl.setAction('get');
qyItemWithEnLbl.setType('ItemType');
qyItemWithEnLbl.setProperty('name', itemTypeName);
qyItemWithEnLbl.setAttribute('select', '*');
qyItemWithEnLbl.setAttribute('language', 'en');
resItemWithEnLbl = qyItemWithEnLbl.apply();
itemTypeLabel = resItemWithEnLbl.getProperty('label', undefined, 'en');
if (itemTypeLabel === undefined) {
itemTypeLabel = itemTypeName;
}
} else {
ArasObj.AlertError(this.getResource('', 'item_methods.unable_get_item_type', itemTypeName), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom));
return;
}
//query all packages existing in DBO
getAllpackages();
/*
* this function write content to modal window
*/
function writeContent(w) {
w.document.write(htmlContent);
}
function ApplyItemInternal(action, type, attr, props) {
var query = new ArasObj.getMostTopWindowWithAras(window).Item();
query.setAction(action);
query.setType(type);
query.setAttribute('doGetItem', 0);
f(attr, true);
f(props);
function f(arr, isAttr) {
if (arr && arr.length != 0) {
for (var i = 0; i < arr.length; i++) {
var tmp = arr[i].split('|');
if (isAttr) {
query.setAttribute(tmp[0], tmp[1]);
} else {
query.setProperty(tmp[0], tmp[1]);
}
}
}
}
return query.apply();
}
/*
* this function request all packages
*/
function getAllpackages() {
packArray = ApplyItemInternal('get', 'PackageDefinition', new Array('select|name, id'), new Array('is_current|1'));
countOfPacks = packArray.getItemCount();
}
/***
* Add selected itemtype to package
* @param strSelectedPack name of package
*/
function addItemsToPackage(strSelectedPack) {
// Get id of PackageDefinition
var strIdOfPackNode = packArray.dom.selectSingleNode('.//Result/Item[name=\'' + strSelectedPack + '\']/id');
// If user didn't checked any package
if (!strIdOfPackNode) {
return;
}
var strIdOfPack = strIdOfPackNode.text;
// Get id of PackageGroup
var qry = ApplyItemInternal('get', 'PackageGroup', new Array('select|id'), new Array('source_id|' + strIdOfPack, 'name|' + itemTypeLabel));
// In case group not exist create new one
if (qry.isError()) {
qry = ApplyItemInternal('add', 'PackageGroup', null, new Array('source_id|' + strIdOfPack, 'name|' + itemTypeLabel));
if (qry.isError()) {
ArasObj.AlertError(ArasObj.getResource('', 'item_methods.unable_add_group', itemTypeLabel), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom));
return;
}
}
var strIdOfGroup = qry.getAttribute('id');
var bWasError = false;
for (var i = 0; i < strArrOfId.length; i++) {
var strKeyedName = ArasObj.getKeyedName(strArrOfId[i], itemTypeName);
qry = ApplyItemInternal('get', 'PackageElement', new Array('select|id'), new Array('source_id|' + strIdOfGroup, 'element_id|' + strArrOfId[i]));
if (qry.isError()) {
qry = ApplyItemInternal('add', 'PackageElement', null, new Array('source_id|' + strIdOfGroup, 'element_id|' + strArrOfId[i], 'name|' + strKeyedName, 'element_type|' + itemTypeName));
if (qry.isError()) {
bWasError = true;
ArasObj.AlertError(ArasObj.getResource('', 'item_methods.unable_add_item', strKeyedName), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom));
}
} else {
bWasError = true;
ArasObj.AlertError(ArasObj.getResource('', 'item_methods.item_already_exsist_in_package', strKeyedName, strSelectedPack));
}
}
if (!bWasError) {
if (strArrOfId.length > 1) {
ArasObj.AlertSuccess(ArasObj.getResource('', 'item_methods.items_added_successfully'));
} else {
ArasObj.AlertSuccess(ArasObj.getResource('', 'item_methods.item_added_successfully'));
}
}
}
/*
*param strNameOfPack - name of new package to be created
*param strArrdependOns - array of package names to be depended by new package
*/
function createPackage(strNameOfPack, strArrdependOns) {
qry = ArasObj.getItemFromServerByName('PackageDefinition', strNameOfPack, 'id');
if (qry && !qry.isError()) {
ArasObj.AlertError(ArasObj.getResource('', 'item_methods.package_with_such_name_already_exist'));
return false;
} else {
qry = ApplyItemInternal('add', 'PackageDefinition', null, new Array('name|' + strNameOfPack));
if (qry.isError()) {
ArasObj.AlertError(ArasObj.getResource('', 'item_methods.unable_add_package_with_name', strNameOfPack), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom));
return false;
}
var strIdOfpack = qry.node.getAttribute('id');
for (var i = 0; i < strArrdependOns.length; i++) {
if ('empty' == strArrdependOns[i]) {
continue;
}
qry = ApplyItemInternal('add', 'PackageDependsOn', null, new Array('name|' + strArrdependOns[i], 'source_id|' + strIdOfpack));
if (qry.isError()) {
ArasObj.AlertError(ArasObj.getResource('', 'item_methods.Unable to add dependency', strArrdependOns[i]), ArasObj.getFaultString(qry.dom), ArasObj.getFaultActor(qry.dom));
return false;
}
}
}
return true;
}
htmlContent = '';
htmlContent += '';
htmlContent += '
' + this.getResource('', 'item_methods.selected_package_from_list') + '
';
htmlContent += '' +
'';
var firstOption = '';
if (countOfPacks > 0) {
htmlContent += '' + this.getResource('', 'item_methods.select_package') + ' ';
firstOption = this.getResource('', 'item_methods.select_package');
} else {
firstOption = this.getResource('', 'item_methods.create_new');
}
htmlContent += '' + this.getResource('', 'item_methods.create_new') + ' ';
for (var i = 0; i < countOfPacks; ++i) {
var packItem = packArray.getItemByIndex(i);
var propName = packItem.getProperty('name');
htmlContent += '' + propName + ' ';
}
htmlContent += ' ' + firstOption + '
';
htmlContent += ' ';
htmlContent += '
';
var win = this.getMostTopWindowWithAras(window);
params.title = this.getResource('', 'item_methods.add_selected_items_to_a_package');
var modalCallback = function(packageName) {
if (packageName) {
if (packageName == 'new') {
htmlContent = '';
htmlContent += '';
htmlContent += '';
htmlContent += '
' + this.getResource('', 'item_methods.create_new_package') + '
';
htmlContent += '' + this.getResource('', 'item_methods.package_name') + '
';
htmlContent += '
';
if (countOfPacks > 0) {
htmlContent += '';
htmlContent += '
' + this.getResource('', 'item_methods.dependency') + '
';
htmlContent += '
';
for (var i = 0; i < countOfPacks; ++i) {
var packItem = packArray.getItemByIndex(i);
var propName = packItem.getProperty('name');
htmlContent += '' + propName + ' ';
}
htmlContent += ' ';
htmlContent += '
';
}
htmlContent += ' ';
htmlContent += ' ';
htmlContent += '
';
params = {
aras: this,
title: this.getResource('', 'item_methods.create_new_package'),
writeContent: writeContent,
dialogWidth: 350,
dialogHeight: 320,
content: 'modalDialog.html'
};
window.setTimeout(function() {
(win.main || win).ArasModules.Dialog.show('iframe', params).promise.then(
function(strNewPack) {
if (strNewPack) {
var regExp = new RegExp('^(.+)=dep=(.+)$', 'i');
var strNewPackName = strNewPack.match(regExp)[1];
var strDepPackage = strNewPack.match(regExp)[2];
regExp = new RegExp('[^;]+', 'ig');
var bResult = createPackage(strNewPackName, strDepPackage.match(regExp));
if (bResult) {
getAllpackages();
addItemsToPackage(strNewPackName);
}
}
}
);
}.bind(this), 0);
} else {
addItemsToPackage(packageName);
}
}
}.bind(this);
params.dialogWidth = 300;
params.dialogHeight = 200;
params.content = 'modalDialog.html';
(win.main || win).ArasModules.Dialog.show('iframe', params).promise.then(modalCallback);
};
/*-- newRelationship
*
* Method to create a new Relationship for an item
* relTypeId = the RelatinshpType id
* srcItem = the source item in the relationship (may be null:i.e. when created with mainMenu)
* searchDialog = true or false : if search dialog to be displayed
* wnd = the window from which the dialog is opened
*
*/
Aras.prototype.newRelationship = function(relTypeId, srcItem, searchDialog, wnd, relatedItem, relatedTypeName, bTestRelatedItemArg, bIsDoGetItemArg, descByTypeName) {
with (this) {
var processAddingRelationship = function(relatedItem) {
if (descByTypeName == undefined) {
descByTypeName = this.getItemTypeName(descByTypeId);
}
var descByItem = this.newItem(descByTypeName);
this.itemsCache.addItem(descByItem);
if (!descByItem) {
return null;
}
if (relatedId != '' && !descByItem.selectSingleNode('related_id')) {
this.createXmlElement('related_id', descByItem);
}
if (relatedItem) {
if (srcItem) {
if (relatedItem == srcItem) {
relatedItem = srcItem.cloneNode(true);
var relationshipsNd = relatedItem.selectSingleNode('Relationships');
if (relationshipsNd) {
relatedItem.removeChild(relationshipsNd);
}
relationshipsNd = null;
relatedItem.setAttribute('action', 'skip');
}
}
if (this.isTempID(relatedId)) {
descByItem.selectSingleNode('related_id').appendChild(relatedItem);
} else {
descByItem.selectSingleNode('related_id').appendChild(relatedItem.cloneNode(true));
}
}
if (relTypeName == 'RelationshipType') {
if (srcItem) {
this.setItemProperty(descByItem, 'source_id', srcItem.getAttribute('id'));
}
}
if (srcItem) {
if (!srcItem.selectSingleNode('Relationships')) {
srcItem.appendChild(srcItem.ownerDocument.createElement('Relationships'));
}
var relationship;
try {
relationship = srcItem.selectSingleNode('Relationships').appendChild(descByItem);
// relationship = srcItem.selectSingleNode('Relationships').appendChild(descByItem.cloneNode(true));
} catch (excep) {
if (excep.number == -2147467259) {
this.AlertError(this.getResource('', 'item_methods.recursion_not_allowed_here'), wnd);
return null;
} else {
throw excep;
}
}
relationship.setAttribute('typeId', descByTypeId);
relationship.setAttribute('action', 'add');
relationship.setAttribute('loaded', '1');
relationship.setAttribute('levels', '0');
if (bIsDoGetItem) {
relationship.setAttribute('doGetItem', '0');
}
this.setItemProperty(relationship, 'source_id', srcItem.getAttribute('id'));
// descByItem.parentNode.removeChild(descByItem);
return relationship;
} else {
return descByItem;
}
}
var bTestRelatedItem;
if (bTestRelatedItemArg == undefined) {
bTestRelatedItem = false;
} else {
bTestRelatedItem = bTestRelatedItemArg;
}
var bIsDoGetItem;
if (bIsDoGetItemArg == undefined) {
bIsDoGetItem = false;
} else {
bIsDoGetItem = bIsDoGetItemArg;
}
var srcItemID;
if (srcItem) {
srcItemID = srcItem.getAttribute('id');
if (!wnd) {
wnd = uiFindWindowEx(srcItemID);
if (!wnd) {
wnd = window;
}
}
} else if (!wnd) {
wnd = window;
}
relType = getRelationshipType(relTypeId).node;
var relTypeName = getItemProperty(relType, 'name');
var relatedTypeId = getItemProperty(relType, 'related_id');
var descByTypeId = getItemProperty(relType, 'relationship_id');
var relatedId = '';
if (relatedItem) {
relatedId = relatedItem.getAttribute('id');
}
var self = this;
if (relatedTypeId) {
if (relatedTypeName == undefined) {
relatedTypeName = getItemTypeName(relatedTypeId);
}
if (searchDialog) {
var params = {
aras: this.getMostTopWindowWithAras(wnd).aras,
itemtypeName: relatedTypeName,
sourceItemTypeName: ((srcItem && srcItem.xml) ? srcItem.getAttribute('type') : ''),
sourcePropertyName: 'related_id',
type: 'SearchDialog'
};
wnd.ArasModules.MaximazableDialog.show('iframe', params);
if (relatedId == undefined) {
return null;
}
relatedId = relatedId.itemID;
if (!relatedId) {
return null;
}
// TODO: should be done in memory no need to call the server
relatedItem = getItemFromServer(relatedTypeName, relatedId, 'id').node;
} else {
if ((relatedItem === undefined) || (bTestRelatedItem == true)) {
relatedItem = newItem(relatedTypeName, null, wnd);
if (relatedItem && relatedItem.then) {
return relatedItem.then(function(relatedItem) {
this.itemsCache.addItem(relatedItem);
if (!relatedItem) {
return null;
}
relatedId = relatedItem.getAttribute('id');
return processAddingRelationship.call(this, relatedItem);
}.bind(this));
} else {
this.itemsCache.addItem(relatedItem);
if (!relatedItem) {
return null;
}
relatedId = relatedItem.getAttribute('id');
return processAddingRelationship.call(this, relatedItem);
}
}
}
}
return processAddingRelationship.call(this, relatedItem);
}
};
/*-- copyItem
*
* Method to copy an item
* item = item to be cloned
*
*/
Aras.prototype.copyItem = function(itemTypeName, itemID) {
if (itemID == undefined) {
return null;
}
var itemNd = this.getItemById('', itemID, 0);
if (itemNd) {
return this.copyItemEx(itemNd);
} else {
if (itemTypeName == undefined) {
return null;
}
var bodyStr = ' ';
} else {
bodyStr += ' action="copyAsNew" />';
}
var res = null;
with (this) {
var statusId = showStatusMessage('status', this.getResource('', 'common.copying_item'), system_progressbar1_gif);
res = soapSend('ApplyItem', bodyStr);
clearStatusMessage(statusId);
}
if (res.getFaultCode() != 0) {
var win = this.uiFindWindowEx(itemID);
if (!win) {
win = window;
}
this.AlertError(res, win);
return null;
}
var itemCopy = res.results.selectSingleNode('//Item');
return itemCopy;
}
};
/*-- saveItem
*
* Method to save an item
* itemID = the id for the item to be saved
* confirmSuccess
*/
Aras.prototype.saveItem = function(itemID, confirmSuccess) {
if (!itemID) {
return null;
}
var itemNd = this.getFromCache(itemID);
if (!itemNd) {
return null;
} else {
return this.saveItemEx(itemNd, confirmSuccess);
}
};
/*-- addItem
*
* Method to add an item
* itemID = the id for the item
*
*/
Aras.prototype.addItem = function(itemID) {
if (!itemID) {
return false;
}
var itemNd = this.getItemById('', itemID, 0);
if (!itemNd) {
return false;
} else {
return this.saveItemEx(itemNd);
}
};
/*-- updateItem
*
* Method to update an item
* itemID = the id for the item
*
*/
Aras.prototype.updateItem = function(itemID) {
if (!itemID) {
return false;
}
var itemNd = this.getItemById('', itemID, 0);
if (!itemNd) {
return false;
} else {
return this.saveItemEx(itemNd);
}
};
/*-- versionItem
*
* Method to version the item
* id = the id for the item
*
*/
Aras.prototype.versionItem = function(itemTypeName, itemID) {
if (!itemID) {
return false;
}
var win = this.uiFindWindowEx(itemID);
if (win) {
win.close();
if (this.uiFindWindowEx(itemID)) {
this.AlertError(this.getResource('', 'item_methods.cannot_close_item_window'));
return false;
}
}
var itemNd = this.getItemById('', itemID, 0);
if (!itemNd) {
return false;
} else {
var res = this.saveItemEx(itemNd, true, true);
if (res && win) {
this.uiShowItemEx(res);
}
return res;
}
};
Aras.prototype.getAffectedItems = function(itemTypeName, itemId) {
var res;
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.getting_affected_items'), system_progressbar1_gif);
res = soapSend('ApplyItem', '- ');
clearStatusMessage(statusId);
}
if (res.getFaultCode() != 0) {
this.AlertError(res);
return null;
}
return res.results.selectNodes('//Item');
}; //function getAffectedItems
Aras.prototype.purgeItem = function Aras_purgeItem(itemTypeName, itemID, silentMode) {
/*-- purgeItem
*
* Method to delete the latest version of the item (or the item if it's not versionable)
* itemTypeName -
* itemID = the id for the item
* silentMode - flag to know if user confirmation is NOT needed
*
*/
return this.PurgeAndDeleteItem_CommonPart(itemTypeName, itemID, silentMode, 'purge');
};
Aras.prototype.deleteItem = function Aras_deleteItem(itemTypeName, itemID, silentMode) {
/*-- deleteItem
*
* Method to delete all versions of the item
* itemTypeName -
* itemID = the id for the item
* silentMode - flag to know if user confirmation is NOT needed
*
*/
return this.PurgeAndDeleteItem_CommonPart(itemTypeName, itemID, silentMode, 'delete');
};
Aras.prototype.GetOperationName_PurgeAndDeleteItem = function Aras_GetOperationName_PurgeAndDeleteItem(purgeORdelete) {
return purgeORdelete == 'delete' ? 'Deleting' : 'Purge';
};
Aras.prototype.Confirm_PurgeAndDeleteItem = function Aras_Confirm_PurgeAndDeleteItem(itemId, keyedName, purgeORdelete) {
var operation = this.GetOperationName_PurgeAndDeleteItem(purgeORdelete);
var win = this.uiFindWindowEx(itemId);
var options = {dialogWidth: 300, dialogHeight: 180, center: true},
params = {
aras: this,
message: this.getResource('', 'item_methods.operation_item_name', operation, keyedName),
buttons: {
btnYes: this.getResource('', 'common.ok'),
btnCancel: this.getResource('', 'common.cancel')
},
defaultButton: 'btnCancel'
},
returnedValue;
if (!win) {
win = window;
}
win.focus();
if (this.Browser.isCh()) {
returnedValue = 'btnCancel';
if (window.confirm(this.getResource('', 'item_methods.operation_item_name', operation, keyedName))) {
returnedValue = 'btnYes';
}
} else {
returnedValue = this.modalDialogHelper.show('DefaultModal', window, params, options, 'groupChgsDialog.html');
}
if(returnedValue === 'btnYes'){
return true;
} else {
return false;
}
};
Aras.prototype.SendSoap_PurgeAndDeleteItem = function Aras_SendSoap_PurgeAndDeleteItem(ItemTypeName, ItemId, purgeORdelete) {
/*-- SendSoap_PurgeAndDeleteItem
*
* This method is for ***internal purposes only***.
*
*/
var Operation = this.GetOperationName_PurgeAndDeleteItem(purgeORdelete);
var StatusId = this.showStatusMessage('status', this.getResource('', 'item_methods.operation_item', Operation), system_progressbar1_gif);
var res = this.soapSend('ApplyItem', '
', null, false);
this.clearStatusMessage(StatusId);
if (res.getFaultCode() != 0) {
var win = this.uiFindWindowEx(ItemId);
if (!win) {
win = window;
}
this.AlertError(res, win);
return false;
}
return true;
};
Aras.prototype.RemoveGarbage_PurgeAndDeleteItem = function Aras_RemoveGarbage_PurgeAndDeleteItem(ItemTypeName, ItemId, DeletedItemTypeName, relationship_id) {
/*-- RemoveGarbage_PurgeAndDeleteItem
*
* This method is for ***internal purposes only***.
*
*/
if (ItemTypeName == 'ItemType' || ItemTypeName == 'RelationshipType') {
if (DeletedItemTypeName) {
//remove instances of the deleted ItemType
this.itemsCache.deleteItems('/Innovator/Items/Item[@type=\'' + DeletedItemTypeName + '\']');
// TODO: remove mainWnd.Cache also.
}
if (relationship_id) {
//remove corresponding ItemType or RelationshipType
this.itemsCache.deleteItems('/Innovator/Items/Item[@id=\'' + relationship_id + '\']');
this.itemsCache.deleteItems('/Innovator/Items/Item[@type=\'RelationshipType\'][relationship_id=\'' + relationship_id + '\']');
}
}
//find and remove all duplicates in dom
//this helps to fix IR-006266 for example
this.itemsCache.deleteItems('/Innovator/Items//Item[@id=\'' + ItemId + '\']');
};
Aras.prototype.PurgeAndDeleteItem_CommonPart = function Aras_PurgeAndDeleteItem_CommonPart(ItemTypeName, ItemId, silentMode, purgeORdelete) {
/*-- PurgeAndDeleteItem_CommonPart
*
* This method is for ***internal purposes only***.
* Is allowed to be called only from inside aras.deleteItem and aras.purgeItem methods.
*
*/
if (silentMode === undefined) {
silentMode = false;
}
var itemNd = this.itemsCache.getItem(ItemId);
if (itemNd) {
return this.PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, purgeORdelete);
} else {
//prepare
if (!silentMode) {
if (!this.Confirm_PurgeAndDeleteItem(ItemId, this.getKeyedName(ItemId), purgeORdelete)) {
return false;
}
}
var DeletedItemTypeName;
var relationship_id;
if (!this.isTempID(ItemId)) {
//save some information
if (ItemTypeName == 'ItemType') {
var tmpItemTypeNd = this.getItemFromServer('ItemType', ItemId, 'name,is_relationship');
if (tmpItemTypeNd) {
tmpItemTypeNd = tmpItemTypeNd.node; //because getItemFromServer returns IOM Item...
}
if (tmpItemTypeNd) {
if (this.getItemProperty(tmpItemTypeNd, 'is_relationship') == '1') {
relationship_id = ItemId;
}
DeletedItemTypeName = this.getItemProperty(tmpItemTypeNd, 'name');
}
tmpItemTypeNd = null;
} else if (ItemTypeName == 'RelationshipType') {
var tmpRelationshipTypeNd = this.getItemFromServer('RelationshipType', ItemId, 'relationship_id,name');
if (tmpRelationshipTypeNd) {
tmpRelationshipTypeNd = tmpRelationshipTypeNd.node; //because getItemFromServer returns IOM Item...
}
if (tmpRelationshipTypeNd) {
relationship_id = this.getItemProperty(tmpRelationshipTypeNd, 'relationship_id');
DeletedItemTypeName = this.getItemProperty(tmpRelationshipTypeNd, 'name');
}
tmpRelationshipTypeNd = null;
} else if (ItemTypeName == 'Preference') {
this.deleteSavedSearchesByPreferenceIDs([ItemId]);
}
//delete
if (!this.SendSoap_PurgeAndDeleteItem(ItemTypeName, ItemId, purgeORdelete)) {
return false;
}
}
//delete all dependent stuff
if (ItemTypeName == 'ItemType' || ItemTypeName == 'RelationshipType') {
this.RemoveGarbage_PurgeAndDeleteItem(ItemTypeName, ItemId, DeletedItemTypeName, relationship_id);
}
this.MetadataCache.RemoveItemById(ItemId);
}
return true;
};
Aras.prototype.deleteSavedSearchesByPreferenceIDs = function Aras_deleteSavedSearchesByPreferenceIDs(preferenceIDs) {
var idsString = '\'' + preferenceIDs.join('\',\'') + '\'';
var qry = this.newIOMItem('SavedSearch', 'get');
qry.SetAttribute('select', 'id');
qry.SetAttribute('where', '[SavedSearch].owned_by_id in (SELECT identity_id FROM [Preference] WHERE id in (' + idsString + ')) AND [SavedSearch].auto_saved=\'1\'');
qry.SetProperty('auto_saved', '1');
var res = qry.apply();
if (!res.isEmpty() && !res.isError()) {
var items = res.getItemsByXPath(this.XPathResult('/Item[@type=\'SavedSearch\']'));
for (var i = 0; i < items.getItemCount(); i++) {
this.MetadataCache.RemoveItemById(items.getItemByIndex(i).getID());
}
var deleteSavedSearchesAml = '' +
' - ' +
'
' +
' ';
res = this.applyAML(deleteSavedSearchesAml);
}
};
Aras.prototype.deletePreferences = function Aras_deletePreferences(preferenceIDs) {
var StatusId = this.showStatusMessage('status', this.getResource('', 'item_methods.operation_item', 'Deleting'), system_progressbar1_gif);
try {
for (var preferenceIndex = 0; preferenceIndex < preferenceIDs.length; preferenceIndex++) {
var preferenceId = preferenceIDs[preferenceIndex];
this.MetadataCache.RemoveItemById(preferenceId);
}
var idsString = '\'' + preferenceIDs.join('\',\'') + '\'';
this.deleteSavedSearchesByPreferenceIDs(preferenceIDs);
var deletePreferencesAml = '' +
' ' +
' ';
res = this.applyAML(deletePreferencesAml);
allChecked = false;
} finally {
this.clearStatusMessage(StatusId);
}
};
/*-- lockItem
*
* Method to lock the item
* id = the id for the item
*
*/
Aras.prototype.lockItem = function Aras_lockItem(itemID, itemTypeName) {
if (itemID) {
var itemNode = this.getFromCache(itemID);
if (itemNode) {
return this.lockItemEx(itemNode);
} else {
if (itemTypeName) {
var ownerWindow = this.uiFindWindowEx(itemID) || window,
bodyStr = ' ',
statusId = this.showStatusMessage('status', this.getResource('', 'common.locking_item_type', itemTypeName), system_progressbar1_gif),
requestResult = this.soapSend('ApplyItem', bodyStr);
this.clearStatusMessage(statusId);
if (requestResult.getFaultCode() != 0) {
this.AlertError(requestResult, ownerWindow);
return null;
}
itemNode = requestResult.results.selectSingleNode(this.XPathResult('/Item'));
if (itemNode) {
this.updateInCache(itemNode);
itemNode = this.getFromCache(itemID);
this.fireEvent('ItemLock', {
itemID: itemNode.getAttribute('id'),
itemNd: itemNode,
newLockedValue: this.isLocked(itemNode)
});
return itemNode;
} else {
this.AlertError(this.getResource('', 'item_methods.failed_get_item_type', itemTypeName), this.getResource('', 'item_methods.xpathresult_of_item_returned_null'), 'common.client_side_err', ownerWindow);
return null;
}
} else {
return null;
}
}
}
return false;
};
/*-- unlockItem
*
* Method to unlock the item
* id = the id for the item
*
*/
Aras.prototype.unlockItem = function(itemID, itemTypeName) {
if (!itemID) {
return null;
}
with (this) {
var itemNd = getFromCache(itemID);
if (itemNd) {
return unlockItemEx(itemNd);
} else {
if (!itemTypeName) {
return null;
} else {
var win = uiFindWindowEx(itemID);
if (!win) {
win = window;
}
var bodyStr = ' ';
var statusId = showStatusMessage('status', getResource('', 'item_methods.unlocking_item'), system_progressbar1_gif);
var res = soapSend('ApplyItem', bodyStr);
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
this.AlertError(res, win);
return null;
}
itemNd = res.results.selectSingleNode(XPathResult('/Item'));
if (!itemNd) {
return null;
}
updateInCache(itemNd);
updateFilesInCache(itemNd);
var params = this.newObject();
params.itemID = itemNd.getAttribute('id');
params.itemNd = itemNd;
params.newLockedValue = this.isLocked(itemNd);
this.fireEvent('ItemLock', params);
return itemNd;
}
}
} //with (this)
};
/*-- loadItems
*
* Method to load an item or items
* typeName = the ItemType name
* body = the query message to get the items
* levels = the levels deep for the returned item configuration
* pageSize = the number of rows to return
* page = the page number
* configPath = the RelationshipType names to include inteh item configuration returned
* select = the list of properties to return
*
*/
Aras.prototype.loadItems = function Aras_loadItems(typeName, body, levels, pageSize, page, configPath, select) {
if (typeName == undefined || typeName == '') {
return false;
}
if (body == undefined) {
body = '';
}
if (levels == undefined) {
levels = 0;
}
if (pageSize == undefined) {
pageSize = '';
}
if (page == undefined) {
page = '';
}
if (configPath == undefined) {
configPath = '';
}
if (select == undefined) {
select = '';
}
levels = parseInt(levels);
var attrs = '', innerBody = '';
if (body != '') {
if (body.charAt(0) != '<') {
attrs = body;
} else {
innerBody = body;
}
}
var soapBody = '- ' + innerBody + '
';
var res;
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.loading', typeName), system_progressbar1_gif);
res = soapSend('ApplyItem', soapBody);
clearStatusMessage(statusId);
}
if (res.getFaultCode() != 0) {
if (this.DEBUG) {
this.AlertError(this.getResource('', 'item_methods.fault_loading'), typeName, res.getFaultCode());
}
return null;
}
if (configPath) {
levels--;
}
var items = res.results.selectNodes(this.XPathResult('/Item'));
var itemsRes = new Array();
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var currentId = item.getAttribute('id');
item.setAttribute('levels', levels);
this.itemsCache.updateItem(item, true);
itemsRes.push(this.itemsCache.getItem(currentId));
}
return itemsRes;
};
/*-- getItem
*
* Method to load an item
* typeName = the ItemType name
* xpath = the XPath to teh item in the dom cache
* body = the query message to get the items
* levels = the levels deep for the returned item configuration
* configPath = the RelationshipType names to include inteh item configuration returned
* select = the list of properties to return
*
*/
Aras.prototype.getItem = function(itemTypeName, xpath, body, levels, configPath, select) {
if (levels == undefined) {
levels = 1;
}
if (typeof (itemTypeName) != 'string') {
itemTypeName = '';
}
var typeAttr = '';
if (xpath.indexOf('@id=') < 0) {
/* POLYITEM: only argument with @type if xpath does not start with @id= */
typeAttr = '[@type="' + itemTypeName + '"]';
}
xpath = '/Innovator/Items/Item' + typeAttr + '[' + xpath + ']';
var node = this.itemsCache.getItemByXPath(xpath);
var loadItemFromServer = false;
// if node was found in cache
if (node) {
// if node is dirty then retreive node from cache after test for completeness
if (this.isDirtyEx(node) || this.isTempEx(node)) {
// if requested levels > than node levels attribute then load item from server
if ((node.getAttribute('levels') - levels) < 0) {
itemTypeName = node.getAttribute('type');
loadItemFromServer = true;
}
} else {// if node not dirty then drop it from cache and load from server original version
if (!itemTypeName) {
itemTypeName = node.getAttribute('type');
}
loadItemFromServer = true;
}
} else {// if node not exists in cache then load item from server
if (itemTypeName != '') {
loadItemFromServer = true;
}
}
if (loadItemFromServer) {
this.loadItems(itemTypeName, body, levels, '', '', configPath, select);
node = this.itemsCache.getItemByXPath(xpath);
}
return node;
};
/*-- getRelatedItem
*
* Method to get related item from relationship
* item = relationship from which related item will be taken
*
*/
Aras.prototype.getRelatedItem = function(item) {
try {
var relatedItem = item.selectSingleNode('related_id/Item');
return relatedItem;
} catch (excep) {
return null;
}
};
/*-- getItemById
*
* Method to load an item by id
* typeName = the ItemType name
* id = the id for the item
* levels = the levels deep for the returned item configuration
* configPath = the RelationshipType names to include inteh item configuration returned
* select = the list of properties to return
*
*/
Aras.prototype.getItemById = function(typeName, id, levels, configPath, select) {
if (id == '') {
return null;
}
if (levels == undefined) {
levels = 1;
}
if (configPath == undefined) {
configPath = '';
}
if (select == undefined) {
select = '';
}
return this.getItem(typeName, '@id="' + id + '"', 'id="' + id + '"', levels, configPath, select);
};
/*-- getItemUsingIdAsParameter
*
* The same as getItemById. The only difference is that method load an item by id passing id like parameter,
* not like attribute. Created because if request item using id as attribute, server will return full item.
* typeName = the ItemType name
* id = the id for the item
* levels = the levels deep for the returned item configuration
* configPath = the RelationshipType names to include inteh item configuration returned
* select = the list of properties to return
*
*/
Aras.prototype.getItemUsingIdAsParameter = function(typeName, id, levels, configPath, select) {
this.getItemById(typeName, id, levels, configPath, select);
};
Aras.prototype.getItemById$skipServerCache = function Aras_getItemById$skipServerCache(typeName, id, levels, select, configPath) {
/*-- getItemById$skipServerCache
*
* IMPORTANT: This is internal system method. Never use it. Will be removed in future !!!
*
* Method to load an item by id
* typeName = the ItemType name
* id = the id for the item
* levels = the levels deep for the returned item configuration
* configPath = the RelationshipType names to include inteh item configuration returned
* select = the list of properties to return
*
*/
if (!id) {
return null;
}
if (levels === undefined) {
levels = 1;
}
if (select === undefined) {
select = '';
}
if (configPath === undefined) {
configPath = '';
}
return this.getItem(typeName, '@id="' + id + '"', '' + id + ' ', levels, configPath, select);
};
/*-- getItemByName
*
* Method to load an item by name property
* typeName = the ItemType name
* name = the name for the item
* levels = the levels deep for the returned item configuration
* configPath = the RelationshipType names to include inteh item configuration returned
* select = the list of properties to return
*
*/
Aras.prototype.getItemByName = function(typeName, name, levels, configPath, select) {
if (levels == undefined) {
levels = 1;
}
return this.getItem(typeName, 'name="' + name + '"', '' + name + ' ', levels, configPath, select);
};
/*-- getItemByKeyedName
*
* Method to load an item by keyed_name property
* typeName = the ItemType name
* keyed_name = the keyed_name for the item
* levels = the levels deep for the returned item configuration
* configPath = the RelationshipType names to include inteh item configuration returned
* select = the list of properties to return
*
*/
Aras.prototype.getItemByKeyedName = function(typeName, keyed_name, levels, configPath, select) {
if (levels == undefined) {
levels = 0;
}
return this.getItem(typeName, 'keyed_name="' + keyed_name + '"', '' + keyed_name + ' ', levels, configPath, select);
};
/*-- getRelationships
*
* Method to get the Relationships for an item
* item = the item
* typeName = the ItemType name for the Relationships
*
*/
Aras.prototype.getRelationships = function(item, typeName) {
with (this) {
if (!item) {
return false;
}
return item.selectNodes('Relationships/Item[@type="' + typeName + '"]');
}
};
/*-- getKeyedName
*
* Method to get key field values for an item
* id = the id for the item
*
*/
Aras.prototype.getKeyedName = function(id, itemTypeName) {
if (arguments.length < 2) {
itemTypeName = '';
}
if (!id) {
return '';
}
with (this) {
var item = itemsCache.getItem(id);
if (!item) {
item = getItemById(itemTypeName, id, 0);
}
if (!item && itemTypeName != '') {
item = getItemFromServer(itemTypeName, id, 'keyed_name').node;
}
if (!item) {
return '';
}
var res = getItemProperty(item, 'keyed_name');
if (!res) {
res = getKeyedNameEx(item);
}
return res;
}
};
Aras.prototype.getKeyedNameAttribute = function(node, element) {
if (!node) {
return;
}
var value;
var tmpNd = node.selectSingleNode(element);
if (tmpNd) {
value = tmpNd.getAttribute('keyed_name');
if (!value) {
value = '';
}
} else {
value = '';
}
return value;
};
function keyedNameSorter(a, b) {
var s1 = parseInt(a[0]);
if (isNaN(s1)) {
return 1;
}
var s2 = parseInt(a[0]);
if (isNaN(s2)) {
return -1;
}
if (s1 < s2) {
return -1;
} else if (s1 == s2) {
return 0;
} else {
return 1;
}
}
Aras.prototype.sortProperties = function sortProperties(ndsCollection) {
if (!ndsCollection) {
return null;
}
var tmpArr = new Array();
for (var i = 0; i < ndsCollection.length; i++) {
tmpArr.push(ndsCollection[i].cloneNode(true));
}
var self = this;
function sortPropertiesNodes(propNd1, propNd2) {
var sorder1 = self.getItemProperty(propNd1, 'sort_order');
if (sorder1 == '') {
sorder1 = 1000000;
}
sorder1 = parseInt(sorder1);
if (isNaN(sorder1)) {
return 1;
}
var sorder2 = self.getItemProperty(propNd2, 'sort_order');
if (sorder2 == '') {
sorder2 = 1000000;
}
sorder2 = parseInt(sorder2);
if (isNaN(sorder2)) {
return -1;
}
if (sorder1 < sorder2) {
return -1;
} else if (sorder1 == sorder2) {
sorder1 = self.getItemProperty(propNd1, 'name');
sorder2 = self.getItemProperty(propNd2, 'name');
if (sorder1 < sorder2) {
return -1;
} else if (sorder1 == sorder2) {
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
return tmpArr.sort(sortPropertiesNodes);
};
/*-- getItemAllVersions
*
* Method to load all the versions of an item
* typeName = the ItemType name
* id = the id for the item
*
*/
Aras.prototype.getItemAllVersions = function(typeName, id) {
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_versions', typeName), system_progressbar1_gif);
var res = soapSend('ApplyItem', ' ');
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return null;
}
return res.results.selectNodes(XPathResult('/Item'));
}
};
/*-- getItemLastVersion
*
* Method to load the latest version for the item
* itemTypeName = the ItemType name
* itemId = the id for the item
*
*/
Aras.prototype.getItemLastVersion = function(typeName, itemId) {
var res = this.soapSend('ApplyItem', ' ');
if (res.getFaultCode() != 0) {
this.AlertError(res);
return null;
}
return res.results.selectSingleNode(this.XPathResult('/Item'));
}; //getItemLastVersion
/*-- getItemWhereUsed
*
* Method to load the where used items for an item
* typeName = the ItemType name
* id = the id for the item
*
*/
Aras.prototype.getItemWhereUsed = function(typeName, id) {
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_where_used'), system_progressbar1_gif);
var res = soapSend('ApplyItem', ' ');
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return null;
}
return res.results.selectSingleNode(XPathResult('/Item'));
}
};
/*-- getClassWhereUsed
*
* Method to load the where class is referenced
* typeId = the ItemType name
* classId = the id of class node
* scanTypes = for this types dependencies will be tracked
* detailed = if true return detailed result, if false return count of dependencies
*
*/
Aras.prototype.getClassWhereUsed = function(typeId, classId, scanTypes, detailed) {
with (this) {
var statusId = showStatusMessage('status', getResource('', 'statusbar.getting_impact_data'), '../images/Progress.gif');
var methodAML =
'- ' +
'
' +
'' + classId + '+ ' +
(detailed ? 'details ' : '') +
(scanTypes ? '' + scanTypes + ' ' : '') +
' ' +
' ';
var res = applyMethod('GetClassWhereUsed', methodAML);
clearStatusMessage(statusId);
var resDom = XmlDocument();
resDom.loadXML(res);
return resDom;
}
};
/*-- getHistoryItems
*
* Method to load the history items for specified item
* typeName = the ItemType name
* id = the id for the item
*
*/
Aras.prototype.getHistoryItems = function(typeName, id) {
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_history'), system_progressbar1_gif);
var res = soapSend('ApplyItem', ' ');
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
return false;
}
var items = res.results.selectNodes(XPathResult('/Item'));
items = res.results.selectNodes(XPathResult('/Item[@type="History"]'));
return items;
}
};
/*-- getItemNextStates
*
* Method to load the promote values
* typeName = the ItemType name
* id = the id for the item
*
*/
Aras.prototype.getItemNextStates = function(typeName, id) {
with (this) {
var res = soapSend('ApplyItem', ' ');
if (res.getFaultCode() != 0) {
try {
var win = windowsByName[id];
this.AlertError(res, win);
} catch (excep) {} //callee server is disappeared or ... error
return null;
}
return res.getResult();
}
};
/*-- promote
*
* Method to promote an item to the next state
* typeName = the ItemType name
* id = the id for the item
* stateName = the next state name
*
*/
Aras.prototype.promote = function Aras_promote(itemTypeName, itemID, stateName, comments) {
var promoteParams = {
typeName: itemTypeName,
id: itemID,
stateName: stateName,
comments: comments
};
return this.promoteItem_implementation(promoteParams);
};
Aras.prototype.promoteItem_implementation = function Aras_promoteItem_implementation(promoteParams, soapController) {
var itemTypeName = promoteParams.typeName;
var itemID = promoteParams.id;
var stateName = promoteParams.stateName;
var comments = promoteParams.comments;
var myItem = this.newIOMItem(itemTypeName, 'promoteItem');
myItem.setID(itemID);
myItem.setProperty('state', stateName);
if (comments) {
myItem.setProperty('comments', comments);
}
//Baseline
var msg = itemTypeName + ' to ' + stateName;
var xml = myItem.dom.xml;
var async = Boolean(soapController && soapController.callback);
this.addIdBeingProcessed(itemID, 'promotion of ' + msg);
var msgId = this.showStatusMessage('status', this.getResource('', 'item_methods.promoting', msg), system_progressbar1_gif);
var self = this;
var globalRes = null;
function afterSoapSend(res) {
if (msgId) {
self.clearStatusMessage(msgId);
}
self.removeIdBeingProcessed(itemID);
if (res.getFaultCode() != 0) {
var win = self.uiFindWindowEx(itemID);
if (!win) {
win = window;
}
self.AlertError(res, win);
}
self.removeFromCache(itemID);
}
if (async) {
var originalCallBack = soapController.callback;
function afterAsyncSoapSend(soapSendRes) {
afterSoapSend(soapSendRes);
originalCallBack(soapSendRes);
}
soapController.callback = afterAsyncSoapSend;
}
globalRes = this.soapSend('ApplyItem', xml, undefined, undefined, soapController);
if (async) {
return null;
}
if (globalRes) {
afterSoapSend(globalRes);
msgId = this.showStatusMessage('status', this.getResource('', 'item_methods.getting_promote_result'), system_progressbar1_gif);
globalRes = this.getItemById(itemTypeName, itemID, 0);
this.clearStatusMessage(msgId);
if (!globalRes) {
globalRes = null;
}
}
return globalRes;
};
Aras.prototype.getItemRelationship = function Aras_getItemRelationship(item, relTypeName, relID, useServer) {
if (!item || !relTypeName || !relID || useServer == undefined) {
return null;
}
var res = item.selectSingleNode('Relationships/Item[@type="' + relTypeName + '" and @id="' + relID + '"]');
if (res) {
return res;
}
if (!useServer) {
return null;
}
var itemID = item.getAttribute('id');
var bodyStr = '' + itemID + ' ' + '' + relID + ' ';
var xpath = '@id=\'' + relID + '\' and source_id=\'' + itemID + '\'';
res = this.getItem(relTypeName, xpath, bodyStr, 0);
with (this) {
if (res != null || res != undefined) {
if (!item.selectSingleNode('Relationships')) {
item.appendChild(item.ownerDocument.createElement('Relationships'));
}
res = res.selectSingleNode('//Item[@type="' + relTypeName + '" and @id="' + relID + '"]');
if (!res) {
return null;
}
res = item.selectSingleNode('Relationships').appendChild(res);
return res;
} else {
return null;
}
}
};
Aras.prototype.getItemRelationships = function(itemTypeName, itemId, relsName, pageSize, page, body, forceReplaceByItemFromServer) {
if (!(itemTypeName && itemId && relsName)) {
return null;
}
if (pageSize == undefined) {
pageSize = '';
}
if (page == undefined) {
page = '';
}
if (body == undefined) {
body = '';
}
if (forceReplaceByItemFromServer == undefined) {
forceReplaceByItemFromServer = false;
}
var res = null;
with (this) {
var itemNd = getItemById(itemTypeName, itemId, 0);
if (!itemNd) {
return null;
}
if (!forceReplaceByItemFromServer && (pageSize == -1 || isTempID(itemId) || (itemNd.getAttribute('levels') && parseInt(itemNd.getAttribute('levels')) > 0))) {
if (!isNaN(parseInt(pageSize)) && parseInt(pageSize) > 0 && !isNaN(parseInt(page)) && parseInt(page) > -1) {
res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '" and @page="' + page + '"]');
if (res && res.length == pageSize) {
return res;
}
} else {
res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '"]');
if (res && res.length > 0) {
return res;
}
}
}
var bodyStr = ' ';
} else {
bodyStr += '>' + body + ' ';
}
var statusId = showStatusMessage('status', getResource('', 'item_methods.loading_relationships', itemTypeName), system_progressbar1_gif);
var res = soapSend('ApplyItem', bodyStr);
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return null;
}
if (!itemNd.selectSingleNode('Relationships')) {
createXmlElement('Relationships', itemNd);
}
var rels = res.results.selectNodes(XPathResult('/Item[@type="' + relsName + '"]'));
var itemRels = itemNd.selectSingleNode('Relationships');
var idsStr = '';
for (var i = 0; i < rels.length; i++) {
var rel = rels[i].cloneNode(true);
var relId = rel.getAttribute('id');
if (i > 0) {
idsStr += ' or ';
}
idsStr += '@id="' + relId + '"';
var prevRel = itemRels.selectSingleNode('Item[@type="' + relsName + '" and @id="' + relId + '"]');
if (prevRel) {
if (forceReplaceByItemFromServer == true) {
// By some reason the previous implementation did not replaced existing on the node
// relationships with the new relationships obtained from the server but rather
// just removed some attributes on them (like "pagesize", etc.). From other side those
// relationships that don't exist on the 'itemNd' are added to it. This is wrong as
// the newly obtained relationships even if they already exist on 'itemNd' might have
// some properties that are different in db from what is in the client memory.
// NOTE: the fix will break the case when the client changes some relationship properties
// in memory and then calls this method expecting that these properties will stay unchanged,
// but: a) this method seems to be called only from getFileURLEx(..); b) if the above
// behavior is expected then another method is probably required which must be called
// something like 'mergeRelationships'.
// by Andrey Knourenko
itemRels.removeChild(prevRel);
} else {
this.mergeItem(prevRel, rel);
continue;
}
}
itemRels.appendChild(rel);
}
itemNd.setAttribute('levels', '0');
if (idsStr == '') {
return null;
}
res = itemRels.selectNodes('Item[@type="' + relsName + '" and (' + idsStr + ')]');
} //with (this)
return res;
};
Aras.prototype.resetLifeCycle = function Aras_resetLifeCycle(itemTypeName, itemID) {
if (!itemTypeName || !itemID) {
return false;
}
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.reseting_life_cycle_state'), system_progressbar1_gif);
var bodyStr = ' ';
var res = soapSend('ApplyItem', bodyStr);
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
var win = uiFindWindowEx(itemID);
if (!win) {
win = window;
}
this.AlertError(res, win);
return false;
}
var itemNd = res.results.selectSingleNode(XPathResult('/Item'));
if (!itemNd) {
return false;
}
return true;
}
};
Aras.prototype.setDefaultLifeCycle = function setDefaultLifeCycle(itemTypeName, itemID) {
if (!itemTypeName || !itemID) {
return false;
}
var statusId = this.showStatusMessage('status', this.getResource('', 'item_methods.reseting_life_cycle_state'), system_progressbar1_gif);
var bodyStr = ' ';
var res = this.soapSend('ApplyItem', bodyStr);
this.clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
var win = this.uiFindWindowEx(itemID);
if (!win) {
win = window;
}
this.AlertError(res, win);
return false;
}
var faultStr = res.getFaultString();
if (faultStr != '') {
return false;
}
this.removeFromCache(itemID);
var itemNd = this.getItemById(itemTypeName, itemID, 0);
if (!itemNd) {
return false;
}
return true;
};
Aras.prototype.resetItemAccess = function(itemTypeName, itemId) {
if (itemTypeName == undefined || itemId == undefined) {
return false;
}
with (this) {
var itemNd = null;
if (itemTypeName == '') {
itemNd = getItemById('', itemId, 0);
if (!itemNd) {
return false;
}
itemTypeName = itemNd.getAttribute('type');
}
var statusId = showStatusMessage('status', getResource('', 'item_methods.reseting_item_access'), system_progressbar1_gif);
var bodyStr = ' ';
var res = soapSend('ApplyItem', bodyStr);
clearStatusMessage(statusId);
try {
var winBN = windowsByName[itemId];
if (res.getFaultCode() != 0) {
this.AlertError(res, winBN);
return false;
}
} catch (excep) {} //callee server is disappeared or ... error
var tempRes = loadItems(itemTypeName, 'id="' + itemId + '"', 0);
if (tempRes) {
return true;
} else {
return false;
}
}
};
Aras.prototype.resetAllItemsAccess = function(itemTypeName) {
if (!itemTypeName) {
return false;
}
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.reseting_item_access'), system_progressbar1_gif);
var bodyStr = ' ';
var res = soapSend('ApplyItem', bodyStr);
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
return true;
}
};
Aras.prototype.populateRelationshipsGrid = function Aras_populateRelationshipsGrid(bodyStr) {
if (!bodyStr) {
return null;
}
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.populating_relationships_grid'), system_progressbar1_gif);
var res = soapSend('PopulateRelationshipsGrid', bodyStr);
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
AlertError(res);
}
return res;
}
};
Aras.prototype.populateRelationshipsTables = function(bodyStr) {
if (!bodyStr) {
return null;
}
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.populating_relationships_tables'), system_progressbar1_gif);
var res = soapSend('PopulateRelationshipsTables', bodyStr);
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
AlertError(res);
return null;
}
return res.results.selectSingleNode('//tables');
}
};
Aras.prototype.getMainTreeItems = function() {
with (this) {
var statusId = showStatusMessage('status', getResource('', 'item_methods.populating_main_tree'), system_progressbar1_gif);
var res = soapSend('GetMainTreeItems', '');
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
AlertError(res);
return null;
}
return res.results.selectSingleNode('//MainTree');
}
};
Aras.prototype.getPermissions = function(access_type, itemID, typeID, typeName) {
if (!(access_type && itemID)) {
return false;
}
if (access_type === 'can_add') {
return this.getItemTypeForClient(itemID, 'id').getAttribute('can_add_for_this_user') === '1';
}
with (this) {
var bodyStr = ' ';
var statusId = showStatusMessage('status', getResource('', 'item_methods.getting_permissions_right'), system_progressbar1_gif);
var res = soapSend('ApplyItem', bodyStr);
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
AlertError(res);
return null;
}
return (res.getResult().text == '1');
}
};
Aras.prototype.getRealPropertyForForeignProperty = function Aras_getRealPropertyForForeignProperty(foreignProperty, currentItemType) {
function getPropertyByCriteria(itemType, criteriaName, criteriaValue) {
if (null == itemType) {
return null;
}
return itemType.selectSingleNode('Relationships/Item[@type=\'Property\' and ' + criteriaName + '=\'' + criteriaValue + '\']');
}
if ('foreign' !== this.getItemProperty(foreignProperty, 'data_type')) {
return foreignProperty;
}
if (null == currentItemType) {
currentItemType = this.getItemTypeDictionary(this.getItemProperty(foreignProperty, 'source_id'), 'id').node;
}
var sourceProp = getPropertyByCriteria(currentItemType, 'id', this.getItemProperty(foreignProperty, 'data_source'));
var foreignItemType = this.getItemTypeDictionary(this.getItemProperty(sourceProp, 'data_source'), 'id').node;
var result = getPropertyByCriteria(foreignItemType, 'id', foreignProperty.selectSingleNode('foreign_property').text);
if ('foreign' == this.getItemProperty(result, 'data_type')) {
result = this.getRealPropertyForForeignProperty(result, foreignItemType);
}
return result;
};
Aras.prototype.getPropertiesOfTypeFile = function Aras_getPropertiesOfTypeFile(ItemTypeNd) {
/*
this function is for internal use *** only ***.
----
ItemTypeNd - node of ItemType
*/
var FileIT_ID_const = this.getFileItemTypeID();
var fileProps = ItemTypeNd.selectNodes('Relationships/Item[@type=\'Property\' and data_type=\'item\' and data_source=\'' + FileIT_ID_const + '\' ' + 'and name!=\'related_id\' and name!=\'config_id\']');
/*
related_id property is ignored here to not treat related_id as a property of relationship (for checkout/checkin) (IR-006449)
config_id property is ignored here to fix IR-006448 (to enable subsequent checkins. to do this all file instances must be locked.
but config_id points to first generation and thus if current generation is 2 or greater checkin is not available)
ItemType File has 2 properties of type File: id and config_id.
This allows user to perform checkin/checkout in context of File instances.
This looks like a logic bug, but there are solutions wich rely on this. (PLM for example)
*/
return fileProps;
};
/*-- applyItemWithFilesCheck
*
* Method to ApplyItem. Checking "do files exist in itemNd" is called before soap send. Returns xml node.
* itemNd = xml node to send in ApplyItem soap action. May contain items with type="File".
* win = item window
* statusMsg = message text to show in status bar. If empty then nothing is shown.
* XPath2ReturnedNd = xpath to select returned node. Default: aras.XPathResult('/Item')
*
*/
Aras.prototype.applyItemWithFilesCheck = function Aras_applyItemWithFilesCheck(itemNd, win, statusMsg, XPath2ReturnedNd) {
if (!XPath2ReturnedNd) {
XPath2ReturnedNd = this.XPathResult('/Item');
}
var res;
var files = itemNd.selectNodes('descendant-or-self::Item[@type="File" and (@action="add" or @action="update")]');
var statusId;
if (statusMsg) {
statusId = this.showStatusMessage('status', statusMsg, system_progressbar1_gif);
}
if (files.length == 0) {
res = this.soapSend('ApplyItem', itemNd.xml);
} else {
res = this.soapSend('generateNewGUID', '');
}
if (res.getFaultCode() != 0) {
this.AlertError(res, win);
res = null;
} else {
if (files.length == 0) {
res = res.results.selectSingleNode(XPath2ReturnedNd);
} else {
res = this.sendFilesWithVaultApplet(itemNd, statusMsg, XPath2ReturnedNd);
}
}
if (statusId) {
this.clearStatusMessage(statusId);
}
return res;
};
Aras.prototype.applyItemWithFilesCheckAsync = function Aras_applyItemWithFilesCheckAsync(itemNd, win, statusMsg, XPath2ReturnedNd) {
if (!XPath2ReturnedNd) {
XPath2ReturnedNd = this.XPathResult('/Item');
}
var res;
var promise;
var files = itemNd.selectNodes('descendant-or-self::Item[@type="File" and (@action="add" or @action="update")]');
var statusId;
if (statusMsg) {
statusId = this.showStatusMessage('status', statusMsg, system_progressbar1_gif);
}
if (files.length == 0) {
res = this.soapSend('ApplyItem', itemNd.xml);
} else {
res = this.soapSend('generateNewGUID', '');
}
if (res.getFaultCode() != 0) {
this.AlertError(res, win);
promise = Promise.resolve(null);
} else {
if (files.length == 0) {
promise = Promise.resolve(res.results.selectSingleNode(XPath2ReturnedNd));
} else {
promise = this.sendFilesWithVaultAppletAsync(itemNd, statusMsg, XPath2ReturnedNd);
}
}
return promise.then(function(res) {
if (statusId) {
this.clearStatusMessage(statusId);
}
return res;
}.bind(this));
};
/** item_methodsEx.js **/
// © Copyright by Aras Corporation, 2004-2012.
/*
* The item extended methods extension for the Aras Object.
* methods in this file use xml nodes as parameters
*/
///
Aras.prototype.isNew = function(itemNd) {
if (!this.isTempEx(itemNd)) {
return false;
}
return ('add' == itemNd.getAttribute('action'));
};
Aras.prototype.isTempEx = function(itemNd) {
if (!itemNd) {
return undefined;
}
return (itemNd.getAttribute('isTemp') == '1');
};
Aras.prototype.isDirtyEx = function(itemNd) {
if (!itemNd) {
return undefined;
}
return (itemNd.selectSingleNode('descendant-or-self::Item[@isDirty="1"]') !== null);
};
Aras.prototype.isLocked = function Aras_isLocked(itemNd) {
if (this.isTempEx(itemNd)) {
return false;
}
return ('' !== this.getItemProperty(itemNd, 'locked_by_id'));
};
Aras.prototype.isLockedByUser = function Aras_isLockedByUser(itemNd) {
if (this.isTempEx(itemNd)) {
return false;
}
var locked_by_id = this.getItemProperty(itemNd, 'locked_by_id');
return (locked_by_id == this.getCurrentUserID());
};
/*-- copyItemEx
*
* Method to copy an item
* itemNd = item to be cloned
*
*/
Aras.prototype.copyItemEx = function(itemNd, action, do_add) {
if (!itemNd) {
return false;
}
if (!action) {
action = 'copyAsNew';
}
if (do_add === undefined || do_add === null) {
do_add = true;
}
var itemTypeName = itemNd.getAttribute('type');
var bodyStr = ' ';
var res = null;
var statusId = this.showStatusMessage('status', this.getResource('', 'common.copying_item'), system_progressbar1_gif);
res = this.soapSend('ApplyItem', bodyStr);
this.clearStatusMessage(statusId);
var faultCode = res.getFaultCode();
if (faultCode !== 0 && faultCode !== '0') {
this.AlertError(res);
return null;
}
var itemCopy = res.results.selectSingleNode('//Item');
return itemCopy;
};
//+++++ saving item +++++
Aras.prototype.checkItemType = function(itemNd, win) {
var isTaskOrItsChildCache;
function isDataSourceSpecified(arasObj) {
var isTaskOrItsChild = itemNd && (arasObj.getItemProperty(itemNd, 'name') == 'InBasket Task' || itemNd.selectSingleNode('../../../../../Item[name=\'InBasket Task\']'));
if (!isTaskOrItsChild) {
if (isTaskOrItsChildCache === undefined) {
var tmpRes = arasObj.applyItem(
'- ' +
'
InBasket Task ' +
'' + itemNd.getAttribute('id') + ' ' +
' ');
if (tmpRes) {
var tmpDoc = arasObj.createXMLDocument();
tmpDoc.loadXML(tmpRes);
tmpRes = tmpDoc.selectSingleNode('//Item') ? true : false;
} else {
tmpRes = false;
}
isTaskOrItsChildCache = tmpRes;
}
isTaskOrItsChild = isTaskOrItsChildCache;
}
if (!propDs && propName != 'related_id' && propName != 'source_id' && !isTaskOrItsChild) {
arasObj.AlertError(arasObj.getResource('', 'item_methods_ex.property_data_source_not_specified', propKeyedName), '', '', win);
return false;
} else {
return true;
}
}
var name = this.getItemProperty(itemNd, 'name');
if (name === '') {
this.AlertError(this.getResource('', 'item_methods_ex.item_type_name_cannot_be_blank'), '', '', win);
return false;
}
var property, propKeyedName, propDt, propName, propDs, tmpStoredLength, storedLength, pattern;
var properties = itemNd.selectNodes('Relationships/Item[@type="Property" and (not(@action) or (@action!="delete" and @action!="purge"))]');
var i;
for (i = 0; i < properties.length; i++) {
property = properties[i];
propKeyedName = this.getKeyedNameEx(property);
propName = this.getItemProperty(property, 'name');
if (!propName) {
this.AlertError(this.getResource('', 'item_methods_ex.item_type_has_property_with_no_name', this.getItemProperty(itemNd, 'label')), win);
return false;
}
propDt = this.getItemProperty(property, 'data_type');
propDs = this.getItemProperty(property, 'data_source');
if (propDt == 'string' || propDt == 'ml_string' || propDt == 'mv_list')
{
tmpStoredLength = this.getItemProperty(property, 'stored_length');
storedLength = parseInt(tmpStoredLength);
if (isNaN(storedLength)) {
this.AlertError(this.getResource('', 'item_methods_ex.length_of_property_not_specified', propKeyedName), '', '', win);
return false;
} else if (storedLength <= 0) {
this.AlertError(this.getResource('', 'item_methods_ex.length_of_property_invalid', propKeyedName, tmpStoredLength), '', '', win);
return false;
}
if ('mv_list' == propDt && !isDataSourceSpecified(this)) {
return false;
}
}
else if ((propDt == 'item' || propDt == 'list' || propDt == 'filter list' || propDt == 'color list' || propDt == 'sequence' || propDt == 'foreign') && !isDataSourceSpecified(this)) {
return false;
}
else if (propDt == 'filter list') {
if (!isDataSourceSpecified(this)) {
return false;
}
pattern = this.getItemProperty(property, 'pattern');
if (!pattern) {
this.AlertError(this.getResource('', 'item_methods_ex.fliter_list_property_has_to_have_pattern', propKeyedName), '', '', win);
return false;
}
var tmpNd_1 = itemNd.selectSingleNode('Relationships/Item[@type="Property" and name="' + pattern + '" and (not(@action) or (@action!="delete" and @action!="purge"))]');
if (!tmpNd_1) {
this.AlertError(this.getResource('', 'item_methods_ex.filter_list_property_has_wrong_pattern', propKeyedName, pattern), win);
return false;
} else if (this.getItemProperty(tmpNd_1, 'name') == this.getItemProperty(property, 'name')) {
this.AlertError(this.getResource('', 'item_methods_ex.property_for_pattern_cannot_property_itself', propKeyedName), '', '', win);
return false;
}
}
}
var discussionTemplates = itemNd.selectNodes('Relationships/Item[@type="DiscussionTemplate" and (not(@action) or (@action!="delete" and @action!="purge"))]');
if (discussionTemplates.length > 0) {
var isRootClassificationExists = false;
for (i = 0; i < discussionTemplates.length; i++) {
var discussionTemplate = discussionTemplates[i];
if (this.getItemProperty(discussionTemplate, 'class_path') === '') {
isRootClassificationExists = true;
}
}
if (!isRootClassificationExists) {
this.AlertError(this.getResource('', 'item_methods_ex.item_type_should_have_discussiontemplate_for_root_class_path', propKeyedName, pattern), win);
return isRootClassificationExists;
}
}
return true;
};
Aras.prototype.checkItemForErrors = function Aras_checkItemForErrors(itemNd, exclusion, itemType, breakOnFirstError, emptyPropertyWithDefaultValueCallback) {
var resultErrors = [];
var propNd, reqId, isRequired, reqName, reqDataType, itemPropVal, defVal;
var typeOfItem = itemNd.getAttribute('type');
if (!typeOfItem) {
return resultErrors;
}
itemType = itemType ? itemType : this.getItemTypeDictionary(typeOfItem).node;
if (!itemType) {
return resultErrors;
}
var propertiesXpath = 'Relationships/Item[@type="Property" and (is_required="1" or data_type="string")' + (exclusion ? ' and name!="' + exclusion + '"' : '') + ']';
var requirements = itemType.selectNodes(propertiesXpath);
for (var i = 0; i < requirements.length; i++) {
propNd = requirements[i];
reqId = propNd.getAttribute('id');
reqName = this.getItemProperty(propNd, 'name');
reqDataType = this.getItemProperty(propNd, 'data_type');
isRequired = (this.getItemProperty(propNd, 'is_required') == '1');
if (!reqName) {
var noNameError = this.getResource('', 'item_methods_ex.item_type_has_property_with_no_name', this.getItemProperty(itemType, 'label'));
resultErrors.push({ message: noNameError });
if (breakOnFirstError) {
return resultErrors;
}
}
var proplabel = this.getItemProperty(propNd, 'label');
if (!proplabel) {
proplabel = this.getItemProperty(propNd, 'keyed_name');
}
if (!proplabel) {
proplabel = '';
}
itemPropVal = this.getItemProperty(itemNd, reqName);
if (isRequired && itemPropVal === '') {
defVal = this.getItemProperty(propNd, 'default_value');
if (defVal) {
if (emptyPropertyWithDefaultValueCallback && typeof(emptyPropertyWithDefaultValueCallback) === 'function') {
var callbackResult = emptyPropertyWithDefaultValueCallback(itemNd, reqName, proplabel, defVal);
if (!callbackResult.result) {
if (callbackResult.message) {
resultErrors.push({ message: callbackResult.message });
} else {
resultErrors.push({});
}
if (breakOnFirstError) {
return resultErrors;
}
}
}
continue;
} else if (!this.isPropFilledOnServer(reqName) && (reqDataType != 'md5' || itemNd.getAttribute('action') == 'add' || itemNd.selectSingleNode(reqName))) {
var fieldRequiredError = this.getResource('', 'item_methods_ex.field_required_provide_value', proplabel);
resultErrors.push({ message: fieldRequiredError });
if (breakOnFirstError) {
return resultErrors;
}
}
}
if (reqDataType == 'string') {
var storedLength = parseInt(this.getItemProperty(propNd, 'stored_length'));
if (!isNaN(storedLength) && itemPropVal.length - storedLength > 0) {
var maxLengthError = this.getResource('', 'item_methods_ex.maximum_length_characters_for_property', proplabel, storedLength, itemPropVal.length);
resultErrors.push({ message: maxLengthError });
if (breakOnFirstError) {
return resultErrors;
}
}
}
}
return resultErrors;
};
Aras.prototype.checkItem = function Aras_checkItem(itemNd, win, exclusion, itemType) {
var self = this;
var defaultFieldCheckCallback = function(itemNode, reqName, proplabel, defVal) {
var ask = self.confirm(self.getResource('', 'item_methods_ex.field_required_default_will_be_used', proplabel, defVal));
if (ask) {
self.setItemProperty(itemNode, reqName, defVal);
}
return {result: ask, message: ''};
};
var errors = this.checkItemForErrors(itemNd, exclusion, itemType, true, defaultFieldCheckCallback);
if (errors.length > 0) {
if (errors[0].message) {
this.AlertError(errors[0].message, '', '', win);
}
}
return errors.length === 0;
};
Aras.prototype.prepareItem4Save = function Aras_prepareItem4Save(itemNd) {
var itemTypeName = itemNd.getAttribute('type');
var itemID, item, items, items2;
var i, j, parentNd;
itemID = itemNd.getAttribute('id');
items = itemNd.selectNodes('.//Item[@id="' + itemID + '"]');
for (i = 0; i < items.length; i++) {
item = items[i];
parentNd = item.parentNode;
parentNd.removeChild(item);
parentNd.text = itemID;
}
items = itemNd.selectNodes('.//Item[@action="delete"]');
for (i = 0; i < items.length; i++) {
item = items[i];
var childs = item.selectNodes('*[count(descendant::Item[@action])=0]');
for (j = 0; j < childs.length; j++) {
var childItem = childs[j];
item.removeChild(childItem);
}
}
items = itemNd.selectNodes('.//Item');
for (i = 0; i < items.length; i++) {
item = items[i];
itemID = item.getAttribute('id');
items2 = itemNd.selectNodes('.//Item[@id="' + itemID + '"][@data_type != "foreign"]');
for (j = 1; j < items2.length; j++) {
item = items2[j];
parentNd = item.parentNode;
parentNd.removeChild(item);
parentNd.text = itemID;
}
}
items = itemNd.selectNodes('.//Item[not(@action) and not(.//Item/@action)]');
for (i = 0; i < items.length; i++) {
items[i].setAttribute('action', 'get');
}
items = itemNd.selectNodes('.//Item[@action="get" and (not(.//Item) or not(.//Item/@action!="get"))]');
for (i = 0; i < items.length; i++) {
item = items[i];
itemID = item.getAttribute('id');
parentNd = item.parentNode;
if (parentNd.nodeName == 'Relationships') {
parentNd.removeChild(item);
} else {
if (itemID) {
parentNd.removeChild(item);
parentNd.text = itemID;
}
}
}
items = itemNd.selectNodes('.//Item[@action="get"]');
for (i = 0; i < items.length; i++) {
items[i].setAttribute('action', 'skip');
}
};
function ClearDependenciesInMetadataCache(aras, itemNd) {
var items = itemNd.selectNodes('descendant-or-self::Item');
for (var i = 0; i < items.length; i++) {
var tmpId = items[i].getAttribute('id');
if (tmpId) {
aras.MetadataCache.RemoveItemById(tmpId);
}
}
var srcId = aras.getItemProperty(itemNd, 'source_id');
if (srcId) {
aras.MetadataCache.RemoveItemById(srcId);
}
//calling new method to clear metadata dates in Cache if Item has certain type
var NeedClearCache = itemNd.getAttribute('type');
if (NeedClearCache == 'ItemType' || NeedClearCache == 'Property' || NeedClearCache == 'Grid Event' || NeedClearCache == 'View' || NeedClearCache == 'TOC View' || NeedClearCache == 'Item Action' || NeedClearCache == 'Item Report' ||
NeedClearCache == 'Client Event' || NeedClearCache == 'Morphae' || NeedClearCache == 'RelationshipType' || NeedClearCache == 'Relationship View' || NeedClearCache == 'Relationship Grid Event' ||
NeedClearCache == 'Can Add' || NeedClearCache == 'History Template' || NeedClearCache == 'History Template Action' || NeedClearCache == 'History Action') {
aras.MetadataCache.DeleteITDatesFromCache();// if saving IT - remove all IT dates from cache, form dates can stay
}
if (NeedClearCache == 'ItemType' || NeedClearCache == 'RelationshipType' || NeedClearCache == 'Relationship View' || NeedClearCache == 'Relationship Grid Event') {
aras.MetadataCache.DeleteRTDatesFromCache();
}
if (NeedClearCache == 'Identity') {
aras.MetadataCache.DeleteITDatesFromCache();
aras.MetadataCache.DeleteIdentityDatesFromCache();
}
//If node isn't not part of ItemType, but List - remove List dates from cache
if (NeedClearCache == 'List' || NeedClearCache == 'Value' || NeedClearCache == 'Filter Value') {
aras.MetadataCache.DeleteListDatesFromCache();
}
//If node isn't not part of ItemType nor List but Form - remove Form and IT dates from cache
//hack: When new ItemType is being created server creates for it new form using "Create Form for ItemType" server method. To update form cache ItemType variant is being added.
if (NeedClearCache == 'Form' || NeedClearCache == 'Form Event' || NeedClearCache == 'Method' || NeedClearCache == 'Body' || NeedClearCache == 'Field' || NeedClearCache == 'Field Event' || NeedClearCache == 'Property' || NeedClearCache == 'List' || NeedClearCache == 'ItemType') {
aras.MetadataCache.DeleteFormDatesFromCache();
aras.MetadataCache.DeleteITDatesFromCache();//remove IT dates on saving Form, since it affects IT
aras.MetadataCache.DeleteClientMethodDatesFromCache();
aras.MetadataCache.DeleteAllClientMethodsDatesFromCache();
}
//If node is searchMode, remove SearchMode dates from cache
if (NeedClearCache == 'SearchMode') {
aras.MetadataCache.DeleteSearchModeDatesFromCache();
}
var _needClearCache = ',' + (NeedClearCache || '').toLowerCase() + ',';
if (',globalpresentationconfiguration,itpresentationconfiguration,presentationconfiguration,presentationcommandbarsection,commandbarsection,commandbarsectionitem,commandbaritem,'.indexOf(_needClearCache) > -1) {
aras.MetadataCache.DeleteConfigurableUiDatesFromCache();
}
if (',presentationconfiguration,presentationcommandbarsection,'.indexOf(_needClearCache) > -1) {
aras.MetadataCache.DeletePresentationConfigurationDatesFromCache();
}
if (NeedClearCache === 'CommandBarSection') {
aras.MetadataCache.DeleteCommandBarSectionDatesFromCache();
}
if (NeedClearCache == 'ItemType' || NeedClearCache === 'cmf_ContentType') {
aras.MetadataCache.DeleteContentTypeByDocumentItemTypeDatesFromCache();
aras.MetadataCache.DeleteITDatesFromCache();//remove IT dates on saving ContentType, since it affects a lot of IT
}
}
Aras.prototype.calcMD5 = function(s) {
return calcMD5(s);
};
(function(){
function _sendFilesWithVaultAppletBefore(itemNd, statusMsg, XPath2ReturnedNd) {
var win = this.uiFindWindowEx2(itemNd);
if (!XPath2ReturnedNd) {
XPath2ReturnedNd = this.XPathResult('/Item');
}
var vaultServerURL = this.getVaultServerURL();
var vaultServerID = this.getVaultServerID();
if (vaultServerURL === '' || vaultServerID === '') {
this.AlertError(this.getResource('', 'item_methods_ex.vault_sever_not_specified'), '', '', win);
return null;
}
var vaultApplet = this.vault;
vaultApplet.clearClientData();
vaultApplet.clearFileList();
var headers = this.getHttpHeadersForSoapMessage('ApplyItem');
headers['VAULTID'] = vaultServerID;
for (var hName in headers) {
vaultApplet.setClientData(hName, headers[hName]);
}
var fileNds = itemNd.selectNodes('descendant-or-self::Item[@type="File" and (@action="add" or @action="update")]');
for (var i = 0; i < fileNds.length; i++) {
var fileNd = fileNds[i];
var fileID = fileNd.getAttribute('id');
if (fileID) {
var fileRels = fileNd.selectSingleNode('Relationships');
if (!fileRels) {
fileRels = this.createXmlElement('Relationships', fileNd);
} else {
var all_located = fileRels.selectNodes('Item[@type=\'Located\']');
// If file has more than one 'Located' then remove all of them except the
// one that points to the default vault of the current user.
// NOTE: it's a FUNDAMENTAL Innovator's approach - file is always
// submitted to the default vault of the current user. If this
// concept will be changed in the future then this code must be modified.
var lcount = all_located.length;
for (var j = 0; j < lcount; j++) {
var located = all_located[j];
var rNd = located.selectSingleNode('related_id');
if (!rNd) {
fileRels.removeChild(located);
} else {
var rvId = '';
var rItemNd = rNd.selectSingleNode('Item[@type=\'Vault\']');
if (rItemNd) {
rvId = rItemNd.getAttribute('id');
} else {
rvId = rNd.text;
}
if (rvId != vaultServerID) {
fileRels.removeChild(located);
}
}
}
}
var fileLocated = fileRels.selectSingleNode('Item[@type=\'Located\']');
if (!fileLocated) {
fileLocated = this.createXmlElement('Item', fileRels);
fileLocated.setAttribute('type', 'Located');
}
if (!fileLocated.getAttribute('action')) {
var newLocatedAction = '';
if (fileNd.getAttribute('action') == 'add') {
newLocatedAction = 'add';
} else {
newLocatedAction = 'merge';
}
fileLocated.setAttribute('action', newLocatedAction);
}
// When file could have only one 'Located' we used on Located the condition 'where="1=1"' which essentially meant
// "add if none or replace any existing Located on the File". With ability of a file to reside in multiple
// vaults (i.e. item of type 'File' might have several 'Located' relationships) the behavior is "add Located
// if file is not there yet; update the Located if the file already in the vault". This is achieved by
// specifying on 'Located' condition 'where="related_id='{vault id}'"'. Note that additional condition
// 'source_id={file id}' will be added on server when the sub-AML - is processed.
if (!fileLocated.getAttribute('id') && !fileLocated.getAttribute('where')) {
fileLocated.setAttribute('where', 'related_id=\'' + vaultServerID + '\'' /*"AND source_id='"+fileID+"'"*/);
}
this.setItemProperty(fileLocated, 'related_id', vaultServerID);
}
//code related to export/import functionality. server_id == donor_id.
var server_id = this.getItemProperty(fileNd, 'server_id');
if (server_id === '') {
//this File is not exported thus check physical file.
var checkedout_path = this.getItemProperty(fileNd, 'checkedout_path');
var filename = this.getItemProperty(fileNd, 'filename');
var FilePath;
var itemId = this.getItemProperty(fileNd, 'id');
var isFileSelected = false;
if (this.getItemProperty(fileNd, 'file_size')) {
isFileSelected = true;
}
if (!isFileSelected || !filename) {
FilePath = vaultApplet.selectFile();
if (!FilePath) {
return null;
}
var parts = FilePath.split(/[\\\/]/);
filename = parts[parts.length - 1];
this.setItemProperty(fileNd, 'filename', filename);
} else {
if (checkedout_path) {
if (0 === checkedout_path.indexOf('/')) {
FilePath = checkedout_path + '/' + filename;
} else {
FilePath = checkedout_path + '\\' + filename;
}
} else {
FilePath = aras.vault.vault.associatedFileList[itemId];
}
}
this.setItemProperty(fileNd, 'checksum', vaultApplet.getFileChecksum(FilePath));
this.setItemProperty(fileNd, 'file_size', vaultApplet.getFileSize(FilePath));
vaultApplet.addFileToList(fileID, FilePath);
}
}
var statusId = this.showStatusMessage('status', statusMsg, system_progressbar1_gif);
var XMLdata = SoapConstants.EnvelopeBodyStart + '
' +
itemNd.xml + ' ' + SoapConstants.EnvelopeBodyEnd;
vaultApplet.setClientData('XMLdata', XMLdata);
return {
vaultServerURL: vaultServerURL,
vaultApplet: vaultApplet,
statusId: statusId,
win: win
};
}
function _sendFilesWithVaultAppletAfter(params, XPath2ReturnedNd, boolRes) {
if (!XPath2ReturnedNd) {
XPath2ReturnedNd = this.XPathResult('/Item');
}
this.clearStatusMessage(params.statusId);
var resXML = params.vaultApplet.getResponse();
if (!boolRes || !resXML) {
this.AlertError(this.getResource('', 'item_methods_ex.failed_upload_file', params.vaultServerURL), '', '', params.win);
if (!boolRes) {
resXML += params.vaultApplet.getLastError();
}
this.AlertError(this.getResource('', 'item_methods_ex.internal_error_occured'), boolRes + '\n' + resXML, this.getResource('', 'common.client_side_err'), params.win);
return null;
}
var soapRes = new SOAPResults(this, resXML);
var faultCode = soapRes.getFaultCode();
if (faultCode !== 0 && faultCode !== '0') {//because user can has just add access and no get access
this.AlertError(soapRes, params.win);
return null;
}
var resDom = soapRes.results;
if (this.hasMessage(resDom)) {// check for message
this.refreshWindows(this.getMessageNode(resDom), resDom);
}
return resDom.selectSingleNode(XPath2ReturnedNd);
}
Aras.prototype.sendFilesWithVaultApplet = function Aras_sendFilesWithVaultApplet(itemNd, statusMsg, XPath2ReturnedNd) {
/*----------------------------------------
* sendFilesWithVaultApplet
*
* Purpose:
* This function is for iternal use only. DO NOT use in User Methods
* Checks physical files.
* Sets headers and send physical files to Vault
*
* Arguments:
* itemNd - xml node to be processed
* statusMsg - string to show in status bar while files being uploaded
* XPath2ReturnedNd = xpath to select returned node. Default: aras.XPathResult('/Item')
*/
var params = _sendFilesWithVaultAppletBefore.call(this, itemNd, statusMsg, XPath2ReturnedNd);
if (!params) {
return params;
}
var boolRes = params.vaultApplet.sendFiles(params.vaultServerURL);
return _sendFilesWithVaultAppletAfter.call(this, params, XPath2ReturnedNd, boolRes);
};
Aras.prototype.sendFilesWithVaultAppletAsync = function Aras_sendFilesWithVaultAppletAsync(itemNd, statusMsg, XPath2ReturnedNd) {
var params = _sendFilesWithVaultAppletBefore.call(this, itemNd, statusMsg, XPath2ReturnedNd);
if (!params) {
return Promise.resolve(params);
}
return params.vaultApplet.vault.sendFilesAsync(params.vaultServerURL).then(function(boolRes) {
return _sendFilesWithVaultAppletAfter.call(this, params, XPath2ReturnedNd, boolRes);
}.bind(this));
};
})();
Aras.prototype.clientItemValidation = function Aras_clientItemValidation(itemTypeName, itemNd, breakOnFirstError, emptyPropertyWithDefaultValueCallback) {
var resultErrors = [];
var checkErrors = [];
//general checks for the item to be saved: all required parameters should be set
if (itemTypeName) {
checkErrors = this.checkItemForErrors(itemNd, null, null, breakOnFirstError, emptyPropertyWithDefaultValueCallback);
if (checkErrors.length > 0) {
resultErrors = resultErrors.concat(checkErrors);
if (breakOnFirstError) {
return resultErrors;
}
}
}
//special checks for relationships and related items
var newRelNodes = itemNd.selectNodes('Relationships/Item[@isDirty=\'1\' or @isTemp=\'1\']');
var iter;
for (iter = 0; iter < newRelNodes.length; iter++) {
checkErrors = this.checkItemForErrors(newRelNodes[iter], 'source_id', null, breakOnFirstError, emptyPropertyWithDefaultValueCallback);
if (checkErrors.length > 0) {
resultErrors = resultErrors.concat(checkErrors);
if (breakOnFirstError) {
return resultErrors;
}
}
}
var newRelatedNodes = itemNd.selectNodes('Relationships/Item/related_id/Item[@isDirty=\'1\' or @isTemp=\'1\']');
for (iter = 0; iter < newRelatedNodes.length; iter++) {
checkErrors = this.checkItemForErrors(newRelatedNodes[iter], 'source_id', null, breakOnFirstError, emptyPropertyWithDefaultValueCallback);
if (checkErrors.length > 0) {
resultErrors = resultErrors.concat(checkErrors);
if (breakOnFirstError) {
return resultErrors;
}
}
}
return resultErrors;
};
(function() {
function _saveItemExBefore(itemNd, confirmSuccess, doVersion) {
if (!itemNd) {
return null;
}
if (confirmSuccess === undefined || confirmSuccess === null) {
confirmSuccess = true;
}
if (doVersion === undefined || doVersion === null) {
doVersion = false;
}
var itemTypeName = itemNd.getAttribute('type');
var win = this.uiFindWindowEx2(itemNd);
//special checks for the item of ItemType type
if (itemTypeName == 'ItemType' && !this.checkItemType(itemNd, win)) {
return null;
}
var self = this;
var defaultFieldCheckCallback = function (itemNode, reqName, proplabel, defVal) {
var ask = self.confirm(self.getResource('', 'item_methods_ex.field_required_default_will_be_used', proplabel, defVal));
if (ask) {
self.setItemProperty(itemNode, reqName, defVal);
}
return {result: ask, message: ''};
};
var validationErrors = this.clientItemValidation(itemTypeName, itemNd, true, defaultFieldCheckCallback);
if (validationErrors.length > 0) {
if (validationErrors[0].message) {
this.AlertError(validationErrors[0].message, '', '', win);
}
return null;
}
var backupCopy = itemNd;
var oldParent = backupCopy.parentNode;
itemNd = itemNd.cloneNode(true);
this.prepareItem4Save(itemNd);
var isTemp = this.isTempEx(itemNd);
if (isTemp) {
itemNd.setAttribute('action', 'add');
this.setItemProperty(itemNd, 'locked_by_id', this.getCurrentUserID());
if (itemTypeName == 'RelationshipType') {
if (!itemNd.selectSingleNode('relationship_id/Item')) {
var rsItemNode = itemNd.selectSingleNode('relationship_id');
if (rsItemNode) {
var rs = this.getItemById('', rsItemNode.text, 0);
if (rs) {
rsItemNode.text = '';
rsItemNode.appendChild(rs.cloneNode(true));
}
}
}
var tmp001 = itemNd.selectSingleNode('relationship_id/Item');
if (tmp001 && this.getItemProperty(tmp001, 'name') === '') {
this.setItemProperty(tmp001, 'name', this.getItemProperty(itemNd, 'name'));
}
}
} else if (doVersion) {
itemNd.setAttribute('action', 'version');
} else {
itemNd.setAttribute('action', 'update');
}
var tempArray = [];
this.doCacheUpdate(true, itemNd, tempArray);
var statusMsg = '';
if (isTemp) {
statusMsg = this.getResource('', 'item_methods_ex.adding', itemTypeName);
} else if (doVersion) {
statusMsg = this.getResource('', 'item_methods_ex.versioning', itemTypeName);
} else {
statusMsg = this.getResource('', 'item_methods_ex.updating', itemTypeName);
}
return {
confirmSuccess: confirmSuccess,
itemTypeName: itemTypeName,
backupCopy: backupCopy,
statusMsg: statusMsg,
oldParent: oldParent,
tempArray: tempArray,
itemNd: itemNd,
win: win
};
}
function _saveItemAfter(res, params)
{
if (!res)
{
return null;
}
//alert("a");
var itemTypeName = params.itemTypeName;
var win = params.win;
var oldParent = params.oldParent;
var backupCopy = params.backupCopy;
var tempArray = params.tempArray;
var confirmSuccess = params.confirmSuccess;
var itemNd = params.itemNd;
var itemID = itemNd.getAttribute('id');
// alert(itemID);
res.setAttribute('levels', '0');
var newID = res.getAttribute('id');
this.updateInCacheEx(backupCopy, res);
var topWindow;
if (win && win.isTearOff)
{
if (win.updateItemsGrid)
{
win.updateItemsGrid(res);
}
topWindow = window.opener ? this.getMostTopWindowWithAras(window.opener) : null;
if (topWindow && topWindow.main)
{
if (itemTypeName == 'ItemType')
{
//alert("b");
//alert(itemID.split(';'));
//topWindow.updateTree(itemID.split(';'));
topWindow.updateTree("Administration");
}
else if (itemTypeName == 'Action')
{
topWindow.UpdateMenuAfterCacheReset(itemTypeName);
}
else if (itemTypeName == 'Report')
{
topWindow.UpdateMenuAfterCacheReset(itemTypeName);
}
else if (itemTypeName == 'SelfServiceReport')
{
if (topWindow.itemTypeName == 'MyReports')
{
topWindow.updateReports();
}
else
{
topWindow.UpdateMenuAfterCacheReset(itemTypeName);
}
}
}
}
else
{
topWindow = this.getMostTopWindowWithAras(window);
if (itemTypeName == 'ItemType')
{
//alert(itemID.split(';'));
topWindow.updateTree(itemID.split(';'));
}
else if (itemTypeName == 'Action')
{
topWindow.UpdateMenuAfterCacheReset(itemTypeName);
}
else if (itemTypeName == 'Report' || itemTypeName == 'SelfServiceReport')
{
topWindow.UpdateMenuAfterCacheReset(itemTypeName);
}
}
if (itemTypeName == 'RelationshipType') {
var relationship_id = this.getItemProperty(itemNd, 'relationship_id');
if (relationship_id) {
this.removeFromCache(relationship_id);
}
} else if (itemTypeName == 'ItemType') {
var oldItemTypeName = !this.isTempEx(itemNd) ? this.getItemTypeName(itemID) : null;
var item_name = (oldItemTypeName) ? oldItemTypeName : this.getItemProperty(itemNd, 'name');
this.deletePropertyFromObject(this.sGridsSetups, item_name);
}
if (oldParent) {
var tmpRes = oldParent.selectSingleNode('Item[@id="' + newID + '"]');
if (tmpRes === null && newID != itemID && oldParent.selectSingleNode('Item[@id="' + itemID + '"]') !== null) {
//possible when related item is versionable and relationship behavior is fixed
//when relationship still points to previous generation.
tmpRes = this.getFromCache(newID);
this.updateInCacheEx(tmpRes, res);
res = this.getFromCache(newID);
} else {
res = tmpRes;
}
} else {
res = this.getFromCache(newID);
}
if (!res) {
return null;
}
this.doCacheUpdate(false, itemNd, tempArray);
ClearDependenciesInMetadataCache(this, itemNd);
if (confirmSuccess) {
var keyed_name = this.getKeyedNameEx(res);
if (keyed_name && '' !== keyed_name) {
this.AlertSuccess(this.getResource('', 'item_methods_ex.item_saved_successfully', '\'' + keyed_name + '\' '), win);
} else {
this.AlertSuccess(this.getResource('', 'item_methods_ex.item_saved_successfully', ''), win);
}
}
params = this.newObject();
params.itemID = itemID;
params.itemNd = res;
this.fireEvent('ItemSave', params);
return res;
}
/*-- saveItemEx
*
* Method to save an item
* id = the id for the item to be saved
*
*/
Aras.prototype.saveItemEx = function Aras_saveItemEx(itemNd, confirmSuccess, doVersion) {
var params = _saveItemExBefore.call(this, itemNd, confirmSuccess, doVersion);
if (!params) {
return params;
}
var res = this.applyItemWithFilesCheck(params.itemNd, params.win, params.statusMsg, this.XPathResult('/Item'));
return _saveItemAfter.call(this, res, params);
};
Aras.prototype.saveItemExAsync = function Aras_saveItemExAsync(itemNd, confirmSuccess, doVersion) {
var params = _saveItemExBefore.call(this, itemNd, confirmSuccess, doVersion);
if (!params) {
return Promise.resolve(params);
}
return this.applyItemWithFilesCheckAsync(params.itemNd, params.win, params.statusMsg, this.XPathResult('/Item')).then(function (res) {
return _saveItemAfter.call(this, res, params);
}.bind(this));
};
})();
Aras.prototype.doCacheUpdate = function Aras_doCacheUpdate(prepare, itemNd, tempArray) {
var nodes;
var i;
if (prepare) {
nodes = itemNd.selectNodes('descendant-or-self::Item[@id and (@action="add" or @action="create")]');
for (i = 0; i < nodes.length; i++) {
tempArray.push(new Array(nodes[i].getAttribute('id'), nodes[i].getAttribute('type')));
}
} else {
for (i = 0; i < tempArray.length; i++) {
nodes = this.itemsCache.getItemsByXPath('/Innovator/Items//Item[@id="' + tempArray[i][0] + '" and (@action="add" or @action="create")]');
for (var o = 0; o < nodes.length; o++) {
nodes[o].setAttribute('action', 'skip');
nodes[o].removeAttribute('isTemp');
nodes[o].removeAttribute('isDirty');
}
if (i === 0) {
continue;
}
var itemID = tempArray[i][0];
}
}
};
Aras.prototype.downloadFile = function ArasDownloadFile(fileNd, preferredName) {
var fileURL = this.getFileURLEx(fileNd);
if (!fileURL) {
this.AlertError(this.getResource('', 'item_methods_ex.failed_download_file_url_empty'));
return false;
}
if (preferredName) {
this.vault.setLocalFileName(preferredName);
}
var isSucceeded = this.vault.downloadFile(fileURL);
if (!isSucceeded) {
this.AlertError(this.getResource('', 'item_methods_ex.failed_download_file'));
return false;
}
return true;
};
// === lockItemEx ====
// Method to lock the item passing the item object
// itemNode = the item
// ===================
Aras.prototype.lockItemEx = function Aras_lockItemEx(itemNode) {
var ownerWindow = this.uiFindWindowEx2(itemNode),
itemID = itemNode.getAttribute('id'),
itemTypeName = itemNode.getAttribute('type'),
itemType = this.getItemTypeDictionary(itemTypeName),
isRelationship = this.getItemProperty(itemType.node, 'is_relationship'),
isPolyItem = this.isPolymorphic(itemType.node);
if (isRelationship == '1' && this.isDirtyEx(itemNode)) {
var sourceNd = itemNode.selectSingleNode('../..');
if (sourceNd && this.isDirtyEx(sourceNd)) {
var itLabel = this.getItemProperty(itemType.node, 'label') || this.getItemProperty(itemType.node, 'name'),
param = {
aras: this,
buttons: {btnOK: this.getResource('', 'common.ok'), btnCancel: this.getResource('', 'common.cancel')},
defaultButton: 'btnCancel',
message: this.getResource('', 'item_methods_ex.locking_it_lose_changes', itLabel)
},
options = {dialogWidth: 300, dialogHeight: 150, center: true},
result;
if (window.showModalDialog) {
result = this.modalDialogHelper.show('DefaultModal', ownerWindow, param, options, 'groupChgsDialog.html');
} else {
result = window.confirm(param.message) ? 'btnYes' : 'btnCancel';
}
if (result == 'btnCancel') {
return null;
}
}
}
var statusId = this.showStatusMessage('status', this.getResource('', 'common.locking_item_type', itemTypeName), system_progressbar1_gif),
bodyStr = ' ',
requestResult = this.soapSend('ApplyItem', bodyStr),
returnedItem;
this.clearStatusMessage(statusId);
var faultCode = requestResult.getFaultCode();
if (faultCode !== 0 && faultCode !== '0') {
this.AlertError(requestResult, ownerWindow);
return null;
}
returnedItem = requestResult.results.selectSingleNode(this.XPathResult('/Item'));
if (returnedItem) {
var oldParent = itemNode.parentNode;
returnedItem.setAttribute('loadedPartialy', '0');
this.updateInCacheEx(itemNode, returnedItem);
if (oldParent) {
itemNode = oldParent.selectSingleNode('Item[@id="' + itemID + '"]') || oldParent.selectSingleNode('Item');
} else {
itemNode = this.getFromCache(itemID);
}
this.fireEvent('ItemLock', {itemID: itemNode.getAttribute('id'), itemNd: itemNode, newLockedValue: this.isLocked(itemNode)});
return itemNode;
} else {
this.AlertError(this.getResource('', 'item_methods_ex.failed_get_item_type_from_sever', itemTypeName), '', '', ownerWindow);
return null;
}
};
// === unlockItemEx ====
// Method to unlock the item passing the item object
// itemNode = the item
// =====================
Aras.prototype.unlockItemEx = function Aras_unlockItemEx(itemNode, saveChanges) {
var itemTypeName = itemNode.getAttribute('type'),
ownerWindow = this.uiFindWindowEx2(itemNode);
if (this.isTempEx(itemNode)) {
this.AlertError(this.getResource('', 'item_methods_ex.failed_unlock_item_type', itemTypeName), '', '', ownerWindow);
return null;
}
var itemType = this.getItemTypeDictionary(itemTypeName),
isPolyItem = (itemType && itemType.node) ? this.isPolymorphic(itemType.node) : false;
if (saveChanges === undefined) {
var isDirty = this.isDirtyEx(itemNode);
if (isDirty) {
var options = {dialogWidth: 400, dialogHeight: 200, center: true},
params = {
aras: this,
message: this.getResource('', 'item_methods_ex.unlocking_discard_your_changes', itemTypeName, this.getKeyedNameEx(itemNode)),
buttons: {
btnYes: this.getResource('', 'common.yes'),
btnSaveAndUnlock: this.getResource('', 'item_methods_ex.save_first'),
btnCancel: this.getResource('', 'common.cancel')
},
defaultButton: 'btnCancel'
},
returnedValue;
if (window.showModalDialog) {
returnedValue = this.modalDialogHelper.show('DefaultModal', ownerWindow, params, options, 'groupChgsDialog.html');
} else {
returnedValue = 'btnCancel';
if (window.confirm(this.getResource('', 'item_methods_ex.save_your_changes', itemTypeName, this.getKeyedNameEx(itemNode)))) {
returnedValue = 'btnSaveAndUnlock';
} else if (window.confirm(this.getResource('', 'item_methods_ex.unlocking_discard_your_changes', itemTypeName, this.getKeyedNameEx(itemNode)))) {
returnedValue = 'btnYes';
}
}
if (returnedValue == 'btnCancel') {
return null;
} else {
saveChanges = (returnedValue != 'btnYes');
}
}
}
if (saveChanges) {
itemNode = this.saveItemEx(itemNode);
if (!itemNode) {
return null;
}
}
var statusId = this.showStatusMessage('status', this.getResource('', 'item_methods_ex.unlocking_itemtype', itemTypeName), system_progressbar1_gif),
itemId = itemNode.getAttribute('id'),
lockedById = itemNode.selectSingleNode('locked_by_id'),
queryResult;
if (!lockedById) {
queryResult = this.soapSend('ApplyItem', ' ');
} else {
queryResult = this.soapSend('ApplyItem', ' ', '', saveChanges);
}
this.clearStatusMessage(statusId);
if (!queryResult.getFaultCode()) {
var resultItem = queryResult.results.selectSingleNode(this.XPathResult('/Item')),
newResult;
if (resultItem) {
resultItem.setAttribute('loadedPartialy', '0');
var oldParent = itemNode.parentNode;
this.updateInCacheEx(itemNode, resultItem);
this.updateFilesInCache(resultItem);
newResult = oldParent ? oldParent.selectSingleNode('Item[@id="' + itemId + '"]') : this.getFromCache(itemId);
resultItem = newResult || resultItem;
this.fireEvent('ItemLock', {itemID: resultItem.getAttribute('id'), itemNd: resultItem, newLockedValue: this.isLocked(resultItem)});
return resultItem;
} else {
this.AlertError(this.getResource('', 'item_methods_ex.failed_get_item_type_from_server', itemTypeName), '', '', ownerWindow);
return null;
}
} else {
this.AlertError(queryResult, ownerWindow);
return null;
}
};
Aras.prototype.updateFilesInCache = function Aras_updateFilesInCache(itemNd) {
var itemTypeName = itemNd.getAttribute('type'),
isDiscoverOnly = itemNd.getAttribute('discover_only') == '1';
if (itemTypeName != 'File' && !isDiscoverOnly) {
var itemType = this.getItemTypeForClient(itemTypeName).node,
fileProperties = this.getPropertiesOfTypeFile(itemType),
propertyName, fileId, fileNode,
queryItem, queryResult, i;
for (i = 0; i < fileProperties.length; i++) {
propertyName = this.getItemProperty(fileProperties[i], 'name');
fileId = this.getItemProperty(itemNd, propertyName);
if (fileId) {
this.removeFromCache(fileId);
queryItem = new this.getMostTopWindowWithAras(window).Item();
queryItem.setType('File');
queryItem.setAction('get');
queryItem.setID(fileId);
queryItem.setAttribute('select', 'filename,file_size,file_type,checkedout_path,comments,checksum,label,mimetype');
queryResult = queryItem.apply();
if (queryResult.isEmpty()) {
continue;
} else {
if (!queryResult.isError()) {
fileNode = queryResult.getItemByIndex(0).node;
this.updateInCache(fileNode);
} else {
this.AlertError(queryResult);
return;
}
}
}
}
}
};
Aras.prototype.purgeItemEx = function Aras_purgeItemEx(itemNd, silentMode) {
/*-- purgeItem
*
* Method to delete the latest version of the item (or the item if it's not versionable)
* itemNd -
* silentMode - flag to know if user confirmation is NOT needed
*
*/
return this.PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, 'purge');
};
Aras.prototype.deleteItemEx = function Aras_deleteItemEx(itemNd, silentMode) {
/*-- deleteItem
*
* Method to delete all versions of the item
* itemNd -
* silentMode - flag to know if user confirmation is NOT needed
*
*/
return this.PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, 'delete');
};
Aras.prototype.PurgeAndDeleteItem_CommonPartEx = function Aras_PurgeAndDeleteItem_CommonPartEx(itemNd, silentMode, purgeORdelete) {
/*-- PurgeAndDeleteItem_CommonPartEx
*
* This method is for ***internal purposes only***.
*
*/
if (silentMode === undefined) {
silentMode = false;
}
var ItemId = itemNd.getAttribute('id');
var ItemTypeName = itemNd.getAttribute('type');
//prepare
if (!silentMode && !this.Confirm_PurgeAndDeleteItem(ItemId, this.getKeyedNameEx(itemNd), purgeORdelete)) {
return false;
}
var DeletedItemTypeName;
var relationship_id;
if (!this.isTempEx(itemNd)) {
//save some information
if (ItemTypeName == 'ItemType') {
if (this.getItemProperty(itemNd, 'is_relationship') == '1') {
relationship_id = ItemId;
}
DeletedItemTypeName = this.getItemProperty(itemNd, 'name');
} else if (ItemTypeName == 'RelationshipType') {
relationship_id = this.getItemProperty(itemNd, 'relationship_id');
DeletedItemTypeName = this.getItemProperty(itemNd, 'name');
}
//delete
if (!this.SendSoap_PurgeAndDeleteItem(ItemTypeName, ItemId, purgeORdelete)) {
return false;
}
}
itemNd.setAttribute('action', 'skip');
//remove node from parent
var tmpNd = itemNd.parentNode;
if (tmpNd) {
tmpNd.removeChild(itemNd);
}
//delete all dependent stuff
this.RemoveGarbage_PurgeAndDeleteItem(ItemTypeName, ItemId, DeletedItemTypeName, relationship_id);
this.MetadataCache.RemoveItemById(ItemId);
return true;
};
Aras.prototype.getKeyedNameEx = function Aras_getKeyedNameEx(itemNd) {
/*----------------------------------------
* getKeyedNameEx
*
* Purpose: build and return keyed name of an Item.
*
* Arguments:
* itemNd - xml node of Item to get keyed name of.
*/
var res = '';
if (itemNd.nodeName != 'Item') {
return res;
}
if ((!this.isDirtyEx(itemNd)) && (!this.isTempEx(itemNd))) {
res = itemNd.getAttribute('keyed_name');
if (res) {
return res;
}
res = this.getItemProperty(itemNd, 'keyed_name');
if (res !== '') {
return res;
}
}
var itemTypeName = itemNd.getAttribute('type');
res = itemNd.getAttribute('id');
var itemType = this.getItemTypeDictionary(itemTypeName);
if (!itemType) {
return res;
}
var relationshipItems = itemType.node.selectNodes('Relationships/Item[@type="Property"]');
var tmpArr = []; //pairs keyOrder -> propValue
var counter = 0;
var i;
for (i = 0; i < relationshipItems.length; i++) {
var propNd = relationshipItems[i];
var propName = this.getItemProperty(propNd, 'name');
if (propName === '') {
continue;
}
var keyOrder = this.getItemProperty(propNd, 'keyed_name_order');
if (keyOrder === '') {
continue;
}
var node = itemNd.selectSingleNode(propName);
if (!node || node.childNodes.length != 1) {
continue;
}
var txt = '';
if (node.firstChild.nodeType == 1) {//if nested Item
txt = this.getKeyedNameEx(node.firstChild);
} else {
txt = node.text;
}
if (txt !== '') {
tmpArr[counter] = new Array(keyOrder, txt);
counter++;
}
}
if (tmpArr.length > 0) {
tmpArr = tmpArr.sort(keyedNameSorter);
res = tmpArr[0][1];
for (i = 1; i < tmpArr.length; i++) {
res += ' ' + tmpArr[i][1];
}
}
return res;
};
Aras.prototype.getKeyedNameAttribute = function(node, element) {
if (!node) {
return;
}
var value;
var tmpNd = node.selectSingleNode(element);
if (tmpNd) {
value = tmpNd.getAttribute('keyed_name');
if (!value) {
value = '';
}
} else {
value = '';
}
return value;
};
function keyedNameSorter(a, b) {
var s1 = parseInt(a[0]);
if (isNaN(s1)) {
return 1;
}
var s2 = parseInt(b[0]);
if (isNaN(s2)) {
return -1;
}
if (s1 < s2) {
return -1;
} else if (s1 == s2) {
return 0;
} else {
return 1;
}
}
/*-- getItemRelationshipsEx
*
* Method to
*
*
*/
Aras.prototype.getItemRelationshipsEx = function(itemNd, relsName, pageSize, page, body, forceReplaceByItemFromServer) {
if (!(itemNd && relsName)) {
return null;
}
if (pageSize === undefined || pageSize === null) {
pageSize = '';
}
if (page === undefined || page === null) {
page = '';
}
if (body === undefined || body === null) {
body = '';
}
if (forceReplaceByItemFromServer === undefined || forceReplaceByItemFromServer === null) {
forceReplaceByItemFromServer = false;
}
var itemID = itemNd.getAttribute('id');
var itemTypeName = itemNd.getAttribute('type');
var res = null;
if (!forceReplaceByItemFromServer && (pageSize == -1 || this.isTempID(itemID) || (itemNd.getAttribute('levels') && parseInt(itemNd.getAttribute('levels')) > 0))) {
if (!isNaN(parseInt(pageSize)) && parseInt(pageSize) > 0 && !isNaN(parseInt(page)) && parseInt(page) > -1) {
res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '" and @page="' + page + '"]');
if (res && res.length == pageSize) {
return res;
}
} else {
res = itemNd.selectNodes('Relationships/Item[@type="' + relsName + '"]');
if (res && res.length > 0) {
return res;
}
}
}
var bodyStr = ' ';
} else {
bodyStr += '>' + body + ' ';
}
res = this.soapSend('ApplyItem', bodyStr);
var faultCode = res.getFaultCode();
if (faultCode !== 0 && faultCode !== '0') {
this.AlertError(res);
return null;
}
if (!itemNd.selectSingleNode('Relationships')) {
this.createXmlElement('Relationships', itemNd);
}
var rels = res.results.selectNodes(this.XPathResult('/Item[@type="' + relsName + '"]'));
var itemRels = itemNd.selectSingleNode('Relationships');
var idsStr = '';
for (var i = 0; i < rels.length; i++) {
var rel = rels[i].cloneNode(true);
var relId = rel.getAttribute('id');
if (i > 0) {
idsStr += ' or ';
}
idsStr += '@id="' + relId + '"';
var prevRel = itemRels.selectSingleNode('Item[@type="' + relsName + '" and @id="' + relId + '"]');
if (prevRel) {
if (forceReplaceByItemFromServer) {
// By some reason the previous implementation did not replaced existing on the node
// relationships with the new relationships obtained from the server but rather
// just removed some attributes on them (like "pagesize", etc.). From other side those
// relationships that don't exist on the 'itemNd' are added to it. This is wrong as
// the newly obtained relationships even if they already exist on 'itemNd' might have
// some properties that are different in db from what is in the client memory.
// NOTE: the fix will break the case when the client changes some relationship properties
// in memory and then calls this method expecting that these properties will stay unchanged,
// but: a) this method seems to be called only from getFileURLEx(..); b) if the above
// behavior is expected then another method is probably required which must be called
// something like 'mergeRelationships'.
// by Andrey Knourenko
itemRels.removeChild(prevRel);
} else {
this.mergeItem(prevRel, rel);
continue;
}
}
itemRels.appendChild(rel);
}
itemNd.setAttribute('levels', '0');
if (idsStr === '') {
return null;
}
res = itemRels.selectNodes('Item[@type="' + relsName + '" and (' + idsStr + ')]');
return res;
};
/*-- getItemLastVersionEx
*
* Method to load the latest version for the item
* itemTypeName = the ItemType name
* itemId = the id for the item
*
*/
Aras.prototype.getItemLastVersionEx = function(itemNd) {
var res = this.soapSend('ApplyItem', ' ');
var faultCode = res.getFaultCode();
if (faultCode !== 0 && faultCode !== '0') {
return null;
}
res = res.results.selectSingleNode(this.XPathResult('/Item'));
if (!res) {
return null;
}
itemNd.parentNode.replaceChild(res, itemNd);
return res;
}; //getItemLastVersionEx
Aras.prototype.downloadItemFiles = function Aras_downloadItemFiles(itemNd) {
/*
this method is for internal use *** only ***
*/
if (!itemNd) {
return false;
}
var itemTypeName = itemNd.getAttribute('type');
var itemType = this.getItemTypeForClient(itemTypeName).node;
var fileProps = this.getPropertiesOfTypeFile(itemType);
for (var i = 0; i < fileProps.length; i++) {
var propNm = this.getItemProperty(fileProps[i], 'name');
var fileNd = itemNd.selectSingleNode(propNm + '/Item');
if (!fileNd) {
var fileID = this.getItemProperty(itemNd, propNm);
if (!fileID) {
continue;
}
fileNd = this.getItemFromServer('File', fileID, 'filename').node;
}
if (!fileNd) {
continue;
}
this.downloadFile(fileNd);
}
return true;
};
Aras.prototype.promoteEx = function Aras_promoteEx(itemNd, stateName, comments, soapController) {
if (!itemNd) {
return null;
}
var itemID = itemNd.getAttribute('id');
var itemTypeName = itemNd.getAttribute('type');
var promoteParams = {
typeName: itemTypeName,
id: itemID,
stateName: stateName,
comments: comments
};
var res = this.promoteItem_implementation(promoteParams, soapController);
if (!res) {
return null;
}
var oldParent = itemNd.parentNode;
this.updateInCacheEx(itemNd, res);
if (oldParent) {
res = oldParent.selectSingleNode('Item[@id="' + itemID + '"]');
} else {
res = this.getFromCache(itemID);
}
var params = this.newObject();
params.itemID = res.getAttribute('id');
params.itemNd = res;
this.fireEvent('ItemSave', params);
return res;
};
Aras.prototype.getFileURLEx = function Aras_getFileURLEx(itemNd) {
/*
* Private method that returns 'Located' pointing to the vault in which the
* specified file resides. The vault is selected by the following algorithm:
* - if file is not stale in the default vault of the current user then return this vault
* - else return the first vault in which the file is not stale
* NOTE: file is called 'not stale' in vault if 'Located' referencing the vault has
* the maximum value of property 'file_version' among other 'Located' of the same file.
*/
function getLocatedForFile(aras, itemNd) {
var fitem = aras.newIOMItem();
fitem.loadAML(itemNd.xml);
var all_located = fitem.getRelationships('Located');
// First find the max 'file_version' among all 'Located' rels
var maxv = 0;
var lcount = all_located.getItemCount();
var i;
var located;
var file_version;
for (i = 0; i < lcount; i++) {
located = all_located.getItemByIndex(i);
file_version = located.getProperty('file_version') * 1;
if (file_version > maxv) {
maxv = file_version;
}
}
var sorted_located = getSortedLocatedList(aras, fitem, all_located);
// Now go through the sorted list and return first non-stale vault
for (i = 0; i < sorted_located.length; i++) {
located = sorted_located[i];
file_version = located.getProperty('file_version') * 1;
if (file_version == maxv) {
return located.node;
}
}
// It should never reach this point as at least one of vaults has non-stale file.
return null;
}
// Build a list of 'Located' sorted by the priorities of vaults that they reference.
// Sorting is done based on the 'ReadPriority' relationships of the current user + the
// default vault of the user + remaining vaults.
function getSortedLocatedList(aras, fitem, all_located) {
var lcount = all_located.getItemCount();
var sorted_located = [];
// Get all required information (default vault; etc.) for the current user
var aml = '- ' +
'
' + aras.getUserID() + ' ' +
' ' +
' - ' +
'
' +
' ';
var ureq = aras.newIOMItem();
ureq.loadAML(aml);
var uresult = ureq.apply();
if (uresult.isError()) {
throw new Error(1, uresult.getErrorString());
}
// Note that because the above AML has 'orderBy' the 'all_rps' collection is sorted
// by ReadPriority.priority.
var all_rps = uresult.getRelationships('ReadPriority');
var rpcount = all_rps.getItemCount();
var i;
var l;
var located;
for (i = 0; i < rpcount; i++) {
var vault = all_rps.getItemByIndex(i).getRelatedItem();
// If the file is in the vault from the "ReadPriority" then add 'Located' that references
// the vault to the sorted list.
for (l = 0; l < lcount; l++) {
located = all_located.getItemByIndex(l);
if (vault.getID() == located.getRelatedItem().getID()) {
sorted_located[sorted_located.length] = located;
break;
}
}
}
// Now append the 'Located' to the default vault to the list if it's not there yet
// (providing that the file is in the default vault).
var dvfound = false;
var default_vault = uresult.getPropertyItem('default_vault');
for (i = 0; i < sorted_located.length; i++) {
if (sorted_located[i].getRelatedItem().getID() == default_vault.getID()) {
dvfound = true;
break;
}
}
if (!dvfound) {
for (i = 0; i < lcount; i++) {
located = all_located.getItemByIndex(i);
if (default_vault.getID() == located.getRelatedItem().getID()) {
sorted_located[sorted_located.length] = located;
break;
}
}
}
// Finally append 'Located' to all remaining vaults that the file resides in but that are
// not in the sorted list yet.
for (i = 0; i < lcount; i++) {
located = all_located.getItemByIndex(i);
var vfound = false;
for (l = 0; l < sorted_located.length; l++) {
if (sorted_located[l].getID() == located.getID()) {
vfound = true;
break;
}
}
if (!vfound) {
sorted_located[sorted_located.length] = located;
}
}
return sorted_located;
}
/*----------------------------------------
* getFileURLEx
*
* Purpose:
* get file URL using the following algorithm:
* - take the default vault of the current user unless the file does not exist or stale in the vault
* - otherwise take the first vault in which the file is not stale
*
* Arguments:
* itemNd - xml node of the File to be downloaded
*
*/
this.getItemRelationshipsEx(itemNd, 'Located', undefined, undefined, undefined, true);
var locatedNd = getLocatedForFile(this, itemNd);
if (!locatedNd) {
this.AlertError(this.getResource('', 'item_methods_ex.failed_get_file_vault_could_not_be_located'));
return '';
}
var vaultNode = locatedNd.selectSingleNode('related_id/Item[@type="Vault"]');
var vault_id = '';
if (!vaultNode) {
vault_id = locatedNd.selectSingleNode('related_id').text;
vaultNode = this.getItemById('Vault', vault_id, 0);
} else {
vault_id = vaultNode.getAttribute('id');
}
var vaultServerURL = vaultNode.selectSingleNode('vault_url').text;
if (vaultServerURL === '') {
return '';
}
vaultServerURL = this.TransformVaultServerURL(vaultServerURL);
var fileID = itemNd.getAttribute('id');
var fileName = this.getItemProperty(itemNd, 'filename');
var fileURL = vaultServerURL +
'?dbName=' + encodeURIComponent(this.getDatabase()) +
'&fileID=' + encodeURIComponent(fileID) +
'&fileName=' + encodeURIComponent(fileName) +
'&vaultId=' + vault_id;
return fileURL;
};
Aras.prototype.replacePolyItemNodeWithNativeItem = function Aras_replacePolyItemNodeWithNativeItem(ritem) {
if (!(ritem && ritem.parentNode)) {
this.AlertError('Item is null or doesn\'t have parent item.');
return ritem;
}
var typeId = ritem.getAttribute('typeId');
var relatedItemType = this.getItemTypeForClient(typeId, 'id').node;
if (!relatedItemType) {
this.AlertError('Can\'t get type of related item.');
return ritem;
}
if (this.isPolymorphic(relatedItemType)) {
var nativeRelatedITID = this.getItemProperty(ritem, 'itemtype');
var relatedItemNd = this.getItemTypeForClient(nativeRelatedITID, 'id').node;
if (!relatedItemNd) {
this.AlertError('Can\'t get native item type of polymorphic item.');
return ritem;
}
var nativeRelated = this.getItemFromServer(this.getItemProperty(relatedItemNd, 'name'), ritem.getAttribute('id'), '*').node;
if (nativeRelated) {
ritem.parentNode.replaceChild(nativeRelated, ritem);
return nativeRelated;
}
}
return ritem;
};
/** itemtype_methods.js **/
// © Copyright by Aras Corporation, 2004-2008.
/*
* The ItemType methods extension for the Aras Object.
*
*/
/*-- getItemTypeProperties
*
* Method to get the properties for the ItemType
* itemType = the itemType
*
*/
Aras.prototype.getItemTypeProperties = function(itemType) {
if (!itemType) {
return;
}
with (this) {
return itemType.selectNodes('Relationships/Item[@type="Property"]');
}
};
Aras.prototype.rebuildView = function(viewId) {
if (!viewId) {
this.AlertError(this.getResource('', 'itemtype_methods.view_to_rebuild_not_specified'), '', '');
return false;
}
with (this) {
var statusId = showStatusMessage('status', this.getResource('', 'itemtype_methods.rebuilding_view'), '../images/Progress.gif');
var res = soapSend('RebuildView', ' ');
clearStatusMessage(statusId);
if (res.getFaultCode() != 0) {
this.AlertError(res);
return false;
}
var formNd = res.results.selectSingleNode('//Item[@type="Form"]');
if (!formNd) {
return false;
}
var oldView = itemsCache.getItemByXPath('/Innovator/Items/Item[@type="ItemType"]/Relationships/Item[@type="View" and @id="' + viewId + '"]');
itemsCache.addItem(formNd);
var formId = formNd.getAttribute('id');
var newView = getItem('View', 'related_id/Item/@id="' + formId + '"', '' + formId + ' ', 0);
if (oldView) {
oldView.parentNode.replaceChild(newView, oldView);
}
if (uiFindWindowEx(viewId)) {
uiReShowItemEx(viewId, newView);
}
}
return true;
};
Aras.prototype.isPolymorphic = function(itemType) {
var implementationType = this.getItemProperty(itemType, 'implementation_type');
return (implementationType == 'polymorphic');
};
Aras.prototype.getMorphaeList = function(itemType) {
var morphae = itemType.selectNodes('Relationships/Item[@type=\'Morphae\']/related_id/Item');
return _fillItemTypeList(morphae, this);
};
Aras.prototype.getPolymorphicsWhereUsedAsPolySource = function(itemTypeId) {
var polyItems = this.applyItem(
'- ' +
'
' +
'- ' +
'
' + itemTypeId + ' ' +
' ' +
' ' +
' ');
if (polyItems) {
var tmpDoc = this.createXMLDocument();
tmpDoc.loadXML(polyItems);
polyItems = tmpDoc.selectNodes('Result/Item[@type=\'ItemType\']');
} else {
return [];
}
return _fillItemTypeList(polyItems, this);
};
function _fillItemTypeList(nodes, aras) {
var result = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var id = node.getAttribute('id');
var name = aras.getItemProperty(node, 'name');
var label = aras.getItemProperty(node, 'label');
if (label === null || label === '') {
label = name;
}
result.push({id: id, name: name, label: label});
}
return result;
}
/** ui_methods.js **/
// (c) Copyright by Aras Corporation, 2004-2011.
///--- User Interface methods ---///
/*
* uiShowItem
*
* parameters:
* 1) itemTypeName - may be empty string if item is in client cache
* 2) itemID - obligatory
* 3) viewMode - 'tab view' or 'openFile'
* if not specified aras.getVariable('viewMode') is used
* 4) isTearOff - true or false, if not specified aras.getVariable('TearOff') is used
*/
Aras.prototype.uiShowItem = function (itemTypeName, itemID, viewMode) {
if (!itemID) return false;
viewMode = viewMode || "tab view";
var itemNd = this.getItemById(itemTypeName, itemID, 0, undefined, "*");
if (!itemNd) return false;
return this.uiShowItemEx(itemNd, viewMode);
};
/*
* uiReShowItem
*
* parameters:
* 1) oldItemId- old id of item to be shown
* 2) itemId - id of item to be shown //usually itemId==oldItemId
* 2) editMode - 'view' or 'edit'
* 3) viewMode - 'tab view', ' or 'openFile'
* 4) isTearOff- true or false.
*/
Aras.prototype.uiReShowItem = function (oldItemId, itemId, editMode, viewMode) {
if (!oldItemId || !itemId) return false;
var itemNd = this.getItemById('', itemId, 0);
if (!itemNd) return false;
if (editMode === undefined || editMode.search(/^view$|^edit$/) === -1) {
if (this.isTempID(itemId) || this.getNodeElement(itemNd, 'locked_by_id') === this.getCurrentUserID())
editMode = 'edit';
else editMode = 'view';
}
viewMode = viewMode || "tab view";
return this.uiReShowItemEx(oldItemId, itemNd, viewMode);
};
Aras.prototype.uiViewXMLInFrame = function Aras_uiViewXMLInFrame(frame, xmldoc, expandNodes) {
if (!frame) return;
var xsldoc = this.createXMLDocument();
var baseUrl = this.getBaseURL();
xsldoc.load(baseUrl + '/styles/default.xsl');
try {
//TODO: there should be a better way to check if method setProperty is supported on xsldoc
xsldoc.setProperty("SelectionNamespaces", 'xmlns:xsl="http://www.w3.org/1999/XSL/Transform"');
}
catch (excep) {
}
xsldoc.selectSingleNode("./xsl:stylesheet/xsl:param").setAttribute("select", "boolean('" + expandNodes + "')");
frame.document.write(xmldoc.transformNode(xsldoc));
};
Aras.prototype.uiViewXMLstringInFrame = function Aras_uiViewXMLstringInFrame(frame, string, expandNodes) {
if (!frame) return;
var xmldoc = this.createXMLDocument();
xmldoc.loadXML(string);
this.uiViewXMLInFrame(frame, xmldoc, expandNodes);
};
Aras.prototype.uiFieldGetValue = function (uiField) {
var uiForm = uiField.form;
var name = uiField.name;
var type = uiField.type;
var value = null,
i;
if (uiField.field_type === 'item') value = uiField.internal_value;
else if (type.search(/^text|^hidden$/) === 0) {
if (uiField.internal_value) value = uiField.internal_value;
else value = uiField.value;
}
else if (type === 'password') {
if (uiField.pwdChanged === 1) value = calcMD5(uiField.value);
else value = uiField.internal_value;
}
else if (type === 'checkbox') value = (uiField.checked) ? 1 : 0;
else if (type === 'select-one') {
if (uiField.selectedIndex !== -1) value = uiField.options[uiField.selectedIndex].value;
}
else if (type === 'radio') {///SNNicky: check!!!!!
value = '';
for (i = 0; i < uiForm[name].length; i++) {
if (uiForm[name][i].checked) {
value = uiForm[name][i].value;
break;
}
}
}
else if (type === 'checkbox_group') {
value = '';
for (i = 0; i < uiForm[name].length; i++) {
if (uiForm[name][i].checked) {
if (value !== '') value += ',';
value += uiForm[name][i].value;
}
}
}
this.AlertError(name + ":" + value, "", ""); //what does this do??
return value;
};
Aras.prototype.getvisiblePropsForItemType = function Aras_getVisiblePropsForItemType(currItemType) {
var itemTypeName = this.getItemProperty(currItemType, 'name');
var itemTypeId = currItemType.getAttribute('id');
var nodes_tmp = [];
var cols = this.getPreferenceItemProperty("Core_GlobalLayout", null, "col_order"),
i;
var visiblePropNds = currItemType.selectNodes(this.getVisiblePropertiesXPath(itemTypeName));
if (cols) {
cols = cols.split(';');
if (visiblePropNds.length === cols.length || visiblePropNds.length + 1 === cols.length) {
for (i = 0; i < visiblePropNds.length; i++) {
var propNm = this.getItemProperty(visiblePropNds[i], 'name');
for (var j = 0; j < cols.length; j++) {
if ((propNm + "_D") === cols[j]) {
nodes_tmp[j] = visiblePropNds[i];
break;
}
}
if (j === cols.length) {
cols = null;
break;
}
}
}
else {
cols = null;
}
}
if (!cols) {
visiblePropNds = this.sortProperties(visiblePropNds);
}
else {
visiblePropNds = [];
for (i = 0; i < nodes_tmp.length; i++) {
if (nodes_tmp[i] !== undefined)
visiblePropNds.push(nodes_tmp[i]);
}
}
return visiblePropNds;
};
Aras.prototype.uiInitItemsGridSetups = function Aras_uiInitItemsGridSetups(currItemType, visibleProps) {
var itemTypeName = this.getItemProperty(currItemType, 'name');
var itemTypeId = currItemType.getAttribute('id'),
i;
if (!itemTypeName) return null;
var self = this;
// var _itemTypeName_ = itemTypeName.replace(/\s/g, '_');
var varsHash = {};
var gridSetups = this.sGridsSetups[itemTypeName];
if (!gridSetups) {
gridSetups = this.newObject();
this.sGridsSetups[itemTypeName] = gridSetups;
}
var colWidths = this.getPreferenceItemProperty('Core_ItemGridLayout', itemTypeId, 'col_widths');
var colOrder = this.getPreferenceItemProperty('Core_ItemGridLayout', itemTypeId, 'col_order');
var flg = ((colWidths === null || colWidths === "") ||
(colOrder === null || colOrder === "") ||
(colWidths.split(";").length !== colOrder.split(";").length));
function CheckCorrectColumnsInfo(arr, suffix) {
if (!arr) return;
for (var i = 0; i < arr.length; i++) {
var colNm = self.getItemProperty(arr[i], "name") + "_" + suffix;
var re = new RegExp("(^|;)" + colNm + "(;|$)");
if (colOrder.search(re) === -1) {
flg = true;
break;
}
colOrder = colOrder.replace(re, "$1$2");
}
}
if (!flg) {
//check if already saved setups are valid
colOrder = colOrder.replace(/(^|;)L($|;)/, "$1$2");
if (!flg) CheckCorrectColumnsInfo(visibleProps, "D");
if (!flg) {
colOrder = colOrder.replace(/;/g, "");
if (colOrder !== "") flg = true;
}
}
if (flg) {
colOrder = this.newArray();
colWidths = this.newArray();
colOrder[0] = "L";
colWidths[0] = 24;
for (i = 0; i < visibleProps.length; i++) {
var prop = visibleProps[i];
var name = this.getItemProperty(prop, "name") + "_D";
var width = parseInt(this.getItemProperty(prop, "column_width"));
if (isNaN(width) || width === 0) width = 100;
colOrder.push(name);
colWidths.push(width);
}
varsHash.col_widths = colWidths.join(";");
varsHash.col_order = colOrder.join(";");
}
else {
colWidths = colWidths.split(';');
flg = false;
//check for zero-width columns
for (i = 0; i < colWidths.length; i++) {
var newVal = parseInt(colWidths[i]);
if (isNaN(newVal) || newVal < 0) {
newVal = (i === 0 ? 24 : parseInt(this.getItemProperty(visibleProps[i - 1], 'column_width')));
if (isNaN(newVal) || newVal <= 0) newVal = 100;
colWidths[i] = newVal;
flg = true;
}
}
if (flg) {
varsHash.col_widths = colWidths.join(";");
}
}
this.setPreferenceItemProperties("Core_ItemGridLayout", itemTypeId, varsHash);
};
Aras.prototype.uiInitRelationshipsGridSetups = function Aras_uiInitRelationshipsGridSetups(relationshiptypeID, Dprops, Rprops, grid_view) {
if (!grid_view) {
grid_view = "left";
}
var self = this,
prop,
i;
var colWidths = this.getPreferenceItemProperty('Core_RelGridLayout', relationshiptypeID, 'col_widths');
var colOrder = this.getPreferenceItemProperty('Core_RelGridLayout', relationshiptypeID, 'col_order');
var flg = ((colWidths === null || colWidths === "") || (colOrder === null || colOrder === "") || (colWidths.split(";").length !== colOrder.split(";").length));
function CheckCorrectColumnsInfo(arr, suffix) {
if (!arr) return;
for (var i = 0; i < arr.length; i++) {
var colNm = self.getItemProperty(arr[i], "name") + "_" + suffix;
var re = new RegExp("(^|;)" + colNm + "(;|$)");
if (colOrder.search(re) === -1) {
flg = true;
break;
}
colOrder = colOrder.replace(re, "$1$2");
}
}
function getColumnDefaultWidth(colNum) {
var colNm = colOrder[colNum];
if (colNm === "L") return 24;
var DR = colNm.substr(colNm.length - 1);
var propNm = colNm.substr(0, colNm.length - 2);
var propArr = null;
if (DR === "D") propArr = Dprops;
else if (DR === "R") propArr = Rprops;
if (propArr) {
for (var i = 0; i < propArr.length; i++) {
var prop = propArr[i];
if (self.getItemProperty(prop, "name") === propNm) {
var column_width = parseInt(self.getItemProperty(prop, "column_width"));
if (isNaN(column_width)) column_width = 100;
return column_width;
}
}
}
return 100;
}
if (!flg) {
//check if already saved setups are valid
if (Rprops) colOrder = colOrder.replace(/(^|;)L($|;)/, "$1$2");
if (!flg) CheckCorrectColumnsInfo(Dprops, "D");
if (!flg) CheckCorrectColumnsInfo(Rprops, "R");
if (!flg) {
colOrder = colOrder.replace(/;/g, "");
if (colOrder !== "") flg = true;
}
if (!flg) {
colOrder = this.getPreferenceItemProperty('Core_RelGridLayout', relationshiptypeID, "col_order");
colWidths = colWidths.split(';');
flg = false;
//check for zero-width columns
for (i = 0; i < colWidths.length; i++) {
var newVal = parseInt(colWidths[i]);
if (isNaN(newVal) || newVal < 0) {
newVal = getColumnDefaultWidth(i);
colWidths[i] = newVal;
flg = true;
}
}
if (flg) this.setPreferenceItemProperties("Core_RelGridLayout", relationshiptypeID, { col_widths: colWidths.join(";") });
return;
}
}
colOrder = this.newArray();
colWidths = this.newArray();
if (Rprops) {
colOrder[0] = "L";
colWidths[0] = 24;
}
// +++ sort columns
var Dpriority = 0, Rpriority = 0;
if (grid_view === "left") {
//related item goes first
Dpriority = 1;
Rpriority = 0;
}
else if (grid_view === "intermix") {
Dpriority = 0;
Rpriority = 0;
}
else {
Dpriority = 0;
Rpriority = 1;
}
var allPropsInfoArr = [];
if (Dprops) {
for (i = 0; i < Dprops.length; i++) {
prop = Dprops[i];
allPropsInfoArr.push(
{
name: this.getItemProperty(prop, "name") + "_D",
width: this.getItemProperty(prop, "column_width"),
sort_order: this.getItemProperty(prop, "sort_order"),
default_search: this.getItemProperty(prop, "default_search"),
priority: Dpriority
});
}
}
if (Rprops) {
for (i = 0; i < Rprops.length; i++) {
prop = Rprops[i];
allPropsInfoArr.push(
{
name: this.getItemProperty(prop, "name") + "_R",
width: this.getItemProperty(prop, "column_width"),
sort_order: this.getItemProperty(prop, "sort_order"),
default_search: this.getItemProperty(prop, "default_search"),
priority: Rpriority
});
}
}
function sorterF(p1, p2) {
var c1 = parseInt(p1.priority);
var c2 = parseInt(p2.priority);
if (c1 < c2) return -1;
else if (c2 < c1) return 1;
else {
c1 = parseInt(p1.sort_order);
c2 = parseInt(p2.sort_order);
if (isNaN(c2)) return -1;
if (isNaN(c1)) return 1;
if (c1 < c2) return -1;
else if (c2 < c1) return 1;
else {
c1 = p1.name;
c2 = p2.name;
if (c1 < c2) return -1;
else if (c2 < c1) return 1;
else return 0;
}
}
}
allPropsInfoArr = allPropsInfoArr.sort(sorterF);
// --- sort columns
for (i = 0; i < allPropsInfoArr.length; i++) {
colOrder.push(allPropsInfoArr[i].name);
var width = parseInt(allPropsInfoArr[i].width);
if (isNaN(width)) width = 100;
colWidths.push(width);
}
this.setPreferenceItemProperties("Core_RelGridLayout", relationshiptypeID, { col_widths: colWidths.join(";"), col_order: colOrder.join(";") });
};
Aras.prototype.uiToggleCheckbox = function (uiField) {
uiField.checked = uiField.checked ? false : true;
};
Aras.prototype.uiGenerateGridXML = function Aras_uiGenerateGridXML(inDom, Dprops, Rprops, typeID, params, getCached) {
var key = this.MetadataCache.CreateCacheKey("uiGenerateGridXML", typeID);
if (params) {
for (var k in params) {
//k can be undefined in IE9 if one of param keyes was empty string, i.e. params[""] = ""
//evaluating value by index: params[""] gives right value, but evaluating it with 'for' gives undefined value.
if (k) {
var additionalParam = k;
if (params[k]) additionalParam += "=" + params[k];
key.push(additionalParam);
}
}
}
var xsl = this.MetadataCache.GetItem(key);
if (xsl)
xsl = xsl.content;
var mainArasObj = this.findMainArasObject();
if (xsl && (getCached === undefined || getCached === true)) {
}
else {
var sXsl = this.uiGenerateGridXSLT(Dprops, Rprops, params, typeID);
xsl = mainArasObj.createXMLDocument();
xsl.loadXML(sXsl);
var itemTypeNd = this.getItemTypeNodeForClient(typeID, "id");
this.MetadataCache.SetItem(key, this.IomFactory.CreateCacheableContainer(xsl, itemTypeNd));
}
var res = inDom.transformNode(xsl);
//replaces VaultURL by FullFileURL
var self = this;
var FixVaultUrl = function (str, srcTag, vaultPrefix, fileId, fullStr) {
var fileUrl = self.IomInnovator.getFileUrl(fileId, self.Enums.UrlType.SecurityToken);
fileUrl = self.browserHelper.escapeUrl(fileUrl);
return srcTag + fileUrl + '"';
};
//replaces all "src" attributes starting with "vault:///"
var FixImageCellSrc = function (str, offsetPos, fullStr) {
return str.replace(/(src=")(vault:\/\/\/\?fileid\=)([^"]*)"/i, FixVaultUrl);
};
//search all elements with attribute fdt="image"
var resultXML = res.replace(/ ]*?>.*?<\/td>/gi, FixImageCellSrc);
//if font-size property exist we should limit cell height by line-height property
resultXML = resultXML.replace(/( ]*? css=.*?)(font-size)/g, "$1line-height:15px; $2");
return resultXML;
};
Aras.prototype.uiPrepareTableWithColumns = function Aras_uiPrepareTableWithColumns(inDom, columnObjects) {
//columnObjects: {name, order, width}
this.uiPrepareDOM4GridXSLT(inDom);
var tableNd = inDom.selectSingleNode(this.XPathResult("/table"));
tableNd.setAttribute("editable", "false");
var columns = tableNd.selectSingleNode("columns");
var inputrow = tableNd.selectSingleNode("inputrow");
// make inputrow invisible by default.
inputrow.setAttribute("visible", "false");
for (var col in columnObjects) {
var columnObject = columnObjects[col];
var column = inDom.createElement("column");
column.setAttribute("name", columnObject.name);
column.setAttribute("order", columnObject.order);
column.setAttribute("width", columnObject.width);
columns.appendChild(column);
var td = inDom.createElement("td");
inputrow.appendChild(td);
}
};
Aras.prototype.uiPrepareDOM4XSLT = function Aras_uiPrepareDOM4XSLT(inDom, itemTypeID, RTorITPrefix, colWidths, colOrder) {
var prefTp = GetPrefixItemTypeName(RTorITPrefix);
var colWidthsArr = colWidths ? colWidths.split(";") : this.getPreferenceItemProperty(prefTp, itemTypeID, "col_widths").split(";");
var colOrderArr = colOrder ? colOrder.split(";") : this.getPreferenceItemProperty(prefTp, itemTypeID, "col_order").split(";");
var columnObjects = {};
for (var i = 0; i < colOrderArr.length; i++) {
columnObjects[i] = { name: colOrderArr[i], order: i, width: colWidthsArr[i] };
}
this.uiPrepareTableWithColumns(inDom, columnObjects);
function GetPrefixItemTypeName(prefix) {
if (!prefix)
prefix = 'IT_';
var result;
if (prefix === 'IT_') {
result = 'Core_ItemGridLayout';
}
else {
result = 'Core_RelGridLayout';
}
return result;
}
};
Aras.prototype.uiGenerateItemsGridXML = function Aras_uiGenerateItemsGridXML(inDom, props, itemtypeID, params) {
return this.uiGenerateGridXML(inDom, props, undefined, itemtypeID, params);
}; //uiGenerateItemsGridXML
Aras.prototype.uiGenerateRelationshipsGridXML = function Aras_uiGenerateRelationshipsGridXML(inDom, Dprops, Rprops, itemTypeId, params, getCached) {
//itemTypeId is id of "is relationship" ItemType
return this.uiGenerateGridXML(inDom, Dprops, Rprops, itemTypeId, params, getCached);
}; //uiGenerateRelationshipsGridXML
Aras.prototype.uiGenerateMainTreeXML = function Aras_uiGenerateMainTreeXML(inDom) {
return this.applyXsltFile(inDom, this.getScriptsURL() + '../styles/mainTree.xsl');
};
Aras.prototype.uiGenerateParametersGrid = function Aras_uiGenerateParametersGrid(itemTypeName, classification) {
/*----------------------------------------
* uiGenerateParametersGrid
*
* Purpose:
* sends request to Innovator Server to generate xml for parameters grid for
* specified ItemType and classification. Returns xml string.
*
* Arguments:
* itemTypeName - name of ItemType
* classification - classification of an Item
*/
var res = null;
if (itemTypeName && classification) {
var classificationDom = this.createXMLDocument();
classificationDom.loadXML(" ");
classificationDom.documentElement.setAttribute("type", itemTypeName);
classificationDom.selectSingleNode("Item/classification").text = classification;
res = this.soapSend("GenerateParametersGrid", classificationDom.xml);
res = res.getResult().selectSingleNode("table");
}
if (res)
{
var tmp = res.selectSingleNode("thead");
var pNd = tmp.selectSingleNode("th[.='Property']");
if (pNd) pNd.text = this.getResource("", "advanced_search.property");
var vNd = tmp.selectSingleNode("th[.='Value']");
if (vNd) vNd.text = this.getResource("", "ui_methods.value");
res = res.xml;
}
else {
var emptyTableXML =
"" +
"" +
" " + this.getResource("", "advanced_search.property") + " " +
" " + this.getResource("", "ui_methods.value") + " " +
" " + this.getResource("", "parametersgrid.sort_order") + " " +
" " +
"" +
" " +
" " +
" " +
" " +
"
";
res = emptyTableXML;
}
var resDom = this.createXMLDocument();
resDom.loadXML(res);
return resDom;
};
Aras.prototype.uiIsParamTabVisible = function Aras_uiIsParamTabVisible(itemNd, itemTypeName) {
var paramTabProperties = this.uiIsParamTabVisibleEx(itemNd, itemTypeName);
return paramTabProperties.show;
};
Aras.prototype.uiGenerateRelationshipsTabbar = function Aras_uiGenerateRelationshipsTabbar(itemTypeName, itemID) {
var res = null;
var itemType;
if (itemTypeName) itemType = this.getItemTypeNodeForClient(itemTypeName);
if (itemType && itemTypeName && itemID) {
var cachedTabbar = this.getItemProperty(itemType, "relationships_tabbar_xml");
if (cachedTabbar && cachedTabbar.indexOf(" ");
res = res.getResult().selectSingleNode("tabbar");
}
}
if (res) {
res = res.xml;
}
else {
var emptyTableXML = " ";
res = emptyTableXML;
}
var resDom = this.createXMLDocument();
resDom.loadXML(res);
return resDom;
};
Aras.prototype.uiGenerateRelationshipsTable = function Aras_uiGenerateRelationshipsTable(itemTypeName, itemID, relationshiptypeID) {
var res = null;
if (itemTypeName && itemID) {
res = this.soapSend("GenerateRelationshipsTable", " ");
res = res.getResult().xml;
}
else {
res = " ";
}
var resDom = this.createXMLDocument();
resDom.loadXML(res);
return resDom;
};
Aras.prototype.uiPrepareDOM4GridXSLT = function Aras_uiPrepareDOM4GridXSLT(dom) {
/*
adds to Envelope Body Result.
removes previous entry entry
*/
var res = dom.selectSingleNode(this.XPathResult());
var tableNd = res.selectSingleNode("table");
if (tableNd) res.removeChild(tableNd);
tableNd = res.appendChild(dom.createElement("table"));
tableNd.appendChild(dom.createElement("columns"));
tableNd.appendChild(dom.createElement("inputrow"));
};
Aras.prototype.uiGenerateGridXSLT = function Aras_uiGenerateGridXSLT(DescByProps_Arr, RelatedProps_Arr, params, typeID) {
var self = this;
if (params === undefined) {
params = {};
}
var itemTypeName = this.getItemTypeName(typeID);
var showLockColumn = Boolean((RelatedProps_Arr === undefined) || RelatedProps_Arr);
var table_xpath = self.XPathResult("/table");
var enable_links = (params.enable_links === undefined || params.enable_links === true);
var enableFileLinks = Boolean(params.enableFileLinks);
var generateOnlyRows = (true === params.only_rows);
var params_bgInvert = (params.bgInvert === undefined || params.bgInvert === false) ? "false" : "true";
var columnsXSLT = [];
var theadXSLT = [];
var listsXSLT = [];
// +++ create header row
function AddHeaderColumn(name, header) {
theadXSLT.push("");
theadXSLT.push(" " + self.escapeXMLAttribute(header) + " ");
theadXSLT.push(" ");
}
function AddHeaderColumns(propsArr, suffix) {
var f2Header = ' [...]';
if (!propsArr) return;
for (var i = 0; i < propsArr.length; i++) {
var prop = propsArr[i];
var propName = self.getItemProperty(prop, "name");
var header = self.getItemProperty(prop, "label");
if (header === "") header = propName;
var dataType = self.getItemProperty(prop, "data_type");
if (dataType === 'item') {
var propDS = self.getItemProperty(prop, 'data_source');
if (propDS) {
var it = self.getItemTypeName(propDS);
if (it) header += f2Header;
}
}
else if (dataType === 'date' || dataType === 'text' || dataType === 'image' || dataType === 'formatted text' || dataType === 'color') {
header += f2Header;
}
AddHeaderColumn(propName + suffix, header);
}
}
if (!generateOnlyRows)
{
theadXSLT.push("");
if (showLockColumn) AddHeaderColumn("L", "");
AddHeaderColumns(DescByProps_Arr, "_D");
AddHeaderColumns(RelatedProps_Arr, "_R");
theadXSLT.push(" ");
// --- create header row
}
var lists = this.newObject();
var reservedListsNum = 2; //because we reserve 2 lists for special needs (e.g. build properties list for filter list pattern in relationships grid)
var listNum = reservedListsNum - 1;
var i;
// +++ create columns
function AddColumn(name, d_width, edit, align, sortStr, bgInvert, password, textColorInvert, flyWeightType) {
columnsXSLT.push("");
columnsXSLT.push("");
columnsXSLT.push(" ");
columnsXSLT.push(" ");
columnsXSLT.push("");
columnsXSLT.push(" ");
columnsXSLT.push(" ");
columnsXSLT.push("");
columnsXSLT.push(" ");
columnsXSLT.push(" ");
columnsXSLT.push(" ");
columnsXSLT.push(" ");
}
function AddColumns(propsArr, suffix) {
if (!propsArr) return;
for (var i = 0; i < propsArr.length; i++) {
var prop = propsArr[i],
propName = self.getItemProperty(prop, "name"),
header = self.getItemProperty(prop, "label") || propName,
data_type = self.getItemProperty(prop, "data_type"),
isForeign = (data_type === "foreign"),
isInBasketTask = (typeID === self.getItemTypeId("InBasket Task")),
column_width = self.getItemProperty(prop, "column_width") || "100",
locale = ' locale="' + self.getSessionContextLocale() + '"',
bgInvert, textColorInvert, password, flyWeightType,
format = "", sortStr = "", editStr = "";
var column_alignment = self.getItemProperty(prop, "column_alignment");
column_alignment = column_alignment ? column_alignment.charAt(0) : "1";
if (isForeign)
{
var sourceProperty = self.uiMergeForeignPropertyWithSource(prop, true);
if (sourceProperty) {
prop = sourceProperty;
data_type = self.getItemProperty(prop, "data_type");
}
}
if (data_type.search(/list$/) != -1) {
var listInfo = self.newObject();
listInfo.listID = self.getItemProperty(prop, "data_source");
listInfo.listType = data_type;
listNum++;
lists[listNum] = listInfo;
editStr = ((data_type == "mv_list") ? "MV_LIST:" : "COMBO:") + listNum;
}
else
{
editStr = "FIELD";
}
switch (data_type) {
case "date":
format = self.getItemProperty(prop, "pattern");
format = self.getDotNetDatePattern(format) || "MM/dd/yyyy";
editStr = "dateTime";
sortStr = 'sort="DATE" inputformat="' + format + '"' + locale;
break;
case "decimal":
format = self.getDecimalPattern(self.getItemProperty(prop, "prec"), self.getItemProperty(prop, "scale"));
sortStr = 'sort="NUMERIC"' + ((format) ? ' inputformat="' + format + '"' : "") + locale;
break;
case "integer":
case "float":
sortStr = 'sort="NUMERIC"' + ((format) ? ' inputformat="' + format + '"' : "") + locale;
break;
case "color list":
case "color":
bgInvert = "false";
textColorInvert = "true";
break;
case "md5":
password = "true";
break;
case "image":
flyWeightType = "IMAGE";
break;
case "qrcode":
flyWeightType = "QRCODE";
break;
case "item":
var dataSource = self.getItemProperty(prop, "data_source"),
dataSourceName = dataSource ? self.getItemTypeName(dataSource) : "";
if (dataSourceName == "File")
{
editStr = "File";
}
else if (!isForeign)
{
editStr = "InputHelper";
}
break;
default:
break;
}
if (isInBasketTask && ("start_date" === propName || "due_date" === propName)) {
bgInvert = "false";
textColorInvert = "true";
}
AddColumn(propName + suffix, column_width, editStr, column_alignment, sortStr, bgInvert, password, textColorInvert, flyWeightType);
}
}
if (!generateOnlyRows)
{
var lockColumnListIndex;
columnsXSLT.push("");
if (showLockColumn)
{
lockColumnListIndex = ++listNum;
AddColumn("L", "24", "COMBO:" + lockColumnListIndex, "c", "");
}
AddColumns(DescByProps_Arr, "_D");
AddColumns(RelatedProps_Arr, "_R");
columnsXSLT.push(" ");
// --- create columns
// +++ create lists
//reserve reservedListsNum lists for special needs
for (var idx = 0; idx < reservedListsNum; idx++)
{
listsXSLT.push("
");
}
if (showLockColumn)
{
var imageStyle = "margin-right: 4px; height: auto; width: auto; max-width: 20px; max-height: 20px;",
iconPrefix = itemTypeName === "InBasket Task" ? "Claimed" : "Locked",
resoucePrefix = itemTypeName === "InBasket Task" ? "claimed" : "locked",
valuesList = ["",
" ",
" ",
" "],
optionsList = ["" + this.getResource("","itemsgrid.locked_criteria_ppm.clear_criteria") + " ",
" " + this.getResource("", "itemsgrid.locked_criteria_ppm." + resoucePrefix + "_by_me"),
" " + this.getResource("", "itemsgrid.locked_criteria_ppm." + resoucePrefix + "_by_others"),
" " + this.getResource("", "itemsgrid.locked_criteria_ppm." + resoucePrefix + "_by_anyone")];
listsXSLT.push("");
for (i = 0; i < optionsList.length; i++) {
listsXSLT.push(" ");
}
listsXSLT.push("
");
}
}
//prepare to request all lists values
var reqListsArr = this.newArray();
for (var listIdx in lists) {
var listInfo = lists[listIdx];
var relType;
if (listInfo.listType == "filter list") {
relType = "Filter Value";
}
else {
relType = "Value";
}
var listDescr = this.newObject();
listDescr.id = listInfo.listID;
listDescr.relType = relType;
reqListsArr.push(listDescr);
}
if (reqListsArr.length > 0) {
var resLists = this.getSeveralListsValues(reqListsArr);
for (var listNum2 in lists) {
var listInfo2 = lists[listNum2];
listsXSLT.push("");
if (listInfo2.listType != "mv_list") {
listsXSLT.push(" ");
}
var listVals = resLists[listInfo2.listID];
if (listVals) {
for (i = 0; i < listVals.length; i++) {
var valNd = listVals[i];
var val = this.getItemProperty(valNd, "value");
var lab = this.getItemProperty(valNd, "label");
if (lab === "") lab = val;
val = this.escapeXMLAttribute(val);
lab = this.escapeXMLAttribute(lab);
listsXSLT.push(" ");
}
}
listsXSLT.push("
");
}
}
// --- create lists
var resXSLTArr = [];
resXSLTArr.push(
"\n");
this.browserHelper.addXSLTCssFunctions(resXSLTArr);
resXSLTArr.push(
"" +
"\n" +
" \n" +
" \n" +
"\n" +
"\n" +
" \n" +
"\n" +
theadXSLT.join("") +
columnsXSLT.join("") +
" \n");
if (!generateOnlyRows) {
resXSLTArr.push(
"\n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n");
}
resXSLTArr.push(
"\n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
"\n" +
listsXSLT.join("") +
" \n" +
"\n" +
" \n" +
" \n" +
" \n" +
"\n" +
" \n" +
" \n" +
" \n" +
" \n");
this.browserHelper.addXSLTInitItemCSSCall(resXSLTArr, "string(css)", "string(fed_css)");
resXSLTArr.push(
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n");
if (RelatedProps_Arr) {
resXSLTArr.push(
" \n" +
" \n" +
" \n");
this.browserHelper.addXSLTInitItemCSSCall(resXSLTArr, "string(related_id/Item/css)", "string(related_id/Item/fed_css)");
resXSLTArr.push(
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n");
}
resXSLTArr.push(
"\n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n");
// +++ lock icon
if (showLockColumn) {
resXSLTArr.push("\n");
resXSLTArr.push("");
if (RelatedProps_Arr) {
resXSLTArr.push("<img src='../images/NullRelated.svg'/> ");
resXSLTArr.push("");
}
var currentUserID = this.getCurrentUserID();
resXSLTArr.push(
" \n" +
" \n" +
"\n" +
"\n" +
" " +
" " +
" <img src='../images/Blocked.svg'/> \n" +
" \n" +
" <img src='../images/New.svg'/> \n" +
" " +
" <img src='" + (itemTypeName !== "InBasket Task" ? "../images/LockedByMe.svg" : "../images/ClaimedByMe.svg") + "'/> " +
" <img src='../images/LockedAndModified.svg'/> " +
" " +
" <img src='" + (itemTypeName !== "InBasket Task" ? "../images/LockedByOthers.svg" : "../images/ClaimedByOthers.svg") + "'/> " +
" " +
" " +
" " +
" <img src=''/> " +
" ");
if (RelatedProps_Arr)
resXSLTArr.push(" ");
resXSLTArr.push(" \n");
resXSLTArr.push(" ");
}
// --- lock icon
// ==== grid rows ===
function GenerateRows(propsArr, xpath_prefix, special_td_attributes, cellCSSVariableName1) {
if (!propsArr) return;
var propItem, name, xpath,
dataType, dataSource, dataSourceName,
restrictedMsgCondition, i;
for (i = 0; i < propsArr.length; ++i) {
propItem = propsArr[i];
name = self.getItemProperty(propItem, "name");
xpath = xpath_prefix + name;
dataType = self.getItemProperty(propItem, "data_type");
restrictedMsgCondition = xpath + "[@is_null='0' and string(.)='']" + (xpath_prefix ? " or related_id[@is_null='0' and string(.)='']" : "");
if ("foreign" == dataType) {
var sourceProperty = self.uiMergeForeignPropertyWithSource(propItem);
if (sourceProperty) {
propItem = sourceProperty;
dataType = self.getItemProperty(propItem, "data_type");
}
}
resXSLTArr.push("");
resXSLTArr.push(" ");
if ("item" == dataType || "color" == dataType || "color list" == dataType) {
resXSLTArr.push("");
if ("item" == dataType) {
dataSource = propItem.selectSingleNode("data_source");
dataSourceName = dataSource ? dataSource.getAttribute("name") : "";
if (enable_links || (enableFileLinks && dataSourceName == "File")) {
var linkItemType = dataSourceName ? "'" + dataSourceName + "'" : "string(" + xpath + "/@type)";
resXSLTArr.push(
"\n" +
" \n" +
" " +
" \n" +
" ' \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" ',' \n" +
" \n" +
" ' \n" +
" \n" +
" \n" +
" ' \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" ',' \n" +
" \n" +
" ' \n" +
" \n" +
" " +
" \n" +
" ");
if (dataSourceName === "File")
{
resXSLTArr.push(
"\n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" ");
}
}
}
else if ("color" == dataType || "color list" == dataType) {
resXSLTArr.push(
"" +
"" +
" " +
" " +
" " +
" ");
}
resXSLTArr.push(" ");
}
var nameCSS = name + "--CSS";
resXSLTArr.push("");
self.browserHelper.addXSLTGetPropertyStyleExCall(resXSLTArr, nameCSS, cellCSSVariableName1, name);
resXSLTArr.push(
"" +
" " + //remove first and last characters
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
"" +
" " +
" " +
" " +
" " +
" " +
" " +
" ");
switch (dataType) {
case "item":
var itemNameProperty = (dataSourceName == "File") ? "filename" : "id/@keyed_name";
resXSLTArr.push(
"" +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
" ");
break;
case "image":
case "qrcode":
resXSLTArr.push(" ");
break;
case "boolean":
resXSLTArr.push(
"<checkbox state=\"" +
"" +
" " +
" " +
" " +
" " +
" " +
" " +
" " +
"\"/>");
break;
case "md5":
resXSLTArr.push("***");
break;
default:
if ("color" != dataType) {
resXSLTArr.push(" ");
}
break;
}
resXSLTArr.push(
" " +
" " +
" \n");
}
}
var special_td_attributes = RelatedProps_Arr ? " bgColor='#f3f3f3'" : "";
GenerateRows(DescByProps_Arr, "", special_td_attributes, "item-CSS");
GenerateRows(RelatedProps_Arr, "related_id/Item/", "", "rItem-CSS");
// ==== end of grid rows ===
resXSLTArr.push(" \n");
resXSLTArr.push(" \n");
resXSLTArr.push(" ");
return resXSLTArr.join("");
};
/*
* uiItemTypeSelectionDialog
*
* parameters:
* 1) itemTypesList - an array of objects like [{id:5, name:'Type5'}]
*/
Aras.prototype.uiItemTypeSelectionDialog = function Aras_uiItemTypeSelectionDialog(itemTypesList, wnd, callback) {
if (!itemTypesList) return;
wnd = wnd || window;
var args = {
title: this.getResource("", "itemtypeselectiondialog.select_item_type"),
itemTypesList: itemTypesList,
aras: this
};
var options = { dialogWidth: 400, dialogHeight: 280 };
var win = this.getMostTopWindowWithAras(wnd);
if (window.showModalDialog && !callback) {
return this.modalDialogHelper.show("DefaultModal", win.main || win, args, options, "ItemTypeSelectionDialog.html");
} else {
args.dialogWidth = 400;
args.dialogHeight = 280;
args.content = "ItemTypeSelectionDialog.html";
if (callback) {
(win.main || win).ArasModules.Dialog.show("iframe", args).promise.then(callback);
} else {
return (win.main || win).ArasModules.Dialog.show("iframe", args).promise;
}
}
};
Aras.prototype.uiItemCanBeLockedByUser = function Aras_uiItemCanBeLockedByUser(itemNd, isRelationship, useSrcAccess) {
/*
this function is for internal use *** only ***.
----------------------------------------------
isRelationship - perhaps, this parameter will be removed in future
------------------------------------------
full list of places where function is used:
item_window.js: updateMenuState
itemsGrid.html: setMenuState
relationshipsGrid.html: updateControls, onMenuCreate
*/
if (itemNd) {
if (this.getItemProperty(itemNd, "is_current") == "0") {
return false;
}
var itemTypeName = itemNd.getAttribute("type");
if (itemTypeName != "File" && !this.isTempEx(itemNd)) {
var lockedByValue = this.getItemProperty(itemNd, "locked_by_id"),
IsMainItemLocked = true;
if (isRelationship && useSrcAccess) {
var sourceId = this.getItemProperty(itemNd, "source_id"),
sourceItem, sourceItemTypeName;
if (sourceId) {
sourceItem = itemNd.selectSingleNode("parent::Relationships/parent::Item[@id='" + sourceId + "']");
if (!sourceItem) {
sourceItemTypeName = this.getItemPropertyAttribute(itemNd, "source_id", "type");
sourceItem = this.getItemById(sourceItemTypeName, sourceId, 0);
}
}
else {
sourceItem = itemNd.selectSingleNode("parent::Relationships/parent::Item");
}
IsMainItemLocked = sourceItem ? this.isLockedByUser(sourceItem) : false;
}
return (IsMainItemLocked && lockedByValue === "");
}
}
return false;
};
Aras.prototype.getItemsOfFileProperties = function Aras_getItemsOfFileProperties(itemNode, ItemTypeNode, eachFileCallback) {
var filePropNodes = this.getPropertiesOfTypeFile(ItemTypeNode),
filePropNodesCount = filePropNodes.length,
files = [],
propName,
prop,
file,
i;
for (i = 0; i < filePropNodesCount; i++) {
propName = this.getItemProperty(filePropNodes[i], "name");
prop = null;
file = null;
if ("id" === propName) {
file = itemNode;
}
if (!file) {
file = itemNode.selectSingleNode(propName + "/Item");
}
if (!file) {
prop = this.getItemProperty(itemNode, propName);
if (prop) {
if (eachFileCallback) {
eachFileCallback(prop);
continue;
}
file = this.getItemById('File', prop, 0);
}
}
if (file) {
files.push(file);
}
}
return files;
};
Aras.prototype.uiIsCheckOutPossible = function Aras_uiIsCheckOutPossible(fileItems, ItemCanBeLockedByUser, ItemIsLockedByUser) {
/*
this function is for internal use *** only ***.
----------------------------------------------
------------------------------------------
full list of places where function is used:
item_window.js: updateMenuState
itemsGrid.html: setMenuState
relationshipsGrid.html: updateControls, onMenuCreate
*/
if (!(ItemCanBeLockedByUser || ItemIsLockedByUser) || !fileItems) return false;
var ThereAreFiles = false;
for (var i = 0; i < fileItems.length; i++) {
var file = fileItems[i];
if (file) {
ThereAreFiles = true;
var FileIsLocked = this.isLocked(file);
var FileIsTemp = this.isTempEx(file);
if (FileIsLocked || FileIsTemp)
return false;
}
}
return ThereAreFiles; //because all rules are checked inside loop above
};
Aras.prototype.uiIsCopyFilePossible = function Aras_uiIsCopyFilePossible(fileItems) {
/*
this function is for internal use *** only ***.
----------------------------------------------
*/
var ThereAreFiles = false;
for (var i = 0; i < fileItems.length; i++) {
var file = fileItems[i];
if (file && !this.isTempEx(file)) {
ThereAreFiles = true;
}
}
return ThereAreFiles; //because all rules are checked inside loop above
};
Aras.prototype.uiWriteObject = function Aras_uiWriteObject(doc, objectHTML) {
doc.write(objectHTML);
};
// method is obsolete, it should be deleted in the major version
Aras.prototype.uiAddConfigLink2Doc4Assembly = function Aras_uiAddConfigLink2Doc4Assembly() {
return true;
};
Aras.prototype.uiGetFilteredObject4Grid = function Aras_uiGetFilteredObject4Grid(itemTypeID, filteredPropName, filterValue) {
var resObj = this.newObject();
resObj.hasError = false;
var itemTypeNd;
try {
itemTypeNd = this.getItemTypeDictionary(this.getItemTypeName(itemTypeID)).node;
} catch (ex) { }
if (!itemTypeNd) {
resObj.hasError = true;
return resObj;
}
var fListNd = itemTypeNd.selectSingleNode("Relationships/Item[@type='Property' and name='" + filteredPropName + "']/data_source");
var fListId = (fListNd) ? fListNd.text : null;
if (!fListId) {
resObj.hasError = true;
return resObj;
}
var _listVals = [""];
var _listLabels = [""];
var optionNds = this.getListFilterValues(fListId);
if (filterValue !== "") optionNds = this.uiGetFilteredListEx(optionNds, "^" + filterValue + "$");
for (var i = 0, L = optionNds.length; i < L; i++) {
var optionNd = optionNds[i];
var label = this.getItemProperty(optionNd, "label");
var value = this.getItemProperty(optionNd, "value");
_listVals.push(value);
if (label === "")
_listLabels.push(value);
else _listLabels.push(label);
}
resObj.values = _listVals;
resObj.labels = _listLabels;
return resObj;
};
/**
* Case insensitive check whether exists such keyed_name in the ItemType.
* Checks if there is an instance of the specified type with a specified keyed name in the DB.
* The check is case insensitive if the DB was setup properly.
* If instance cannot be defined uniquely - the first matched is used.
* If instance doesn't exists in DB then boolean false is returned.
* @param {string} itemTypeName - the ItemType name
* @param {string} keyed_name - the keyed name
* @param {boolean} skipDialog - skip showing the dialog (default value undefined (false))
* @returns {boolean|Object}
*/
Aras.prototype.uiGetItemByKeyedName = function Aras_uiGetItemByKeyedName(itemTypeName, keyed_name, skipDialog) {
function createCacheKey(arasObj, keyed_name) {
return arasObj.CreateCacheKey("uiGetItemByKeyedName", itemTypeName, keyed_name);
}
var key = createCacheKey(this, keyed_name);
var res = this.MetadataCache.GetItem(key);
if (!res) {
var q = this.newIOMItem(itemTypeName, "get");
q.setAttribute("select", "keyed_name");
q.setProperty("keyed_name", keyed_name);
var r = q.apply();
if (r.isError()) {
return false;
}
var putInCache = false;
if (r.isCollection()) {
var candidates = [];
for (var i = 0, L = r.getItemCount(); i < L; i++) {
var candidate = r.getItemByIndex(i);
if (candidate.getProperty("keyed_name") === keyed_name) //do case sensitive check
{
candidates.push(candidate);
}
}
if (1 === candidates.length) {
r = candidates[0];
putInCache = true;
}
else {
if (candidates.length > 1) {
r = candidates[0];
}
else {
r = r.getItemByIndex(0);
}
if (!skipDialog) {
var param = {
buttons: {btnOK: "OK"},
defaultButton: "btnOK",
message: this.getResource("", "ui_methods.item_cannot_defined_uniquely"),
aras: this,
dialogWidth: 300,
dialogHeight: 150,
center: true,
content: "groupChgsDialog.html"
};
var win = this.getMostTopWindowWithAras(window);
(win.main || win).ArasModules.Dialog.show("iframe", param);
}
}
}
else {
putInCache = true;
}
res = r.node;
if (putInCache) {
this.MetadataCache.SetItem(key, res);
var actual_keyed_name = r.getProperty("keyed_name");
if (actual_keyed_name !== keyed_name)//this is possible in a case when the DB is case-insensitive
{//cache mapping to correct keyed name also.
var newKey = createCacheKey(this, actual_keyed_name);
if (!this.MetadataCache.GetItem(newKey)) {
this.MetadataCache.SetItem(newKey, res.cloneNode(true));
}
}
}
}
res = res.cloneNode(true);
return res;
};
// Retrieves window body size, the width and the height of the object including padding,
// but not including margin, border, or scroll bar.
Aras.prototype.getDocumentBodySize = function Aras_GetDocumentBodySize(document) {
var res = this.newObject();
res.width = 0;
res.height = 0;
if (document) {
res.width = document.body.clientWidth;
res.height = document.body.clientHeight;
}
return res;
};
// Retrieves the width of the rectangle that bounds the text in the text field.
Aras.prototype.getFieldTextWidth = function Aras_getFieldTextWidth(field) {
if (field) {
var r = field.createTextRange();
if (r !== null)
return r.boundingWidth;
}
else
return 0;
};
// Calculate html element coordinates on a parent window.
Aras.prototype.uiGetElementCoordinates = function Aras_uiGetElementCoordinates(oNode) {
var oCurrentNode = oNode;
var iLeft = 0;
var iTop = 0;
var iScrollLeft = 0;
var iScrollTop = 0;
var topWindow = this.getMostTopWindowWithAras(window);
var topOfWindow = topWindow.screenY || topWindow.screenTop || 0;
var leftOfWindow = topWindow.screenX || topWindow.screenLeft || 0;
var titleHeight = window.outerHeight - window.innerHeight; // calculate height of titlebar + menubar + navigation toolbar + bookmarks toolbar + tab bar; http://www.gtalbot.org/BugzillaSection/Bug195867GDR_WindowOpen.html#OuterHeightVersusHeightOrInnerHeight
while (oCurrentNode) {
iLeft += oCurrentNode.offsetLeft;
iTop += oCurrentNode.offsetTop;
iScrollLeft += oCurrentNode.scrollLeft;
iScrollTop += oCurrentNode.scrollTop;
if (!oCurrentNode.offsetParent) {
var tmpFrame = null;
try {
oCurrentNode = oCurrentNode.ownerDocument.defaultView ? oCurrentNode.ownerDocument.defaultView.frameElement : null;
} catch (ex) {
//access denied case
oCurrentNode = null;
}
} else {
oCurrentNode = oCurrentNode.offsetParent;
}
}
//+++ IR-008672 (Date dialog is shown not near date field after scrolling)
var readScroll;
if (oNode.ownerDocument.compatMode && oNode.ownerDocument.compatMode === 'CSS1Compat') readScroll = oNode.ownerDocument.documentElement;
else readScroll = oNode.ownerDocument.body;
iScrollLeft += readScroll.scrollLeft;
iScrollTop += readScroll.scrollTop;
res = {};
res.left = iLeft - (iScrollLeft - leftOfWindow);
res.top = iTop - (iScrollTop - topOfWindow) + titleHeight; // add height of browser bars.
res.scrollLeft = iScrollLeft;
res.scrollTop = iScrollTop;
res.screenLeft = leftOfWindow;
res.screenTop = topOfWindow;
res.barsHeight = titleHeight;
//--- IR-008672 (Date dialog is shown not near date field after scrolling)
return res;
};
// Calculate coordinates of window, that would be shown near element
Aras.prototype.uiGetRectangleToShowWindowNearElement = function Aras_uiGetRectangleToShowWindowNearElement(element, windowSize, rectangleInsideElement, eventObject, isGrid) {
if (!element) {
throw new Error(1, this.getResource("", "ui_methods.parameter_element_not_specified"));
}
var parentCoords = this.uiGetElementCoordinates(element);
var dTop, dLeft, dHeight, dWidth;
var boundHeight;
var hackForAddProjectDialog = false;
if (element.name === "date_start_target" || element.name === "date_due_target") {
var isAddProjectForm = element.ownerDocument && element.ownerDocument.formID === "1CF50C86BD1141A9863451B7634B2F04";
if (isAddProjectForm && element.ownerDocument.defaultView) {
hackForAddProjectDialog = true;
}
}
if (eventObject && !window.viewMode && !hackForAddProjectDialog) // for dialog windows
{
var topY = (eventObject.screenY - eventObject.clientY) || 0;
var leftX = (eventObject.screenX - eventObject.clientX) || 0;
dTop = topY + parentCoords.top - parentCoords.screenTop - parentCoords.barsHeight;
dLeft = leftX + parentCoords.left - parentCoords.screenLeft;
}
else {
var keyToAvoidExplicitTopUsage = "top";
dTop = parentCoords[keyToAvoidExplicitTopUsage];
dLeft = parentCoords.left;
}
if (rectangleInsideElement) {
dTop += rectangleInsideElement.y;
if (!isGrid) {
dTop += rectangleInsideElement.height;
dLeft += rectangleInsideElement.x;
}
boundHeight = rectangleInsideElement.height;
}
else if (element.offsetHeight !== undefined) {
if (!hackForAddProjectDialog) {
dTop += element.offsetHeight;
}
boundHeight = element.offsetHeight;
}
if (windowSize) {
dHeight = windowSize.height !== undefined ? windowSize.height : 200;
dWidth = windowSize.width !== undefined ? windowSize.width : 250;
var dx = screen.availWidth - (dLeft + dWidth);
var dy = screen.availHeight - (dTop + dHeight);
if (dx < 0) dLeft += dx;
if (dy < 0) dTop -= (dHeight + boundHeight + parentCoords.barsHeight);
}
return { top: dTop,
left: dLeft,
width: dWidth,
height: dHeight
};
};
///
/// Show modal dialog from the specified URL using the specified dialog parameters, options
/// from "param" near element "child" of "parent" element
///
Aras.prototype.uiShowDialogNearElement = function Aras_uiShowDialogNearElement(element, dialogUrl, dialogParameters, dialogOptions, dialogSize, rectangleInsideElement, eventObject, isGrid) {
if (!element) throw new Error(1, this.getResource("", "ui_methods.parameter_element_not_specified"));
if (dialogOptions === undefined) dialogOptions = "status:0; help:0; center:no;";
if (dialogSize === undefined) {
dialogSize = { width: 250, height: 200 };
if (dialogUrl && dialogUrl.toLowerCase().indexOf("datedialog.html") > -1)
dialogSize = { width: 257, height: 270 };
}
var wndRect = this.uiGetRectangleToShowWindowNearElement(element, dialogSize, rectangleInsideElement, eventObject, isGrid);
var dialogPositionOptions =
"dialogHeight:" + wndRect.height +
"px; dialogWidth:" + wndRect.width +
"px; dialogTop:" + wndRect.top +
"px; dialogLeft:" + wndRect.left +
"px; ";
dialogOptions = dialogPositionOptions + dialogOptions;
var wnd = window;
if (element.ownerDocument && element.ownerDocument.defaultView) {
wnd = element.ownerDocument.defaultView;
}
var res = wnd.showModalDialog(dialogUrl, dialogParameters, dialogOptions);
return res;
};
Aras.prototype.uiShowControlsApiReferenceCommand = function Aras_uiShowControlsApiReferenceCommand(isJavaScript) {
var topHelpUrl = this.getTopHelpUrl();
var re = /^(.*)[\\\/]([^\\\/]*)$/; //finds the last '\' or '/'
if (!topHelpUrl || !re.test(topHelpUrl)) {
this.AlertError(this.getResource("", "ui_methods.cannot_determine_tophelpurl"));
return;
}
topHelpUrl = RegExp.$1;
var apiReferenceFolder = isJavaScript ? "APIReferenceJavaScript" : "APIReferenceDotNet";
window.open(topHelpUrl + "/" + apiReferenceFolder + "/Html/Index.html");
};
/** ui_methodsEx.js **/
// (c) Copyright by Aras Corporation, 2004-2013.
Aras.prototype.uiRegWindowEx = function ArasUiRegWindowEx(itemID, win) {
/*-- uiRegWindowEx
*
* registers window as Innovator window.
* All Innovator windows get events notifications.
* All Innovator windows are closed when main window is closed.
*
*/
if (!itemID || !win) {
return false;
}
var winName = this.mainWindowName + "_" + itemID;
this.windowsByName[winName] = win;
return true;
};
Aras.prototype.uiUnregWindowEx = function ArasUiUnregWindowEx(itemID) {
/*-- uiUnregWindowEx
*
* unregisters window as Innovator window (should be called when item window is closed).
* All Innovator windows get events notifications.
* All Innovator windows are closed when main window is closed.
*
*/
if (!itemID) {
return false;
}
var winName = this.mainWindowName + "_" + itemID;
this.deletePropertyFromObject(this.windowsByName, winName);
return true;
};
Aras.prototype.uiFindWindowEx = function ArasUiFindWindowEx(itemID) {
/*-- uiUnregWindowEx
*
* finds registered Innovator window.
*
*/
if (!itemID) {
return null;
}
var winName = this.mainWindowName + "_" + itemID;
var res = null;
try {
res = this.windowsByName[winName];
if (res === undefined) {
res = null;
}
} catch (excep) {
}
if (res && this.isWindowClosed(res)) {
this.uiUnregWindowEx(itemID);
return null;
}
return res;
};
Aras.prototype.uiFindWindowEx2 = function (itemNd) {
var itemID = itemNd.getAttribute("id");
var win = this.uiFindWindowEx(itemID);
if (!win) {
try {
var parentItemNd = itemNd.selectSingleNode("../../../..");
if (parentItemNd && parentItemNd.nodeType != 9) {
var pid = parentItemNd.getAttribute("id");
win = this.uiFindWindowEx(pid);
}
} catch (exc1) {
}
}
if (!win) {
win = window;
}
return win;
};
Aras.prototype.uiOpenWindowEx = function ArasUiOpenWindowEx(itemID, params, alertErrorWin) {
if (!itemID) {
return null;
}
if (params === undefined) {
params = "";
}
var topWindow = this.getMostTopWindowWithAras(window);
var isMainWindow = (topWindow.name === this.mainWindowName);
var mainArasObject = this.getMainArasObject();
var isMainArasObject = (this === mainArasObject);
if (!topWindow.opener && !isMainArasObject) {
return mainArasObject.uiOpenWindowEx(itemID, params);
}
if (!isMainWindow && topWindow.opener && !this.isWindowClosed(topWindow.opener)) {
var wnd = topWindow.opener.aras.uiOpenWindowEx(itemID, params, this.getCurrentWindow());
if (!wnd.opener && topWindow.opener) {
wnd.opener = topWindow.opener;
}
return wnd;
} else {
var winName = this.mainWindowName + "_" + itemID;
var win = null;
if (this.browserHelper.newWindowCanBeOpened(this)) {
this.browserHelper.lockNewWindowOpen(this, true);
try {
if (!window.arasTabs || params.indexOf("isOpenInTearOff=true") > -1) {
win = topWindow.open(this.getScriptsURL() + "../scripts/blank.html", winName, params);
} else {
win = arasTabs.open(this.getScriptsURL() + "../scripts/blank.html", winName);
}
}
finally
{
this.browserHelper.lockNewWindowOpen(this, false);
}
if (!win) {
this.AlertError(this.getResource("", "ui_methods_ex.innovator_failed_to_open_new_window"), alertErrorWin, "");
}
} else {
this.AlertSuccess(this.getResource("", "ui_methods_ex.another_window_opening_is_in_progress"));
return false;
}
if (win) {
try {//substitute opener for the new window
if (topWindow.opener && !this.isWindowClosed(topWindow.opener) && topWindow.opener.name == this.mainWindowName) {
//according to CVS commits this is fix for IR-001690 "Toolbar does not load" (read background).
//Something to workaround google popup blocker.
win.opener = topWindow.opener;
}
} catch (excep) { /* security exception may occur */ }
}
return win;
}
};
Aras.prototype.uiCloseWindowEx = function (itemID) {
if (!itemID) {
return false;
}
var win = this.uiFindWindowEx(itemID);
if (win) {
win.close();
}
return true;
};
/*
* uiGetFormID4ItemEx - function to get id of form correspondent to the item (itemNd) and mode
* (result depends on current user)
*
* parameters:
* itemNd - xml node of item to find correspondent form
* formType - string, representing mode: 'add', 'view', 'edit' or 'print'
*/
Aras.prototype.uiGetFormID4ItemEx = function ArasUiGetFormID4ItemEx(itemNd, formType) {
function findMaxPriorityFormID(itemType, roles, formType) {
var i;
var arasObj = self;
var returnNodes;
var tryGetClassificationFormWithoutFormType = function () {
xp = "Relationships/Item[@type='View' and not(type='complete') and not(type='preview') and " + strRoles + "][not(form_classification[@is_null='1'])]/related_id/Item[@type='Form']";
return itemType.selectNodes(xp);
};
if (typeof (roles) == "string") {
var tmpRoles = roles;
roles = [];
roles.push(tmpRoles);
}
var strRoles = "(role='" + roles.join("' or role='") + "')";
if (classification) {
var xp = "Relationships/Item[@type='View' and " + strRoles + " and type='" + formType + "'][not(form_classification[@is_null='1'])]/related_id/Item[@type='Form']";
var formIds = [];
var nodes = itemType.selectNodes(xp);
var tmpNds = nodes.length > 0 ? nodes : tryGetClassificationFormWithoutFormType();
if (tmpNds.length > 0) {
for (i = 0; i < tmpNds.length; i++) {
var formClassification = tmpNds[i].parentNode.parentNode.selectSingleNode("form_classification").text;
if (arasObj.areClassPathsEqual(formClassification, classification)) {
formIds.push(tmpNds[i].getAttribute("id"));
}
}
} else {
returnNodes = null;
}
if (formIds.length > 0) {
var additionalXp = "[@id='" + formIds.join("' or @id='") + "']";
xp += additionalXp;
returnNodes = itemType.selectNodes(xp);
}
}
if (!(returnNodes && (returnNodes.length !== 0))) {
returnNodes = itemType.selectNodes("Relationships/Item[@type='View' and string(form_classification)='' and " + strRoles + " and type='" + formType + "']/related_id/Item[@type='Form']");
}
var formNds = returnNodes;
if (formNds.length === 0) {
return "";
}
var currForm = formNds[0];
var currPriority = arasObj.getItemProperty(formNds[0].selectSingleNode("../.."), "display_priority");
if (currPriority === "") {
currPriority = Number.POSITIVE_INFINITY;
}
for (i = 1; i < formNds.length; i++) {
var priority = arasObj.getItemProperty(formNds[i].selectSingleNode("../.."), "display_priority");
if (priority === "") {
priority = Number.POSITIVE_INFINITY;
}
if (currPriority > priority) {
currPriority = priority;
currForm = formNds[i];
}
}
return currForm.getAttribute("id");
}
function findMaxPriorityFormIDForItemType(anItemType, formType) {
var res = findMaxPriorityFormID(anItemType, identityId, formType);
if (res) {
return res;
}
if (formType != "default" && formType != "complete") {
res = findMaxPriorityFormID(anItemType, identityId, "default");
if (res) {
return res;
}
}
res = findMaxPriorityFormID(anItemType, userIdentities, formType);
if (res) {
return res;
}
if (formType != "default" && formType != "complete") {
res = findMaxPriorityFormID(anItemType, userIdentities, "default");
if (res) {
return res;
}
}
return undefined;
}
if (!itemNd) {
return "";
}
if (!formType || formType.search(/^default$|^add$|^view$|^edit$|^print|^preview$|^search|^complete$/) == -1) {
return "";
}
var userIdentities = this.getIdentityList().split(",");
if (userIdentities.length === 0) {
return "";
}
var userNd = null;
var tmpUserID = this.getCurrentUserID();
if (tmpUserID == this.getUserID()) {
userNd = this.getLoggedUserItem();
} else {
userNd = this.getItemFromServerWithRels("User", tmpUserID, "id", "Alias", "related_id(id)", true).node;
}
if (!userNd) {
return "";
}
var identityNd = userNd.selectSingleNode("Relationships/Item[@type='Alias']/related_id/Item[@type='Identity']");
if (!identityNd) {
return "";
}
var identityId = identityNd.getAttribute("id");
var itemTypeName = itemNd.getAttribute("type");
var itemTypeNd = this.getItemTypeNodeForClient(itemTypeName, "name");
var classification;
var classificationNode = itemNd.selectSingleNode("classification");
if (classificationNode) {
classification = classificationNode.text;
}
var self = this;
var formID = findMaxPriorityFormIDForItemType(itemTypeNd, formType);
if (!formID && this.getItemProperty(itemTypeNd, "implementation_type") == "polymorphic") {
var itemtypeId = this.getItemProperty(itemNd, "itemtype");
if (itemtypeId) {
itemTypeNd = this.getItemTypeNodeForClient(itemtypeId, "id");
if (itemTypeNd) {
formID = findMaxPriorityFormIDForItemType(itemTypeNd, formType);
}
}
}
return formID;
};
/*
* uiGetRelationshipView4ItemTypeEx - function to get Relationship View of ItemType
* (result depends on current user)
*
* parameters:
* itemType - xml node of ItemType
*/
Aras.prototype.uiGetRelationshipView4ItemTypeEx = function ArasUiGetRelationshipView4ItemTypeEx(itemType) {
if (!itemType) {
return null;
}
var userIdentities = this.getIdentityList().split(",");
if (userIdentities.length === 0) {
return null;
}
var userNd = null;
var tmpUserID = this.getCurrentUserID();
if (tmpUserID == this.getUserID()) {
userNd = this.getLoggedUserItem();
} else {
userNd = this.getItemFromServerWithRels("User", tmpUserID, "id", "Alias", "related_id(id)", true).node;
}
if (!userNd) {
return null;
}
var identityNd = userNd.selectSingleNode("Relationships/Item[@type='Alias']/related_id/Item[@type='Identity']");
if (!identityNd) {
return null;
}
var identityId = identityNd.getAttribute("id");
var res = itemType.selectSingleNode("Relationships/Item[@type='Relationship View' and (related_id/Item/@id='" + identityId + "' or related_id='" + identityId + "')]");
if (!res) {
for (var i = 0; i < userIdentities.length; i++) {
res = itemType.selectSingleNode("Relationships/Item[@type='Relationship View' and (related_id/Item/@id='" + userIdentities[i] + "' or related_id='" + userIdentities[i] + "')]");
if (res) {
break;
}
}
}
return res;
};
/*
* uiGetTOCView4ItemTypeEx - function to get TOC View of ItemType
* (result depends on current user)
*
* parameters:
* itemType - xml node of ItemType
*/
Aras.prototype.uiGetTOCView4ItemTypeEx = function ArasUiGetTOCView4ItemTypeEx(itemType) {
if (!itemType) {
return null;
}
var userIdentities = this.getIdentityList().split(",");
if (userIdentities.length === 0) {
return null;
}
var userNd = null;
var tmpUserID = this.getCurrentUserID();
if (tmpUserID == this.getUserID()) {
userNd = this.getLoggedUserItem();
} else {
userNd = this.getItemFromServerWithRels("User", tmpUserID, "id", "Alias", "related_id(id)", true).node;
}
if (!userNd) {
return null;
}
var identityNd = userNd.selectSingleNode("Relationships/Item[@type='Alias']/related_id/Item[@type='Identity']");
if (!identityNd) {
return null;
}
var identityId = identityNd.getAttribute("id");
var res = itemType.selectSingleNode("Relationships/Item[@type='TOC View' and (related_id/Item/@id='" + identityId + "' or related_id='" + identityId + "')]");
if (!res) {
for (var i = 0; i < userIdentities.length; i++) {
res = itemType.selectSingleNode("Relationships/Item[@type='TOC View' and (related_id/Item/@id='" + userIdentities[i] + "' or related_id='" + userIdentities[i] + "')]");
if (res) {
break;
}
}
}
return res;
};
/*
* uiGetForm4ItemEx - function to get form xml node correspondent to the item (itemNd) and mode
* (result depends on current user)
*
* parameters:
* itemNd - xml node of item to find correspondent form
* formType - string, representing mode: 'add', 'view', 'edit' or 'print'
*/
Aras.prototype.uiGetForm4ItemEx = function (itemNd, formType) {
if (!itemNd) {
return null;
}
if (!formType || formType.search(/^default$|^add$|^view$|^edit$|^preview$|^print$|^search|^complete$/) == -1) {
return null;
}
var formID = this.uiGetFormID4ItemEx(itemNd, formType);
var formNd = formID ? this.getFormForDisplay(formID).node : null;
return formNd;
};
/*
* uiShowItemEx
*
* parameters:
* 1) itemNd - item to be shown
* 2) viewMode - 'tab view' or 'openFile'
* 3) isOpenInTearOff - true or false
*/
Aras.prototype.uiShowItemEx = function ArasUiShowItemEx(itemNd, viewMode, isOpenInTearOff) {
function onShowItem(inDom, inArgs) {
var itemTypeName = inDom.getAttribute('type');
var itemType = this.getItemTypeNodeForClient(itemTypeName);
var onShowItemEv = itemType.selectNodes("Relationships/Item[@type='Client Event' and client_event='OnShowItem']/related_id/Item");
try {
if (onShowItemEv.length) {
return this.evalMethod(this.getItemProperty(onShowItemEv[0], "name"), inDom, inArgs);
} else {
return this.evalMethod("OnShowItemDefault", inDom, inArgs);
}
} catch (exp) {
this.AlertError(this.getResource("", "item_methods.event_handler_failed"),
this.getResource("", "item_methods.event_handler_failed_with_message", exp.description),
this.getResource("", "common.client_side_err"));
return false;
}
}
if (!itemNd) {
return false;
}
if (itemNd.getAttribute("discover_only") === "1") {
this.AlertError(this.getResource("", "ui_methods_ex.discover_only_item_cannot_be_opened"), "", "");
return false;
}
var itemTypeName = itemNd.getAttribute("type");
viewMode = viewMode || "tab view";
var asyncResult = onShowItem.call(this, itemNd, { viewMode: viewMode, isOpenInTearOff: isOpenInTearOff });
if (!asyncResult) {
asyncResult = ModulesManager.createAsyncResult();
asyncResult.resolve();
}
return asyncResult;
};
Aras.prototype.uiOpenEmptyWindowEx = function ArasUiOpenEmptyWindowEx(itemNd) {
var itemID = itemNd.getAttribute("id");
var win = this.uiFindAndSetFocusWindowEx(itemID);
if (win !== null) {
return true;
}
win = this.uiOpenWindowEx(itemID, "scrollbars=no,resizable=yes,status=yes");
if (!win) {
return false;
}
this.uiRegWindowEx(itemID, win);
return true;
};
Aras.prototype.uiFindAndSetFocusWindowEx = function ArasUiFindAndSetFocusWindowEx(itemID) {
var win = this.uiFindWindowEx(itemID);
if (win) {
if (win.opener === undefined) {
this.uiUnregWindowEx(itemID);
win = null;
} else {
this.browserHelper.setFocus(win);
}
} else {
win = null;
}
return win;
};
/*
* uiReShowItemEx
*
* parameters:
* 1) oldItemID- old id of item to be shown
* 2) itemNd - item to be shown //usually itemId==oldItemId
* 3) viewMode - "tab view" or "openFile"
*/
Aras.prototype.uiReShowItemEx = function ArasUiReShowItemEx(oldItemID, itemNd, viewMode) {
if (!oldItemID) {
return false;
}
if (!itemNd) {
return false;
}
viewMode = viewMode || "tab view";
var win = this.uiFindWindowEx(oldItemID);
if (!win || this.isWindowClosed(win)) {
return this.uiShowItemEx(itemNd, viewMode);
}
var itemWin;
if (win.getItem) {
itemWin = win.getItem();
} else {
itemWin = win.item;
}
var itemID = itemNd.getAttribute("id");
var itemTypeName = itemNd.getAttribute("type");
if (itemTypeName == "File" && viewMode == "openFile") {
return this.uiShowItemEx(itemNd, viewMode);
}
var isReloadFrm = false;
var oldFormId = this.uiGetFormID4ItemEx(itemWin, win.isEditMode ? "edit" : "view");
var newIsEditMode = (this.isTempEx(itemNd) || this.isLockedByUser(itemNd)) ? true : false;
var newFormId = this.uiGetFormID4ItemEx(itemNd, win.isEditMode ? "edit" : "view");
if (!newFormId) {
var doc = win.frames.instance.document;
doc.open();
doc.write("" + this.getResource("", "ui_methods_ex.form_not_specified_for_you", win.isEditMode ? "edit" : "view") + " ");
doc.close();
return;
}
if (oldItemID != itemID) {
this.uiUnregWindowEx(oldItemID);
this.uiRegWindowEx(itemID, win);
isReloadFrm = true;
if (newFormId != oldFormId) {
if (win.name != "work") {
win.close();
isReloadFrm = false;
}
}
}
this.RefillWindow(itemNd, win, isReloadFrm);
if (win.updateMenu) {
win.updateMenu();
}
};
Aras.prototype.RefillWindow = function ArasRefillWindow(itemNd, win, isReloadFrm) {
var itemWin;
if (win.getItem) {
itemWin = win.getItem();
} else {
itemWin = win.item;
}
if (itemWin && "update" == itemWin.getAttribute("action") && itemWin.getAttribute("id") != itemNd.getAttribute("id")) {
isReloadFrm = true;
}
var itemID = itemNd.getAttribute("id");
var typeID = itemNd.getAttribute("typeId");
var itemTypeName = this.getItemTypeName(typeID);
var winName = this.mainWindowName + "_" + itemID;
win.name = winName;
if (win.setItem) {
win.setItem(itemNd);
} else {
win.item = itemNd;
}
win.itemID = itemID;
var itemTypeNd = this.getItemTypeNodeForClient(itemTypeName);
win.itemType = itemTypeNd;
var newIsEditMode = (this.isTempEx(itemNd) || this.isLockedByUser(itemNd)) ? true : false;
win.isTearOff = true;
win.itemTypeName = itemTypeName;
if (win.updateRootItem) {
if (!win.isEditModeUnchangeable) {
win.isEditMode = newIsEditMode;
}
var queryString;
if (isReloadFrm && win.relationships) {
var openTab = win.relationships.relTabbar.GetSelectedTab();
queryString = { db: this.getDatabase(), ITName: itemTypeName, relTypeID: openTab, itemID: itemID, editMode: (win.isEditMode ? 1 : 0), tabbar: "1", toolbar: "1", where: "tabview" };
}
win.updateRootItem(itemNd, queryString);
if (win.getViewersTabs) {
var updateSidebar = function () {
setTimeout(function () {
var tabsControl = win.getViewersTabs();
var currentTabId = tabsControl.getCurrentTabId();
var callback = function (viewerContainer) {
var frame = viewerContainer.getChildren()[0].viewerFrame;
if (frame && !frame.contentWindow.SSVCViewer) {
frame.contentWindow.onViewerIsReady = function () {
var args = frame.contentWindow.VC.Utils.Page.GetParams();
frame.contentWindow.SSVCViewer.displayFile(args.fileUrl);
};
}
};
tabsControl.selectTab(currentTabId, callback);
document.removeEventListener("loadSideBar", updateSidebar);
}, 0);
};
document.addEventListener("loadSideBar", updateSidebar);
}
} else {
this.AlertError(this.getResource("", "ui_methods_ex.function_update_root_item_not_implemented"), "", "", win);
}
if (win.document.getElementById("edit") && win.document.getElementById("form_frame")) {
this.uiShowItemInFrameEx(win.getElementById("form_frame"), win.item, (win.isEditMode ? "edit" : "view"));
}
};
Aras.prototype.uiPopulatePropertiesOnWindow = function ArasUiPopulatePropertiesOnWindow(hostWindow, itemNd, itemTypeNd, formNd, isEditMode, mode, userChangeHandler) {
var itemID;
var itemTypeName;
var itemTypeID;
var iomItem;
var formID = formNd.getAttribute("id");
var winParams = {};
winParams.aras = this;
winParams.viewMode = mode;
winParams.isEditMode = isEditMode;
winParams.formID = formID;
winParams.formNd = formNd;
//uiShowItemInFrameEx method where current method is called calculate itemTypeNd from itemNd, it is not possible to have itemNd wihtout itemTypeNd calculated
if (itemNd && itemTypeNd) {
itemID = itemNd.getAttribute("id");
iomItem = this.newIOMItem();
iomItem.dom = itemNd.ownerDocument;
iomItem.node = itemNd;
winParams.item = itemNd;
winParams.itemNd = itemNd;
winParams.thisItem = iomItem;
//In case of SearchMode form (for example search by criteria @{0}) itemNd exist, but it is query AML which doesn't have id at all, make sure that isTemp in that case
//set to true
winParams.itemID = itemID;
winParams.isTemp = this.isTempEx(itemNd);
}
//method uiDrawFormEx is not require to have itemNd populated, for example on Form editor. But itemTypeNd in this case should be populated (it will be used to populate list on forms fields)
if (itemTypeNd) {
itemTypeID = itemTypeNd.getAttribute("id");
itemTypeName = this.getItemProperty(itemTypeNd, "name");
winParams.itemTypeID = itemTypeID;
winParams.itemType = itemTypeNd;
winParams.itemTypeNd = itemTypeNd;
winParams.itemTypeName = itemTypeName;
}
if (userChangeHandler) {
winParams.userChangeHandler = userChangeHandler;
}
//it is assuming that there is no racing conditions for two or more forms opened in the same time. First form will be loaded, then second form will erase windowArgumentsExchange and setup it again.
//In case of error it will be required to fix more than just creating something like hostWindow._<%form_id%>_params,
//because it can be situation when two items with the same form is opened simulteneously from the same origin window.
//It will be required to pass some guid to the window, but it is not allowed to add it to query string, due to cache issues.
//It will be requried to use window.name property which is set up as