예제 #1
0
        public AbstractLeadProcessor(int leadNumber, AmoAccount acc, ProcessQueue processQueue, Log log, CancellationToken token)
        {
            _leadRepo            = acc.GetRepo <Lead>();
            _processQueue        = processQueue;
            _token               = token;
            _acc                 = acc;
            _leadNumber          = leadNumber;
            _log                 = log;
            custom_fields_values = new();
            tags                 = new();

            try
            {
                Thread.Sleep((int)TimeSpan.FromSeconds(3).TotalMilliseconds);
                lead = _leadRepo.GetById(leadNumber);
                if (lead is not null && lead._embedded is not null && lead._embedded.tags is not null)
                {
                    tags = lead._embedded.tags;
                }
            }
            catch (Exception e)
            {
                _processQueue.Stop(leadNumber.ToString());
                _processQueue.Remove(leadNumber.ToString());
                _log.Add($"Error: Unable to create leadProcessor {leadNumber}: {e.Message}");
            }
        }
예제 #2
0
        public Task Success()
        {
            if (_token.IsCancellationRequested)
            {
                _processQueue.Remove($"ret2corp-{_leadNumber}");
                return(Task.FromCanceled(_token));
            }

            try
            {
                Lead lead = _leadRepo.GetById(_leadNumber);

                var retLeadId = lead.GetCFIntValue(724771);

                if (retLeadId == 0)
                {
                    _processQueue.Remove($"ret2corp-{_leadNumber}");
                    return(Task.CompletedTask);
                }

                _sourceLeadRepo.Save(new Lead()
                {
                    id          = retLeadId,
                    pipeline_id = 3558781,
                    status_id   = 142
                });

                _processQueue.Remove($"ret2corp-{_leadNumber}");
                return(Task.CompletedTask);
            }
            catch (Exception e)
            {
                _processQueue.Remove($"ret2corp-{_leadNumber}");
                _log.Add($"Не получилось синхронизировать сделку {_leadNumber} из корп. в розницу: {e.Message}.");
                return(Task.FromException(e));
            }
        }
예제 #3
0
        public Task Run()
        {
            if (_token.IsCancellationRequested)
            {
                _processQueue.Remove($"initial_{_leadNumber}");
                return(Task.FromCanceled(_token));
            }

            try
            {
                bool model = false;

                var lead = _leadRepo.GetById(_leadNumber);

                if (lead?._embedded?.tags is not null &&
                    lead._embedded.tags.Any(x => x.name == "WA"))
                {
                    var events = _leadRepo.GetEntityEvents(_leadNumber);

                    if (events.Any(x => x.type == "incoming_chat_message" &&
                                   x.value_after is not null &&
                                   x.value_after.Any(x => x.message is not null &&
                                                     x.message.origin == "wahelp.whatbot.1")))
                    {
                        model = true;
                    }
                }

                _leadRepo.Save(new Lead()
                {
                    id          = lead.id,
                    name        = "Новая сделка",
                    pipeline_id = model ? 4647979 : 4289935,
                    status_id   = model ? 42656578 : 40102252
                });

                _processQueue.Remove($"initial_{_leadNumber}");
                return(Task.CompletedTask);
            }
            catch (Exception e)
            {
                _log.Add($"Unable to process ppie lead {lead.id}: {e.Message}");

                _processQueue.Remove($"initial_{_leadNumber}");
                return(Task.FromException(e));
            }
        }
예제 #4
0
        protected void UpdateLeadFromAmo()
        {
            if (_leadNumber == 0)
            {
                return;
            }

            try { lead = _leadRepo.GetById(_leadNumber); }
            catch (Exception e) { throw new Exception($"Error updating lead: {e}"); }

            List <Tag> allTags = new(tags);

            if (lead._embedded is not null && lead._embedded.tags is not null)
            {
                allTags.AddRange(lead._embedded.tags);
            }

            tags = allTags.Distinct(new TagComparer()).ToList();
        }
