DocSpace-buildtools/products/ASC.CRM/Server/Middlewares/WebToLeadFromHandlerMiddleware.cs

448 lines
17 KiB
C#
Raw Normal View History

2021-03-02 16:29:07 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
2021-03-13 12:22:14 +00:00
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
2021-03-13 12:22:14 +00:00
using System.Web;
2021-03-02 16:29:07 +00:00
using ASC.Common.Logging;
using ASC.Core;
2021-03-13 12:22:14 +00:00
using ASC.Core.Common.Settings;
using ASC.CRM.Classes;
2021-03-02 16:29:07 +00:00
using ASC.CRM.Core;
using ASC.CRM.Core.Dao;
using ASC.CRM.Core.Entities;
using ASC.CRM.Core.Enums;
using ASC.CRM.Resources;
using ASC.MessagingSystem;
using ASC.Web.Core;
using ASC.Web.CRM.Classes;
using ASC.Web.CRM.Configuration;
using ASC.Web.CRM.Services.NotifyService;
2021-03-13 12:22:14 +00:00
using Microsoft.AspNetCore.Builder;
2021-03-02 16:29:07 +00:00
using Microsoft.AspNetCore.Http;
2021-03-13 12:22:14 +00:00
using Microsoft.Extensions.Options;
2021-03-02 16:29:07 +00:00
namespace ASC.Web.CRM.HttpHandlers
{
2021-03-13 12:22:14 +00:00
public class WebToLeadFromHandlerMiddleware
2021-03-02 16:29:07 +00:00
{
private HttpContext _context;
private readonly RequestDelegate _next;
2021-03-13 12:22:14 +00:00
public Global Global { get; set; }
public WebItemSecurity WebItemSecurity { get; set; }
public SecurityContext SecurityContext { get; set; }
2021-05-05 14:09:05 +00:00
public CrmSecurity CRMSecurity { get; set; }
2021-03-13 12:22:14 +00:00
public MessageTarget MessageTarget { get; set; }
public ILog Logger { get; set; }
public NotifyClient NotifyClient { get; set; }
public MessageService MessageService { get; set; }
public SettingsManager SettingsManager { get; set; }
public DaoFactory DaoFactory { get; set; }
public WebToLeadFromHandlerMiddleware(
RequestDelegate next
)
2021-03-02 16:29:07 +00:00
{
_next = next;
}
private String GetValue(String propertyName)
{
return _context.Request.Form[propertyName];
}
private bool CheckPermission()
{
try
{
var webFromKey = GetValue("web_form_key");
if (String.IsNullOrEmpty(webFromKey))
return false;
var webFromKeyAsGuid = new Guid(webFromKey);
2021-05-05 14:09:05 +00:00
var TenantSettings = SettingsManager.Load<CrmSettings>();
2021-03-13 12:22:14 +00:00
2021-03-02 16:29:07 +00:00
return TenantSettings.WebFormKey == webFromKeyAsGuid;
}
catch (Exception)
{
return false;
}
}
2021-03-13 12:22:14 +00:00
public async System.Threading.Tasks.Task Invoke(HttpContext context,
WebItemSecurity webItemSecurity,
SecurityContext securityContext,
2021-05-05 14:09:05 +00:00
CrmSecurity crmSecurity,
2021-03-13 12:22:14 +00:00
MessageTarget messageTarget,
MessageService messageService,
Global global,
IOptionsMonitor<ILog> logger,
NotifyClient notifyClient,
SettingsManager settingsManager,
DaoFactory daoFactory)
2021-03-02 16:29:07 +00:00
{
try
{
2021-03-13 12:22:14 +00:00
WebItemSecurity = webItemSecurity;
SecurityContext = securityContext;
2021-04-06 17:33:28 +00:00
CRMSecurity = crmSecurity;
2021-03-13 12:22:14 +00:00
MessageTarget = messageTarget;
MessageService = messageService;
Global = global;
Logger = logger.Get("ASC.CRM");
NotifyClient = notifyClient;
SettingsManager = settingsManager;
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
_context = context;
2021-03-02 16:29:07 +00:00
2021-08-18 14:04:16 +00:00
SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (!CheckPermission())
{
throw new Exception(CRMSettingResource.WebToLeadsForm_InvalidKeyException);
}
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var productInfo = WebItemSecurity.GetSecurityInfo(ProductEntryPoint.ID.ToString());
if (!productInfo.Enabled)
{
throw new Exception(CRMCommonResource.CRMProductIsDisabled);
}
Contact contact;
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var fieldCollector = new NameValueCollection();
2021-03-02 16:29:07 +00:00
2021-06-04 14:38:42 +00:00
var addressTemplate = new Dictionary<String, Object>();
2021-03-13 12:22:14 +00:00
foreach (String addressPartName in Enum.GetNames(typeof(AddressPart)))
addressTemplate.Add(addressPartName.ToLower(), "");
2021-06-04 14:38:42 +00:00
var addressTemplateStr = JsonSerializer.Serialize(addressTemplate);
2021-03-02 16:29:07 +00:00
2022-01-12 12:34:58 +00:00
bool isCompany;
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var isCompanyString = GetValue("is_company");
var firstName = GetValue("firstName");
var lastName = GetValue("lastName");
var companyName = GetValue("companyName");
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (!String.IsNullOrEmpty(isCompanyString))
{
if (!Boolean.TryParse(isCompanyString, out isCompany))
2021-03-02 16:29:07 +00:00
{
2021-03-13 12:22:14 +00:00
throw new ArgumentException();
2021-03-02 16:29:07 +00:00
}
2021-03-13 12:22:14 +00:00
}
else //old scheme
{
if (!String.IsNullOrEmpty(firstName))
2021-03-02 16:29:07 +00:00
{
2021-03-13 12:22:14 +00:00
isCompany = false;
2021-03-02 16:29:07 +00:00
}
2021-03-13 12:22:14 +00:00
else if (!String.IsNullOrEmpty(companyName))
2021-03-02 16:29:07 +00:00
{
2021-03-13 12:22:14 +00:00
isCompany = true;
2021-03-02 16:29:07 +00:00
}
else
{
2021-03-13 12:22:14 +00:00
throw new ArgumentException();
}
}
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (isCompany)
{
contact = new Company();
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
((Company)contact).CompanyName = companyName;
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
fieldCollector.Add(CRMContactResource.CompanyName, companyName);
}
else
{
contact = new Person();
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
((Person)contact).FirstName = firstName;
((Person)contact).LastName = lastName;
((Person)contact).JobTitle = GetValue("jobTitle");
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
fieldCollector.Add(CRMContactResource.FirstName, firstName);
fieldCollector.Add(CRMContactResource.LastName, lastName);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (!String.IsNullOrEmpty(GetValue("jobTitle")))
fieldCollector.Add(CRMContactResource.JobTitle, ((Person)contact).JobTitle);
}
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
contact.About = GetValue("about");
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (!String.IsNullOrEmpty(contact.About))
fieldCollector.Add(CRMContactResource.About, contact.About);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (!String.IsNullOrEmpty(GetValue("is_shared")))
{
contact.ShareType = Convert.ToBoolean(GetValue("is_shared"))
? ShareType.ReadWrite
: ShareType.None;
}
else
{
contact.ShareType = (ShareType)(Convert.ToInt32(GetValue("share_type")));
}
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
contact.ID = daoFactory.GetContactDao().SaveContact(contact);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var messageAction = contact is Company
? MessageAction.CompanyCreatedWithWebForm
: MessageAction.PersonCreatedWithWebForm;
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
MessageService.Send(MessageInitiator.System, messageAction,
MessageTarget.Create(contact.ID), contact.GetTitle());
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var contactInfos = new List<ContactInfo>();
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
foreach (var key in _context.Request.Form.Keys)
{
if (key.StartsWith("customField_"))
{
var fieldID = Convert.ToInt32(key.Split(new[] { '_' })[1]);
String fieldValue = GetValue(key);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (String.IsNullOrEmpty(fieldValue)) continue;
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var customField = daoFactory.GetCustomFieldDao().GetFieldDescription(fieldID);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (customField == null ||
!(customField.EntityType == EntityType.Contact ||
customField.EntityType == EntityType.Company && isCompany ||
customField.EntityType == EntityType.Person && !isCompany)) continue;
2021-03-02 16:29:07 +00:00
2021-05-17 14:50:55 +00:00
if (customField.Type == CustomFieldType.CheckBox)
2021-03-13 12:22:14 +00:00
{
fieldValue = fieldValue == "on" || fieldValue == "true" ? "true" : "false";
}
fieldCollector.Add(customField.Label, fieldValue);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
daoFactory.GetCustomFieldDao().SetFieldValue(isCompany ? EntityType.Company : EntityType.Person, contact.ID, fieldID, fieldValue);
}
else if (key.StartsWith("contactInfo_"))
{
var nameParts = key.Split(new[] { '_' }).Skip(1).ToList();
var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]);
var category = Convert.ToInt32(nameParts[1]);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
bool categoryIsExists = Enum.GetValues(ContactInfo.GetCategory(contactInfoType))
.Cast<object>()
.Any(categoryEnum => (int)categoryEnum == category);
if (!categoryIsExists)
2022-01-14 13:12:37 +00:00
throw new ArgumentException($"Category for {nameParts[0]} not found");
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (contactInfoType == ContactInfoType.Address)
{
var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]);
var findedAddress =
contactInfos.Find(
item =>
(category == item.Category) && (item.InfoType == ContactInfoType.Address));
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (findedAddress == null)
{
findedAddress = new ContactInfo
{
Category = category,
InfoType = contactInfoType,
Data = addressTemplateStr,
ContactID = contact.ID
};
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
contactInfos.Add(findedAddress);
2021-03-02 16:29:07 +00:00
}
Dictionary<string, object> addressParts = JsonSerializer.Deserialize<Dictionary<string, object>>(findedAddress.Data);
2021-03-13 12:22:14 +00:00
addressParts[addressPart.ToString().ToLower()] = GetValue(key);
string newJson = JsonSerializer.Serialize(addressParts);
2021-06-04 14:38:42 +00:00
findedAddress.Data = JsonSerializer.Serialize(addressParts);
2021-03-13 12:22:14 +00:00
continue;
2021-03-02 16:29:07 +00:00
}
2021-03-13 12:22:14 +00:00
var fieldValue = GetValue(key);
if (String.IsNullOrEmpty(fieldValue)) continue;
contactInfos.Add(new ContactInfo
2021-03-02 16:29:07 +00:00
{
2021-03-13 12:22:14 +00:00
Category = category,
InfoType = contactInfoType,
Data = fieldValue,
ContactID = contact.ID,
IsPrimary = true
});
}
2022-01-12 15:42:03 +00:00
else if (string.Equals(key, "tag", StringComparison.OrdinalIgnoreCase))
2021-03-13 12:22:14 +00:00
{
var tags = _context.Request.Form["tag"];
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
daoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, tags);
2021-03-02 16:29:07 +00:00
}
2021-03-13 12:22:14 +00:00
}
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
contactInfos.ForEach(
item =>
fieldCollector[item.InfoType.ToLocalizedString()] =
PrepareteDataToView(item.InfoType, item.Data));
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
daoFactory.GetContactInfoDao().SaveList(contactInfos, contact);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var notifyList = GetValue("notify_list");
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (!String.IsNullOrEmpty(notifyList))
NotifyClient.SendAboutCreateNewContact(
notifyList
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => new Guid(item)).ToList(), contact.ID, contact.GetTitle(), fieldCollector);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var managersList = GetValue("managers_list");
SetPermission(contact, managersList);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (contact is Person && !String.IsNullOrEmpty(companyName))
AssignPersonToCompany((Person)contact, companyName, managersList, daoFactory);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
if (contact is Company && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName))
AssignCompanyToPerson((Company)contact, firstName, lastName, managersList, daoFactory);
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
SecurityContext.Logout();
2021-03-02 16:29:07 +00:00
2021-03-13 12:22:14 +00:00
var newURL = new UriBuilder(GetValue("return_url")).Uri.AbsoluteUri;
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.Found;
context.Response.Headers.Add("Location", newURL);
await context.Response.WriteAsync("<HTML><Head>");
2022-01-14 13:12:37 +00:00
await context.Response.WriteAsync($"<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={newURL}\">");
await context.Response.WriteAsync($"<Script>window.location='{newURL}';</Script>");
2021-03-13 12:22:14 +00:00
await context.Response.WriteAsync("</Head>");
await context.Response.WriteAsync("</HTML>");
2021-03-02 16:29:07 +00:00
}
catch (Exception error)
{
2021-03-13 12:22:14 +00:00
Logger.Error(error);
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await context.Response.WriteAsync(HttpUtility.HtmlEncode(error.Message));
2021-03-02 16:29:07 +00:00
}
}
private String PrepareteDataToView(ContactInfoType contactInfoType, String data)
{
if (contactInfoType != ContactInfoType.Address) return data;
var addressParts = JsonDocument.Parse(data).RootElement;
2021-03-02 16:29:07 +00:00
var address = new StringBuilder();
foreach (AddressPart addressPartEnum in Enum.GetValues(typeof(AddressPart)))
address.Append(addressParts.GetProperty(addressPartEnum.ToString().ToLower()).GetString() + " ");
2021-03-02 16:29:07 +00:00
return address.ToString();
}
public bool IsReusable
{
get { return false; }
}
protected void SetPermission(Contact contact, String privateList)
{
if (String.IsNullOrEmpty(privateList)) return;
var selectedUsers = privateList
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => new Guid(item)).ToList();
CRMSecurity.SetAccessTo(contact, selectedUsers);
}
protected void AssignCompanyToPerson(Company company, String firstName, String lastName, String privateList, DaoFactory daoFactory)
{
var person = new Person
{
FirstName = firstName,
LastName = lastName,
CompanyID = company.ID
};
person.ID = daoFactory.GetContactDao().SaveContact(person);
SetPermission(person, privateList);
}
protected void AssignPersonToCompany(Person person, String companyName, String privateList, DaoFactory daoFactory)
{
Company company;
var findedCompanies = daoFactory.GetContactDao().GetContactsByName(companyName, true).ToList();
if (findedCompanies.Count == 0)
{
company = new Company
{
CompanyName = companyName
};
company.ID = daoFactory.GetContactDao().SaveContact(company);
SetPermission(company, privateList);
}
else
{
company = (Company)findedCompanies[0];
}
daoFactory.GetContactDao().AddMember(person.ID, company.ID);
}
}
2021-03-13 12:22:14 +00:00
public static class WebToLeadFromHandlerMiddlewareExtensions
{
public static IApplicationBuilder UseWebToLeadFromHandlerHandler(this IApplicationBuilder builder)
{
return builder.UseMiddleware<WebToLeadFromHandlerMiddleware>();
}
}
2021-03-02 16:29:07 +00:00
}