/* * * (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 ASC.Api.Collections; using ASC.Api.Core; using ASC.Api.CRM.Wrappers; using ASC.Common.Threading.Progress; using ASC.Common.Web; using ASC.CRM.Core; using ASC.CRM.Core.Entities; using ASC.CRM.Core.Enums; using ASC.CRM.Model; 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.Studio.Core; using Autofac; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Web; using Contact = ASC.CRM.Core.Entities.Contact; namespace ASC.Api.CRM { public partial class CRMController { /// /// 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 ContactWrapper 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 ContactWrapperHelper.GetContactWrapper(contact); } public IEnumerable GetContactsByID(IEnumerable contactid) { var contacts = DaoFactory.GetContactDao().GetContacts(contactid.ToArray()).Where(r => r != null && CRMSecurity.CanAccessTo(r)); return ToListContactWrapper(contacts.ToList()); } /// /// 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 ToListContactWrapper(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 ContactWrapper 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 ToContactWrapper(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(ToContactWrapper); //} ///// ///// 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 ContactBaseWrapper 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 ToContactBaseWrapper(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 OpportunityWrapper AddDealToContact(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().AddMember(opportunityid, contactid); var messageAction = contact is Company ? MessageAction.OpportunityLinkedCompany : MessageAction.OpportunityLinkedPerson; MessageService.Send(messageAction, MessageTarget.Create(contact.ID), opportunity.Title, contact.GetTitle()); return OpportunityWrapperHelper.Get(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 OpportunityWrapper 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 OpportunityWrapperHelper.Get(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( 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.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) { result = ToListContactWrapper(DaoFactory.GetContactDao().GetContacts( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, fromIndex, count, contactsOrderBy, responsibleid, isShared)); ApiContext.SetDataPaginated(); ApiContext.SetDataFiltered(); ApiContext.SetDataSorted(); } else { result = ToListContactWrapper(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 = ToSimpleListContactWrapper(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 = ToSimpleListContactWrapper(DaoFactory.GetContactDao().GetContacts( searchString, tags, contactStageInt, contactTypeInt, contactListView, fromDate, toDate, fromIndex, count, contactsOrderBy, responsibleid, isShared)); ApiContext.SetDataPaginated(); ApiContext.SetDataFiltered(); ApiContext.SetDataSorted(); } else { result = ToSimpleListContactWrapper(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 => ContactWrapperHelper.GetContactBaseWithEmailWrapper(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 => ContactWrapperHelper.GetContactBaseWrapper(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(); return ToListContactWrapper(DaoFactory.GetContactDao().GetMembers(companyid).Where(CRMSecurity.CanAccessTo).ToList()); } /// /// 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 PersonWrapper AddPeopleToCompany(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().AddMember(personid, companyid); MessageService.Send(MessageAction.CompanyLinkedPerson, MessageTarget.Create(new[] { company.ID, person.ID }), company.GetTitle(), person.GetTitle()); return (PersonWrapper)ContactWrapperHelper.GetContactWrapper(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 PersonWrapper 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 (PersonWrapper)ContactWrapperHelper.GetContactWrapper(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 PersonWrapper CreatePerson([FromForm] CreateOrUpdatePersonInDto 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 = (PersonWrapper)ContactWrapperHelper.GetContactWrapper(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 ContactWrapper 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 ContactWrapperHelper.GetContactWrapper(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 PersonWrapper UpdatePerson([FromQuery] int personid, [FromForm] CreateOrUpdatePersonInDto 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 = (PersonWrapper)ContactWrapperHelper.GetContactWrapper(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 CompanyWrapper CreateCompany( [FromForm] CreateOrUpdateCompanyInDto 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 = (CompanyWrapper)ContactWrapperHelper.GetContactWrapper(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(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 => ContactWrapperHelper.GetContactBaseWrapper(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(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 => ContactWrapperHelper.GetContactBaseWrapper(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 CompanyWrapper UpdateCompany( [FromQuery]int companyid, [FromForm] CreateOrUpdateCompanyInDto 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 (CompanyWrapper)ContactWrapperHelper.GetContactWrapper(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 ContactWrapper 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 ContactWrapperHelper.GetContactWrapper(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 ContactWrapper 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 ContactWrapperHelper.GetContactWrapper(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 ContactWrapper 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 ContactWrapperHelper.GetContactWrapper(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 ContactWrapper 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 = ContactWrapperHelper.GetContactWrapper(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]SetAccessToBatchContactInDto 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 contactWrapper = SetAccessToContact(id, isShared, managerList); result.Add(contactWrapper); } 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( [FromForm] SetAccessToBatchContactByFilterInDto 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 ToListContactWrapper(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 ContactWrapper 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 ContactWrapperHelper.GetContactWrapper(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 => ContactWrapperHelper.GetContactBaseWrapper(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 => ContactWrapperHelper.GetContactBaseWithPhoneWrapper(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 => ContactWrapperHelper.GetContactBaseWithPhoneWrapper(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 => ContactWrapperHelper.GetContactWrapper(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.Api.CRM.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(List fileIDs, List contactIds, String subject, String body, bool 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(string template, 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 ToSimpleListContactWrapper(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 => ContactWrapperHelper.GetContactBaseWrapperQuick(item)); var tmpListCanDelete = contactDao.CanDelete(tmpList.Select(item => item.Id).ToArray()); foreach (var contactBaseWrapperQuick in tmpList) { contactBaseWrapperQuick.CanDelete = contactBaseWrapperQuick.CanEdit && tmpListCanDelete[contactBaseWrapperQuick.Id]; peopleCompanyList.Add(contactBaseWrapperQuick.Id, contactBaseWrapperQuick); } } 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 { ContactInfoWrapperHelper.Get(item) }); } else { contactInfos[item.ContactID].Add(ContactInfoWrapperHelper.Get(item)); } } } ); var nearestTasks = DaoFactory.GetTaskDao().GetNearestTask(contactIDs.ToArray()); IEnumerable taskCategories = new List(); if (nearestTasks.Any()) { taskCategories = DaoFactory.GetListItemDao().GetItems(ListType.TaskCategory).ConvertAll(item => TaskCategoryWrapperHelper.Get(item)); } foreach (var contact in itemList) { ContactWrapper contactWrapper; var person = contact as Person; if (person != null) { var people = person; var peopleWrapper = ContactWrapperHelper.GetPersonWrapperQuick(people); if (people.CompanyID > 0 && peopleCompanyList.ContainsKey(people.CompanyID)) { peopleWrapper.Company = peopleCompanyList[people.CompanyID]; } contactWrapper = peopleWrapper; } else { var company = contact as Company; if (company != null) { contactWrapper = ContactWrapperHelper.GetCompanyWrapperQuick(company); } else { throw new ArgumentException(); } } contactWrapper.CommonData = contactInfos.ContainsKey(contact.ID) ? contactInfos[contact.ID] : new List(); TaskBaseWrapper taskWrapper = null; if (nearestTasks.ContainsKey(contactWrapper.Id)) { var task = nearestTasks[contactWrapper.Id]; taskWrapper = TaskWrapperHelper.GetTaskBaseWrapper(task); if (task.CategoryID > 0) { taskWrapper.Category = taskCategories.First(x => x.Id == task.CategoryID); } } result.Add(new ContactWithTaskWrapper { Contact = contactWrapper, Task = taskWrapper }); } #region CanDelete for main contacts if (result.Count > 0) { var resultListCanDelete = contactDao.CanDelete(result.Select(item => item.Contact.Id).ToArray()); foreach (var contactBaseWrapperQuick in result) { contactBaseWrapperQuick.Contact.CanDelete = contactBaseWrapperQuick.Contact.CanEdit && resultListCanDelete[contactBaseWrapperQuick.Contact.Id]; } } #endregion return result; } private ContactWrapper ToContactWrapper(Contact contact) { return ToListContactWrapper(new List { contact }).Single(); } private IEnumerable ToListContactWrapper(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 => ContactWrapperHelper.GetContactBaseWrapperQuick(item)); var tmpListCanDelete = contactDao.CanDelete(tmpList.Select(item => item.Id).ToArray()); foreach (var contactBaseWrapperQuick in tmpList) { contactBaseWrapperQuick.CanDelete = contactBaseWrapperQuick.CanEdit && tmpListCanDelete[contactBaseWrapperQuick.Id]; peopleCompanyList.Add(contactBaseWrapperQuick.Id, contactBaseWrapperQuick); } } var companiesMembersCount = contactDao.GetMembersCount(companyIDs.Distinct().ToArray()); var contactStatusIDs = itemList.Select(item => item.StatusID).Distinct().ToArray(); var contactInfos = new Dictionary>(); var haveLateTask = DaoFactory.GetTaskDao().HaveLateTask(contactIDs); var contactStatus = DaoFactory.GetListItemDao() .GetItems(contactStatusIDs) .ToDictionary(item => item.ID, item => new ContactStatusBaseWrapper(item)); var personsCustomFields = DaoFactory.GetCustomFieldDao().GetEnityFields(EntityType.Person, personsIDs.ToArray()); var companyCustomFields = DaoFactory.GetCustomFieldDao().GetEnityFields(EntityType.Company, companyIDs.ToArray()); var customFields = personsCustomFields.Union(companyCustomFields) .GroupBy(item => item.EntityID).ToDictionary(item => item.Key, item => item.Select(ToCustomFieldBaseWrapper)); var addresses = new Dictionary>(); var taskCount = DaoFactory.GetTaskDao().GetTasksCount(contactIDs); var contactTags = DaoFactory.GetTagDao().GetEntitiesTags(EntityType.Contact); 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 { ContactInfoWrapperHelper.Get(item) }); else contactInfos[item.ContactID].Add(ContactInfoWrapperHelper.Get(item)); } } ); foreach (var contact in itemList) { ContactWrapper contactWrapper; var person = contact as Person; if (person != null) { var people = person; var peopleWrapper = ContactWrapperHelper.GetPersonWrapperQuick(people); if (people.CompanyID > 0 && peopleCompanyList.ContainsKey(people.CompanyID)) { peopleWrapper.Company = peopleCompanyList[people.CompanyID]; } contactWrapper = peopleWrapper; } else { var company = contact as Company; if (company != null) { contactWrapper = ContactWrapperHelper.GetCompanyWrapperQuick(company); if (companiesMembersCount.ContainsKey(contactWrapper.Id)) { ((CompanyWrapper)contactWrapper).PersonsCount = companiesMembersCount[contactWrapper.Id]; } } else { throw new ArgumentException(); } } if (contactTags.ContainsKey(contact.ID)) { contactWrapper.Tags = contactTags[contact.ID].OrderBy(x => x); } if (addresses.ContainsKey(contact.ID)) { contactWrapper.Addresses = addresses[contact.ID]; } contactWrapper.CommonData = contactInfos.ContainsKey(contact.ID) ? contactInfos[contact.ID] : new List(); if (contactStatus.ContainsKey(contact.StatusID)) { contactWrapper.ContactStatus = contactStatus[contact.StatusID]; } contactWrapper.HaveLateTasks = haveLateTask.ContainsKey(contact.ID) && haveLateTask[contact.ID]; contactWrapper.CustomFields = customFields.ContainsKey(contact.ID) ? customFields[contact.ID] : new List(); contactWrapper.TaskCount = taskCount.ContainsKey(contact.ID) ? taskCount[contact.ID] : 0; result.Add(contactWrapper); } #region CanDelete for main contacts if (result.Count > 0) { var resultListCanDelete = contactDao.CanDelete(result.Select(item => item.Id).ToArray()); foreach (var contactBaseWrapperQuick in result) { contactBaseWrapperQuick.CanDelete = contactBaseWrapperQuick.CanEdit && resultListCanDelete[contactBaseWrapperQuick.Id]; } } #endregion return result; } } }