예제 #5
0
        public PPIELeadsProcessor(int leadNumber, AmoAccount acc, ProcessQueue processQueue, Log log, CancellationToken token)
        {
            _leadRepo     = acc.GetRepo <Lead>();
            _processQueue = processQueue;
            _token        = token;
            _leadNumber   = leadNumber;
            _log          = log;

            try
            {
                Thread.Sleep((int)TimeSpan.FromSeconds(3).TotalMilliseconds);
                lead = _leadRepo.GetById(leadNumber);
            }
            catch (Exception e)
            {
                _processQueue.Stop(leadNumber.ToString());
                _processQueue.Remove(leadNumber.ToString());
                _log.Add($"Error: Unable to create leadProcessor {leadNumber}: {e.Message}");
            }
        }
예제 #6
0
        public Task Send()
        {
            if (_token.IsCancellationRequested)
            {
                _processQueue.Remove($"corp2ret-{_leadNumber}");
                return(Task.FromCanceled(_token));
            }
            try
            {
                #region Getting source entities
                Lead sourceLead = _sourceLeadRepo.GetById(_leadNumber);

                if (sourceLead._embedded is null ||
                    sourceLead._embedded.contacts is null ||
                    !sourceLead._embedded.contacts.Any())
                {
                    return(Task.CompletedTask);
                }

                var sourceContacts = _sourceContRepo.BulkGetById(sourceLead._embedded.contacts.Select(x => (int)x.id));
                #endregion

                Lead lead = new() {
                    name = sourceLead.name,
                    responsible_user_id = GetResponsibleUserId((int)sourceLead.responsible_user_id),
                    _embedded           = new()
                };

                List <Note> calls = new();
                List <Note> notes = new();

                foreach (var c in sourceContacts)
                {
                    #region Prepare contacts
                    string phone = c.GetCFStringValue(33575);
                    string email = c.GetCFStringValue(33577);

                    phone = phone.Trim().Replace("+", "").Replace("-", "").Replace(" ", "").Replace("(", "").Replace(")", "");
                    phone = phone.StartsWith("89") ? $"7{phone[1..]}" : phone;

                    email = email.Trim().Replace(" ", "");

                    if (phone == "" && email == "")
                    {
                        continue;
                    }
                    #endregion

                    var contactNotes = _sourceContRepo.GetEntityNotes((int)c.id);
                    notes.AddRange(contactNotes.Where(x => x.note_type == "common"));
                    calls.AddRange(contactNotes.Where(x => x.note_type == "call_in" || x.note_type == "call_out"));

                    #region Checking for contacts
                    List <Contact> similarContacts = new();

                    Contact contact = new() {
                        name = c.name,
                        responsible_user_id = lead.responsible_user_id,
                    };

                    try
                    {
                        if (phone != "")
                        {
                            similarContacts.AddRange(_contRepo.GetByCriteria($"query={phone}"));
                        }

                        if (email != "")
                        {
                            similarContacts.AddRange(_contRepo.GetByCriteria($"query={email}"));
                        }
                    }
                    catch (Exception e) { _log.Add($"Не удалось осуществить поиск похожих контактов: {e}"); }

                    if (similarContacts.Any())
                    {
                        contact.id = similarContacts.First().id;
                        contact.responsible_user_id = similarContacts.First().responsible_user_id;
                        lead.responsible_user_id    = similarContacts.First().responsible_user_id;
                        _log.Add($"Найден похожий контакт: {similarContacts.First().id}.");
                    }
                    else
                    {
                        contact.custom_fields_values = new();

                        if (email != "")
                        {
                            contact.AddNewCF(264913, email);
                        }

                        if (phone != "")
                        {
                            contact.AddNewCF(264911, phone);
                        }
                    }

                    lead._embedded.contacts = new() { contact };
                    break;
                    #endregion
                }

                #region Setting pipeline and status if any
                lead.pipeline_id = 3198184;
                lead.status_id   = 32532880;
                #endregion

                #region Getting comments
                var leadNotes = _sourceLeadRepo.GetEntityNotes(_leadNumber);
                notes.AddRange(leadNotes.Where(x => x.note_type == "common"));
                calls.AddRange(leadNotes.Where(x => x.note_type == "call_in" || x.note_type == "call_out"));

                StringBuilder sb = new();

                if (sourceLead.HasCF(748383))     //Тип обращения
                {
                    sb.Append($"{sourceLead.GetCFStringValue(748383)}\r\n");
                }

                foreach (var n in notes)
                {
                    sb.Append($"{n.parameters.text}\r\n");
                }

                string comment = sb.ToString();
                #endregion

                #region Tags
                List <Tag> tags = new() { TagList.GetRetTagByName("Сделка из корп. отдела") };
                if (sourceLead._embedded is not null &&
                    sourceLead._embedded.tags is not null &&
                    sourceLead._embedded.tags.Any())
                {
                    foreach (var t in sourceLead._embedded.tags)
                    {
                        tags.Add(new() { name = t.name });
                    }
                }

                lead._embedded.tags = new(tags);
                #endregion

                #region Custom fields
                lead.AddNewCF(724771, sourceLead.id);       //поле corp_id

                if (sourceLead.HasCF(748383))               //Тип обращения
                {
                    lead.AddNewCF(639075, sourceLead.GetCFValue(748383));
                }
                if (sourceLead.HasCF(758213))               //Сайт
                {
                    lead.AddNewCF(639081, sourceLead.GetCFValue(758213));
                }
                if (sourceLead.HasCF(758215))               //Посадочная страница
                {
                    lead.AddNewCF(639083, sourceLead.GetCFValue(758215));
                }
                if (sourceLead.HasCF(748385))               //Маркер
                {
                    lead.AddNewCF(639085, sourceLead.GetCFValue(748385));
                }
                if (sourceLead.HasCF(758217))               //roistat
                {
                    lead.AddNewCF(639073, sourceLead.GetCFValue(758217));
                }
                #endregion

                var created = _leadRepo.AddNewComplex(lead);

                _log.Add($"Создана новая сделка {created.First()}");

                #region Adding notes
                if (created.Any() &&
                    comment != "")
                {
                    _leadRepo.AddNotes(created.First(), comment);
                }

                if (created.Any() &&
                    calls.Any())
                {
                    foreach (var n in calls.Select(x => new Note()
                    {
                        entity_id = created.First(),
                        note_type = x.note_type,
                        parameters = x.parameters
                    }))
                    {
                        _leadRepo.AddNotes(n);
                    }
                }
                #endregion

                _processQueue.Remove($"corp2ret-{_leadNumber}");

                return(Task.CompletedTask);
            }
            catch (Exception e)
            {
                _processQueue.Remove($"corp2ret-{_leadNumber}");
                _log.Add($"Не получилось перенести сделку {_leadNumber} из корп. в розницу: {e.Message}.");
                return(Task.FromException(e));
            }
        }
