public async Task <string> SendLead(SendLeadto1CDTo lead)
        {
            var dto1CLead = new SendLeadto1CDTo();

            dto1CLead = lead.Adapt <SendLeadto1CDTo>(mapper);

            if (dto1CLead.isValid == false)
            {
                throw new ArgumentException(String.Join(" | ", dto1CLead.GetValidateErrors()));
            }

            var result = await database.Persons.InviteTo1C(dto1CLead.Adapt <AddLeadDTO>(mapper));

            if (result != "Студент зачислен")
            {
                throw new ArgumentException();
            }

            return(String.IsNullOrEmpty(result) ? null : result);
        }
Exemple #2
0
        public void SendLead2()
        {
            var commonDTO = new SendLeadto1CDTo
            {
                ContractTitle = "ТстДГВор",
                //ContractGroup = "Тест",
                //ContractEducationStart = "2019-03-10".ToDateTime('-'),
                //ContractEducationEnd = "2019-03-13".ToDateTime('-').AddDays(10),
                //ContractExpire = "2019-03-20".ToDateTime('-').AddDays(180),
                ContractPrice = 8000,
                //DecreeTitle = "ТстПрикз",
                ProgramGuid = "3a660dca-9f7b-11e6-80e7-0cc47a4b75cc",
                UserGuid    = "5bf0c9ee-8973-11e6-8102-10c37b94684b"
            };

            var serviceDTO = commonDTO.Adapt <AddLeadDTO>();

            var sdf = new UnitOfWork("Kloder", "Kaligula2");

            //  var sss = sdf.Persons.InviteTo1C(serviceDTO).Result;
        }
