Exemple #1
0
        public Price GetPrice()
        {
            var currentPromo = PromoCodes.Find(pc => pc.PromoEnd > DateTime.Now);
            var promoPrice   = currentPromo != null ? price * (100 - currentPromo.Percentage) / 100: (decimal?)null;

            return(Price.Create(price, promoPrice));
        }
Exemple #2
0
        public void Test01()
        {
            var sw    = Stopwatch.StartNew();
            var codes = PromoCodes.Generate().Take(1000).ToList();

            sw.Stop();
            var time = sw.ElapsedMilliseconds;

            Assert.AreEqual(1000, codes.Count);

            foreach (var code in codes)
            {
                var numbersArray = code.Select(x => int.Parse(x.ToString())).ToList();
                Assert.AreEqual(9, numbersArray.Count);

                var hasAnyLetterMoreOccurrencesThan2 = numbersArray
                                                       .GroupBy(letter => letter, (letter, list) => new { Count = list.Count() })
                                                       .Any(result => result.Count > 2);
                Assert.IsFalse(hasAnyLetterMoreOccurrencesThan2);

                var index = 9;
                var sum   = numbersArray.Aggregate(0, (a, b) => a + b * index--);
                Assert.AreEqual(sum % 11, 0);
            }
        }
        public async Task <int> AddPromocodesAsync(int promocodeCount, int promoCodeValue)
        {
            if (promocodeCount == 0)
            {
                return((int)StatusCode.ExpectationFailed);
            }

            for (int i = 0; i < promocodeCount; i++)
            {
                var chars  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*$!";
                var random = new Random();
                var result = new string(
                    Enumerable.Repeat(chars, 8)
                    .Select(s => s[random.Next(s.Length)])
                    .ToArray());

                PromoCodes proCode = new PromoCodes();
                proCode.PromoCodeId     = Guid.NewGuid();
                proCode.PromoCodePoints = promoCodeValue;
                proCode.PromoCode       = result;

                await _promoCodesRepository.AddAsync(proCode);

                await _promoCodesRepository.Uow.SaveChangesAsync();
            }
            return((int)StatusCode.SuccessfulStatusCode);
        }
Exemple #4
0
        public async Task <IActionResult> PostPromoCodes([FromBody] PromoCodes promoCodes)
        {
            _context.PromoCodes.Add(promoCodes);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetPromoCodes", new { id = promoCodes.Id }, promoCodes));
        }
 private void LoadInfoAndShow(string code)
 {
     PromoCodes.Get(code, promoCode => {
         ShowFullInfoWithoutActions(promoCode);
     }, error => {
         _console.LogE(string.Format("Failed to get promo code: {0}", error.Message));
     });
 }
 public void ClaimPromoCode(string code)
 {
     PromoCodes.Claim(code, promoCode => {
         ShowFullInfoWithoutActions(promoCode);
     }, error => {
         _console.LogE(string.Format("Failed to claim promo code: {0}", error.Message));
     });
 }
