Exemplo n.º 1
0
        public LeadResponse ChargifySuscription(string subscription_id, string customer_id)
        {
            var response = new LeadResponse();
            SubscriptionService chargifyService = new SubscriptionService();
            ISubscription       subscription    = chargifyService.GetSubscription(int.Parse(subscription_id));
            ICustomer           customerResult  = subscription.Customer;

            try
            {
                var leadRepository = new LeadRepository();
                var newLead        = new Lead()
                {
                    Aliases             = "",
                    CountryCode         = "USA(+1)",
                    DateCreated         = DateTime.Now,
                    DateUpdated         = DateTime.Now,
                    Email               = customerResult.Email,
                    FirstName           = customerResult.FirstName,
                    LastName            = customerResult.LastName,
                    Keywords            = "",
                    PhoneNumber         = customerResult.Phone,
                    MarketSegments      = "",
                    OtherMarketSegments = "",
                    IntakeEmailSentDate = DateTime.Now,
                    IntakeToken         = subscription_id,
                    IntakeUrl           = "",
                    IsActive            = true,
                    IsIntakeAnswered    = false
                };
                leadRepository.Add(newLead);
                leadRepository.SaveChanges();

                var currentLead = newLead;
                if (currentLead != null)
                {
                    response.Lead = new LeadDto()
                    {
                        idLead      = currentLead.idLead,
                        FirstName   = currentLead.FirstName,
                        LastName    = currentLead.LastName,
                        CountryCode = currentLead.CountryCode,
                        PhoneNumber = currentLead.PhoneNumber,
                        Email       = currentLead.Email
                    };
                    response.Acknowledgment = true;
                    response.Message        = "Success";
                }
                else
                {
                    response.Acknowledgment = false;
                    response.Message        = "Unable to Find a lead with that token";
                }
            }
            catch (Exception ex)
            {
                response.Acknowledgment = false;
                response.Message        = "Error Updating a Lead: " + ex.Message;
            }
            return(response);
        }
Exemplo n.º 2
0
        public LeadResponse GetLeadByToken(string token)
        {
            var response = new LeadResponse();

            try
            {
                var leadRepository = new LeadRepository();
                var currentLead    = leadRepository.Query().FirstOrDefault(x => x.IntakeToken == token);
                if (currentLead != null)
                {
                    response.Lead = new LeadDto()
                    {
                        idLead      = currentLead.idLead,
                        FirstName   = currentLead.FirstName,
                        LastName    = currentLead.LastName,
                        CountryCode = currentLead.CountryCode,
                        PhoneNumber = currentLead.PhoneNumber,
                        Email       = currentLead.Email
                    };
                    response.Acknowledgment = true;
                    response.Message        = "Success";
                }
                else
                {
                    response.Acknowledgment = false;
                    response.Message        = "Unable to Find a lead with that token";
                }
            }
            catch (Exception ex)
            {
                response.Acknowledgment = false;
                response.Message        = "Error Updating a Lead: " + ex.Message;
            }
            return(response);
        }
