public Task Run() { if (_token.IsCancellationRequested) { _processQueue.Remove(_taskName); return(Task.FromCanceled(_token)); } try { #region Checking for contacts if (!IsValidField(_email) && !IsValidField(_phone)) { throw new ArgumentException("Запрос без контактов"); } #endregion #region Checking contact List <Contact> similarContacts = new(); try { if (IsValidField(_phone)) { similarContacts.AddRange(_contRepo.GetByCriteria($"query={_phone}&with=leads")); } if (IsValidField(_email)) { similarContacts.AddRange(_contRepo.GetByCriteria($"query={_email}&with=leads")); } } catch (Exception e) { throw new InvalidOperationException($"Не удалось осуществить поиск похожих контактов: {e}"); } #endregion if (!similarContacts.Any()) { throw new InvalidOperationException("Не найдено подходящитх контактов в amoCRM."); } foreach (var c in similarContacts.Distinct(new ContactsComparer())) { _contRepo.AddNotes((int)c.id, $"Поступила оплата в размере {_price} от контакта {_phone}, {_email}"); } _processQueue.Remove(_taskName); return(Task.CompletedTask); } catch (Exception e) { _log.Add($"Не удалось учесть оплату для контакта {_phone}, {_email}: {e}."); _processQueue.Remove(_taskName); return(Task.FromException(e)); } }
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)); } }
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)); } }
protected void AddNote(string note) { try { _leadRepo.AddNotes(_leadNumber, note); } catch (Exception e) { throw new Exception($"Error adding note: {e}"); } }