Exemple #7
0
        public IActionResult ApplyPromoCode([FromBody] PromoCodes promocode)
        {
            List <PromoCodeList> promoCode = new List <PromoCodeList>();

            //string GetConnectionString = PromoCodeController.GetConnectionString();
            // string GetConnectionString = configuration.GetSection("ConnectionString").GetSection("DefaultConnection").Value;

            try
            {
                DataSet ds = Data.PromoCode.ApplyPromoCode(promocode).DataSet;

                string rowsAffected = ds.Tables[0].Rows[0]["Status"].ToString();

                if (rowsAffected == "Success")
                {
                    DataTable dt = ds.Tables[1];

                    if (dt.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            PromoCodeList promo = new PromoCodeList();
                            promo.PromocodeID    = (int)dt.Rows[i]["PromocodeID"];
                            promo.PromocodeText  = (dt.Rows[i]["PromocodeText"] == DBNull.Value ? "" : dt.Rows[i]["PromocodeText"].ToString());
                            promo.PromoType      = (dt.Rows[i]["PromoType"] == DBNull.Value ? "" : dt.Rows[i]["PromoType"].ToString());
                            promo.PromocodeValue = (dt.Rows[i]["PromocodeValue"] == DBNull.Value ? 0 : (decimal)dt.Rows[i]["PromocodeValue"]);
                            //promo.NumberofUsePerUser = (dt.Rows[i]["NumberofUsePerUser"] == DBNull.Value ? 0 : (int)dt.Rows[i]["NumberofUsePerUser"]);
                            promo.UserId     = (dt.Rows[i]["UserId"] == DBNull.Value ? 0 : (int)dt.Rows[i]["UserId"]);
                            promo.StartDate  = (dt.Rows[i]["StartDate"] == DBNull.Value ? "" : dt.Rows[i]["StartDate"].ToString());
                            promo.ExpiryDate = (dt.Rows[i]["ExpiryDate"] == DBNull.Value ? "" : dt.Rows[i]["ExpiryDate"].ToString());

                            promoCode.Add(promo);
                        }

                        return(StatusCode((int)HttpStatusCode.OK, promoCode));
                    }
                    else
                    {
                        return(StatusCode((int)HttpStatusCode.OK, new { }));
                    }
                }

                else
                {
                    return(StatusCode((int)HttpStatusCode.Forbidden, new { error = new { message = rowsAffected } }));
                }
            }

            catch (Exception e)
            {
                string SaveErrorLog = Data.Common.SaveErrorLog("ApplyPromoCode", e.Message);

                return(StatusCode((int)HttpStatusCode.InternalServerError, new { error = new { message = e.Message } }));
            }
        }
        /// <summary>
        /// Removes all quantities of a product in the shopping cart, clears all promocodes if no items remain
        /// </summary>
        /// <param name="product">The Product to remove</param>
        public void RemoveProduct(ProductBase product)
        {
            OrderDetail orderDetail = Order.OrderDetails.Find(p => p.Product.Id == product.Id);

            if (!(orderDetail == null))
            {
                Order.OrderDetails.Remove(orderDetail);
            }

            if (Order.OrderDetails.Count == 0)
            {
                PromoCodes.Clear();
            }
        }
        public async Task <IActionResult> CreatePromoCode(PromoCodes promoCode)
        {
            if (promoCode.EndDate.Value < promoCode.StartDate.Value || promoCode.EndDate.Value == promoCode.StartDate.Value)
            {
                return(RedirectToAction("PromoCodeFailure"));
            }
            else
            {
                _context.PromoCodes.Add(promoCode);
                await _context.SaveChangesAsync();

                return(RedirectToAction("PromoCodeAdded"));
            }
        }