Exemplo n.º 3
0
        public HttpResponseMessage Post(Lead request)
        {
            LeadResponse response = new LeadResponse()
            {
                LeadId       = 10000000 + new Random().Next(),
                IsCapped     = false,
                Messages     = new[] { "Thank you for submitting your details,", "" },
                IsSuccessful = true,
                IsDuplicate  = false
            };

            request.LeadId = response.LeadId;

            if (!CheckIfExists(request))
            {
                InsertData(request);
            }
            else
            {
                response.IsDuplicate  = true;
                response.IsSuccessful = false;
                response.Messages     = new[] { "duplicate on [email/ contact number],", "" };
            }

            response.Messages[1] = $" your ID is { response.LeadId}";
            UpdateLead(response, request);

            Console.WriteLine($"Lead received {request.FirstName} {request.Surname}");

            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Exemplo n.º 4
0
        public LeadResponse CreateLead(LeadDto leadDto, bool sendMail)
        {
            var response = new LeadResponse();

            try
            {
                UserService _userService = new UserService();

                // _userService.GetUserInformation
                if (ValidateLeadEmail(leadDto.Email))
                {
                    var leadRepository = new LeadRepository();
                    var newLead        = new Lead()
                    {
                        Aliases             = leadDto.Aliases,
                        CountryCode         = leadDto.CountryCode,
                        DateCreated         = leadDto.DateCreated,
                        DateUpdated         = leadDto.DateUpdated,
                        Email               = leadDto.Email,
                        FirstName           = leadDto.FirstName,
                        LastName            = leadDto.LastName,
                        Keywords            = leadDto.Keywords,
                        PhoneNumber         = leadDto.PhoneNumber,
                        MarketSegments      = leadDto.MarketSegments,
                        OtherMarketSegments = leadDto.OtherMarketSegments,
                        IntakeEmailSentDate = DateTime.Now,
                        IntakeToken         = leadDto.IntakeToken,
                        IntakeUrl           = leadDto.IntakeUrl,
                        IsActive            = true,
                        IsIntakeAnswered    = false
                    };
                    leadRepository.Add(newLead);
                    leadRepository.SaveChanges();
                    leadDto.idLead          = newLead.idLead;
                    response.Acknowledgment = true;
                    response.Message        = "Success";

                    if (sendMail)
                    {
                        SendLeadConfirmationEmail(leadDto.Email, leadDto.FirstName, leadDto.IntakeUrl);
                    }
                    response.Lead = leadDto;
                }
                else
                {
                    //response.Acknowledgment = false;
                    //response.Message = "Error Adding a Lead: Email already exist";
                    //response.Lead = null;
                    throw new System.ArgumentException("The email is already registered as a user. Please choose another one.");
                }
            }
            catch (Exception ex)
            {
                response.Acknowledgment = false;
                response.Message        = ex.Message;
                response.Lead           = null;
            }
            return(response);
        }
Exemplo n.º 5
0
        public IHttpActionResult Create(Lead Lead)
        {
            string            exceptionMsg      = string.Empty;
            UnidadNegocioKeys?_unidadNegocioKey = null;
            object            objEnvio          = null;
            LeadResponse      Rpta = new LeadResponse();

            try
            {
                /// Obtiene Token para envío a Salesforce
                var authSf    = RestBase.GetToken();
                var token     = authSf[OutParameter.SF_Token].ToString();
                var crmServer = authSf[OutParameter.SF_UrlAuth].ToString();

                /// Envío de cotizacion a Salesforce
                var leadSF = new List <object>();
                leadSF.Add(Lead.ToSalesforceEntity());

                try
                {
                    ClearQuickLog("body_request.json", "Lead");      /// ♫ Trace
                    objEnvio = new { datos = leadSF };
                    QuickLog(objEnvio, "body_request.json", "Lead"); /// ♫ Trace
                    var response = RestBase.ExecuteByKeyWithServer(crmServer, SalesforceKeys.LeadCreateMethod, Method.POST, objEnvio, true, token);
                    if (response.StatusCode.Equals(HttpStatusCode.OK))
                    {
                        dynamic jsonResponse = new JavaScriptSerializer().DeserializeObject(response.Content);
                        foreach (var jsResponse in jsonResponse["Leads"])
                        {
                            Rpta.CodigoRetorno  = jsResponse[OutParameter.SF_CodigoRetorno];
                            Rpta.MensajeRetorno = jsResponse[OutParameter.SF_MensajeRetorno];
                            Rpta.IdLeadSf       = jsResponse[OutParameter.SF_IdLead];
                        }
                    }
                }
                catch (Exception ex)
                {
                    Rpta.CodigoRetorno  = ApiResponseCode.ErrorCode;
                    Rpta.MensajeRetorno = ex.Message;
                    exceptionMsg        = ex.Message;
                }
                return(Ok(Rpta));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
            finally
            {
                (new
                {
                    Body = objEnvio,
                    UnidadNegocio = _unidadNegocioKey.ToString(),
                    Exception = exceptionMsg
                }).TryWriteLogObject(_logFileManager, _clientFeatures);
            }
        }
Exemplo n.º 6
0
        private void SetFieldFromCustomField(DataFor1C dataFor1C, LeadResponse item)
        {
            //foreach (var custom_field in item.custom_fields)
            //{
            //	switch (custom_field.name)
            //	{
            //		case "Адрес объекта": dataFor1C.address = custom_field.values[0].value; break;

            //	}
            //}
        }
        public void UpdateOrCreate(LeadResponse lead)
        {
            if (lead.Lead != null)
            {
                var    tableName = "Заявки";
                string AtRecord_ID;
                if (IsDealExist(lead.Lead.ID))
                {
                    return;
                }

                var updating = lead.GetUpdatingRecord();

                string newStatus;
                if (TryGetNewLeadStatus(lead.Lead.Type, lead.Lead.Status, out newStatus))
                {
                    updating.fields.Add("Статус заявки", newStatus);
                }

                if (lead.Lead.ASSIGNED_BY_ID != null)
                {
                    var assignUserID = GetFirstRecordID("Пользователи B24", "{ID B24}='" + lead.Lead.ASSIGNED_BY_ID + "'");

                    Log.Debug("Получение пользователя по ID " + lead.Lead.ASSIGNED_BY_ID);
                    if (string.IsNullOrWhiteSpace(assignUserID))
                    {
                        Log.Debug("Обновление справочника пользователей");
                        RefreshUsersDictionary(lead.Lead.AssignUser, out assignUserID);
                        Log.Debug("Новый ID: " + assignUserID);
                    }
                    if (!string.IsNullOrWhiteSpace(assignUserID))
                    {
                        updating.fields.Add("Ответственный New", new string[] { assignUserID });
                    }
                }

                lock (_leadLocker)
                {
                    AtRecord_ID = GetFirstRecordID(tableName, $"Lead_ID='{lead.Lead.ID}'");
                    if (AtRecord_ID != null)
                    {
                        UpdateRecord(tableName, AtRecord_ID, updating);
                    }
                    else
                    {
                        updating.fields.Add("Lead_ID", lead.Lead.ID);
                        CreateRecord(tableName, updating);
                    }
                }
            }
        }
Exemplo n.º 8
0
        public JsonResult AddLead(string token, string firstName, string lastName, string email, string countryCode, string phoneNumber, string aliases, string keywords, string productName, string productURL, string marketSegments, string otherMarketSegments, string competitors, string notes, string idLead, string ProductType)
        {
            try
            {
                //TODO Prepare Image for Database
                token = Guid.NewGuid().ToString();

                var leadDto = new LeadDto()
                {
                    //The intake token to identify the "lead" in the database
                    IntakeToken = token,

                    //from the First Step
                    FirstName   = firstName,
                    LastName    = lastName,
                    Email       = email,
                    CountryCode = countryCode,
                    PhoneNumber = phoneNumber,
                    DateUpdated = DateTime.Now,
                    DateCreated = DateTime.Now,
                    IntakeUrl   = "",

                    //From the 2nd step
                    Aliases             = aliases,
                    Keywords            = keywords,
                    ProductName         = productName,
                    ProductURL          = productURL,
                    MarketSegments      = marketSegments,
                    OtherMarketSegments = otherMarketSegments,
                    Competitors         = competitors,
                    Notes    = notes,
                    IsActive = true,
                    //idLead = int.Parse(idLead)
                };
                LeadResponse response = _leadService.CreateLead(leadDto, false);

                if (response.Acknowledgment == false && ProductType == "Trial")
                {
                    throw new System.ArgumentException("The email is already registered as a user. Please choose another one.");
                }

                var url = ConfigurationManager.AppSettings[ProductType] + "?first_name=" + firstName + "&last_name=" + lastName + "&email=" + email + "&reference=" + token + "&phone=" + countryCode + phoneNumber;
                return(Json(new { success = true, toUrl = url }));
            }catch (Exception e)
            {
                return(Json(new { success = false, message = e.Message }));
            }
            ///return Redirect(url);
        }
Exemplo n.º 9
0
 public HttpResponseMessage Post([FromBody] LeadRequest leadInfo)
 {
     try {
         Helper helper = new Helper();
         orgService = helper.ConnectCRM(crmUrl, logger);
         if (helper.IsValidRequestAuthentication())
         {
             logger.Info("Lead request started");
             if (ModelState.IsValid)
             {
                 var          response = helper.CreateLead(orgService, logger, leadInfo);
                 LeadResponse leadRes  = new LeadResponse
                 {
                     leadId  = response.leadId.ToString(),
                     message = response.message.ToString()
                 };
                 logger.Info("200 : LeadId = " + response.leadId.ToString());
                 return(Request.CreateResponse(HttpStatusCode.OK, leadRes));
             }
             else
             {
                 logger.Info("400 : Invalid Request " + ModelState.Values);
                 return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
             }
         }
         else
         {
             logger.Info("401 : Authentication Failed!");
             return(Request.CreateResponse(HttpStatusCode.Unauthorized, new MessageOutput {
                 message = "Caller was not authenticated!"
             }));
         }
     }
     catch (FaultException <IOrganizationService> ex)
     {
         logger.Info("Lead was not created " + ex.Message);
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, new MessageOutput {
             message = "Lead was not created. Please Try again!" + ex.Message
         }));
     }
     catch (Exception ex)
     {
         logger.Info("Lead was not created " + ex.Message);
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, new MessageOutput {
             message = "Lead was not created. Please Try again!" + ex.Message
         }));
     }
 }
