Example #1
0
        public async void DoAction(object sender, CrmEvent e)
        {
            if (e.Entity != "contacts" || String.IsNullOrEmpty(e.EntityId) || e.ContactType != "contact")
            {
                return;
            }

            Contact contact = null;

            try
            {
                var idConvert = int.TryParse(e.EntityId, out int id);

                if (idConvert)
                {
                    var action = new FindContactActions(crm, currentLogger);

                    var result = await action.LookForContact(id);

                    contact = result?.Adapt <Contact>(mapper);
                }
            }
            catch (Exception ex)
            {
                currentLogger.LogError(ex, "Ошибка при поиске контакта в Crm");
                return;
            }

            if (contact == null)
            {
                currentLogger.LogWarning("Контакт [ Id -" + e.EntityId + " ] не найден в CRM");
                return;
            }


            var hasGuid = contact.Guid();

            if (!String.IsNullOrEmpty(hasGuid))
            {
                return;
            }

            try
            {
                var guid = await new FindGuidAction(database).Find(contact);

                if (!String.IsNullOrEmpty(guid))
                {
                    contact.Guid(guid);

                    await crm.Contacts.Update(
                        contact.GetChanges().Adapt <ContactDTO>(mapper)
                        );

                    currentLogger.LogInformation("Обновление Guid - {Guid}, для пользователя Id - {User}", guid, contact.Id);
                }
            }
            catch (NullReferenceException ex)
            {
                currentLogger.LogDebug(ex, "Ошибка, нулевое значение {@Contacts}", contact);
                return;
            }
            catch (Exception ex)
            {
                currentLogger.LogError(ex, "Ошибка обновления пользователя. [{@Id}]", contact.Id);
            }
        }
        public async Task <bool> CreateRecallTask(CallBackDTO model)
        {
            Contact contact;

            try
            {
                // Check available contact
                var action = new FindContactActions(crm, logger);
                var result = await action.LookForContact(phone : model.UserPhone);

                contact = result?.Adapt <Contact>(mapper);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Ошибка при поиске контакта в Crm");
                return(false);
            }

            // Create contact
            if (contact == null)
            {
                var buildContact = new Common.BusinessLogicHelpers.Crm.Builders.ContactBuilder();
                buildContact.Name(model.UserName);
                buildContact.Phone(model.UserPhone);
                contact = (Contact)buildContact;

                contact.ResponsibleUserId = GetManager(model);

                var contactDTO = contact.Adapt <ContactDTO>(mapper);

                try
                {
                    System.Threading.Tasks.Task taskPrepareContactLog = System.Threading.Tasks.Task.Factory.StartNew(
                        () => logger.LogInformation("Подготовлен контакт для добавления - {@Contact}", contact)
                        );

                    var query = crm.Contacts.Add(contactDTO).Result;
                    contact = query.Adapt <Contact>(mapper);

                    System.Threading.Tasks.Task taskreateContactLog = System.Threading.Tasks.Task.Factory.StartNew(
                        () => logger.LogInformation("Создан контакт {Name} | {Id}", contactDTO.Name, contact.Id)
                        );
                }
                catch (Exception ex)
                {
                    logger.LogWarning(ex, "Ошибка создания контакта с сайта");
                    return(false);
                }
            }

            if (contact != null)
            {
                var manager = GetManager(model);

                var modelTask = new TaskDTO()
                {
                    ElementId   = contact.Id,
                    ElementType = (int)ElementTypeEnum.Контакт,
                    Text        = "Клиент заказал обратный звонок!" + "\r\n"
                                  + "Со страницы мероприятия- " + model.ProgramTitle + "\r\n" +
                                  "URL.: " + model.Url,
                    ResponsibleUserId = manager,
                    CompleteTillAt    = DateTime.Now
                };

                logger.LogInformation("Подготовлена задача - {Task}", modelTask);

                try
                {
                    var tsk = crm.Tasks.Add(new[] { modelTask }).Result;
                }
                catch (Exception ex)
                {
                    logger.LogWarning(ex, "Ошибка создания задачи для контакта - " + contact.Id);
                    return(false);
                }
            }

            return(true);
        }