Exemple #10
0
        public void AddPromoCode(PromoCode promoCode)
        {
            if (!PromoCodes.Any())
            {
                PromoCodes.Add(promoCode);
                return;
            }

            if (PromoCodes.Any(pc => pc.PromoEnd > DateTime.Now))
            {
                throw new ThereIsAlreadyActivePromoCodeException($"There is already active promo code until {promoCode.PromoEnd.ToShortDateString()}");
            }

            PromoCodes.Add(promoCode);
        }
 private void ShowMyPromoCode()
 {
     if (GetSocial.GetCurrentUser().PrivateProperties.ContainsKey(MyPromoCodeKey))
     {
         ShowPromoCode(GetSocial.GetCurrentUser().PrivateProperties[MyPromoCodeKey]);
     }
     else
     {
         PromoCodes.Create(PromoCodeContent.CreateRandomCode().AddProperty(MyPromoCodeKey, "true"), promoCode => {
             var userUpdate = new UserUpdate().AddPrivateProperty(MyPromoCodeKey, promoCode.Code);
             GetSocial.GetCurrentUser().UpdateDetails(userUpdate, ShowMyPromoCode,
                                                      error => _console.LogE(string.Format("Failed to set private property: {0}", error.Message), showImmediately: false));
         }, error => _console.LogE(string.Format("Failed to create promo code: {0}", error.Message), showImmediately: false));
     }
 }
        public async Task <bool> UpdatePromoCode(PromoCodeModel promoCodes)
        {
            PromoCodes code = new PromoCodes
            {
                Id            = promoCodes.Id,
                PromocodeName = promoCodes.PromocodeName,
                Code          = promoCodes.Code,
                Validity      = promoCodes.Validity,
                Discount      = promoCodes.Discount,
            };

            await _promoCodeRepository.UpdatePromoCode(code);

            return(true);
        }
    private void DrawCreatePromoCodeBody()
    {
        GUILayout.Label("Promo code(leave empty for random): ", GSStyles.NormalLabelText);
        _code = GUILayout.TextField(_code, GSStyles.TextField);

        GUILayout.Label("Max Claim Count(0 or empty for unlim): ", GSStyles.NormalLabelText);
        _maxClaimCount = GUILayout.TextField(_maxClaimCount, GSStyles.TextField);
        _maxClaimCount = Regex.Replace(_maxClaimCount, @"[^0-9]", "");

        GUILayout.Label("Start date('dd/MM/yyyy HH:mm:ss' or 'dd/MM/yyy'): ", GSStyles.NormalLabelText);
        _startDate = GUILayout.TextField(_startDate, GSStyles.TextField);

        GUILayout.Label("End date('dd/MM/yyyy HH:mm:ss' or 'dd/MM/yyy'): ", GSStyles.NormalLabelText);
        _endDate = GUILayout.TextField(_endDate, GSStyles.TextField);

        DemoGuiUtils.DynamicRowFor(_data, "Custom data");

        DemoGuiUtils.DrawButton("Create", () => {
            if (_loading)
            {
                return;
            }
            _loading      = true;
            var promoCode = (_code == null || _code.Length > 0 ? PromoCodeContent.CreateWithCode(_code) : PromoCodeContent.CreateRandomCode());
            promoCode.AddProperties(_data.ToDictionary(data => data.Key, data => data.Val));
            promoCode.MaxClaimCount = Convert.ToUInt32(_maxClaimCount);
            var startDate           = ParseDate(_startDate);
            var endDate             = ParseDate(_endDate);
            if (startDate.HasValue && endDate.HasValue)
            {
                Debug.LogFormat("{0} => {1}", startDate, endDate);
                promoCode.SetTimeLimit(startDate.Value, endDate.Value);
            }
            PromoCodes.Create(promoCode,
                              code => {
                _loading = false;
                ShowFullInfoWithoutActions(code);
            }, error => {
                _loading = false;
                _console.LogE(string.Format("Failed to create promo code: {0}", error.Message));
            }
                              );
        }, style: GSStyles.Button);

        DemoGuiUtils.DrawButton("Back", () => {
            _createPromoCode = false;
        }, style: GSStyles.Button);
    }
        public async Task <bool> CreatePromoCode(PromoCodeModel promoCodes, Guid id)
        {
            PromoCodes code = new PromoCodes
            {
                PromocodeName = promoCodes.PromocodeName,
                Code          = promoCodes.Code,
                Validity      = promoCodes.Validity,
                Discount      = promoCodes.Discount,
                CreatedBy     = id,
                UpdatedBy     = id
            };

            await _promoCodeRepository.CreatePromoCode(code);

            return(true);
        }