Exemple #3
0
        public void SendLeadto1CDTo_AddLeadDTO()
        {
            var commonDTO = new SendLeadto1CDTo
            {
                ProgramGuid            = "7da38f8f-9f71-11e6-80e7-0cc47a4b75cc", // 3a660dca-9f7b-11e6-80e7-0cc47a4b75cc
                UserGuid               = "cef55369-cd46-11e8-8103-0cc47a4b75cc", //5bf0c9ee-8973-11e6-8102-10c37b94684b
                ContractTitle          = "ТстДГВор",
                ContractGroup          = "Тест",
                ContractEducationStart = "2018-10-10".ToDateTime('-'),
                ContractEducationEnd   = "2018-10-10".ToDateTime('-').AddDays(10),
                ContractExpire         = "2018-10-10".ToDateTime('-').AddDays(180),
                ContractPrice          = 8000,
                DecreeTitle            = "ТстПрикз"
            };

            var serviceDTO = commonDTO.Adapt <AddLeadDTO>();

            Assert.AreEqual(serviceDTO.ProgramGuid, "7da38f8f-9f71-11e6-80e7-0cc47a4b75cc");
            Assert.AreEqual(serviceDTO.ContractSubGroup, "");
            Assert.AreEqual(serviceDTO.ContractEducationEnd, new DateTime(2018, 10, 20));
        }
        public async void DoAction(object sender, CrmEvent e)
        {
            if (e.Entity != "leads" || String.IsNullOrEmpty(e.EntityId))
            {
                return;
            }
            var @event = e.Events.FirstOrDefault();

            if (@event.Event != "status" ||
                (@event.CurrentValue != "19368232" & @event.CurrentValue != "142" & @event.CurrentValue != "18855166"))
            {
                return;
            }

            if (@event.CurrentValue == "142" & @event.Pipeline != "917056")
            {
                return;
            }

            Lead    lead    = null;
            Contact contact = null;

            var contactGuid = String.Empty;

            #region Получить сделку
            try
            {
                var queryLead = await crm.Leads.Get().Filter(i => i.Id = int.Parse(e.EntityId)).Execute();

                lead = queryLead.FirstOrDefault().Adapt <Lead>(mapper);
                if (lead == null)
                {
                    throw new NullReferenceException();
                }
            }
            catch (NullReferenceException ex)
            {
                currentLogger.LogWarning(ex, "Сделка ID - {ID} не найдена", e.EntityId);
                return;
            }
            catch (Exception ex)
            {
                currentLogger.LogDebug(ex, "Ошибка при запросе Lead - {ID}", e.EntityId);
            }
            #endregion


            #region Получить контакт
            if (lead.MainContact != null)
            {
                try
                {
                    var queryContact = await crm.Contacts.Get().Filter(i => i.Id = lead.MainContact.Id).Execute();

                    contact = queryContact.FirstOrDefault().Adapt <Contact>(mapper);
                    if (contact == null)
                    {
                        throw new NullReferenceException();
                    }
                }
                catch (NullReferenceException ex)
                {
                    currentLogger.LogWarning(ex, "Контакт ID - {ID} не найден", lead.MainContact.Id);
                    return;
                }
                catch (Exception ex)
                {
                    currentLogger.LogError(ex, "Ошибка при запросе Contact - {ID}", lead.MainContact.Id);
                }
            }
            #endregion

            contactGuid = contact.Guid();

            #region Отправить пользователя в 1С если отсутствует

            if (String.IsNullOrEmpty(contact.Guid()))
            {
                var userActions = new Actions.User1C(database, loggerFactory, mapper);

                string guid = String.Empty;

                try
                {
                    guid = await userActions.Create(contact);

                    if (guid == null)
                    {
                        throw new NullReferenceException();
                    }
                }
                catch (NullReferenceException ex)
                {
                    currentLogger.LogWarning(ex, "Контакт ID - {ID} не создан в 1С", contact.Id);

                    var note = new NoteDTO()
                    {
                        ElementId   = contact.Id,
                        ElementType = (int)ElementTypeEnum.Контакт,
                        NoteType    = 25,
                        Params      = new NoteParams
                        {
                            Text    = "Ошибка сохранения пользователя в 1С.",
                            Service = "WebApi | "
                        }
                    };

                    var queryCreateTask = await crm.Notes.Add(note);

                    return;
                }
                catch (ArgumentException ex)
                {
                    var exceptionNote = new NoteDTO()
                    {
                        ElementId   = contact.Id,
                        ElementType = (int)ElementTypeEnum.Контакт,
                        NoteType    = 4,
                        Text        = "Ошибка сохранения пользователя в 1С. Сообщение - " + ex.Message
                    };

                    var queryCreateTask = await crm.Notes.Add(exceptionNote);

                    return;
                }
                catch (Exception ex)
                {
                    currentLogger.LogDebug(ex, "Ошибка при сохранении пользователя в 1С");
                    return;
                }

                contactGuid = guid;

                var noteSucces = new NoteDTO()
                {
                    ElementId   = contact.Id,
                    ElementType = (int)ElementTypeEnum.Контакт,
                    NoteType    = 25,
                    Params      = new NoteParams
                    {
                        Text    = "Контакт занесен в 1С",
                        Service = "WebApi | "
                    }
                };

                var queryCreateTaskSucces = await crm.Notes.Add(noteSucces);

                contact.Guid(guid);

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


            var dto = new SendLeadto1CDTo();
            dto.ProgramGuid   = lead.Guid();
            dto.UserGuid      = contactGuid;
            dto.ContractPrice = lead.Price.Value;
            dto.ContractTitle = contact.Name;
            dto.DecreeTitle   = contact.Name;

            if (lead.Pipeline.Id == 917056 || lead.Pipeline.Id == 920008 || lead.Pipeline.Id == 1102975)
            {
                dto.ContractEducationStart = lead.SeminarDate().Value;
                dto.ContractEducationEnd   = lead.SeminarDate().Value.AddDays(3);
                dto.ContractExpire         = lead.SeminarDate().Value.AddDays(3);
                dto.ContractGroup          = lead.SeminarDate().Value.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture);
            }

            if (lead.Pipeline.Id == 920011 || lead.Pipeline.Id == 1042456)
            {
                dto.ContractEducationStart = lead.ProgramStartDate().Value;
                dto.ContractEducationEnd   = lead.ProgramStartDate().Value.AddDays(180);
                dto.ContractExpire         = lead.ContractExpireDate().Value;

                dto.ContractGroup = "Общая группа";

                if (lead.Pipeline.Id == 1042456)
                {
                    dto.ContractGroup = lead.DistantGroup().Value;
                }
                if (lead.Pipeline.Id == 920011)
                {
                    dto.ContractGroup = lead.FullTimeGroup().Value;
                }

                dto.ContractSubGroup = lead.SubGroup()?.Value ?? "";
            }

            var userActions3 = new Actions.User1C(database, loggerFactory, mapper);

            try
            {
                var result = await userActions3.SendLead(dto);

                var note = new NoteDTO()
                {
                    ElementId   = lead.Id,
                    ElementType = (int)ElementTypeEnum.Сделка,
                    NoteType    = 25,
                    Params      = new NoteParams
                    {
                        Text    = "Сделка успешно отправлена в 1С.",
                        Service = "WebApi | "
                    }
                };

                var queryCreateTask = await crm.Notes.Add(note);

                currentLogger.LogInformation("Сделка успешно отправлена в 1С. Мероприятие - {Event} [{LeadId}] | Контакт - {Name} [{ContactId}]", lead.Name, lead.Id, contact.Name, contact.Id);

                lead.IsInService1C(true);

                await crm.Leads.Update(lead.GetChanges().Adapt <LeadDTO>(mapper));
            }
            catch (ArgumentException ex)
            {
                var exceptionNote = new NoteDTO()
                {
                    ElementId   = lead.Id,
                    ElementType = (int)ElementTypeEnum.Сделка,
                    NoteType    = 4,
                    Text        = "Ошибка ошибка отправки сделки в 1С. Проверьте поля данных или зачислите вручную."
                };

                var queryCreateTask = await crm.Notes.Add(exceptionNote);

                currentLogger.LogWarning(ex, "Ошибка отправки сделки в 1С");
            }
            catch (Exception ex)
            {
                currentLogger.LogWarning(ex, "Ошибка ошибка отправки сделки в 1С");
            }
        }