Exemplo n.º 10
0
        public void TestAirTableClientStringBuilding()
        {
            LeadResponse leadResponse = new LeadResponse();
            Lead         lead         = new Lead();

            leadResponse.Lead = lead;
            ContactResponse contactResponse = new ContactResponse();
            Contact         contact         = new Contact();

            contactResponse.Contact = contact;
            DealResponse dealResponse = new DealResponse();
            Deal         deal         = new Deal();

            dealResponse.Deal = deal;
            CompanyResponse companyResponse = new CompanyResponse();
            Company         company         = new Company();

            companyResponse.Company = company;

            Assert.IsTrue(string.IsNullOrEmpty(deal.AirTableClientString));
            Assert.IsTrue(string.IsNullOrEmpty(lead.AirTableClientString));

            lead.NAME  = "Alex";
            lead.PHONE = new List <PHONE> {
                new PHONE()
                {
                    VALUE = "123"
                }
            };

            Assert.AreEqual(lead.AirTableClientString, "Alex (123)");

            deal.Contact  = contactResponse;
            contact.NAME  = "Alex";
            contact.PHONE = new List <PHONE> {
                new PHONE {
                    VALUE = "123"
                }
            };

            Assert.AreEqual(deal.AirTableClientString, "Alex (123)");

            deal.Company  = companyResponse;
            company.TITLE = "Company";

            Assert.AreEqual(deal.AirTableClientString, "Company Alex (123)");
        }