Exemple #15
0
 public static DataTable ApplyPromoCode(PromoCodes promocode)
 {
     try
     {
         string ConnectionString        = Common.GetConnectionString();
         List <SqlParameter> parameters = new List <SqlParameter>();
         parameters.Add(new SqlParameter("@PromocodeText", promocode.PromocodeText));
         parameters.Add(new SqlParameter("@UserId", promocode.UserId));
         //Execute the query
         using (DataTable dt = SqlHelper.ExecuteDataset(ConnectionString, CommandType.StoredProcedure, "spApplyPromoCode", parameters.ToArray()).Tables[0])
         {
             return(dt);
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        public async Task CreatePromoCode(PromoCodes promoCodes)
        {
            using IDbConnection _connection = new SqlConnection(_connectionString);
            _connection.Open();

            var procedure = "uspPromoCode_Add";

            var reader = await _connection.ExecuteAsync(
                procedure,
                new
            {
                promoCodes.PromocodeName,
                promoCodes.Code,
                promoCodes.Validity,
                promoCodes.Discount,
                promoCodes.CreatedBy
            },
                commandType : CommandType.StoredProcedure,
                commandTimeout : 10);
        }
Exemple #17
0
        public async Task <IActionResult> PutPromoCodes([FromRoute] int id, [FromBody] PromoCodes promoCodes)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != promoCodes.Id)
            {
                return(BadRequest());
            }

            _context.Entry(promoCodes).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PromoCodesExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            var response = new GenericResponse()
            {
                Data           = promoCodes,
                Success        = true,
                HttpStatusCode = HttpStatusCode.OK,
                Message        = MessagesConstants.PromoCodeUpdate
            };

            return(Ok(response));
        }
        public async Task <HttpResponseMessage> DeletePromoCode(Guid id)
        {
            PromoCodes promoCode = _context.PromoCodes.Find(id);

            if (promoCode != null)
            {
                _context.PromoCodes.Remove(promoCode);
            }
            int changes = await _context.SaveChangesAsync();

            var response = new HttpResponseMessage();

            if (changes > 0)
            {
                response.StatusCode   = HttpStatusCode.OK;
                response.ReasonPhrase = "OK";
            }
            else
            {
                response.StatusCode   = HttpStatusCode.BadRequest;
                response.ReasonPhrase = "Bad Request";
            }
            return(response);
        }
Exemple #19
0
        public void Test00()
        {
            var sum = PromoCodes.GetPromoCodeFormulaSum(new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });

            Assert.AreEqual(165, sum);
        }
        /// <summary>
        /// Adds and processes a promo code
        /// </summary>
        /// <param name="promoCode"></param>
        public void AddPromoCode(PromoCode promoCode)
        {
            // check constraints
            if (PromoCodes.Exists(p => p.Code == promoCode.Code))
            {
                throw new Exception("Cannot enter same promo code twice!");
            }

            if (promoCode.SpecialPriceItem != null && !Order.OrderDetails.Exists(o => o.ProductId == promoCode.SpecialPriceItem.Id))
            {
                throw new Exception("Must purchase special item to receive discount: " + promoCode.SpecialPriceItem.Name);
            }

            if (promoCode.WithPurchaseOf != null && !Order.OrderDetails.Exists(o => o.ProductId == promoCode.WithPurchaseOf.Id))
            {
                throw new Exception("Must purchase qualifying item: " + promoCode.WithPurchaseOf.Name);
            }

            if (promoCode.MinimumQualifyingPurchase != null && TotalExtendedPrice < promoCode.MinimumQualifyingPurchase)
            {
                throw new Exception("Must have a minimum purchase of $" + promoCode.MinimumQualifyingPurchase.ToString());
            }

            if (promoCode.CodeStart != null && DateTime.Now < promoCode.CodeStart)
            {
                DateTime codeStart = (DateTime)promoCode.CodeStart;
                throw new Exception("Code is not valid until " + codeStart.ToShortDateString());
            }

            if (promoCode.CodeEnd != null && DateTime.Now > promoCode.CodeEnd)
            {
                throw new Exception("Code is expired!");
            }

            // Apply promotions
            if (promoCode.PromotionalItem != null)
            {
                Order.OrderDetails.Add(new OrderDetail()
                {
                    Product           = promoCode.PromotionalItem,
                    UnitPrice         = promoCode.PromotionalItemPrice ?? 0,
                    Quantity          = 1,
                    IsPromotionalItem = true,
                    PlacedInCart      = DateTime.Now,
                    Shipping          = 0
                });
            }

            // special price may be zero; only apply if a percentage is not given
            if ((promoCode.PercentOffItem == null || promoCode.PercentOffItem == 0) && promoCode.SpecialPriceItem != null)
            {
                OrderDetail item = Order.OrderDetails.Find(o => o.Product.Id == promoCode.SpecialPriceItem.Id);
                item.UnitPrice = promoCode.SpecialPrice ?? 0;
            }

            // percent off item
            if (promoCode.PercentOffItem != null && promoCode.PercentOffItem > 0 && promoCode.SpecialPriceItem != null)
            {
                OrderDetail item = Order.OrderDetails.Find(o => o.Product.Id == promoCode.SpecialPriceItem.Id);
                item.UnitPrice = PercentOff(item.UnitPrice, promoCode.PercentOffItem ?? 0);
            }

            // percent off order
            if (promoCode.PercentOffOrder != null && promoCode.PercentOffOrder > 0)
            {
                for (int i = 0; i < Order.OrderDetails.Count; i++)
                {
                    OrderDetail item = Order.OrderDetails[i];
                    item.UnitPrice = PercentOff(item.UnitPrice, promoCode.PercentOffOrder ?? 0);
                }
            }

            // Add promocode to list
            PromoCodes.Add(promoCode);
        }