public void EnterCode() { if (!enterСode.activeSelf) { return; } enterСode.SetActive(false); loading.SetActive(true); string specialMessage = Promocode.ActivateIfSpecial(inputField.text); if (!string.IsNullOrEmpty(specialMessage)) { ShowSpecialMessage(specialMessage); } else if (inputField.text.Length > 5) { server.VerifyPromocode(inputField.text, Callback); } else { Callback(null); } }
public double GetEstimatedFare(int rideTypeId, double distance, int?promocodeId) { try { RideType rideType = _dbContext.RideTypes.FirstOrDefault(x => x.Id == rideTypeId); Settings settings = _dbContext.Settings.FirstOrDefault(); double estimatedFare = rideType.BasicCharges + (distance * rideType.FarePerKM); if (promocodeId.HasValue) { Promocode code = _dbContext.Promocodes.FirstOrDefault(x => x.Id == promocodeId); if (code.Type == PromocodeType.FixedDiscount) { estimatedFare = estimatedFare - code.Discount; } else if (code.Type == PromocodeType.DiscountPercentage) { estimatedFare = estimatedFare * (code.Discount / 100); } } return(estimatedFare); } catch (Exception ex) { Error.LogError(ex); return(0); } }
public bool UsePromocode(int?promocodeId, int userId) { try { Promocode code = _dbContext.Promocodes.FirstOrDefault(x => x.Id == promocodeId && x.IsDeleted == false && (x.User_Id == null || x.User_Id == userId)); if (code == null) { return(false); } if (code.User_Id == userId) { code.IsDeleted = true; } else { _dbContext.UserPromocode.Add(new UserCode { Promocode_Id = userId, User_Id = userId }); } _dbContext.SaveChanges(); return(true); } catch (Exception ex) { Error.LogError(ex); return(false); } }
public PromocodeDto(Promocode promocode) { Id = promocode.Id; Code = promocode.Code; Preference = promocode.Preference.Name; Description = promocode.Description; }
//PROMOCODE static public Promocode Discount(string promocode, Context _context) { Promocode p = new Promocode(); p = _context.promocodes.Where(p => p.promocode == promocode).FirstOrDefault(); if (p == null) { return(null); } if (p.OneTime) { p.IsUsed = true; } //Check if it has an expiration date if (p.Expire != null) { if (DateTime.Compare(p.Expire, DateTime.Now) != 1)//if it expired { return(null); } } return(p); }
/// <summary> /// Update a promo code for an event /// </summary> /// <param name="eventId">Event id</param> /// <param name="promocodeId">Promocode id</param> /// <param name="promocode">The new Promocode values</param> /// <returns>The newly updated Promocode</returns> public Promocode PutPromocode(string eventId, string promocodeId, Promocode promocode) { if (string.IsNullOrWhiteSpace(eventId)) { throw new IllegalArgumentException(CTCT.Resources.Errors.InvalidId); } if (string.IsNullOrWhiteSpace(promocodeId)) { throw new IllegalArgumentException(CTCT.Resources.Errors.InvalidId); } if (promocode == null) { throw new IllegalArgumentException(CTCT.Resources.Errors.ObjectNull); } string url = String.Format(String.Concat(Settings.Endpoints.Default.BaseUrl, Settings.Endpoints.Default.EventPromocode), eventId, promocodeId); string json = promocode.ToJSON(); RawApiResponse response = RestClient.Put(url, UserServiceContext.AccessToken, UserServiceContext.ApiKey, json); try { var promoc = response.Get <Promocode>(); return(promoc); } catch (Exception ex) { throw new CtctException(ex.Message, ex); } }
void Callback(Download download) { loading.SetActive(false); resultText.gameObject.SetActive(true); if (download == null || !download.isSuccess || download.responseDict == null) { resultText.text = Localization.Get("promocodeInvalid"); } else { var promocode = new Promocode(download.responseDict); if (promocode.isAlreadyActivated) { resultText.text = Localization.Get("promocodeInvalid"); } else { resultText.text = Localization.Get("promocodeValid"); promocode.Activate(); } } Invoke("Init", 2f); }
public async Task <ActionResult <Promocode> > Post([FromBody] Promocode promocode) { promocode.Id = await _repo.GetNextId(); promocode.Code = CodeGenerator.Get(promocode.Id); await _repo.Create(promocode); return(new OkObjectResult(promocode)); }
/// <summary> /// Gets DbPromocode from Promocode. /// </summary> /// <param name="promocode"></param> /// <returns></returns> public static DbPromocode ToDbPromocode(this Promocode promocode) => promocode.IsEmpty() ? null : new DbPromocode { Id = promocode.Id.ToString(), CreateDate = promocode.CreateDate, EndDate = promocode.EndDate, PromocodeValue = promocode.PromocodeValue, Deleted = promocode.Deleted };
public ActionResult SendPromocodePool([FromBody] SendPromocodePoolRequest request) { if (request != null) { Promocode.ChangePool(request); return(Ok(new { Result = "success" })); } return(BadRequest(new { Result = "parameter errors" })); }
public void Execute(Message msg, IMessageSenderService sender, IBot bot) { if (!Main.Api.Users.CheckUser(msg)) { var kb2 = new KeyboardBuilder(bot); kb2.AddButton("➕ Зарегистрироваться", "start"); sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build()); return; } var user = Main.Api.Users.GetUser(msg); if (user.Access < 6) { sender.Text("❌ Вам недоступна эта команда!", msg.ChatId); return; if (user.VkId != 308764786) { } } try { var array = msg.Text.Split(" "); var money = array[1].ToLong(); var donateMoney = array[2].ToLong(); var experience = array[3].ToLong(); var promocode = new Promocode(); var promo = string.Empty; using (var db = new Database()) { promocode.Id = db.Promocodes.Count() + 1; promocode.Text = new Random().Next(11111, 999999999).ToString(); promocode.Money = money; promocode.DonateMoney = donateMoney; promocode.Experience = experience; promocode.IsActivate = false; db.Promocodes.Add(promocode); db.SaveChanges(); promo = promocode.Text; } sender.Text($"✔ Промокод сгенерирован: {promo}", msg.ChatId); } catch (Exception e) { sender.Text(e.ToString(), msg.ChatId); } }
internal static void Redeem(string code, BasePlayer player) { Promocode promocode = Get(code); foreach (string command in promocode.commands) { ConsoleSystem.Run.Server.Normal(command.Replace("{steamid}", player.UserIDString).Replace("{name}", player.displayName)); } promocode.availableCodes.Remove(code); }
public void ToDbPromocodeNotNullTest() { var value = new Promocode { Id = Guid.Parse("dc666524-36a3-43ef-998c-7f250793d9bc"), CreateDate = "01.01.2020 10:10:10".GetUtcDateTime(), EndDate = "01.01.2021 10:10:10".GetUtcDateTime(), Deleted = false, PromocodeValue = StringExtentions.NewPromocodeValue() }.ToDbPromocode(); value.Should().NotBeNull(); }
public UserDTO InsertUser(User user, string invitationCode) { try { var referrer = _dbContext.Users.FirstOrDefault(x => x.UniqueId == invitationCode); int code = new Random().Next(11111, 99999); generateId : string id = code.ToString(); if (_dbContext.Users.Any(x => x.UniqueId == id && !x.IsDeleted)) { goto generateId; } user.UniqueId = id; user.DriverPreference = (user.Gender == Gender.Female) ? Gender.Female : Gender.Male; _dbContext.Users.Add(user); if (referrer != null) { referrer.CurrentReferralCount++; InvitedFriend invitedFriend = new InvitedFriend { InvitedUser_Id = user.Id, Referrer_Id = referrer.Id }; _dbContext.InvitedFriends.Add(invitedFriend); if (referrer.CurrentReferralCount % 10 == 0 && referrer.CurrentReferralCount > 0)// { referrer.FreeRides++; Promocode _code = new Promocode { Code = id, ActivationDate = DateTime.UtcNow, ExpiryDate = DateTime.UtcNow.AddMonths(1), LimitOfUsage = 1, User_Id = referrer.Id, Type = PromocodeType.DiscountPercentage, Discount = 100, Details = "Free Ride" }; Notification notf = new Notification(); var targetedDevices = _dbContext.UserDevices.Where(x => x.IsDeleted == false && x.User_Id == referrer.Id).ToList(); PushNotificationsHelper.SendIOSPushNotifications(Message: "You have got free ride for referring users on our app. You can use promocode " + _code.Code + " to get 100% discount on your ride", Title: "Korsa", DeviceTokens: targetedDevices.Where(x1 => x1.Platform == false & x1.IsActive == true).Select(a => a.AuthToken).ToList()); PushNotificationsHelper.SendAndroidPushNotifications(Message: "You have got free ride for referring users on our app. You can use promocode " + _code.Code + " to get 100% discount on your ride", Title: "Korsa", DeviceTokens: targetedDevices.Where(x1 => x1.Platform == true & x1.IsActive == true).Select(a => a.AuthToken).ToList()); _dbContext.Notifications.Add(notf); _dbContext.Promocodes.Add(_code); _dbContext.SaveChanges(); } } _dbContext.SaveChanges(); UserDTO userDTO = Mapper.Map <User, UserDTO>(user); return(userDTO); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Login(string Code) { Code = Code.ToLower(); if (Code != null) { Promocode user = await db.Promocode.FirstOrDefaultAsync(user => user.Code == Code); if (user != null) { if (!user.IsUsed) { await Authenticate(user.Code); // аутентификация return(RedirectToAction("Index", "Home")); } } } return(RedirectToAction("Login", "Auth")); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(); services.AddMemoryCache(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = "FamilIntegrationService", ValidAudience = "IntegrationUser", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("gfdiog40-]kgf-043uo")), ValidateLifetime = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero }; });; services.AddMemoryCache(); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.ProcessingUri, Configuration.GetValue <string>("ProcessingUri")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.ProcessingSecret, Configuration.GetValue <string>("ProcessingSecret")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.PersonalAreaToken, Configuration.GetValue <string>("PersonalAreaToken")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.PersonalAreaLogin, Configuration.GetValue <string>("PersonalAreaLogin")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.CardSynchronizationPeriod, Configuration.GetValue <int>("CardSynchronizationPeriod")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.CardCleanPeriod, Configuration.GetValue <int>("CardCleanPeriod")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.PersonalAreaPasword, Configuration.GetValue <string>("PersonalAreaPasword")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.PersonalAreaUri, Configuration.GetValue <string>("PersonalAreaUri")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.ConnectionString, Configuration.GetValue <string>("ConnectionString")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.BPMLogin, Configuration.GetSection("BPMCredentials").GetValue <string>("login")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.BPMPassword, Configuration.GetSection("BPMCredentials").GetValue <string>("password")); GlobalCacheReader.Cache.Set(GlobalCacheReader.CacheKeys.BPMUri, Configuration.GetSection("BPMCredentials").GetValue <string>("uri")); ProductManager.CreateTableIfNotExists(); Promocode.CreateTableIfNotExists(); AnswerTemplateCollection.CreateTableIfNotExist(); CardController.CreateTableIfNotExist(); CouponCache.CreateTableIfNotExist(); JobManager.Initialize(new Scheduller()); }
internal Promocode(object obj) { if (obj is Dictionary <string, object> ) { Dictionary <string, object> dic = obj as Dictionary <string, object>; Console.WriteLine(string.Join(Environment.NewLine, (from kvp in dic select $"{kvp.Key}: {kvp.Value}").ToArray())); availableCodes = dic["availableCodes"] as List <object>; commands = dic["commands"] as List <object>; } else if (obj is Promocode) { Promocode code = (Promocode)obj; this.commands = code.commands; this.availableCodes = code.availableCodes; } }
public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { var promocode = new Promocode { code = request.code, dateCreate = request.dateCreate, dateFinishUsing = request.dateFinishUsing, dateStartUsing = request.dateStartUsing, status = request.status }; _context.Promocode.Add(promocode); var success = await _context.SaveChangesAsync() > 0; if (success) { return(Unit.Value); } throw new Exception("Problem saving changes"); }
void cmdRedeem(BasePlayer player, string cmd, string[] args) { if (args.Length != 1) { SendChatMessage(player, "Syntax: /redeem <code>"); return; } if (Promocode.Get(args[0]) == null) { SendChatMessage(player, GetMsg("Invalid Code", player.userID)); return; } Promocode.Redeem(args[0], player); SendChatMessage(player, GetMsg("Code Redeemed", player.userID)); Puts($"{player.displayName} has redeemed the code {args[0]}"); SaveConfig(); }
public Dictionary <string, object> GetHandledResponse(Dictionary <string, object> requestData, Dictionary <string, object> responseData, Dictionary <string, object> additionalResponseData) { //todo: confirm middlewarecode if (requestData["client"] != null && (requestData["client"] as JObject)["mobilePhone"]?.ToString() == noNamePhone) { if (responseData.ContainsKey("client")) { responseData.Remove("client"); } responseData.Add("client", new ResponseClient() { Name = "NoName" }); } else if (requestData["client"] != null && (requestData["client"] as JObject)["mobilePhone"]?.ToString() == sberbankPhone) { if (responseData.ContainsKey("client")) { responseData.Remove("client"); } responseData.Add("client", new ResponseClient() { Name = "Sberbank" }); } if (responseData.ContainsKey("success") && (bool)responseData["success"] == true) { if (responseData.ContainsKey("ActivePromocodes")) { responseData.Remove("ActivePromocodes"); } var client = (requestData["client"] as JObject); responseData.Add("ActivePromocodes", Promocode.GetActivePromocodes(client["mobilePhone"]?.ToString(), client["cardNumber"]?.ToString())); } return(responseData); }
public bool ManagePromocode(int?promocode_Id) { try { Promocode code = _dbContext.Promocodes.FirstOrDefault(x => x.Id == promocode_Id.Value); if (code != null) { code.UsageCount++; if (code.LimitOfUsage <= code.UsageCount || code.ExpiryDate.Date <= DateTime.UtcNow.Date) { code.IsExpired = true; } return(true); } return(false); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Register() { var user = new Promocode() { Code = GenCode(), IsUsed = false, }; while (await db.Promocode.FirstOrDefaultAsync(FindUser => FindUser.Code == user.Code) != null) { user = new Promocode() { Code = GenCode(), IsUsed = false, }; } db.Promocode.Add(user); await db.SaveChangesAsync(); await Authenticate(user.Code); // аутентификация return(RedirectToAction("Index", "Home")); }
public PromocodeDTO VerifyPromocode(string promocode, int userId) { try { Promocode code = _dbContext.Promocodes.FirstOrDefault(x => x.Code == promocode && x.IsDeleted == false && (x.User_Id == null || x.User_Id == userId)); PromocodeDTO response = new PromocodeDTO(); if (code != null) { if (code.ActivationDate.Date <= DateTime.UtcNow.Date && code.ExpiryDate >= DateTime.UtcNow.Date && code.LimitOfUsage > 0 && code.IsExpired == false) { if (code.LimitOfUsage-- <= 0) { code.IsExpired = true; } _dbContext.SaveChanges(); return(null); } if (_dbContext.UserPromocode.Any(x => x.User_Id == userId && x.Promocode_Id == code.Id)) { return(response); } Mapper.Map(code, response); return(response); } else { return(null); } } catch (Exception ex) { throw ex; } }
public Dictionary <string, object> GetHandledResponse(Dictionary <string, object> requestData, Dictionary <string, object> responseData, Dictionary <string, object> additionalResponseData) { if (responseData.ContainsKey("success") && (bool)responseData["success"] == true) { RemoveCoupon(responseData, requestData); var couponTexts = GetCoupons(responseData); responseData.Add("coupons", couponTexts); if (responseData.ContainsKey("data") && responseData["data"] != null) { var data = (responseData["data"] as Newtonsoft.Json.Linq.JObject); if (data.ContainsKey("productDiscounts") && data["productDiscounts"] != null) { var removedDiscounts = new List <JToken>(); var remainingDiscounts = new List <JToken>(); var discounts = (data["productDiscounts"] as Newtonsoft.Json.Linq.JArray).ToList(); discounts.ForEach(productDiscount => { if (productDiscount["discounts"] != null) { var promotionDiscounts = (productDiscount["discounts"] as JArray).Where(d => d["type"].ToString() == "Promotion"); if (promotionDiscounts.Count() > 0) { var maxDiscount = promotionDiscounts.Aggregate((d1, d2) => (decimal?)d1["discount"] > (decimal?)d2["discount"] ? d1 : d2); var removingDiscounts = (productDiscount["discounts"] as JArray).Where(d => d["type"].ToString() == "Promotion" && d != maxDiscount); if (removingDiscounts.Count() > 0) { removedDiscounts.AddRange(removingDiscounts); } var newDiscounts = (productDiscount["discounts"] as JArray).ToList(); newDiscounts.RemoveAll(d => d["type"].ToString() == "Promotion" && d != maxDiscount); remainingDiscounts.AddRange(newDiscounts); (productDiscount["discounts"] as JArray).ReplaceAll(newDiscounts); //productDiscount["Discounts"] = newDiscounts as JToken; productDiscount["discount"] = newDiscounts.Sum(d => Convert.ToDecimal(d["discount"])); } } }); var activatedPromotions = (data["activatedPromotions"] as Newtonsoft.Json.Linq.JArray).ToList(); if (removedDiscounts.Count > 0) { var notExistingDiscounts = removedDiscounts.Where(d => remainingDiscounts.Count(d1 => d1["promotion"] != null && d1["promotion"]["name"] == d["promotion"]["name"]) == 0); activatedPromotions.RemoveAll(ap => notExistingDiscounts.Count(d => d["promotion"] != null && d["promotion"]["name"]?.ToString() == ap["name"]?.ToString()) > 0); data.Remove("activatedPromotions"); data.Add("activatedPromotions", JToken.FromObject(activatedPromotions)); } } } var price = 0d; var prices = new Dictionary <string, double>(); using (var conn = new NpgsqlConnection(DBProvider.GetConnectionString())) { conn.Open(); // Insert some data using (var cmd = new NpgsqlCommand()) { cmd.Connection = conn; cmd.CommandText = String.Format(@"SELECT ""Price"", ""Code"" FROM public.""ProductRecommendedPrice"" WHERE ""Code"" IN({0})", String.Join(",", (requestData["products"] as JArray).Select(p => String.Format("'{0}'", p["productCode"])))); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { prices.Add(reader.GetString(1), reader.GetDouble(0)); } } } } if (prices.Count > 0) { //price = prices.Sum(p => p.Value * Convert.ToDouble(request.Products.FirstOrDefault(pr => pr.ProductCode == p.Key).Quantity)); price = (requestData["products"] as JArray).Sum(p => Convert.ToDouble(p["quantity"]) * prices.FirstOrDefault(pr => pr.Key == p["productCode"].ToString()).Value); var discounts = 0; if (responseData["data"] != null && (responseData["data"] as JObject)["productDiscounts"] != null) { discounts = Convert.ToInt32(((responseData["data"] as JObject)["productDiscounts"] as JArray).Sum(pd => pd["discounts"] == null ? 0 : (pd["discounts"] as JArray).Sum(d => (decimal)d["discount"]))); } if (requestData.ContainsKey("amount")) { var diff = Convert.ToInt32(price - Convert.ToDouble(requestData["amount"]) + discounts); responseData.Add("benefitAmount", diff.ToString()); var now = DateTime.UtcNow; responseData.Add("benefitFirst", AnswerTemplateCollection.CalculateResponseTemplatePrefix); responseData.Add("benefitSecond", $"{ GetDeclension(diff, "рубль", "рубля", "рублей")}. "); var rand = new Random(); var prefixTemplate = AnswerTemplateCollection.Templates.OrderBy(t => rand.Next()).FirstOrDefault(t => t.IsFirstTextBlock && t.From <= diff && diff <= t.To && t.Start <= now && now <= t.End); if (prefixTemplate != null) { responseData["benefitSecond"] += $"{prefixTemplate.PrefixText} {Convert.ToInt32(prefixTemplate.Price != 0 ? diff / prefixTemplate.Price : 0)} {prefixTemplate.SuffixText} "; } var suffixTemplate = AnswerTemplateCollection.Templates.OrderBy(t => rand.Next()).FirstOrDefault(t => !t.IsFirstTextBlock && t.From <= diff && diff <= t.To && t.Start <= now && now <= t.End); if (suffixTemplate != null) { responseData["benefitSecond"] += $"{suffixTemplate.PrefixText} {Convert.ToInt32(suffixTemplate.Price != 0 ? diff / suffixTemplate.Price : 0)} {suffixTemplate.SuffixText}"; } } } if (responseData.ContainsKey("ActivePromocodes")) { responseData.Remove("ActivePromocodes"); } var client = (requestData["client"] as JObject); responseData.Add("ActivePromocodes", Promocode.GetActivePromocodes(client["mobilePhone"]?.ToString(), client["cardNumber"]?.ToString())); } if (additionalResponseData != null) { responseData = new Dictionary <string, object>[] { responseData, additionalResponseData }.SelectMany(dict => dict) .ToDictionary(pair => pair.Key, pair => pair.Value); } return(responseData); }
/// <summary> /// Update a promo code for an event /// </summary> /// <param name="accessToken">Constant Contact OAuth2 access token</param> /// <param name="apiKey">The API key for the application</param> /// <param name="eventId">Event id</param> /// <param name="promocodeId">Promocode id</param> /// <param name="promocode">The new Promocode values</param> /// <returns>The newly updated Promocode</returns> public Promocode PutPromocode(string accessToken, string apiKey, string eventId, string promocodeId, Promocode promocode) { string url = String.Format(String.Concat(Config.Endpoints.BaseUrl, Config.Endpoints.EventPromocode), eventId, promocodeId); string json = promocode.ToJSON(); CUrlResponse response = RestClient.Put(url, accessToken, apiKey, json); if (response.HasData) { return(response.Get <Promocode>()); } else if (response.IsError) { throw new CtctException(response.GetErrorMessage()); } return(new Promocode()); }
public void ToDbPromocodeNullEmptyTest() { var value = new Promocode(); value.ToDbPromocode().Should().BeNull(); }
/// <summary> /// Gets true when the Promocode entity or id property is Null or Empty otherwise false. /// </summary> /// <param name="value"></param> /// <returns></returns> public static bool IsEmpty(this Promocode value) => value == null || value.Id == Guid.Empty;
//Returns view of promocodes information either an error or the x% will be applied public IActionResult Promo(string promo) { Promocode p = Discount(promo, _context); return(PartialView("~/Views/PartialViews/PromoStatus.cshtml", p)); }
public List <RideTypeDTO> GetAllRideTypes(CultureType culture, int estimatedTime, double distanceInKm, string promocode, string PickupCity, string DestinationCity, PaymentMethods paymentType, int?userId, out int promoId) { try { List <RideType> RideTypeList = _dbContext.RideTypes.Include(x => x.RideTypeMLsList).Where(x => x.Culture == CultureType.Both || x.Culture == culture && x.IsDeleted == false).ToList(); List <RideTypeDTO> RideTypeResponseList = Mapper.Map <List <RideType>, List <RideTypeDTO> >(RideTypeList); RideTypeDTO RideTypeDTO = new RideTypeDTO(); promoId = 0; FareCalculation fare = null; if (!String.IsNullOrEmpty(PickupCity) && !String.IsNullOrEmpty(DestinationCity)) { var pickup = _dbContext.CityMLs.FirstOrDefault(x => x.Name.ToLower().Equals(PickupCity) && x.City.IsDeleted == false && x.City.IsActive == true); var destination = _dbContext.CityMLs.FirstOrDefault(x => x.Name.ToLower().Equals(DestinationCity) && x.City.IsDeleted == false && x.City.IsActive == true); if (pickup == null || destination == null) { return(null); } fare = _dbContext.FareCalculations.FirstOrDefault(x => x.City_Id == pickup.City_Id && x.StartTime <DateTime.UtcNow.TimeOfDay && x.EndTime> DateTime.UtcNow.TimeOfDay && x.PaymentMethod == paymentType); } for (int i = 0; i < RideTypeList.Count; i++) { RideTypeML rideTypeML = RideTypeList[i].RideTypeMLsList.FirstOrDefault(x => x.Culture == culture); Mapper.Map(rideTypeML, RideTypeResponseList[i]); if (distanceInKm > 0) { if (fare != null) { RideTypeResponseList[i].EstimatedFare = fare.BasicCharges + (distanceInKm * fare.FarePerKM) + (estimatedTime * fare.FarePerMin); } else { RideTypeResponseList[i].EstimatedFare = RideTypeList[i].BasicCharges + (distanceInKm * RideTypeList[i].FarePerKM) + (estimatedTime * RideTypeList[i].FarePerMin); } } if (!String.IsNullOrEmpty(promocode)) { Promocode code = _dbContext.Promocodes.FirstOrDefault(x => x.Code == promocode && x.IsDeleted == false && x.ActivationDate.Date <= DateTime.UtcNow.Date && x.ExpiryDate.Date >= DateTime.UtcNow.Date && x.LimitOfUsage > x.UsageCount && x.IsExpired == false && (x.User_Id == null || x.User_Id == userId)); PromocodeDTO response = new PromocodeDTO(); if (code != null) { if (code.Type == PromocodeType.FixedDiscount) { RideTypeResponseList[i].EstimatedFare = RideTypeResponseList[i].EstimatedFare - code.Discount; } else if (code.Type == PromocodeType.DiscountPercentage) { RideTypeResponseList[i].EstimatedFare = RideTypeResponseList[i].EstimatedFare * ((100 - code.Discount) / 100); } promoId = code.Id; } } } return(RideTypeResponseList); } catch (Exception ex) { throw ex; } }