/* * * (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. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Collections; using ASC.Api.Core; using ASC.Api.CRM; using ASC.Common.Threading.Progress; using ASC.Common.Web; using ASC.Core; using ASC.Core.Users; using ASC.CRM.ApiModels; 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.Api.Models; using ASC.Web.Api.Routing; using ASC.Web.CRM.Classes; using ASC.Web.CRM.Services.NotifyService; using ASC.Web.Studio.Core; using Autofac; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Contact = ASC.CRM.Core.Entities.Contact; namespace ASC.CRM.Api { public class ContactsController : BaseApiController { private readonly MailSender _mailSender; private readonly FileSizeComment _fileSizeComment; private readonly ContactPhotoManager _contactPhotoManager; private readonly EmployeeWraperHelper _employeeWraperHelper; private readonly UserFormatter _userFormatter; private readonly SetupInfo _setupInfo; private readonly SecurityContext _securityContext; private readonly NotifyClient _notifyClient; private readonly ApiContext _apiContext; private readonly MessageService _messageService; private readonly MessageTarget _messageTarget; public ContactsController(CrmSecurity crmSecurity, DaoFactory daoFactory, ApiContext apiContext, MessageTarget messageTarget, MessageService messageService, NotifyClient notifyClient, SecurityContext securityContext, SetupInfo setupInfo, UserFormatter userFormatter, EmployeeWraperHelper employeeWraperHelper, ContactPhotoManager contactPhotoManager, FileSizeComment fileSizeComment, MailSender mailSender, IMapper mapper) : base(daoFactory, crmSecurity, mapper) { _apiContext = apiContext; _messageTarget = messageTarget; _messageService = messageService; _notifyClient = notifyClient; _securityContext = securityContext; _setupInfo = setupInfo; _userFormatter = userFormatter; _employeeWraperHelper = employeeWraperHelper; _contactPhotoManager = contactPhotoManager; _fileSizeComment = fileSizeComment; _mailSender = mailSender; _mapper = mapper; } /// /// Returns the detailed information about the contact with the ID specified in the request /// /// Contact ID /// Contact /// Get contact by ID /// Contacts /// /// [Read(@"contact/{contactid:int}")] public ContactDto GetContactByID(int contactid) { if (contactid <= 0) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().GetByID(contactid); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); return _mapper.Map(contact); } public IEnumerable GetContactsByID(IEnumerable contactid) { var contacts = _daoFactory.GetContactDao().GetContacts(contactid.ToArray()).Where(r => r != null && _crmSecurity.CanAccessTo(r)).ToList(); return _mapper.Map, List>(contacts); } /// /// Returns the contact list for the project with the ID specified in the request /// /// /// Get contacts by project ID /// /// Project ID /// Contacts /// /// Contact list /// /// [Read(@"contact/project/{projectid:int}")] public IEnumerable GetContactsByProjectID(int projectid) { if (projectid <= 0) throw new ArgumentException(); var contacts = _daoFactory.GetContactDao().GetContactsByProjectID(projectid); return _mapper.Map, List>(contacts.ToList()); } ///// ///// Links the selected contact to the project with the ID specified in the request ///// ///// Contact ID ///// Project ID ///// Contacts ///// Link contact with project ///// ///// ///// Contact Info //[Create(@"contact/{contactid:int}/project/{projectid:int}")] //public ContactDto SetRelativeContactToProject(int contactid, int projectid) //{ // if (contactid <= 0 || projectid <= 0) throw new ArgumentException(); // var contact = DaoFactory.GetContactDao().GetByID(contactid); // if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); // var project = ProjectsDaoFactory.ProjectDao.GetById(projectid); // if (project == null) throw new ItemNotFoundException(); // using (var scope = DIHelper.Resolve()) // { // if (!scope.Resolve().CanLinkContact(project)) throw CRMSecurity.CreateSecurityException(); // } // DaoFactory.GetContactDao().SetRelativeContactProject(new List { contactid }, projectid); // var messageAction = contact is Company ? MessageAction.ProjectLinkedCompany : MessageAction.ProjectLinkedPerson; // MessageService.Send(messageAction, MessageTarget.Create(contact.ID), project.Title, contact.GetTitle()); // return ToContactDto(contact); //} ///// ///// Links the selected contacts to the project with the ID specified in the request ///// ///// Contact IDs array ///// Project ID ///// Contacts ///// Link contact list with project ///// ///// ///// ///// Contact list ///// //[Create(@"contact/project/{projectid:int}")] //public IEnumerable SetRelativeContactListToProject(IEnumerable contactid, int projectid) //{ // if (contactid == null) throw new ArgumentException(); // var contactIds = contactid.ToList(); // if (!contactIds.Any() || projectid <= 0) throw new ArgumentException(); // var project = ProjectsDaoFactory.ProjectDao.GetById(projectid); // if (project == null) throw new ItemNotFoundException(); // using (var scope = DIHelper.Resolve()) // { // if (!scope.Resolve().CanLinkContact(project)) // throw CRMSecurity.CreateSecurityException(); // } // var contacts = DaoFactory.GetContactDao().GetContacts(contactIds.ToArray()).Where(CRMSecurity.CanAccessTo).ToList(); // contactIds = contacts.Select(c => c.ID).ToList(); // DaoFactory.GetContactDao().SetRelativeContactProject(contactIds, projectid); // MessageService.Send(MessageAction.ProjectLinkedContacts, MessageTarget.Create(contactIds), project.Title, contacts.Select(x => x.GetTitle())); // return contacts.ConvertAll(ToContactDto); //} ///// ///// Removes the link with the selected project from the contact with the ID specified in the request ///// ///// Contact ID ///// Project ID ///// Contacts ///// Remove contact from project ///// ///// Contact info ///// //[Delete(@"contact/{contactid:int}/project/{projectid:int}")] //public ContactBaseDto RemoveRelativeContactToProject(int contactid, int projectid) //{ // if (contactid <= 0 || projectid <= 0) throw new ArgumentException(); // var contact = DaoFactory.GetContactDao().GetByID(contactid); // if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); // var project = ProjectsDaoFactory.ProjectDao.GetById(projectid); // using (var scope = DIHelper.Resolve()) // { // if (project == null || !scope.Resolve().CanLinkContact(project)) throw new ItemNotFoundException(); // } // DaoFactory.GetContactDao().RemoveRelativeContactProject(contactid, projectid); // var action = contact is Company ? MessageAction.ProjectUnlinkedCompany : MessageAction.ProjectUnlinkedPerson; // MessageService.Send(action, MessageTarget.Create(contact.ID), project.Title, contact.GetTitle()); // return ToContactBaseDto(contact); //} /// /// Adds the selected opportunity to the contact with the ID specified in the request. The same as AddMemberToDeal /// /// Opportunity ID /// Contact ID /// Add contact opportunity /// Contacts /// /// /// Opportunity /// [Create(@"contact/{contactid:int}/opportunity/{opportunityid:int}")] public OpportunityDto AddDealToContact([FromRoute] int contactid, [FromRoute] int opportunityid) { if ((opportunityid <= 0) || (contactid <= 0)) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().GetByID(contactid); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); var opportunity = _daoFactory.GetDealDao().GetByID(opportunityid); if (opportunity == null || !_crmSecurity.CanAccessTo(opportunity)) throw new ItemNotFoundException(); _daoFactory.GetDealDao().AddMember(opportunityid, contactid); var messageAction = contact is Company ? MessageAction.OpportunityLinkedCompany : MessageAction.OpportunityLinkedPerson; _messageService.Send(messageAction, _messageTarget.Create(contact.ID), opportunity.Title, contact.GetTitle()); return _mapper.Map(opportunity); } /// /// Deletes the selected opportunity from the contact with the ID specified in the request /// /// Opportunity ID /// Contact ID /// Delete contact opportunity /// Contacts /// /// /// Opportunity /// [Delete(@"contact/{contactid:int}/opportunity/{opportunityid:int}")] public OpportunityDto DeleteDealFromContact(int contactid, int opportunityid) { if ((opportunityid <= 0) || (contactid <= 0)) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().GetByID(contactid); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); var opportunity = _daoFactory.GetDealDao().GetByID(opportunityid); if (opportunity == null || !_crmSecurity.CanAccessTo(opportunity)) throw new ItemNotFoundException(); _daoFactory.GetDealDao().RemoveMember(opportunityid, contactid); return _mapper.Map(opportunity); } /// /// Returns the list of all contacts in the CRM module matching the parameters specified in the request /// /// Tag /// Contact stage ID (warmth) /// Contact type ID /// /// Start date /// End date /// Responsible ID /// Responsible ID /// Get contact list /// Contacts /// /// Contact list /// [Read(@"contact/filter")] public IEnumerable GetContacts( [FromQuery] IEnumerable tags, [FromQuery] int? contactStage, [FromQuery] int? contactType, [FromQuery] ContactListViewType contactListView, [FromQuery] Guid? responsibleid, [FromQuery] bool? isShared, [FromQuery] ApiDateTime fromDate, [FromQuery] ApiDateTime toDate) { IEnumerable result; OrderBy contactsOrderBy; ContactSortedByType sortBy; var searchString = _apiContext.FilterValue; if (ASC.CRM.Classes.EnumExtension.TryParse(_apiContext.SortBy, true, out sortBy)) { contactsOrderBy = new OrderBy(sortBy, !_apiContext.SortDescending); } else if (String.IsNullOrEmpty(_apiContext.SortBy)) { contactsOrderBy = new OrderBy(ContactSortedByType.Created, false); } else { contactsOrderBy = null; } var fromIndex = (int)_apiContext.StartIndex; var count = (int)_apiContext.Count; var contactStageInt = contactStage.HasValue ? contactStage.Value : -1; var contactTypeInt = contactType.HasValue ? contactType.Value : -1; if (contactsOrderBy != null) { var contacts = _daoFactory.GetContactDao().GetContacts( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, fromIndex, count, contactsOrderBy, responsibleid, isShared); result = _mapper.Map, List>(contacts); _apiContext.SetDataPaginated(); _apiContext.SetDataFiltered(); _apiContext.SetDataSorted(); } else { result = _mapper.Map, List>(_daoFactory.GetContactDao().GetContacts( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, 0, 0, null, responsibleid, isShared)); } int totalCount; if (result.Count() < count) { totalCount = fromIndex + result.Count(); } else { totalCount = _daoFactory.GetContactDao().GetContactsCount( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, responsibleid, isShared); } _apiContext.SetTotalCount(totalCount); return result; } /// /// Returns the list of the contacts for auto complete feature. /// /// String part of contact name, lastname or email. /// Max result count /// Search contact list /// Contacts /// /// Contact list /// /// false [Read(@"contact/simple/byEmail")] public IEnumerable SearchContactsByEmail(string term, int maxCount) { var result = ToSimpleListContactDto(_daoFactory.GetContactDao().SearchContactsByEmail( term, maxCount)); return result; } /// /// Returns the list of all contacts in the CRM module matching the parameters specified in the request /// /// Tag /// Contact stage ID (warmth) /// Contact type ID /// /// Responsible ID /// Responsible ID /// Start date /// End date /// Get contact list /// Contacts /// /// Contact list /// /// false [Read(@"contact/simple/filter")] public IEnumerable GetSimpleContacts( IEnumerable tags, int? contactStage, int? contactType, ContactListViewType contactListView, Guid? responsibleid, bool? isShared, ApiDateTime fromDate, ApiDateTime toDate) { IEnumerable result; OrderBy contactsOrderBy; ContactSortedByType sortBy; var searchString = _apiContext.FilterValue; if (ASC.CRM.Classes.EnumExtension.TryParse(_apiContext.SortBy, true, out sortBy)) { contactsOrderBy = new OrderBy(sortBy, !_apiContext.SortDescending); } else if (String.IsNullOrEmpty(_apiContext.SortBy)) { contactsOrderBy = new OrderBy(ContactSortedByType.DisplayName, true); } else { contactsOrderBy = null; } var fromIndex = (int)_apiContext.StartIndex; var count = (int)_apiContext.Count; var contactStageInt = contactStage.HasValue ? contactStage.Value : -1; var contactTypeInt = contactType.HasValue ? contactType.Value : -1; if (contactsOrderBy != null) { result = ToSimpleListContactDto(_daoFactory.GetContactDao().GetContacts( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, fromIndex, count, contactsOrderBy, responsibleid, isShared)); _apiContext.SetDataPaginated(); _apiContext.SetDataFiltered(); _apiContext.SetDataSorted(); } else { result = ToSimpleListContactDto(_daoFactory.GetContactDao().GetContacts( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, 0, 0, null, responsibleid, isShared)); } int totalCount; if (result.Count() < count) { totalCount = fromIndex + result.Count(); } else { totalCount = _daoFactory.GetContactDao().GetContactsCount( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, responsibleid, isShared); } _apiContext.SetTotalCount(totalCount); return result; } /// /// Get the group of contacts with the IDs specified in the request /// /// Contact ID list /// /// /// Get contact group /// Contacts /// /// Contact list /// /// false [Read(@"contact/mail")] public IEnumerable GetContactsForMail(IEnumerable contactids) { if (contactids == null) throw new ArgumentException(); var contacts = _daoFactory.GetContactDao().GetContacts(contactids.ToArray()); var result = contacts.Select(x => _mapper.Map(x)); return result; } /// /// Deletes the list of all contacts in the CRM module matching the parameters specified in the request /// /// Tag /// Contact stage ID (warmth) /// Contact type ID /// /// Start date /// End date /// /// /// Delete the list of all contacts /// Contacts /// /// Contact list /// [Delete(@"contact/filter")] public IEnumerable DeleteBatchContacts( IEnumerable tags, int? contactStage, int? contactType, ContactListViewType contactListView, ApiDateTime fromDate, ApiDateTime toDate) { int contactStageInt = contactStage.HasValue ? contactStage.Value : -1; int contactTypeInt = contactType.HasValue ? contactType.Value : -1; var contacts = _daoFactory.GetContactDao().GetContacts( _apiContext.FilterValue, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, 0, 0, null); contacts = _daoFactory.GetContactDao().DeleteBatchContact(contacts); _messageService.Send(MessageAction.ContactsDeleted, _messageTarget.Create(contacts.Select(c => c.ID)), contacts.Select(c => c.GetTitle())); return contacts.Select(x => _mapper.Map(x)); } /// /// Returns the list of all the persons linked to the company with the ID specified in the request /// /// Company ID /// /// Get company linked persons list /// Contacts /// /// Linked persons /// [Read(@"contact/company/{companyid:int}/person")] public IEnumerable GetPeopleFromCompany(int companyid) { if (companyid <= 0) throw new ArgumentException(); var company = _daoFactory.GetContactDao().GetByID(companyid); if (company == null || !_crmSecurity.CanAccessTo(company)) throw new ItemNotFoundException(); var contacts = _daoFactory.GetContactDao().GetMembers(companyid).Where(_crmSecurity.CanAccessTo).ToList(); return _mapper.Map, List>(contacts); } /// /// Adds the selected person to the company with the ID specified in the request /// /// Company ID /// Person ID /// Add person to company /// Contacts /// /// /// /// Person /// [Create(@"contact/company/{companyid:int}/person")] public PersonDto AddPeopleToCompany([FromRoute] int companyid, [FromBody] int personid) { if ((companyid <= 0) || (personid <= 0)) throw new ArgumentException(); var company = _daoFactory.GetContactDao().GetByID(companyid); var person = _daoFactory.GetContactDao().GetByID(personid); if (person == null || company == null || !_crmSecurity.CanAccessTo(person) || !_crmSecurity.CanAccessTo(company)) throw new ItemNotFoundException(); _daoFactory.GetContactDao().AddMember(personid, companyid); _messageService.Send(MessageAction.CompanyLinkedPerson, _messageTarget.Create(new[] { company.ID, person.ID }), company.GetTitle(), person.GetTitle()); return (PersonDto)_mapper.Map(person); } /// /// Deletes the selected person from the company with the ID specified in the request /// /// Company ID /// Person ID /// Delete person from company /// Contacts /// /// /// /// Person /// [Delete(@"contact/company/{companyid:int}/person")] public PersonDto DeletePeopleFromCompany(int companyid, int personid) { if ((companyid <= 0) || (personid <= 0)) throw new ArgumentException(); var company = _daoFactory.GetContactDao().GetByID(companyid); var person = _daoFactory.GetContactDao().GetByID(personid); if (person == null || company == null || !_crmSecurity.CanAccessTo(person) || !_crmSecurity.CanAccessTo(company)) throw new ItemNotFoundException(); _daoFactory.GetContactDao().RemoveMember(personid); _messageService.Send(MessageAction.CompanyUnlinkedPerson, _messageTarget.Create(new[] { company.ID, person.ID }), company.GetTitle(), person.GetTitle()); return (PersonDto)_mapper.Map(person); } /// /// Creates the person with the parameters (first name, last name, description, etc.) specified in the request /// /// First name /// Last name /// Post /// Company ID /// Person description text /// Person privacy: 0 - not shared, 1 - shared for read/write, 2 - shared for read only /// List of managers for the person /// User field list /// Contact photo (upload using multipart/form-data) /// Create person /// Contacts /// Person /// [Create(@"contact/person")] public PersonDto CreatePerson([FromBody] CreateOrUpdatePersonRequestDto intDto) { string firstName = intDto.FirstName; string lastName = intDto.LastName; string jobTitle = intDto.JobTitle; int companyId = intDto.CompanyId; string about = intDto.About; ShareType shareType = intDto.ShareType; IEnumerable managerList = intDto.ManagerList; IEnumerable> customFieldList = intDto.CustomFieldList; IEnumerable photo = intDto.Photos; if (companyId > 0) { var company = _daoFactory.GetContactDao().GetByID(companyId); if (company == null || !_crmSecurity.CanAccessTo(company)) throw new ItemNotFoundException(); } var peopleInst = new Person { FirstName = firstName, LastName = lastName, JobTitle = jobTitle, CompanyID = companyId, About = about, ShareType = shareType }; peopleInst.ID = _daoFactory.GetContactDao().SaveContact(peopleInst); peopleInst.CreateBy = _securityContext.CurrentAccount.ID; peopleInst.CreateOn = DateTime.UtcNow; var managerListLocal = managerList != null ? managerList.ToList() : new List(); if (managerListLocal.Any()) { _crmSecurity.SetAccessTo(peopleInst, managerListLocal); } if (customFieldList != null) { foreach (var field in customFieldList) { if (string.IsNullOrEmpty(field.Value)) continue; _daoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, peopleInst.ID, field.Key, field.Value); } } var outDto = (PersonDto)_mapper.Map(peopleInst); var photoList = photo != null ? photo.ToList() : new List(); if (photoList.Any()) { outDto.SmallFotoUrl = ChangeContactPhoto(peopleInst.ID, photoList); } _messageService.Send(MessageAction.PersonCreated, _messageTarget.Create(peopleInst.ID), peopleInst.GetTitle()); return outDto; } /// /// Changes the photo for the contact with the ID specified in the request /// /// Contact ID /// Contact photo (upload using multipart/form-data) /// Change contact photo /// Contacts /// /// /// Path to contact photo /// [Update(@"contact/{contactid:int}/changephoto")] public string ChangeContactPhoto(int contactid, IEnumerable photo) { if (contactid <= 0) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().GetByID(contactid); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); var firstPhoto = photo != null ? photo.FirstOrDefault() : null; if (firstPhoto == null) throw new ArgumentException(); var fileStream = firstPhoto.OpenReadStream(); if (firstPhoto.Length == 0 || !firstPhoto.ContentType.StartsWith("image/") || !fileStream.CanRead) throw new InvalidOperationException(CRMErrorsResource.InvalidFile); if (_setupInfo.MaxImageUploadSize > 0 && _setupInfo.MaxImageUploadSize < firstPhoto.Length) throw new Exception(_fileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false)); return _contactPhotoManager.UploadPhoto(fileStream, contactid, false).Url; } /// /// Changes the photo for the contact with the ID specified in the request /// /// Contact ID /// contact photo url /// Change contact photo /// Contacts /// /// /// Path to contact photo /// [Update(@"contact/{contactid:int}/changephotobyurl")] public string ChangeContactPhoto(int contactid, string photourl) { if (contactid <= 0 || string.IsNullOrEmpty(photourl)) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().GetByID(contactid); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); return _contactPhotoManager.UploadPhoto(photourl, contactid, false).Url; } /// /// Merge two selected contacts /// /// the first contact ID for merge /// the second contact ID for merge /// Merge contacts /// Contacts /// /// /// /// /// Contact /// [Update(@"contact/merge")] public ContactDto MergeContacts(int fromcontactid, int tocontactid) { if (fromcontactid <= 0 || tocontactid <= 0) throw new ArgumentException(); var fromContact = _daoFactory.GetContactDao().GetByID(fromcontactid); var toContact = _daoFactory.GetContactDao().GetByID(tocontactid); if (fromContact == null || toContact == null) throw new ItemNotFoundException(); if (!_crmSecurity.CanEdit(fromContact) || !_crmSecurity.CanEdit(toContact)) throw _crmSecurity.CreateSecurityException(); _daoFactory.GetContactDao().MergeDublicate(fromcontactid, tocontactid); var resultContact = _daoFactory.GetContactDao().GetByID(tocontactid); var messageAction = resultContact is Person ? MessageAction.PersonsMerged : MessageAction.CompaniesMerged; _messageService.Send(messageAction, _messageTarget.Create(new[] { fromContact.ID, toContact.ID }), fromContact.GetTitle(), toContact.GetTitle()); return _mapper.Map(resultContact); } /// /// Updates the selected person with the parameters (first name, last name, description, etc.) specified in the request /// /// Person ID /// First name /// Last name /// Post /// Company ID /// Person description text /// Person privacy: 0 - not shared, 1 - shared for read/write, 2 - shared for read only /// List of persons managers /// User field list /// Contact photo (upload using multipart/form-data) /// Update person /// Contacts /// Person /// /// [Update(@"contact/person/{personid:int}")] public PersonDto UpdatePerson([FromQuery] int personid, [FromBody] CreateOrUpdatePersonRequestDto inDto) { string firstName = inDto.FirstName; string lastName = inDto.LastName; string jobTitle = inDto.JobTitle; int companyId = inDto.CompanyId; string about = inDto.About; ShareType shareType = inDto.ShareType; IEnumerable managerList = inDto.ManagerList; IEnumerable> customFieldList = inDto.CustomFieldList; IEnumerable photo = inDto.Photos; if (personid <= 0 || string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName)) throw new ArgumentException(); var peopleInst = new Person { ID = personid, FirstName = firstName, LastName = lastName, JobTitle = jobTitle, CompanyID = companyId, About = about, ShareType = shareType }; _daoFactory.GetContactDao().UpdateContact(peopleInst); peopleInst = (Person)_daoFactory.GetContactDao().GetByID(peopleInst.ID); var managerListLocal = managerList != null ? managerList.ToList() : new List(); if (managerListLocal.Any()) { _crmSecurity.SetAccessTo(peopleInst, managerListLocal); } if (customFieldList != null) { var existingCustomFieldList = _daoFactory.GetCustomFieldDao().GetFieldsDescription(EntityType.Person).Select(fd => fd.ID).ToList(); foreach (var field in customFieldList) { if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key)) continue; _daoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Person, peopleInst.ID, field.Key, field.Value); } } var outDto = (PersonDto)_mapper.Map(peopleInst); var photoList = photo != null ? photo.ToList() : new List(); if (photoList.Any()) { outDto.SmallFotoUrl = ChangeContactPhoto(peopleInst.ID, photoList); } _messageService.Send(MessageAction.PersonUpdated, _messageTarget.Create(peopleInst.ID), peopleInst.GetTitle()); return outDto; } /// /// Creates the company with the parameters specified in the request /// /// Company name /// Company description text /// Linked person list /// Company privacy: 0 - not shared, 1 - shared for read/write, 2 - shared for read only /// List of managers for the company /// User field list /// Contact photo (upload using multipart/form-data) /// Create company /// Contacts /// Company /// [Create(@"contact/company")] public CompanyDto CreateCompany([FromBody] CreateOrUpdateCompanyRequestDto inDto) { var personList = inDto.PersonList; string companyName = inDto.CompanyName; string about = inDto.About; ShareType shareType = inDto.ShareType; IEnumerable managerList = inDto.ManagerList; IEnumerable> customFieldList = inDto.CustomFieldList; IEnumerable photo = inDto.Photos; var companyInst = new Company { CompanyName = companyName, About = about, ShareType = shareType }; companyInst.ID = _daoFactory.GetContactDao().SaveContact(companyInst); companyInst.CreateBy = _securityContext.CurrentAccount.ID; companyInst.CreateOn = DateTime.UtcNow; if (personList != null) { foreach (var personID in personList) { var person = _daoFactory.GetContactDao().GetByID(personID); if (person == null || !_crmSecurity.CanAccessTo(person)) continue; AddPeopleToCompany(companyInst.ID, personID); } } var managerListLocal = managerList != null ? managerList.ToList() : new List(); if (managerListLocal.Any()) { _crmSecurity.SetAccessTo(companyInst, managerListLocal); } if (customFieldList != null) { var existingCustomFieldList = _daoFactory.GetCustomFieldDao().GetFieldsDescription(EntityType.Company).Select(fd => fd.ID).ToList(); foreach (var field in customFieldList) { if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key)) continue; _daoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Company, companyInst.ID, field.Key, field.Value); } } var wrapper = (CompanyDto)_mapper.Map(companyInst); var photoList = photo != null ? photo.ToList() : new List(); if (photoList.Any()) { wrapper.SmallFotoUrl = ChangeContactPhoto(companyInst.ID, photoList); } _messageService.Send(MessageAction.CompanyCreated, _messageTarget.Create(companyInst.ID), companyInst.GetTitle()); return wrapper; } /// /// Quickly creates the list of companies /// /// /// Quick company list creation /// /// Company name /// Contacts /// Contact list /// [Create(@"contact/company/quick")] public IEnumerable CreateCompany([FromBody] IEnumerable companyName) { if (companyName == null) throw new ArgumentException(); var contacts = new List(); var recordIndex = 0; foreach (var item in companyName) { if (string.IsNullOrEmpty(item)) continue; contacts.Add(new Company { ID = recordIndex++, CompanyName = item, ShareType = ShareType.None }); } if (contacts.Count == 0) return null; _daoFactory.GetContactDao().SaveContactList(contacts); var selectedManagers = new List { _securityContext.CurrentAccount.ID }; foreach (var ct in contacts) { _crmSecurity.SetAccessTo(ct, selectedManagers); } return contacts.ConvertAll(x => _mapper.Map(x)); } /// /// Quickly creates the list of persons with the first and last names specified in the request /// /// /// Quick person list creation /// /// Pairs: user first name, user last name /// /// /// /// Contacts /// Contact list /// [Create(@"contact/person/quick")] public IEnumerable CreatePerson([FromBody] IEnumerable> data) { if (data == null) return null; var contacts = new List(); var recordIndex = 0; foreach (var item in data) { if (string.IsNullOrEmpty(item.Key) || string.IsNullOrEmpty(item.Value)) continue; contacts.Add(new Person { ID = recordIndex++, FirstName = item.Key, LastName = item.Value, ShareType = ShareType.None }); } if (contacts.Count == 0) return null; _daoFactory.GetContactDao().SaveContactList(contacts); var selectedManagers = new List { _securityContext.CurrentAccount.ID }; foreach (var ct in contacts) { _crmSecurity.SetAccessTo(ct, selectedManagers); } _messageService.Send(MessageAction.PersonsCreated, _messageTarget.Create(contacts.Select(x => x.ID)), contacts.Select(x => x.GetTitle())); return contacts.ConvertAll(x => _mapper.Map(x)); } /// /// Updates the selected company with the parameters specified in the request /// /// Company ID /// Company name /// Company description text /// Company privacy: 0 - not shared, 1 - shared for read/write, 2 - shared for read only /// List of company managers /// User field list /// Update company /// Contacts /// /// /// Company /// [Update(@"contact/company/{companyid:int}")] public CompanyDto UpdateCompany( [FromRoute] int companyid, [FromBody] CreateOrUpdateCompanyRequestDto intDto) { string companyName = intDto.CompanyName; string about = intDto.About; ShareType shareType = intDto.ShareType; IEnumerable managerList = intDto.ManagerList; IEnumerable> customFieldList = intDto.CustomFieldList; IEnumerable photo = intDto.Photos; var companyInst = new Company { ID = companyid, CompanyName = companyName, About = about, ShareType = shareType }; _daoFactory.GetContactDao().UpdateContact(companyInst); companyInst = (Company)_daoFactory.GetContactDao().GetByID(companyInst.ID); var managerListLocal = managerList != null ? managerList.ToList() : new List(); if (managerListLocal.Any()) { _crmSecurity.SetAccessTo(companyInst, managerListLocal); } if (customFieldList != null) { var existingCustomFieldList = _daoFactory.GetCustomFieldDao().GetFieldsDescription(EntityType.Company).Select(fd => fd.ID).ToList(); foreach (var field in customFieldList) { if (string.IsNullOrEmpty(field.Value) || !existingCustomFieldList.Contains(field.Key)) continue; _daoFactory.GetCustomFieldDao().SetFieldValue(EntityType.Company, companyInst.ID, field.Key, field.Value); } } _messageService.Send(MessageAction.CompanyUpdated, _messageTarget.Create(companyInst.ID), companyInst.GetTitle()); return (CompanyDto)_mapper.Map(companyInst); } /// /// Updates the selected contact status /// /// Contact ID /// Contact status ID /// Update status in contact by id /// Contacts /// /// /// /// Company /// [Update(@"contact/{contactid:int}/status")] public ContactDto UpdateContactStatus(int contactid, int contactStatusid) { if (contactid <= 0 || contactStatusid < 0) throw new ArgumentException(); var dao = _daoFactory.GetContactDao(); if (contactStatusid > 0) { var curListItem = _daoFactory.GetListItemDao().GetByID(contactStatusid); if (curListItem == null) throw new ItemNotFoundException(); } var companyInst = dao.GetByID(contactid); if (companyInst == null || !_crmSecurity.CanAccessTo(companyInst)) throw new ItemNotFoundException(); if (!_crmSecurity.CanEdit(companyInst)) throw _crmSecurity.CreateSecurityException(); dao.UpdateContactStatus(new List { companyInst.ID }, contactStatusid); companyInst.StatusID = contactStatusid; var messageAction = companyInst is Company ? MessageAction.CompanyUpdatedTemperatureLevel : MessageAction.PersonUpdatedTemperatureLevel; _messageService.Send(messageAction, _messageTarget.Create(companyInst.ID), companyInst.GetTitle()); return _mapper.Map(companyInst); } /// /// Updates status of the selected company and all its participants /// /// Company ID /// Contact status ID /// Update company and participants status /// Contacts /// /// /// /// Company /// [Update(@"contact/company/{companyid:int}/status")] public ContactDto UpdateCompanyAndParticipantsStatus(int companyid, int contactStatusid) { if (companyid <= 0 || contactStatusid < 0) throw new ArgumentException(); var dao = _daoFactory.GetContactDao(); if (contactStatusid > 0) { var curListItem = _daoFactory.GetListItemDao().GetByID(contactStatusid); if (curListItem == null) throw new ItemNotFoundException(); } var companyInst = dao.GetByID(companyid); if (companyInst == null || !_crmSecurity.CanAccessTo(companyInst)) throw new ItemNotFoundException(); if (companyInst is Person) throw new Exception(CRMErrorsResource.ContactIsNotCompany); var forUpdateStatus = new List(); forUpdateStatus.Add(companyInst.ID); var members = dao.GetMembersIDsAndShareType(companyInst.ID); foreach (var m in members) { if (_crmSecurity.CanAccessTo(m.Key, EntityType.Person, m.Value, 0)) { forUpdateStatus.Add(m.Key); } } dao.UpdateContactStatus(forUpdateStatus, contactStatusid); _messageService.Send(MessageAction.CompanyUpdatedTemperatureLevel, _messageTarget.Create(companyInst.ID), companyInst.GetTitle()); _messageService.Send(MessageAction.CompanyUpdatedPersonsTemperatureLevel, _messageTarget.Create(companyInst.ID), companyInst.GetTitle()); return _mapper.Map(companyInst); } /// /// Updates status of the selected person, related company and all its participants /// /// Person ID /// Contact status ID /// Update person, related company and participants status /// Contacts /// /// /// /// Person /// [Update(@"contact/person/{personid:int}/status")] public ContactDto UpdatePersonAndItsCompanyStatus(int personid, int contactStatusid) { if (personid <= 0 || contactStatusid < 0) throw new ArgumentException(); if (contactStatusid > 0) { var curListItem = _daoFactory.GetListItemDao().GetByID(contactStatusid); if (curListItem == null) throw new ItemNotFoundException(); } var dao = _daoFactory.GetContactDao(); var personInst = dao.GetByID(personid); if (personInst == null || !_crmSecurity.CanAccessTo(personInst)) throw new ItemNotFoundException(); if (personInst is Company) throw new Exception(CRMErrorsResource.ContactIsNotPerson); var forUpdateStatus = new List(); var companyID = ((Person)personInst).CompanyID; if (companyID != 0) { var companyInst = dao.GetByID(companyID); if (companyInst == null) throw new ItemNotFoundException(); if (!_crmSecurity.CanAccessTo(companyInst)) { forUpdateStatus.Add(personInst.ID); dao.UpdateContactStatus(forUpdateStatus, contactStatusid); } else { forUpdateStatus.Add(companyInst.ID); var members = dao.GetMembersIDsAndShareType(companyInst.ID); foreach (var m in members) { if (_crmSecurity.CanAccessTo(m.Key, EntityType.Person, m.Value, 0)) { forUpdateStatus.Add(m.Key); } } dao.UpdateContactStatus(forUpdateStatus, contactStatusid); } } else { forUpdateStatus.Add(personInst.ID); dao.UpdateContactStatus(forUpdateStatus, contactStatusid); } _messageService.Send(MessageAction.PersonUpdatedTemperatureLevel, _messageTarget.Create(personInst.ID), personInst.GetTitle()); _messageService.Send(MessageAction.PersonUpdatedCompanyTemperatureLevel, _messageTarget.Create(personInst.ID), personInst.GetTitle()); personInst = dao.GetByID(personInst.ID); return _mapper.Map(personInst); } /// /// Get access rights to the contact with the ID specified in the request /// /// Get contact access rights /// Contacts /// /// /// /// User list [Read(@"contact/{contactid:int}/access")] public IEnumerable GetContactAccessList(int contactid) { if (contactid <= 0) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().GetByID(contactid); if (contact == null) throw new ItemNotFoundException(); if (!_crmSecurity.CanAccessTo(contact)) throw _crmSecurity.CreateSecurityException(); return _crmSecurity.IsPrivate(contact) ? _crmSecurity.GetAccessSubjectTo(contact) .Select(item => _employeeWraperHelper.Get(item.Key)) : new List(); } /// /// Sets access rights for other users to the contact with the ID specified in the request /// /// Contact ID /// Contact privacy: private or not /// List of managers /// Set contact access rights /// Contacts /// /// /// /// /// Contact /// [Update(@"contact/{contactid:int}/access")] public ContactDto SetAccessToContact(int contactid, bool isShared, IEnumerable managerList) { if (contactid <= 0) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().GetByID(contactid); if (contact == null) throw new ItemNotFoundException(); if (!_crmSecurity.CanEdit(contact)) throw _crmSecurity.CreateSecurityException(); SetAccessToContact(contact, isShared, managerList, false); var wrapper = _mapper.Map(contact); return wrapper; } private void SetAccessToContact(Contact contact, bool isShared, IEnumerable managerList, bool isNotify) { var managerListLocal = managerList != null ? managerList.Distinct().ToList() : new List(); if (managerListLocal.Any()) { if (isNotify) { var notifyUsers = managerListLocal.Where(n => n != _securityContext.CurrentAccount.ID).ToArray(); if (contact is Person) _notifyClient.SendAboutSetAccess(EntityType.Person, contact.ID, _daoFactory, notifyUsers); else _notifyClient.SendAboutSetAccess(EntityType.Company, contact.ID, _daoFactory, notifyUsers); } _crmSecurity.SetAccessTo(contact, managerListLocal); } else { _crmSecurity.MakePublic(contact); } _daoFactory.GetContactDao().MakePublic(contact.ID, isShared); } /// /// Sets access rights for other users to the list of contacts with the IDs specified in the request /// /// Contact ID list /// Company privacy: shared or not /// List of managers /// Set contact access rights /// Contacts /// /// /// /// Contact list /// [Update(@"contact/access")] public IEnumerable SetAccessToBatchContact( [FromBody] SetAccessToBatchContactRequestDto inDto) { var contactid = inDto.ContactID; var isShared = inDto.isShared; var managerList = inDto.ManagerList; if (contactid == null) throw new ArgumentException(); var result = new List(); foreach (var id in contactid) { var contactDto = SetAccessToContact(id, isShared, managerList); result.Add(contactDto); } return result; } /// /// Sets access rights for the selected user to the list of contacts with the parameters specified in the request /// /// Contact privacy: private or not /// List of managers /// Tag /// Contact stage ID (warmth) /// Contact type ID /// /// Start date /// End date /// Set contact access rights /// Contacts /// /// /// /// Contact list /// [Update(@"contact/filter/access")] public IEnumerable SetAccessToBatchContact( [FromBody] SetAccessToBatchContactByFilterRequestDto inDto) { IEnumerable tags = inDto.Tags; int? contactStage = inDto.ContactStage; int? contactType = inDto.ContactType; ContactListViewType contactListView = inDto.ContactListView; ApiDateTime fromDate = inDto.FromDate; ApiDateTime toDate = inDto.ToDate; bool isPrivate = inDto.isPrivate; IEnumerable managerList = inDto.ManagerList; int contactStageInt = contactStage.HasValue ? contactStage.Value : -1; int contactTypeInt = contactType.HasValue ? contactType.Value : -1; var result = new List(); var contacts = _daoFactory.GetContactDao().GetContacts( _apiContext.FilterValue, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, 0, 0, null); if (!contacts.Any()) return Enumerable.Empty(); foreach (var contact in contacts) { if (contact == null) throw new ItemNotFoundException(); if (!_crmSecurity.CanEdit(contact)) continue; SetAccessToContact(contact, isPrivate, managerList, false); result.Add(contact); } return _mapper.Map, List>(result); } /// /// Deletes the contact with the ID specified in the request from the portal /// /// Delete contact /// Contacts /// Contact ID /// /// /// /// Contact /// [Delete(@"contact/{contactid:int}")] public ContactDto DeleteContact(int contactid) { if (contactid <= 0) throw new ArgumentException(); var contact = _daoFactory.GetContactDao().DeleteContact(contactid); if (contact == null) throw new ItemNotFoundException(); var messageAction = contact is Person ? MessageAction.PersonDeleted : MessageAction.CompanyDeleted; _messageService.Send(messageAction, _messageTarget.Create(contact.ID), contact.GetTitle()); return _mapper.Map(contact); } /// /// Deletes the group of contacts with the IDs specified in the request /// /// Contact ID list /// /// /// Delete contact group /// Contacts /// /// Contact list /// [Update(@"contact")] public IEnumerable DeleteBatchContacts(IEnumerable contactids) { if (contactids == null) throw new ArgumentException(); var contacts = _daoFactory.GetContactDao().DeleteBatchContact(contactids.ToArray()); _messageService.Send(MessageAction.ContactsDeleted, _messageTarget.Create(contactids), contacts.Select(c => c.GetTitle())); return contacts.Select(x => _mapper.Map(x)); } /// /// Returns the list of 30 contacts in the CRM module with prefix /// /// /// searchType /// /// /// Contacts /// /// Contact list /// /// false [Read(@"contact/byprefix")] public IEnumerable GetContactsByPrefix(string prefix, int searchType, EntityType entityType, int entityID) { var result = new List(); var allContacts = new List(); if (entityID > 0) { var findedContacts = new List(); switch (entityType) { case EntityType.Opportunity: allContacts = _daoFactory.GetContactDao().GetContacts(_daoFactory.GetDealDao().GetMembers(entityID)); break; case EntityType.Case: allContacts = _daoFactory.GetContactDao().GetContacts(_daoFactory.GetCasesDao().GetMembers(entityID)); break; } foreach (var c in allContacts) { var person = c as Person; if (person != null) { var people = person; if (_userFormatter.GetUserName(people.FirstName, people.LastName).IndexOf(prefix, StringComparison.Ordinal) != -1) { findedContacts.Add(person); } } else { var company = (Company)c; if (company.CompanyName.IndexOf(prefix, StringComparison.Ordinal) != -1) { findedContacts.Add(c); } } } result.AddRange(findedContacts.Select(x => _mapper.Map(x))); _apiContext.SetTotalCount(findedContacts.Count); } else { const int maxItemCount = 30; if (searchType < -1 || searchType > 3) throw new ArgumentException(); allContacts = _daoFactory.GetContactDao().GetContactsByPrefix(prefix, searchType, 0, maxItemCount); result.AddRange(allContacts.Select(x => _mapper.Map(x))); } return result; } /// /// Returns the list contacts in the CRM module with contact information /// /// Contact information type /// Data /// Category /// Contact importance: primary or not /// Contacts /// /// Contact list /// [Read(@"contact/bycontactinfo")] public IEnumerable GetContactsByContactInfo(ContactInfoType? infoType, String data, int? category, bool? isPrimary) { if (!infoType.HasValue) throw new ArgumentException(); var ids = _daoFactory.GetContactDao().GetContactIDsByContactInfo(infoType.Value, data, category, isPrimary); var result = _daoFactory.GetContactDao().GetContacts(ids.ToArray()).ConvertAll(x => _mapper.Map(x)); return result; } ///// ///// ///// ///// ///// ///// Contacts ///// //[Read(@"contact/{contactid:int}/tweets")] //public List GetUserTweets(int contactid, int count) //{ // var MessageCount = 10; // var twitterAccounts = DaoFactory.GetContactInfoDao().GetList(contactid, ContactInfoType.Twitter, null, null); // if (twitterAccounts.Count == 0) // throw new ResourceNotFoundException( // Newtonsoft.Json.JsonConvert.SerializeObject( // new // { // message = "", // description = CRMSocialMediaResource.SocialMediaAccountNotFoundTwitter // } // )); // var apiInfo = TwitterApiHelper.GetTwitterApiInfoForCurrentUser(); // TwitterDataProvider twitterProvider = new TwitterDataProvider(apiInfo); // List messages = new List(); // foreach (var twitterAccount in twitterAccounts) // { // try // { // messages.AddRange(twitterProvider.GetUserTweets(twitterAccount.ID, twitterAccount.Data, MessageCount)); // } // catch (ResourceNotFoundException ex) // { // throw new ResourceNotFoundException( // Newtonsoft.Json.JsonConvert.SerializeObject( // new // { // message = ex.Message, // description = String.Format("{0}: {1}", CRMSocialMediaResource.ErrorUnknownTwitterAccount, twitterAccount.Data) // } // )); // } // catch (Exception ex) // { // throw new Exception( // Newtonsoft.Json.JsonConvert.SerializeObject( // new // { // message = ex.Message, // description = String.Format("{0}: {1}", CRMSocialMediaResource.ErrorUnknownTwitterAccount, twitterAccount.Data) // } // )); // } // } // return messages.OrderByDescending(m => m.PostedOn).Take(MessageCount).ToList(); //} ///// ///// ///// ///// ///// Contacts ///// //[Read(@"contact/twitterprofile")] //public List FindTwitterProfiles(string searchText) //{ // try // { // TwitterApiInfo apiInfo = TwitterApiHelper.GetTwitterApiInfoForCurrentUser(); // if (apiInfo == null) // throw new SocialMediaAccountNotFound(CRMSocialMediaResource.SocialMediaAccountNotFoundTwitter); // TwitterDataProvider provider = new TwitterDataProvider(apiInfo); // List users = provider.FindUsers(searchText); // /*List users = new List(); // users.Add(new TwitterUserInfo { Description = "I'm a cool user", SmallImageUrl = "http://localhost/TeamLab/products/crm/data/0/photos/00/00/10/contact_10_50_50.jpg", UserName = "User", ScreenName = "user", UserID = 1 }); // users.Add(new TwitterUserInfo { Description = "I'm a cool user", SmallImageUrl = "http://localhost/TeamLab/products/crm/data/0/photos/00/00/10/contact_10_50_50.jpg", UserName = "User", ScreenName = "user", UserID = 1 }); // users.Add(new TwitterUserInfo { Description = "I'm a cool user", SmallImageUrl = "http://localhost/TeamLab/products/crm/data/0/photos/00/00/10/contact_10_50_50.jpg", UserName = "User", ScreenName = "user", UserID = 1 });*/ // return users; // } // catch (Exception ex) { // throw new SocialMediaUI(DaoFactory).ProcessError(ex, "ASC.CRM.Api.CRMApi.FindTwitterProfiles"); // } //} /// /// /// /// /// /// /// Contacts /// [Delete(@"contact/{contactid:int}/avatar")] public string DeleteContactAvatar(int contactId, string contactType, bool uploadOnly) { bool isCompany; if (contactId != 0) { var contact = _daoFactory.GetContactDao().GetByID(contactId); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); if (!_crmSecurity.CanEdit(contact)) throw _crmSecurity.CreateSecurityException(); isCompany = contact is Company; } else { isCompany = contactType != "people"; } if (!uploadOnly) { _contactPhotoManager.DeletePhoto(contactId); return _contactPhotoManager.GetBigSizePhoto(0, isCompany); } return ""; } ///// ///// ///// ///// ///// Contacts ///// //[Read(@"contact/{contactid:int}/socialmediaavatar")] //public List GetContactSMImages(int contactId) //{ // return new SocialMediaUI(DaoFactory).GetContactSMImages(contactId); //} ///// ///// ///// ///// ///// Contacts ///// //[Create(@"contact/socialmediaavatar")] //public List GetContactSMImagesByNetworks(List socialNetworks) //{ // if (socialNetworks == null || socialNetworks.Count == 0) // { // return new List(); // } // var twitter = new List(); // foreach (var sn in socialNetworks) // { // if (sn.InfoType == ContactInfoType.Twitter) twitter.Add(sn.Data); // } // return new SocialMediaUI(DaoFactory).GetContactSMImages(twitter); //} ///// ///// ///// ///// ///// ///// ///// ///// ///// Contacts ///// //[Update(@"contact/{contactid:int}/avatar")] //public ContactPhotoManager.PhotoData UploadUserAvatarFromSocialNetwork(int contactId, SocialNetworks socialNetwork, string userIdentity, bool uploadOnly, string tmpDirName) //{ // if (socialNetwork != SocialNetworks.Twitter) // throw new ArgumentException(); // if (contactId != 0) // { // var contact = DaoFactory.GetContactDao().GetByID(contactId); // if (contact == null || !CRMSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); // if (!CRMSecurity.CanEdit(contact)) throw CRMSecurity.CreateSecurityException(); // } // if (socialNetwork == SocialNetworks.Twitter) // { // var provider = new TwitterDataProvider(TwitterApiHelper.GetTwitterApiInfoForCurrentUser()); // var imageUrl = provider.GetUrlOfUserImage(userIdentity, TwitterDataProvider.ImageSize.Original); // return UploadAvatar(contactId, imageUrl, uploadOnly, tmpDirName, false); // } // return null; //} /// false [Create(@"contact/mailsmtp/send")] public IProgressItem SendMailSMTPToContacts( SendMailSMTPToContactsRequestDto inDto) { List fileIDs = inDto.FileIDs; List contactIds = inDto.ContactIds; String subject = inDto.Subject; String body = inDto.Body; bool storeInHistory = inDto.StoreInHistory; if (contactIds == null || contactIds.Count == 0 || String.IsNullOrEmpty(body)) throw new ArgumentException(); var contacts = _daoFactory.GetContactDao().GetContacts(contactIds.ToArray()); _messageService.Send(MessageAction.CrmSmtpMailSent, _messageTarget.Create(contactIds), contacts.Select(c => c.GetTitle())); return _mailSender.Start(fileIDs, contactIds, subject, body, storeInHistory); } /// false [Create(@"contact/mailsmtp/preview")] public string GetMailSMTPToContactsPreview([FromForm] string template, [FromForm] int contactId) { if (contactId == 0 || String.IsNullOrEmpty(template)) throw new ArgumentException(); var manager = new MailTemplateManager(_daoFactory); return manager.Apply(template, contactId); } /// false [Read(@"contact/mailsmtp/status")] public IProgressItem GetMailSMTPToContactsStatus() { return _mailSender.GetStatus(); } /// false [Update(@"contact/mailsmtp/cancel")] public IProgressItem CancelMailSMTPToContacts() { var progressItem = _mailSender.GetStatus(); _mailSender.Cancel(); return progressItem; } /// false [Update(@"contact/{contactid:int}/creationdate")] public void SetContactCreationDate(int contactId, ApiDateTime creationDate) { var dao = _daoFactory.GetContactDao(); var contact = dao.GetByID(contactId); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); dao.SetContactCreationDate(contactId, creationDate); } /// false [Update(@"contact/{contactid:int}/lastmodifeddate")] public void SetContactLastModifedDate(int contactId, ApiDateTime lastModifedDate) { var dao = _daoFactory.GetContactDao(); var contact = dao.GetByID(contactId); if (contact == null || !_crmSecurity.CanAccessTo(contact)) throw new ItemNotFoundException(); dao.SetContactLastModifedDate(contactId, lastModifedDate); } private ContactPhotoManager.PhotoData UploadAvatar(int contactID, string imageUrl, bool uploadOnly, string tmpDirName, bool checkFormat = true) { if (contactID != 0) { return _contactPhotoManager.UploadPhoto(imageUrl, contactID, uploadOnly, checkFormat); } if (string.IsNullOrEmpty(tmpDirName) || tmpDirName == "null") tmpDirName = null; return _contactPhotoManager.UploadPhotoToTemp(imageUrl, tmpDirName, checkFormat); } private IEnumerable ToSimpleListContactDto(IReadOnlyList itemList) { if (itemList.Count == 0) return new List(); var result = new List(); var personsIDs = new List(); var companyIDs = new List(); var contactIDs = new int[itemList.Count]; var peopleCompanyIDs = new List(); var peopleCompanyList = new Dictionary(); var contactDao = _daoFactory.GetContactDao(); for (var index = 0; index < itemList.Count; index++) { var contact = itemList[index]; if (contact is Company) { companyIDs.Add(contact.ID); } else { var person = contact as Person; if (person != null) { personsIDs.Add(person.ID); if (person.CompanyID > 0) { peopleCompanyIDs.Add(person.CompanyID); } } } contactIDs[index] = itemList[index].ID; } if (peopleCompanyIDs.Count > 0) { var tmpList = contactDao.GetContacts(peopleCompanyIDs.ToArray()).ConvertAll(item => _mapper.Map(item)); var tmpListCanDelete = contactDao.CanDelete(tmpList.Select(item => item.Id).ToArray()); foreach (var contactBaseDtoQuick in tmpList) { contactBaseDtoQuick.CanDelete = contactBaseDtoQuick.CanEdit && tmpListCanDelete[contactBaseDtoQuick.Id]; peopleCompanyList.Add(contactBaseDtoQuick.Id, contactBaseDtoQuick); } } var contactInfos = new Dictionary>(); var addresses = new Dictionary>(); _daoFactory.GetContactInfoDao().GetAll(contactIDs).ForEach( item => { if (item.InfoType == ContactInfoType.Address) { if (!addresses.ContainsKey(item.ContactID)) { addresses.Add(item.ContactID, new List
{ new Address(item) }); } else { addresses[item.ContactID].Add(new Address(item)); } } else { if (!contactInfos.ContainsKey(item.ContactID)) { contactInfos.Add(item.ContactID, new List { _mapper.Map(item) }); } else { contactInfos[item.ContactID].Add(_mapper.Map(item)); } } } ); var nearestTasks = _daoFactory.GetTaskDao().GetNearestTask(contactIDs.ToArray()); IEnumerable taskCategories = new List(); if (nearestTasks.Any()) { taskCategories = _daoFactory.GetListItemDao().GetItems(ListType.TaskCategory).ConvertAll(item => _mapper.Map(item)); } foreach (var contact in itemList) { ContactDto contactDto; var person = contact as Person; if (person != null) { var people = person; var peopleDto = _mapper.Map(people); if (people.CompanyID > 0 && peopleCompanyList.ContainsKey(people.CompanyID)) { peopleDto.Company = peopleCompanyList[people.CompanyID]; } contactDto = peopleDto; } else { var company = contact as Company; if (company != null) { contactDto = _mapper.Map(company); } else { throw new ArgumentException(); } } contactDto.CommonData = contactInfos.ContainsKey(contact.ID) ? contactInfos[contact.ID] : new List(); TaskBaseDto taskDto = null; if (nearestTasks.ContainsKey(contactDto.Id)) { var task = nearestTasks[contactDto.Id]; taskDto = _mapper.Map(task); if (task.CategoryID > 0) { taskDto.Category = taskCategories.First(x => x.Id == task.CategoryID); } } result.Add(new ContactWithTaskDto { Contact = contactDto, Task = taskDto }); } #region CanDelete for main contacts if (result.Count > 0) { var resultListCanDelete = contactDao.CanDelete(result.Select(item => item.Contact.Id).ToArray()); foreach (var contactBaseDtoQuick in result) { contactBaseDtoQuick.Contact.CanDelete = contactBaseDtoQuick.Contact.CanEdit && resultListCanDelete[contactBaseDtoQuick.Contact.Id]; } } #endregion return result; } } }