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 List <Amo_id> Run() { if (_company1C.amo_ids is null) { _company1C.amo_ids = new(); } try { #region Checking if company already linked to entity and updating if possible if (_company1C.amo_ids.Any(x => x.account_id == _amo_acc)) { foreach (var c in _company1C.amo_ids.Where(x => x.account_id == _amo_acc)) { try { UpdateCompanyInAmo(_company1C, _compRepo, c.entity_id, _amo_acc, _filter); _log.Add($"Updated company {c.entity_id} in amo."); return(_company1C.amo_ids); } catch (Exception e) { _log.Add($"Unable to update company {c.entity_id} in amo {e}"); } } } #endregion #region Checking company List <Company> similarCompanies = new(); if (_company1C.INN is not null && _company1C.INN != "") { similarCompanies.AddRange(_compRepo.GetByCriteria($"query={_company1C.INN.Trim().Replace(" ", "")}")); } if (_company1C.phone is not null && _company1C.phone != "") { similarCompanies.AddRange(_compRepo.GetByCriteria($"query={_company1C.phone.Trim().Replace("+", "").Replace("-", "").Replace(" ", "").Replace("(", "").Replace(")", "")}")); } if (_company1C.email is not null && _company1C.email != "") { similarCompanies.AddRange(_compRepo.GetByCriteria($"query={_company1C.email.Trim().Replace(" ", "")}")); } #endregion #region Updating found company if (similarCompanies.Any()) { UpdateCompanyInAmo(_company1C, _compRepo, similarCompanies.First().id, _amo_acc, _filter); _company1C.amo_ids.Add(new() { account_id = _amo_acc, entity_id = similarCompanies.First().id }); _log.Add($"Found and updated company {similarCompanies.First().id} in amo"); return(_company1C.amo_ids); } if (similarCompanies.Distinct(new CompaniesComparer()).Count() > 1) { _log.Add($"Check for doubles: {JsonConvert.SerializeObject(similarCompanies.Distinct(new CompaniesComparer()).Select(x => new { x.id, x.account_id }), Formatting.Indented)}"); } #endregion #region Creating new company var compId = CreateCompanyInAmo(_company1C, _compRepo, _amo_acc, _filter); if (_company1C.amo_ids is null) { _company1C.amo_ids = new(); } _company1C.amo_ids.Add(new() { account_id = 19453687, entity_id = compId }); #endregion _log.Add($"Created company {compId} in amo."); } catch (Exception e) { _log.Add($"Unable to update company in amo from 1C: {e.Message}"); } return(_company1C.amo_ids); }
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(_taskName); return(Task.FromCanceled(_token)); } try { #region Checking for contacts if (!IsValidField(_email) && !IsValidField(_phone)) { _log.Add("Request without contacts"); _processQueue.Remove(_taskName); return(Task.CompletedTask); } #endregion #region Checking company List <Company> similarCompanies = new(); try { if (IsValidField(_phone)) { similarCompanies.AddRange(_compRepo.GetByCriteria($"query={_phone}&with=leads")); } if (IsValidField(_email)) { similarCompanies.AddRange(_compRepo.GetByCriteria($"query={_email}&with=leads")); } } catch (Exception e) { _log.Add($"Не удалось осуществить поиск похожих компаний: {e}"); } #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) { _log.Add($"Не удалось осуществить поиск похожих контактов: {e}"); } #endregion #region Getting similar leads List <Lead> similarLeads = new(); List <int> leadIds = new(); foreach (var c in similarCompanies) { if (c._embedded is not null && c._embedded.leads is not null) { leadIds.AddRange(c._embedded.leads.Select(x => x.id)); } } foreach (var c in similarContacts) { if (c._embedded is not null && c._embedded.leads is not null) { leadIds.AddRange(c._embedded.leads.Select(x => x.id)); } } if (!leadIds.Any()) { _log.Add($"Не удалось учесть оплату для контакта {_phone}, {_email} - Не найдено сделок"); _processQueue.Remove(_taskName); return(Task.CompletedTask); } similarLeads.AddRange(_leadRepo.BulkGetById(leadIds.Distinct()).Where(x => x.pipeline_id == 4697182 && x.status_id == 43009222)); if (!similarLeads.Any()) { _log.Add($"Не удалось учесть оплату для контакта {_phone}, {_email} - Не найдено неоплаченных сделок"); _processQueue.Remove(_taskName); return(Task.CompletedTask); } #endregion Lead lead = new() { id = similarLeads.First().id, pipeline_id = 4697182, status_id = 43009228 }; try { _leadRepo.Save(lead); } catch (Exception e) { _log.Add($"Не удалось сохранить сделку {lead.id}: {e}."); throw; } _processQueue.Remove(_taskName); return(Task.CompletedTask); } catch (Exception e) { _log.Add($"Не удалось учесть оплату для сделки: {e}."); _processQueue.Remove(_taskName); return(Task.FromException(e)); } }