Exemplo n.º 11
0
        public async Task <ActionResult> SubmitLead(LeadViewModel model)
        {
            try
            {
                //TODO: 6. Call the WebAPI service here & pass results to UI

                string apiUrl = "http://localhost:8099/api/lead/submit";

                string sessionID = HttpContext.Session.SessionID;

                LeadResponse apiResponse = new LeadResponse();

                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await client.PostAsync <LeadViewModel>(apiUrl, model, new JsonMediaTypeFormatter());

                    if (response.IsSuccessStatusCode)
                    {
                        var data = await response.Content.ReadAsStringAsync();

                        apiResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <LeadResponse>(data);
                    }
                }

                LeadViewModel result = new LeadViewModel()
                {
                    Results = new LeadResultViewModel()
                    {
                        LeadId       = new Random().Next(),
                        IsSuccessful = true,

                        Message = String.Join("", apiResponse.Messages)
                    }
                };

                return(View("Index", result));
            }
            catch (Exception ex)
            {
                return(View("Index", ex.Message));
            }
        }
Exemplo n.º 12
0
        public HttpResponseMessage Post(Lead request)
        {
            LeadResponse response = new LeadResponse()
            {
                LeadId       = 10000000 + new Random().Next(),
                IsCapped     = false,
                Messages     = new[] { "Success from WebAPI" },
                IsSuccessful = true,
                IsDuplicate  = false
            };

            //TODO: 7. Write the lead to the DB

            Console.WriteLine($"Lead received {request.FirstName} {request.Surname}");

            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Exemplo n.º 13
0
        public HttpResponseMessage Post(Lead request)
        {
            //TODO: 7. Write the lead to the DB
            var result = writeToDB(request);

            LeadResponse response = new LeadResponse()
            {
                LeadId       = result.Item1,
                IsDuplicate  = result.Item2,
                IsSuccessful = result.Item3,
                IsCapped     = result.Item4,
                Messages     = result.Item5.Split(';'),
            };

            Console.WriteLine($"Lead received {request.FirstName} {request.Surname}");

            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Exemplo n.º 14
0
        public LeadResponse GetLead(string id)
        {
            LeadResponse leadResponse = GetEntity <LeadResponse>(BitrixSettings.GET_LEAD, id);

            if (leadResponse.Lead != null)
            {
                if (leadResponse.Lead.CONTACT_ID != null && leadResponse.Lead.CONTACT_ID != "0")
                {
                    leadResponse.Lead.Contact = GetContact(leadResponse.Lead.CONTACT_ID);
                }
                if (leadResponse.Lead.ASSIGNED_BY_ID != null && leadResponse.Lead.ASSIGNED_BY_ID != "0")
                {
                    leadResponse.Lead.AssignUser = GetUser(leadResponse.Lead.ASSIGNED_BY_ID);
                }
                leadResponse.Lead.TimeLine = GetTimeLine(id, "lead");
            }
            return(leadResponse);
        }
Exemplo n.º 15
0
        /// <summary>
        /// It Fetches Leads Information from the Database
        /// </summary>
        /// <returns>If Data Found return Response Data else null or Exception</returns>
        public List <LeadBuddyResponse> ListOfLeads()
        {
            try
            {
                List <LeadBuddyResponse> leadBuddyList = null;
                List <LeadResponse>      leadsList     = null;
                List <BuddyResponse>     buddyList     = null;
                using (SqlConnection conn = new SqlConnection(sqlConnectionString))
                {
                    leadsList = new List <LeadResponse>();
                    buddyList = new List <BuddyResponse>();
                    SqlCommand cmd = new SqlCommand("spGetAllLeads", conn);
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;

                    conn.Open();
                    SqlDataReader dataReader = cmd.ExecuteReader();
                    while (dataReader.Read())
                    {
                        LeadResponse responseData = new LeadResponse()
                        {
                            ID    = Convert.ToInt32(dataReader["MentorID"]),
                            Name  = dataReader["Name"].ToString(),
                            Buddy = buddyList
                        };
                        buddyList          = GetBuddiesUnderALead(responseData.ID);
                        responseData.Buddy = buddyList;
                        leadsList.Add(responseData);
                    }
                    conn.Close();
                    LeadBuddyResponse leadBuddyResponse = new LeadBuddyResponse
                    {
                        Leads = leadsList
                    };
                    leadBuddyList = new List <LeadBuddyResponse>();
                    leadBuddyList.Add(leadBuddyResponse);
                }
                return(leadBuddyList);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 16
0
        public static LeadResponse ToLeadResponse(this Jobs jobs)
        {
            var result = new LeadResponse
            {
                Id              = jobs.Id,
                ContactName     = jobs.ContactName,
                CreatedDateTime = jobs.CreatedAt.DateTime,
                Suburb          = jobs.Suburb.Name,
                CategoryName    = jobs.Category.Name,
                Description     = jobs.Description,
                Price           = jobs.Price.ToString(),
                ContactEmail    = jobs.ContactEmail,
                ContactNumber   = jobs.ContactPhone,
                Postcode        = jobs.Suburb.Postcode,
                Status          = jobs.Status
            };

            return(result);
        }
Exemplo n.º 17
0
        private void UpdateLead(LeadResponse response, Lead request)
        {
            string query = "UPDATE dbo.Lead SET IsDuplicate = @IsDuplicate, IsSuccessful = @IsSuccessful " +
                           "WHERE  Email = @Email AND ContactNumber = @ContactNumber";

            // create connection and command
            using (SqlConnection cn = new SqlConnection(_connectionString))
                using (SqlCommand cmd = new SqlCommand(query, cn))
                {
                    // define parameters and their values
                    cmd.Parameters.Add("@IsDuplicate", SqlDbType.Bit).Value            = response.IsDuplicate;
                    cmd.Parameters.Add("@IsSuccessful", SqlDbType.Bit).Value           = response.IsSuccessful;
                    cmd.Parameters.Add("@Email", SqlDbType.VarChar, 255).Value         = request.EmailAddress;
                    cmd.Parameters.Add("@ContactNumber", SqlDbType.VarChar, 255).Value = request.ContactNumber;

                    // open connection, execute INSERT, close connection
                    cn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                }
        }
Exemplo n.º 18
0
 internal LeadResponse CreateLead(IOrganizationService orgService, ILog logger, LeadRequest leadInfo)
 {
     try
     {
         logger.Info("Create Lead started");
         LeadResponse response = new LeadResponse();
         Entity       lead     = new Entity("lead");
         if (!string.IsNullOrEmpty(leadInfo.subject))
         {
             lead.Attributes["subject"] = leadInfo.subject;
         }
         if (!string.IsNullOrEmpty(leadInfo.firstName))
         {
             lead.Attributes["firstname"] = leadInfo.firstName;
         }
         if (!string.IsNullOrEmpty(leadInfo.lastName))
         {
             lead.Attributes["lastname"] = leadInfo.lastName;
         }
         if (!string.IsNullOrEmpty(leadInfo.jobTitle))
         {
             lead.Attributes["jobtitle"] = leadInfo.jobTitle;
         }
         if (!string.IsNullOrEmpty(leadInfo.emailAddress))
         {
             lead.Attributes["emailaddress1"] = leadInfo.emailAddress;
         }
         Guid leadId = orgService.Create(lead);
         response.leadId  = leadId.ToString();
         response.message = "Lead sucessfully created";
         logger.Info("Lead Sucessfully created in CRM");
         return(response);
     }
     catch (Exception ex)
     {
         logger.Error(ex.InnerException.ToString());
         throw new Exception(ex.InnerException.ToString());
     }
 }
Exemplo n.º 19
0
        private void SetFieldFromCustomField(DataFor1C dataFor1C, LeadResponse item)
        {
            foreach (var custom_field in item.custom_fields)
            {
                var    vals  = custom_field.values;
                string value = vals != null && vals.Any() ? vals[0]?.value : null;

                switch (custom_field.name)
                {
                case "Адрес объекта": dataFor1C.address = value; break;

                case "Объем работ (м2)": dataFor1C.scopeOfWork = value; break;

                case "Толщина (мм)": dataFor1C.thickness = value; break;

                case "Этаж клиента": dataFor1C.floor = value; break;

                case "Доплата": dataFor1C.basicPayment = value; break;

                case "Предоплата": dataFor1C.prepayment = value; break;

                case "Площадка": dataFor1C.districtName = value; break;

                case "Бюджет": dataFor1C.budget = value; break;

                case "Дом": dataFor1C.house = value; break;

                case "Подъезд": dataFor1C.doorNumber = value; break;

                case "Количество комнат": dataFor1C.numberOfRooms = value; break;

                case "Корпус": dataFor1C.houseBlock = value; break;

                case "Тип дома": dataFor1C.typeOfHouse = value; break;

                case "Стоимость работ": dataFor1C.costOfWork = value; break;

                case "Стоимость материала": dataFor1C.costOfMaterials = value; break;

                case "ЖК": dataFor1C.housingCooperative = value; break;

                case "Номер квартиры": dataFor1C.apartment = value; break;

                case "Замерщики": dataFor1C.gauger1 = value; break;

                case "Прораб": dataFor1C.foreman = value; break;

                case "Дата начала работ": dataFor1C.createDate = value; break;

                case "Дата выдачи": dataFor1C.passportIssueDate = value; break;

                case "Кем выдан": dataFor1C.passportIssuedBy = value; break;

                case "Номер": dataFor1C.passportNumer = value; break;

                case "Адрес регистрации": dataFor1C.passportRegistrationAddress = value; break;

                case "Исполнители":
                {
                    var count = custom_field.values.Count();
                    foreach (var itemTeam in custom_field.values)
                    {
                        if (dataFor1C.team == "")
                        {
                            dataFor1C.team += itemTeam.value;
                        }
                        else
                        {
                            dataFor1C.team += "|" + itemTeam.value;
                        }
                    }
                    break;
                }

                case "Насос": dataFor1C.pump = value; break;

                case "Заказал материал": dataFor1C.personOrderedMaterial = value; break;

                case "план Демпферная лента м/п": dataFor1C.damperBeltPlan = value; break;

                case "план Песок м³": dataFor1C.sandPlan = value; break;

                case "план Цемент кг": dataFor1C.cementPlan = value; break;

                case "план Пленка м²": dataFor1C.membranePlan = value; break;

                case "план Фибрв кг.": dataFor1C.fiberglassPlan = value; break;

                case "Принял материал": dataFor1C.personAcceptedMaterial = value; break;

                case "факт Демпф лента м/п": dataFor1C.damperBeltFact = value; break;

                case "факт Песок м³": dataFor1C.sandFact = value; break;

                case "факт Цемент кг": dataFor1C.cementFact = value; break;

                case "факт Пленка м²": dataFor1C.membraneFact = value; break;

                case "факт Фибров кг.": dataFor1C.fiberglassFact = value; break;
                }
            }
        }
 public void DeleteIfExist(LeadResponse lead)
 {
     DeleteAllRecords("Заявки", $"Lead_ID='{lead.Lead.ID}'");
 }
Exemplo n.º 21
0
        private void FillDataFromContacts(GetDataFromAmoCRM getDataFromAmoCRM, DataFor1C dataFor1C, LeadResponse item)
        {
            var contacts = getDataFromAmoCRM.GetContacts(item.main_contact_id, item.linked_company_id);

            if (contacts != null && contacts.Count() > 0)
            {
                dataFor1C.nameContact1 = contacts[0].name;
                dataFor1C.codeContact  = contacts[0].id.ToString();
                if (contacts.Count() >= 1)
                {
                    foreach (var custom_field in contacts[0].custom_fields)
                    {
                        switch (custom_field.name)
                        {
                        case "Телефон":
                            foreach (var phone in custom_field.values)
                            {
                                if (dataFor1C.phonesContact1 == "")
                                {
                                    dataFor1C.phonesContact1 += phone.value;
                                }
                                else
                                {
                                    dataFor1C.phonesContact1 += "|" + phone.value;
                                }
                            }
                            break;

                        case "Email":
                            dataFor1C.email = custom_field.values[0].value; break;
                        }
                    }
                }
            }
            else
            {
                Log.WriteInfo("not found contact for " + item.name);
            }

            var leadsAndContacts = getDataFromAmoCRM.GetLeadsAndContacts(item.id);

            foreach (var itemLinks in leadsAndContacts)
            {
                if (itemLinks.contact_id == item.main_contact_id.ToString())
                {
                    continue;
                }

                var contacts2 = getDataFromAmoCRM.GetContacts(itemLinks.contact_id, "");

                dataFor1C.nameContact2 = contacts2[0].name;
                foreach (var custom_field in contacts2[0].custom_fields)
                {
                    switch (custom_field.name)
                    {
                    case "Телефон":
                        foreach (var phone in custom_field.values)
                        {
                            if (phone.value == "")
                            {
                                continue;
                            }

                            if (dataFor1C.phonesContact2 == "")
                            {
                                dataFor1C.phonesContact2 += phone.value;
                            }
                            else
                            {
                                dataFor1C.phonesContact2 += "|" + phone.value;
                            }
                        }
                        break;
                    }
                }
            }
        }