예제 #7
0
        private static Request GetProcessedLeadRequest(Lead lead, int sheetId, IAmoRepo <Company> compRepo)
        {
            #region Оганизация
            string A = "";
            if (lead._embedded.companies.Any())
            {
                A = compRepo.GetById(lead._embedded.companies.FirstOrDefault().id).name;
            }
            #endregion

            #region Назначение платежа
            string B = lead.GetCFStringValue(118509);
            #endregion

            #region Кол-во человек
            int C = lead.GetCFIntValue(611005);
            if (C == 0)
            {
                C++;
            }
            #endregion

            #region Сумма
            int E = (int)lead.price;
            #endregion

            #region Стоимость
            string D = @"=INDIRECT(""R[0]C[1]"", FALSE)/INDIRECT(""R[0]C[-1]"", FALSE)";
            #endregion

            #region Дата прихода
            long payment_date_unix;
            if (lead.custom_fields_values.Any(x => x.field_id == 118675))
            {
                payment_date_unix = (long)lead.custom_fields_values.FirstOrDefault(x => x.field_id == 118675).values[0].value;
            }
            else
            {
                payment_date_unix = 0;
            }
            string F = DateTimeOffset.FromUnixTimeSeconds(payment_date_unix).UtcDateTime.AddHours(3).ToShortDateString();
            #endregion

            #region Номер квитанции
            string G = lead.GetCFStringValue(118609);
            #endregion

            #region  асчет
            string H = lead.GetCFStringValue(118545);
            #endregion

            #region Исполнитель
            string I = lead.GetCFStringValue(162301);
            #endregion

            #region Номер сделки
            int J = lead.id;
            #endregion

            #region % сделки
            int K = lead.GetCFIntValue(613663);
            #endregion

            #region Вознаграждение
            string L = @"=INDIRECT(""R[0]C[-7]"", FALSE)*INDIRECT(""R[0]C[-1]"", FALSE)/100";
            #endregion

            return(GetRowRequest(sheetId, GetCellData(A, B, C, D, E, F, G, H, I, J, K, L)));
        }
