Something went wrong on our end
-
Christoph Manhart authored
[Projekt: xRM-ContactManagement][TicketNr.: 1078253][Mailbridge setzt Verantwortlichen in Aktivität nicht]
Christoph Manhart authored[Projekt: xRM-ContactManagement][TicketNr.: 1078253][Mailbridge setzt Verantwortlichen in Aktivität nicht]
process.js 11.46 KiB
import("system.translate");
import("Keyword_lib");
import("EmailUtil_lib");
import("Util_lib");
import("system.question");
import("system.datetime");
import("system.vars");
import("system.util");
import("ActivityTask_lib");
import("system.tools");
import("Employee_lib");
import("system.db");
import("system.mail");
import("system.text");
import("Sql_lib");
import("KeywordRegistry_basic");
//TODO: comment library
function IncomingEmailExecutor(pMail)
{
//whenver this function is called it may not be in a context where a alias is given: the mail-importing-entity for example has no alias.
//therefore set it here manually
this._alias = null;
this.locale = null;//this is maybe set later when determining an affected user for history
this.setAlias();
this.rawMail = pMail;
this.mailSubject = this.rawMail[mail.MAIL_SUBJECT] || "";
this.mailSender = this.rawMail[mail.MAIL_SENDER];
this.mailSentDate = this.rawMail[mail.MAIL_SENTDATE];
this.filename = this.rawMail.filename;
var mailRecipientsTo = this.rawMail[mail.RECIPIENT_TO].split(";");
var mailRecipientsCc = this.rawMail[mail.RECIPIENT_CC].split(";");
var mailRecipientsBcc = this.rawMail[mail.RECIPIENT_BCC].split(";");
this.mailRecipients = mailRecipientsTo.concat(mailRecipientsCc, mailRecipientsBcc).filter(function (elem){
return elem != "" && elem != null;
});
this._senderInfo = null;
//activity data and failbackActivityData will be merged later to get all the data we need
//we always want to prefer contacts that are active to those who are inactive (that applies to the sender and to the recipients)
this.activityData = {
links: []
};
this.failbackActivityData = {
employeeContactId: "",
direction: $KeywordRegistry.activityDirection$incoming()
};
}
IncomingEmailExecutor.prototype.setActivityEmployeeContact = function (pContactId, pLanguageIso3, pSetAsFailback)
{
//autodetect language if not given
if (pLanguageIso3 == undefined)
{
var lang = newSelect("CONTACT.ISOLANGUAGE", this._alias)
.from("CONTACT")
.where("CONTACT.CONTACTID", pContactId)
.cell();
if (lang)
pLanguageIso3 = lang;
}
if (pSetAsFailback)
{
this.failbackActivityData.employeeContactId = pContactId;
this.failbackActivityData.employeeContactLanguage = pLanguageIso3;
}
else
{
this.activityData.employeeContactId = pContactId;
this.activityData.links.push(["Person", pContactId]);
this.activityData.employeeContactLanguage = pLanguageIso3;
}
}
IncomingEmailExecutor.prototype.setAlias = function(pAlias)
{
this._alias = pAlias || db.getCurrentAlias();
}
IncomingEmailExecutor.prototype.getMailtextAsHtml = function()
{
var textInfos = [
translate.withArguments("Sender: %0", [this.rawMail[mail.MAIL_SENDER]], this.locale),
translate.withArguments("Recipients: %0", [this.mailRecipients.join(", ")], this.locale)
];
var attachmentInfos = mail.getAttachmentInfos(this.rawMail);
var attachmentCount = attachmentInfos.length;
if (attachmentCount == 0)
textInfos.push(translate.text("no attachments", this.locale));
else
{
if (attachmentCount == 1)
textInfos.push(translate.withArguments("%0 attachment:", [attachmentCount], this.locale));
else
textInfos.push(translate.withArguments("%0 attachments:", [attachmentCount], this.locale));
var attachmentHtml = "";
var fileName;
for (var i = 0; i < attachmentCount; i++)
{
//don't use a <ul><li.......</ul> here since it does not look good in the client
[fileName] = text.decodeMS(attachmentInfos[i]);
attachmentHtml += "\n" + (i > 0 ? "<br/>" : "") + "● " + fileName;
}
textInfos.push(attachmentHtml);
}
textInfos = textInfos.map(function (el)
{
return "<p>" + el + "</p><br>";
});
//since the activity has always and only a HTML-content-field we need to ensure that there will be always a HTML-content
if (this.rawMail[mail.MAIL_HTMLTEXT])
textInfos.push("<br/>\n" + this.rawMail[mail.MAIL_HTMLTEXT]);
else
textInfos.push("<br/>\n" + text.text2html(this.rawMail[mail.MAIL_TEXT], true));
var res = textInfos.join("\n");
return res;
}
IncomingEmailExecutor.prototype.getSenderInfo = function()
{
if (this._senderInfo == null)
this._senderInfo = this.mailSender ? IncomingEmailExecutor.getContactDataByEmail(this.mailSender, this._alias) : [];
return this._senderInfo;
}
IncomingEmailExecutor.prototype.insertUnlinkedMail = function ()
{
var unlinkedMailId = util.getNewUUID();
var cols = ["AB_UNLINKEDMAILID", "SUBJECT", "SENTDATE", "SENDER", "RECIPIENTS", "MAIL", "USER_NEW", "DATE_NEW"];
var vals = [unlinkedMailId, this.mailSubject, this.mailSentDate, this.mailSender, this.mailRecipients.join(", "), mail.toRFC(this.rawMail), vars.get("$sys.user"), datetime.date()];
db.insertData("AB_UNLINKEDMAIL", cols, null, vals, this._alias);
return {
unlinkedMailId: unlinkedMailId
};
}
IncomingEmailExecutor.prototype.isUnlinkable = function ()
{
return this.getSenderInfo().length == 0;
}
IncomingEmailExecutor.getContactDataByEmail = function (pMailAddress, pAlias)
{
var mailAddress = EmailUtils.extractAddress(pMailAddress).toUpperCase();
return newSelect("CONTACT.CONTACTID, CONTACT.STATUS, CONTACT.PERSON_ID, CONTACT.ISOLANGUAGE", pAlias)
.from("COMMUNICATION")
.join("CONTACT", "COMMUNICATION.CONTACT_ID = CONTACT.CONTACTID")
.where("COMMUNICATION.ADDR", mailAddress, "upper(#) = ?")
.table();
}
IncomingEmailExecutor.prototype.createActivity = function(pAdditionalLinks)
{
var senderContacts = {
prefered: [],
failback: []
};
this.getSenderInfo().forEach(this._getProcessingFunction(true, senderContacts), this);
this.activityData.links = this.activityData.links.concat(senderContacts.prefered.length > 0 ? senderContacts.prefered : senderContacts.failback);
for (var i = 0, l = this.mailRecipients.length; i < l; i++)
{
var recipientsInfo = IncomingEmailExecutor.getContactDataByEmail(this.mailRecipients[i], this._alias);
var recipientContacts = {
prefered: [],
failback: []
};
recipientsInfo.forEach(this._getProcessingFunction(false, recipientContacts), this);
this.activityData.links = this.activityData.links.concat(recipientContacts.prefered.length > 0 ? recipientContacts.prefered : recipientContacts.failback);
}
var langIso3 = this.activityData.employeeContactLanguage || this.failbackActivityData.employeeContactLanguage;
var langIso2;
if (langIso3)
{
langIso2 = LanguageKeywordUtils.Iso2FromIso3(langIso3, this._alias);
if (langIso2)
this.locale = langIso2;
}
//collecting all the information and combine it for the creation
var activityDataForInsert = {
subject: this.mailSubject,
content: this.getMailtextAsHtml(),
categoryKeywordId: $KeywordRegistry.activityCategory$mail(),
directionKeywordId: this.activityData.direction || this.failbackActivityData.direction
};
if (vars.get("$sys.isclient") == "true"){
activityDataForInsert.responsibleContactId = EmployeeUtils.getCurrentContactId();
} else {
activityDataForInsert.responsibleContactId = this.activityData.employeeContactId ? this.activityData.employeeContactId : this.failbackActivityData.employeeContactId;
}
var activityLinks = this.activityData.links || this.failbackActivityData.links;
if (pAdditionalLinks)
activityLinks = activityLinks.concat(pAdditionalLinks);
activityLinks = ArrayUtils.distinct2d(activityLinks);//TODO: better check before adding the elements into the array if it already exists there
var activityDocs = [[this.filename || "mail.eml", util.encodeBase64String(mail.toRFC(this.rawMail)), true]];
var activityRes = ActivityUtils.insertNewActivity(activityDataForInsert, activityLinks, activityDocs, this._alias, this.mailSentDate);
return activityRes;
}
IncomingEmailExecutor.prototype.deleteUnlinkedMail = function (pUnlinkedMailId)
{
newWhereIfSet("AB_UNLINKEDMAIL.AB_UNLINKEDMAILID", pUnlinkedMailId, undefined, undefined, this._alias)
.deleteData(true, "AB_UNLINKEDMAIL");
}
IncomingEmailExecutor.prototype.autoProcess = function(pUnlinkedMailId)
{
let tempResult = {};
tempResult.isUnlinkedMail = false;
if (this.isUnlinkable())
{
tempResult.isUnlinkedMail = true;
if (pUnlinkedMailId)
return {
unlinkedMailId: pUnlinkedMailId
};
}
tempResult.activityId = this.createActivity().activityId;
this.deleteUnlinkedMail(pUnlinkedMailId);
return tempResult;
}
IncomingEmailExecutor.prototype._getProcessingFunction = function (pIsSender, pTargetArray)
{
return function(contactInfoRow) {
var [contactId, contactStatus, contactPersonId, languageIso3] = contactInfoRow;
//there *should* only exist no or one user per contactid, never two or more - so getUser (not getUsers) should be fine
var user = tools.getUserByAttribute(tools.CONTACTID, [contactId]);
var isEmployee = user != null;
var isContactActive = contactStatus == $KeywordRegistry.contactStatus$active();
//if a user was already found we can skip determining the correct user since only one user can be set as "RESPONSIBLE" in the activity
if (isEmployee && !this.activityData.employeeContactId)
{
var direction = pIsSender ? $KeywordRegistry.activityDirection$outgoing() : $KeywordRegistry.activityDirection$incoming();
if (isContactActive)
{
this.setActivityEmployeeContact(contactId, languageIso3);
this.activityData.direction = direction;
}
else
{
//if the user is inactive, we may find a better (=active) user later
this.setActivityEmployeeContact(contactId, languageIso3, true);
this.failbackActivityData.direction = direction;
}
}
else
{
var context = contactPersonId == "" ? "Organisation" : "Person"
if(context == "Person")//add Organisation to the Activity as Link
{
var orgData = newSelect(["CONTACT.CONTACTID", "CONTACT.STATUS"], this._alias)
.from("CONTACT")
.join("CONTACT", "anyContact.ORGANISATION_ID = CONTACT.ORGANISATION_ID and CONTACT.PERSON_ID is null", "anyContact")
.whereIfSet(["CONTACT", "CONTACTID", "anyContact"], contactId)
.arrayRow()
if (orgData[1] == $KeywordRegistry.contactStatus$active())
pTargetArray["prefered"].push(["Organisation", orgData[0]]);
else
pTargetArray["failback"].push(["Organisation", orgData[0]]);
}
var link = [context, contactId];
if (isContactActive)
pTargetArray["prefered"].push(link);
else
pTargetArray["failback"].push(link);
}
};
}