PageRenderTime 38ms CodeModel.GetById 2ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 1ms

/web/studio/ASC.Web.Studio/Products/CRM/HttpHandlers/WebToLeadFromHandler.ashx.cs

https://github.com/DevExperience/ONLYOFFICE-Server
C# | 376 lines | 274 code | 75 blank | 27 comment | 55 complexity | f13a1a906b84233d8e2d11e9117e58ea MD5 | raw file
  1/*
  2(c) Copyright Ascensio System SIA 2010-2014
  3
  4This program is a free software product.
  5You can redistribute it and/or modify it under the terms 
  6of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
  7Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
  8to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of 
  9any third-party rights.
 10
 11This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty 
 12of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For details, see 
 13the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 14
 15You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
 16
 17The  interactive user interfaces in modified source and object code versions of the Program must 
 18display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
 19 
 20Pursuant to Section 7(b) of the License you must retain the original Product logo when 
 21distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under 
 22trademark law for use of our trademarks.
 23 
 24All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
 25content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
 26International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 27*/
 28
 29using System;
 30using System.Collections.Specialized;
 31using System.Text;
 32using System.Web;
 33using ASC.CRM.Core;
 34using ASC.CRM.Core.Entities;
 35using ASC.Core;
 36using ASC.MessagingSystem;
 37using ASC.Web.CRM.Classes;
 38using System.Collections.Generic;
 39using System.Linq;
 40using System.Xml.Linq;
 41using ASC.Web.CRM.Services.NotifyService;
 42using Newtonsoft.Json.Linq;
 43using ASC.Web.CRM.Resources;
 44using log4net;
 45using ASC.Web.Core;
 46using ASC.Web.CRM.Configuration;
 47using ASC.Web.CRM.Core.Enums;
 48
 49namespace ASC.Web.CRM.HttpHandlers
 50{
 51    public class WebToLeadFromHandler : IHttpHandler
 52    {
 53        private HttpContext _context;
 54
 55        private String GetValue(String propertyName)
 56        {
 57            return _context.Request.Form[propertyName];
 58        }
 59
 60        private bool CheckPermission()
 61        {
 62            try
 63            {
 64                var webFromKey = GetValue("web_form_key");
 65
 66                if (String.IsNullOrEmpty(webFromKey))
 67                    return false;
 68
 69                var webFromKeyAsGuid = new Guid(webFromKey);
 70
 71                return Global.TenantSettings.WebFormKey == webFromKeyAsGuid;
 72            }
 73            catch(Exception)
 74            {
 75                return false;
 76            }
 77        }
 78
 79        public void ProcessRequest(HttpContext context)
 80        {
 81            try
 82            {
 83                _context = context;
 84
 85                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
 86
 87                if (!CheckPermission())
 88                {
 89                    throw new Exception(CRMSettingResource.WebToLeadsForm_InvalidKeyException);
 90                }
 91
 92                var productInfo = WebItemSecurity.GetSecurityInfo(ProductEntryPoint.ID.ToString());
 93                if (!productInfo.Enabled)
 94                {
 95                    throw new Exception(CRMCommonResource.CRMProductIsDisabled);
 96                }
 97
 98                Contact contact;
 99
100                var fieldCollector = new NameValueCollection();
101
102                var addressTemplate = new JObject();
103                foreach (String addressPartName in Enum.GetNames(typeof(AddressPart)))
104                    addressTemplate.Add(addressPartName.ToLower(), "");
105                var addressTemplateStr = addressTemplate.ToString();
106
107                var isCompany = false;
108
109                var isCompanyString = GetValue("is_company");
110                var firstName = GetValue("firstName");
111                var lastName = GetValue("lastName");
112                var companyName = GetValue("companyName");
113
114                if (!String.IsNullOrEmpty(isCompanyString))
115                {
116                    if (!Boolean.TryParse(isCompanyString, out isCompany))
117                    {
118                        throw new ArgumentException();
119                    }
120                }
121                else //old scheme
122                {
123                    if (!(String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName)))
124                    {
125                        isCompany = false;
126                    }
127                    else if (!String.IsNullOrEmpty(companyName))
128                    {
129                        isCompany = true;
130                    }
131                    else
132                    {
133                        throw new ArgumentException();
134                    }
135                }
136
137
138                if (isCompany)
139                {
140                    contact = new Company();
141
142                    ((Company)contact).CompanyName = companyName;
143
144                    fieldCollector.Add(CRMContactResource.CompanyName, companyName);
145                }
146                else
147                {
148                    contact = new Person();
149
150                    ((Person)contact).FirstName = firstName;
151                    ((Person)contact).LastName = lastName;
152                    ((Person)contact).JobTitle = GetValue("jobTitle");
153
154                    fieldCollector.Add(CRMContactResource.FirstName, firstName);
155                    fieldCollector.Add(CRMContactResource.LastName, lastName);
156
157                    if (!String.IsNullOrEmpty(GetValue("jobTitle")))
158                        fieldCollector.Add(CRMContactResource.JobTitle, ((Person)contact).JobTitle);
159                }
160
161                contact.About = GetValue("about");
162
163                if (!String.IsNullOrEmpty(contact.About))
164                    fieldCollector.Add(CRMContactResource.About, contact.About);
165
166                if (!String.IsNullOrEmpty(GetValue("is_shared")))
167                {
168                    contact.ShareType = Convert.ToBoolean(GetValue("is_shared")) ? ShareType.ReadWrite : ShareType.None;
169                }
170                else
171                {
172                    contact.ShareType = (ShareType)(Convert.ToInt32(GetValue("share_type")));
173                }
174
175                contact.ID = Global.DaoFactory.GetContactDao().SaveContact(contact);
176                
177                var messageAction = contact is Company ? MessageAction.CompanyCreatedWithWebForm : MessageAction.PersonCreatedWithWebForm;
178                MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, contact.GetTitle());
179
180                var contactInfos = new List<ContactInfo>();
181
182                foreach (var key in _context.Request.Form.AllKeys)
183                {
184                    if (key.StartsWith("customField_"))
185                    {
186                        var fieldID = Convert.ToInt32(key.Split(new[] {'_'})[1]);
187                        String fieldValue = GetValue(key);
188
189                        if (String.IsNullOrEmpty(fieldValue)) continue;
190
191                        var customField = Global.DaoFactory.GetCustomFieldDao().GetFieldDescription(fieldID);
192
193                        if (customField == null ||
194                            !(customField.EntityType == EntityType.Contact ||
195                              customField.EntityType == EntityType.Company && isCompany ||
196                              customField.EntityType == EntityType.Person && !isCompany)) continue;
197
198                        if (customField.FieldType == CustomFieldType.CheckBox)
199                        {
200                            fieldValue = fieldValue == "on" || fieldValue == "true" ? "true" : "false";
201                        }
202                        fieldCollector.Add(customField.Label, fieldValue);
203
204                        Global.DaoFactory.GetCustomFieldDao().SetFieldValue(isCompany ? EntityType.Company : EntityType.Person, contact.ID, fieldID, fieldValue);
205                    }
206                    else if (key.StartsWith("contactInfo_"))
207                    {
208                        var nameParts = key.Split(new[] {'_'}).Skip(1).ToList();
209                        var contactInfoType = (ContactInfoType)Enum.Parse(typeof(ContactInfoType), nameParts[0]);
210                        var category = Convert.ToInt32(nameParts[1]);
211
212                        bool categoryIsExists = Enum.GetValues(ContactInfo.GetCategory(contactInfoType)).Cast<object>()
213                                                    .Any(categoryEnum => (int)categoryEnum == category);
214                        if (!categoryIsExists)
215                            throw new ArgumentException(String.Format("Category for {0} not found", nameParts[0]));
216
217                        if (contactInfoType == ContactInfoType.Address)
218                        {
219                            var addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), nameParts[2]);
220
221                            var findedAddress = contactInfos.Find(item => (category == item.Category) && (item.InfoType == ContactInfoType.Address));
222
223                            if (findedAddress == null)
224                            {
225                                findedAddress = new ContactInfo
226                                    {
227                                        Category = category,
228                                        InfoType = contactInfoType,
229                                        Data = addressTemplateStr,
230                                        ContactID = contact.ID
231                                    };
232
233                                contactInfos.Add(findedAddress);
234                            }
235
236                            var addressParts = JObject.Parse(findedAddress.Data);
237
238                            addressParts[addressPart.ToString().ToLower()] = GetValue(key);
239
240                            findedAddress.Data = addressParts.ToString();
241
242                            continue;
243                        }
244
245                        var fieldValue = GetValue(key);
246
247                        if (String.IsNullOrEmpty(fieldValue)) continue;
248
249                        contactInfos.Add(new ContactInfo
250                            {
251                                Category = category,
252                                InfoType = contactInfoType,
253                                Data = fieldValue,
254                                ContactID = contact.ID,
255                                IsPrimary = true
256                            });
257                    }
258                    else if (String.Compare(key, "tag", true) == 0)
259                    {
260                        var tags = _context.Request.Form.GetValues("tag");
261
262                        Global.DaoFactory.GetTagDao().SetTagToEntity(EntityType.Contact, contact.ID, tags);
263                    }
264                }
265
266                contactInfos.ForEach(item => fieldCollector[item.InfoType.ToLocalizedString()] = PrepareteDataToView(item.InfoType, item.Data));
267
268                Global.DaoFactory.GetContactInfoDao().SaveList(contactInfos);
269
270                var notifyList = GetValue("notify_list");
271
272                if (!String.IsNullOrEmpty(notifyList))
273                    NotifyClient.Instance.SendAboutCreateNewContact(
274                        notifyList
275                            .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
276                            .Select(item => new Guid(item)).ToList(), contact.ID, contact.GetTitle(), fieldCollector);
277
278                var managersList = GetValue("managers_list");
279                SetPermission(contact, managersList);
280
281                if (contact is Person && !String.IsNullOrEmpty(companyName))
282                    AssignPersonToCompany((Person)contact, companyName, managersList);
283
284                if (contact is Company && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName))
285                    AssignCompanyToPerson((Company)contact, firstName, lastName, managersList);
286
287                SecurityContext.Logout();
288
289                var newURL = new UriBuilder(GetValue("return_url")).Uri.AbsoluteUri;
290                context.Response.Buffer = true;
291                context.Response.Status = "302 Object moved";
292                context.Response.AddHeader("Location", newURL);
293                context.Response.Write("<HTML><Head>");
294                context.Response.Write(String.Format("<META HTTP-EQUIV=Refresh CONTENT=\"0;URL={0}\">", newURL));
295                context.Response.Write(String.Format("<Script>window.location='{0}';</Script>", newURL));
296                context.Response.Write("</Head>");
297                context.Response.Write("</HTML>");
298            }
299            catch(Exception error)
300            {
301                LogManager.GetLogger("ASC.CRM").Error(error);
302                context.Response.StatusCode = 400;
303                context.Response.Write(HttpUtility.HtmlEncode(error.Message));
304            }
305        }
306
307        private String PrepareteDataToView(ContactInfoType contactInfoType, String data)
308        {
309            if (contactInfoType != ContactInfoType.Address) return data;
310
311            var addressParts = JObject.Parse(data);
312
313            var address = new StringBuilder();
314
315            foreach (AddressPart addressPartEnum in Enum.GetValues(typeof(AddressPart)))
316                address.Append(addressParts[addressPartEnum.ToString().ToLower()] + " ");
317
318            return address.ToString();
319        }
320
321        public bool IsReusable
322        {
323            get { return false; }
324        }
325
326        protected void SetPermission(Contact contact, String privateList)
327        {
328            if (String.IsNullOrEmpty(privateList)) return;
329
330            var selectedUsers = privateList
331                .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
332                .Select(item => new Guid(item)).ToList();
333
334            CRMSecurity.SetAccessTo(contact, selectedUsers);
335        }
336
337        protected void AssignCompanyToPerson(Company company, String firstName, String lastName, String privateList)
338        {
339            var person = new Person
340                {
341                    FirstName = firstName,
342                    LastName = lastName,
343                    CompanyID = company.ID
344                };
345            person.ID = Global.DaoFactory.GetContactDao().SaveContact(person);
346            SetPermission(person, privateList);
347        }
348
349
350        protected void AssignPersonToCompany(Person person, String companyName, String privateList)
351        {
352            Company company;
353
354            var findedCompanies = Global.DaoFactory.GetContactDao().GetContactsByName(companyName)
355                                        .Where(item => item is Company).ToList();
356
357            if (findedCompanies.Count == 0)
358            {
359                company = new Company
360                    {
361                        CompanyName = companyName
362                    };
363
364                company.ID = Global.DaoFactory.GetContactDao().SaveContact(company);
365
366                SetPermission(company, privateList);
367            }
368            else
369            {
370                company = (Company)findedCompanies[0];
371            }
372
373            Global.DaoFactory.GetContactDao().AddMember(person.ID, company.ID);
374        }
375    }
376}