예제 #8
0
        public Task Run()
        {
            if (_token.IsCancellationRequested)
            {
                _processQueue.Remove($"setCourse-{_leadNumber}");
                return(Task.FromCanceled(_token));
            }

            try
            {
                Lead lead = _repo.GetById(_leadNumber);

                if (lead._embedded is not null &&
                    lead._embedded.catalog_elements is not null &&
                    lead._embedded.catalog_elements.Any())
                {
                    CatalogElement catalogElement = _repo.GetCEById(lead._embedded.catalog_elements.First().id);

                    if (catalogElement is null ||
                        catalogElement.custom_fields is null ||
                        !catalogElement.custom_fields.Any(x => x.id == 647993))
                    {
                        throw new Exception("Incorrect catalog element, no article field.");
                    }

                    Lead result = new(){ id = _leadNumber };
                    result.AddNewCF(357005, catalogElement.custom_fields.First(x => x.id == 647993).values[0].value);

                    _repo.Save(result);

                    _processQueue.Remove($"setCourse-{_leadNumber}");
                    return(Task.CompletedTask);
                }

                _repo.AddNotes(new Note()
                {
                    entity_id = _leadNumber, note_type = "common", parameters = new Note.Params()
                    {
                        text = "Укажите, пожалуйста, товар в сделке."
                    }
                });

                var events = _repo.GetEntityEvents(_leadNumber)
                             .Where(x => x.type == "lead_status_changed")
                             .OrderByDescending(x => x.created_at)
                             .ToList();

                if (!events.Any())
                {
                    _repo.Save(new Lead()
                    {
                        id          = _leadNumber,
                        pipeline_id = 3198184,
                        status_id   = 32532880
                    });

                    _processQueue.Remove($"setCourse-{_leadNumber}");
                    return(Task.CompletedTask);
                }

                int recentPipelineId = events.First().value_before.First().lead_status.pipeline_id;
                int recentStatusId   = events.First().value_before.First().lead_status.id;

                int[] forbiddenStatuses = new int[] {
                    142,
                    143,
                    32532886,
                    32533195,
                    32533198,
                    32533201,
                    32533204,
                    33625285,
                    33817816
                };

                if (!forbiddenStatuses.Contains(recentStatusId))
                {
                    _repo.Save(new Lead()
                    {
                        id          = _leadNumber,
                        pipeline_id = recentPipelineId,
                        status_id   = recentStatusId
                    });
                }

                _processQueue.Remove($"setCourse-{_leadNumber}");
                return(Task.CompletedTask);
            }
            catch (Exception e)
            {
                _processQueue.Remove($"setCourse-{_leadNumber}");
                _log.Add($"Не получилось установить курс в сделке {_leadNumber}: {e.Message}.");
                return(Task.FromException(e));
            }
        }