Esempio n. 1
0
        public IHttpActionResult PutPromotionCode(int id, PromotionCode promotionCode)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != promotionCode.PromotionCodeId)
            {
                return(BadRequest());
            }

            db.Entry(promotionCode).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PromotionCodeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public void CreatesCommand()
        {
            var commandDto = BuildCreatePurchaseApplicationCommandDto();

            var result = CreatePurchaseApplicationCommand.Create(commandDto);

            result.IsSuccess.Should().BeTrue();
            result.IfSuccess(command =>
            {
                command.Products.Count.Should().Be(commandDto.Products.Count);
                var expectedLink = Link.Create(commandDto.Products.First().Link.ValueUnsafe()).IfFail(() => null);
                command.Products.First().Link.Should().Be(expectedLink);
                var expectedUnits = Units.Create(commandDto.Products.First().Units).IfFail(() => null);
                command.Products.First().Units.Should().Be(expectedUnits);
                var expectedAdditionalInformation = AdditionalInformation.Create(commandDto.Products.First().AdditionalInformation).IfFail(() => null);
                command.Products.First().AdditionalInformation.IsSome.Should().BeTrue();
                command.Products.First().AdditionalInformation.IfSome(x => x.Should().Be(expectedAdditionalInformation));
                var expectedPromotionCode = PromotionCode.Create(commandDto.Products.First().PromotionCode).IfFail(() => null);
                command.Products.First().PromotionCode.IsSome.Should().BeTrue();
                command.Products.First().PromotionCode.IfSome(x => x.Should().Be(expectedPromotionCode));
                var expectedClientName = Name.Create(commandDto.Client.Email).IfFail(() => null);
                command.ClientProp.Name.Should().Be(expectedClientName);
                var expectedClientPhoneNumber = PhoneNumber.Create(commandDto.Client.PhoneNumber).IfFail(() => null);
                command.ClientProp.PhoneNumber.Should().Be(expectedClientPhoneNumber);
                var expectedClientEmail = Email.Create(commandDto.Client.Email).IfFail(() => null);
                command.ClientProp.Email.Should().Be(expectedClientEmail);
                var expectedPurchaseApplicationAdditionalInformation = AdditionalInformation.Create(commandDto.AdditionalInformation).IfFail(() => null);
                command.AdditionalInformation.IsSome.Should().BeTrue();
                command.AdditionalInformation.IfSome(x => x.Should().Be(expectedPurchaseApplicationAdditionalInformation));
            });
        }
Esempio n. 3
0
 public JsonResult CheckCode(string code, int IDTour)
 {
     try
     {
         using (var db = new MyDbDataContext())
         {
             DateTime      today = DateTime.Now;
             PromotionCode Pcode = db.PromotionCodes.FirstOrDefault(c => c.Code == code &&
                                                                    today <= c.EndDay && today >= c.StartDay && c.Status == true);
             if (Pcode != null)
             {
                 /*
                  * 1-het ma
                  * 2-ok co ma va con luot dung
                  * 3-loi ko co ma nao
                  */
                 if (Pcode.Used >= Pcode.Total)
                 {
                     return(Json(new { Result = "OK", Message = "1" }));
                 }
                 else
                 {
                     return(Json(new { Result = "OK", Message = "2", rate = Pcode.Rate / 100 }));
                 }
             }
             return(Json(new { Result = "ERROR", Message = "3" }));
         }
     }
     catch (Exception ex)
     {
         return(Json(new { Result = "ERROR", ex.Message }));
     }
 }
Esempio n. 4
0
        public IHttpActionResult PostPromotionCode(PromotionCode promotionCode)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.PromotionCodes.Add(promotionCode);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (PromotionCodeExists(promotionCode.promotionCode1))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = promotionCode.promotionCode1 }, promotionCode));
        }
        public IHttpActionResult PostPromotionCodeTracking(PromotionCodeTracking promotionCodeTracking)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            PromotionCode promotionCode = db.PromotionCodes.Find(promotionCodeTracking.promotionCode);

            if (promotionCode == null)
            {
                return(BadRequest(ModelState));
            }
            else
            {
                Nullable <double> comissionPercent = promotionCode.percentEarn;
                if (comissionPercent != null)
                {
                    promotionCodeTracking.moneyEarned = (promotionCodeTracking.totalAmoutOfOrder) * (comissionPercent.Value / 100);
                }
            }
            DateTime date = DateTime.Now;

            promotionCodeTracking.timeOfUsing = date;
            db.PromotionCodeTrackings.Add(promotionCodeTracking);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = promotionCodeTracking.trackingId }, promotionCodeTracking));
        }
Esempio n. 6
0
        public ActionResult Update(int id)
        {
            var db = new MyDbDataContext();

            //string cookieClient = Request.Cookies["name_client"].Value;
            //string deCodecookieClient = CryptorEngine.Decrypt(cookieClient, true);
            //string userName = deCodecookieClient.Substring(0, deCodecookieClient.IndexOf("||"));
            //var user = db.Users.FirstOrDefault(a => a.UserName == userName);
            //if (user.UserContent == true)
            //{
            //    int cout = 0;
            //    HttpCookie langCookie = Request.Cookies["lang_client"];
            //    while (langCookie != null)
            //    {
            //        langCookie.Expires = DateTime.Now.AddDays(-30);
            //        HttpContext.Response.Cookies.Add(langCookie);
            //        cout++;
            //        if (cout == 10)
            //            break;
            //    }
            //    cout = 0;
            //    HttpCookie nameCookie = Request.Cookies["name_client"];
            //    while (nameCookie != null)
            //    {
            //        nameCookie.Expires = DateTime.Now.AddDays(-30);
            //        HttpContext.Response.Cookies.Add(nameCookie);
            //        cout++;
            //        if (cout == 10)
            //            break;
            //    }
            //    CurrentSession.ClearAll();
            //    return View();
            //}

            ViewBag.Title = "Udpate Promotion";

            PromotionCode detailPro = db.PromotionCodes.FirstOrDefault(a => a.ID == id);

            if (detailPro == null)
            {
                TempData["Messages"] = "Does not exist";
                return(RedirectToAction("Index"));
            }
            LoadData();
            var pro = new EPromotionCode
            {
                Code        = detailPro.Code,
                Rate        = detailPro.Rate,
                StartDay    = detailPro.StartDay,
                EndDay      = detailPro.EndDay,
                Status      = detailPro.Status,
                Total       = detailPro.Total,
                Description = detailPro.Description,
                Used        = detailPro.Used,
            };

            return(View(pro));
        }
Esempio n. 7
0
 public override int GetHashCode()
 {
     return(HashCodeBuilder.Combine(
                Name?.ToLower(CultureInfo.InvariantCulture),
                Publisher?.ToLower(CultureInfo.InvariantCulture),
                Product?.ToLower(CultureInfo.InvariantCulture),
                PromotionCode?.ToLower(CultureInfo.InvariantCulture),
                Version?.ToLower(CultureInfo.InvariantCulture)));
 }
Esempio n. 8
0
        private async Task <PostCreateCouponResponse> CreateCouponBodyAsync(PostCreateCouponRequest request)
        {
            using var transaction = await _unitOfWork.BeginTransactionAsync();

            var promotionCode = new PromotionCode();

            try
            {
                request.RedeemBy  = request.RedeemBy.Date;
                request.BeginDate = DateTime.Today;
                var coupon = await _couponService.CreateCouponAsync(request);

                await _unitOfWork.SaveChangesAsync();

                var couponOptions = new CouponCreateOptions()
                {
                    Id               = coupon.Id.ToString(),
                    Name             = coupon.Name,
                    AmountOff        = (long)(coupon.DiscountPrice * 100),
                    Currency         = "eur",
                    Duration         = "repeating",
                    DurationInMonths = request.DurationInMonths,
                    RedeemBy         = coupon.EndDate,
                };

                await _stripeCouponService.CreateAsync(couponOptions);

                // Hate stripe already
                var promoCodeOptions = new PromotionCodeCreateOptions()
                {
                    Coupon       = coupon.Id.ToString(),
                    Code         = coupon.Name,
                    Restrictions = new()
                    {
                        MinimumAmount         = (long)(coupon.OrderOverPrice * 100),
                        MinimumAmountCurrency = "eur"
                    }
                };

                promotionCode = await _promotionCodeService.CreateAsync(promoCodeOptions);

                promotionCode.Created = promotionCode.Created.Date;

                await transaction.CommitAsync();
            }
            catch (StripeException)
            {
                await transaction.RollbackAsync();

                throw;
            }

            var response = _mapper.Map <PostCreateCouponResponse>(promotionCode);

            return(response);
        }
Esempio n. 9
0
        public int CreatePromotionCode(PromotionCode model)
        {
            using (var cmd = new SqlCommand(@"INSERT	INTO Gungnir..tbl_PromotionCode
            (
                Code,
                UserId,
                StartTime,
                EndTime,
                CreateTime,
                Status,
                Description,
                Discount,
                MinMoney,
                CodeChannel,
                RuleID,
                PromtionName,
                Issuer,
				Creater
            )VALUES(
            RIGHT(ABS(CAST(CHECKSUM(NEWID()) AS BIGINT) * CHECKSUM(NEWID())), 12),
            @UserID,
            @StartDate,
            @EndDate,
            GETDATE(),
            0,
            @Description,
            @Discount,
            @Minmoney,
            @Channel,
            @RuleID,
            @PromtionName,
            @Issuer,
			@Creater);
            SELECT @@IDENTITY; "))
            {
                cmd.Parameters.AddWithValue("@UserID", model.UserID);
                cmd.Parameters.AddWithValue("@StartDate", model.StartTime);
                cmd.Parameters.AddWithValue("@EndDate", model.EndTime);
                cmd.Parameters.AddWithValue("@Description", model.Description);
                cmd.Parameters.AddWithValue("@Discount", model.Discount);
                cmd.Parameters.AddWithValue("@Minmoney", model.MinMoney);
                cmd.Parameters.AddWithValue("@Channel", model.CodeChannel);
                cmd.Parameters.AddWithValue("@RuleID", model.RuleID);
                cmd.Parameters.AddWithValue("@PromtionName", model.PromotionName);
                cmd.Parameters.AddWithValue("@Issuer", model.Issuer);
                cmd.Parameters.AddWithValue("@Creater", model.Creater);

                var obj = DbHelper.ExecuteScalar(cmd);
                if (obj != null)
                {
                    return(int.Parse(obj.ToString()));
                }
                return(0);
            }
        }
Esempio n. 10
0
        public IHttpActionResult GetPromotionCode(int id)
        {
            PromotionCode promotionCode = db.PromotionCodes.Find(id);

            if (promotionCode == null)
            {
                return(NotFound());
            }

            return(Ok(promotionCode));
        }
Esempio n. 11
0
 public PromotionCode CreateAService(PromotionCode pcService)
 {
     //Save and return currently added service if it exists
     if (pcService != null)
     {
         _db.PromotionCodes.Add(pcService);
         _db.SaveChanges();
         return(pcService);
     }
     return(null);
 }
Esempio n. 12
0
        public IHttpActionResult PostPromotionCode(PromotionCode promotionCode)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            promotionCode.Code = PromotionCode.GenerateCoupon(5);
            db.PromotionCodes.Add(promotionCode);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = promotionCode.PromotionCodeId }, promotionCode));
        }
Esempio n. 13
0
        public IHttpActionResult DeletePromotionCode(string id)
        {
            PromotionCode promotionCode = db.PromotionCodes.Find(id);

            if (promotionCode == null)
            {
                return(NotFound());
            }

            db.PromotionCodes.Remove(promotionCode);
            db.SaveChanges();

            return(Ok(promotionCode));
        }
 public async Task <IHttpActionResult> Post(PromotionCode data)
 {
     try
     {
         _uow.PromotionCode.IU(data);
         return(Ok());
     }
     catch (BusinessException ex)
     {
         return(BadRequest(ex.Message));
     }
     catch (Exception ex)
     {
         _log.Error(ex);
         return(BadRequest(this.General_Err));
     }
 }
Esempio n. 15
0
        public bool VerifPromotionCode(string code)
        {
            PromotionCode promotionCode = null;

            try
            {
                promotionCode = db.PromotionCodes.First(f => f.Code == code && f.DateEnd >= DateTime.Now && f.DateStart <= DateTime.Now);
            }
            catch (InvalidOperationException e)
            {
            }

            if (promotionCode == null)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 16
0
 public static int InsertPromotionCode(SqlDbHelper dbhelper, PromotionCode PC)
 {
     using (var cmd = new SqlCommand("[Gungnir]..[PromotionCode_CreatePromotionCode]"))
     {
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@UserId", PC.UserID);
         cmd.Parameters.AddWithValue("@StartTime", PC.StartTime);
         cmd.Parameters.AddWithValue("@EndTime", PC.EndTime);
         cmd.Parameters.AddWithValue("@OrderId", PC.OrderID);
         cmd.Parameters.AddWithValue("@Status", PC.Status);
         cmd.Parameters.AddWithValue("@Type", PC.Type);
         cmd.Parameters.AddWithValue("@Description", PC.Description);
         cmd.Parameters.AddWithValue("@Discount", PC.Discount);
         cmd.Parameters.AddWithValue("@MinMoney", PC.MinMoney);
         cmd.Parameters.AddWithValue("@RuleID", PC.RuleID);
         cmd.Parameters.AddWithValue("@Code", PC.Code);
         return(dbhelper.ExecuteNonQuery(cmd));
     }
 }
Esempio n. 17
0
        public ActionResult Create(EPromotionCode model)
        {
            using (var db = new MyDbDataContext())
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        if (db.PromotionCodes.ToList().Find(x => x.Code == model.Code) != null)
                        {
                            TempData["Messages"] = "is exist code";
                            return(View(model));
                        }
                        var pro = new PromotionCode
                        {
                            Code        = model.Code,
                            Rate        = model.Rate,
                            StartDay    = model.StartDay,
                            EndDay      = model.EndDay,
                            Total       = model.Total,
                            Used        = model.Used,
                            Description = model.Description,
                            Status      = model.Status,
                        };

                        db.PromotionCodes.InsertOnSubmit(pro);
                        db.SubmitChanges();

                        TempData["Messages"] = "Successful";
                        return(RedirectToAction("Index"));
                    }
                    catch (Exception exception)
                    {
                        LoadData();
                        ViewBag.Messages = "Error: " + exception.Message;
                        return(View(model));
                    }
                }
                LoadData();
                return(View(model));
            }
        }
Esempio n. 18
0
 public JsonResult Delete(int id)
 {
     try
     {
         using (var db = new MyDbDataContext())
         {
             PromotionCode del = db.PromotionCodes.FirstOrDefault(c => c.ID == id);
             if (del != null)
             {
                 db.PromotionCodes.DeleteOnSubmit(del);
                 db.SubmitChanges();
                 return(Json(new { Result = "OK", Message = "Successful" }));
             }
             return(Json(new { Result = "ERROR", Message = "Does not exist" }));
         }
     }
     catch (Exception ex)
     {
         return(Json(new { Result = "ERROR", ex.Message }));
     }
 }
Esempio n. 19
0
        public bool SavePromoCode(string promo, string email)
        {
            bool result = false;

            try
            {
                using (dekkOnlineEntities db = new dekkOnlineEntities())
                {
                    var useremail     = db.AspNetUsers.Where(s => s.Email == email).FirstOrDefault();
                    var promocodeuser = db.PromotionCode.Where(s => s.IdCode == promo).FirstOrDefault();
                    if (promocodeuser == null)
                    {
                        DateTime      date1   = DateTime.Now;
                        DateTime      date2   = date1.AddYears(50);
                        PromotionCode promous = new PromotionCode();
                        promous.IdCode          = promo;
                        promous.IdUser          = useremail.Id;
                        promous.PercentCode     = 10;
                        promous.DateStart       = date1;
                        promous.DateEnd         = date2;
                        promous.Points          = 10;
                        promous.DescriptionCode = "PromoCode for Costumer";
                        db.PromotionCode.Add(promous);
                        db.SaveChanges();
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// Gets information about a coupon.
        /// </summary>
        private async Task <Coupon?> GetCoupon(PromotionCode promo)
        {
            promo.Coupon.Metadata.TryGetValue("plan", out string?plan);
            promo.Coupon.Metadata.TryGetValue("email", out string?email);

            Coupon coupon = new Coupon()
            {
                Code           = promo.Code,
                Name           = promo.Coupon.Name,
                Id             = promo.Coupon.Id,
                ApiId          = promo.Id,
                AmountOff      = promo.Coupon.AmountOff,
                PercentOff     = promo.Coupon.PercentOff,
                Expired        = promo.ExpiresAt < DateTime.UtcNow,
                Active         = promo.Active && promo.Coupon.Valid,
                ValidForPlan   = plan,
                ValidForEmail  = email,
                Duration       = promo.Coupon.Duration,
                DurationMonths = promo.Coupon.DurationInMonths
            };

            return(coupon);
        }
Esempio n. 21
0
        public ActionResult Update(EPromotionCode model)
        {
            //Kiểm tra xem alias thuộc tour này đã tồn tại chưa
            var db = new MyDbDataContext();

            if (ModelState.IsValid)
            {
                try
                {
                    PromotionCode Pro = db.PromotionCodes.FirstOrDefault(b => b.ID == model.ID);
                    if (Pro != null)
                    {
                        Pro.Code        = model.Code;
                        Pro.StartDay    = model.StartDay;
                        Pro.EndDay      = model.EndDay;
                        Pro.Rate        = model.Rate;
                        Pro.Status      = model.Status;
                        Pro.Used        = model.Used;
                        Pro.Total       = model.Total;
                        Pro.Description = model.Description;

                        db.SubmitChanges();

                        TempData["Messages"] = "Successful";
                        return(RedirectToAction("Index"));
                    }
                }
                catch (Exception exception)
                {
                    LoadData();
                    ViewBag.Messages = "Error: " + exception.Message;
                    return(View());
                }
            }
            LoadData();
            return(View(model));
        }
Esempio n. 22
0
        public void CreatesProductList()
        {
            var productDto = buildProductDto();

            var result = Product.Create(new List <Product.Dto> {
                productDto
            }.AsReadOnly());

            result.IsSuccess.Should().BeTrue();
            result.IfSuccess(products =>
            {
                products.Count.Should().Be(1);
                var expectedLink = Link.Create(productDto.Link).IfFail(() => null);
                products.First().Link.Should().Be(expectedLink);
                var expectedUnits = Units.Create(productDto.Units).IfFail(() => null);
                products.First().Units.Should().Be(expectedUnits);
                products.First().AdditionalInformation.IsSome.Should().BeTrue();
                var expectedAdditionalInformation = AdditionalInformation.Create(productDto.AdditionalInformation).IfFail(() => null);
                products.First().AdditionalInformation.IfSome(x => x.Should().Be(expectedAdditionalInformation));
                var expectedPromotionCode = PromotionCode.Create(productDto.PromotionCode).IfFail(() => null);
                products.First().PromotionCode.IsSome.Should().BeTrue();
                products.First().PromotionCode.IfSome(x => x.Should().Be(expectedPromotionCode));
            });
        }
Esempio n. 23
0
 private void RegisterPromotionCode(string promtionCode)
 {
     PromotionCode.SendKeys(promtionCode);
     LogManager.Instance.WriteToLog(LogManager.elogLevel.Debug, "enter promtionCode: " + promtionCode + " to input field");
 }
Esempio n. 24
0
        public JsonResult ImportGrade()
        {
            try
            {
                //初始化优惠项目
                var promotionItems = PromotionItemInitialization();

                if (Request.Files.Count > 0)
                {
                    var file = Request.Files[0];
                    if (!file.FileName.Contains(".xlsx") && !file.FileName.Contains(".xls"))
                    {
                        return(Json(new { Status = -1, Error = "请上传.xlsx文件或者.xls文件!" }, "text/html"));
                    }

                    var excel = new Controls.ExcelHelper(file.InputStream, file.FileName);
                    var dt    = excel.ExcelToDataTable("sheet1", true);

                    #region 初始化失败数据表结构
                    DataTable failData = new DataTable();
                    failData.Columns.Add(new DataColumn("会员卡号", typeof(string)));
                    failData.Columns.Add(new DataColumn("会员姓名", typeof(string)));
                    failData.Columns.Add(new DataColumn("会员手机", typeof(string)));
                    failData.Columns.Add(new DataColumn("数量", typeof(string)));
                    failData.Columns.Add(new DataColumn("服务项目", typeof(string)));
                    #endregion

                    #region 插入成功数据表结构
                    DataTable finishData = new DataTable();
                    finishData.Columns.Add(new DataColumn("会员卡号", typeof(string)));
                    finishData.Columns.Add(new DataColumn("会员姓名", typeof(string)));
                    finishData.Columns.Add(new DataColumn("会员手机", typeof(string)));
                    finishData.Columns.Add(new DataColumn("数量", typeof(string)));
                    finishData.Columns.Add(new DataColumn("服务项目", typeof(string)));
                    #endregion

                    Dictionary <string, Guid> insertUsers = new Dictionary <string, Guid>();

                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow failRow               = failData.NewRow();
                        DataRow finishRow             = finishData.NewRow();
                        bool    sendPromotionCodeFail = false;

                        #region step 1 清理出表格中手机号字段为空的数据
                        if (null == dr["会员手机"] || string.IsNullOrWhiteSpace(dr["会员手机"].ToString().Trim()))
                        {
                            for (int i = 0; i < dr.ItemArray.Length; i++)
                            {
                                failRow[i] = dr[i];
                            }
                            failData.Rows.Add(failData);
                            continue;
                        }
                        #endregion

                        #region step 1: 获取UserID或者添加用户到UserObject
                        var tempUserId      = YLHUserManager.GetUserId(dr["会员手机"].ToString().Trim()); //获取是否已经是tuhu用户
                        var dtExistedMobile = insertUsers.ContainsKey(dr["会员手机"].ToString().Trim());  //是否是已经插入的用户

                        //主表不存在手机用户
                        //插入主表用户数据、YLH表用户数据
                        if (string.IsNullOrEmpty(tempUserId) && dtExistedMobile == false)
                        {
                            tbl_UserObjectModel userObject = new tbl_UserObjectModel();
                            Guid newGuid = Guid.NewGuid();

                            #region generate userObjectModel
                            //u_user_id
                            userObject.u_user_id = newGuid.ToString("B");
                            //会员手机号
                            userObject.u_mobile_number = dr["会员手机"].ToString().Trim();
                            //会员姓名
                            userObject.u_last_name =
                                (null == dr["会员姓名"] || string.IsNullOrWhiteSpace(dr["会员姓名"].ToString().Trim()) || "NULL" == dr["会员姓名"].ToString().Trim().ToUpper())
                                ? dr["会员手机"].ToString().Trim() : dr["会员姓名"].ToString().Trim();
                            //会员邮箱
                            userObject.u_email_address    = dr["会员手机"].ToString().Trim() + "@whguanggu.com";
                            userObject.u_application_name = "Import";
                            userObject.Category           = "武汉光谷一路店";
                            #endregion
                            #region 插入到数据库,如果插入失败,加入脏数据表,否则加入正常数据表
                            try
                            {
                                YLHUserManager.InsertUserObject(userObject);
                            }
                            catch (Exception ex)
                            {
                                for (int i = 0; i < dr.ItemArray.Length; i++)
                                {
                                    failRow[i] = dr[i];
                                }
                                failData.Rows.Add(failRow);
                                WebLog.LogException(ex);
                                break;
                            }
                            #endregion

                            YLHUserInfoModel ylhUserInfo = new YLHUserInfoModel();

                            #region generate ylh_UserInfo
                            ylhUserInfo.u_user_id  = newGuid.ToString("B");
                            ylhUserInfo.MemberName = (null == dr["会员姓名"] || string.IsNullOrWhiteSpace(dr["会员姓名"].ToString().Trim()) || "NULL" == dr["会员姓名"].ToString().Trim().ToUpper())
                                ? dr["会员手机"].ToString().Trim() : dr["会员姓名"].ToString().Trim();
                            ylhUserInfo.MemberNumber   = dr["会员卡号"].ToString().Trim();
                            ylhUserInfo.MemberPhone    = dr["会员手机"].ToString().Trim();
                            ylhUserInfo.Tag            = "武汉光谷一路店";
                            ylhUserInfo.CreatedTime    = DateTime.Now;
                            ylhUserInfo.UpdatedTime    = DateTime.Now;
                            ylhUserInfo.MemberBirthday = DateTime.Now;
                            ylhUserInfo.MemberAddress  = string.Empty;
                            ylhUserInfo.Integration    = 0;
                            #endregion
                            #region 插入到数据库,如果插入失败,加入脏数据表,否则加入正常数据表
                            try
                            {
                                YLHUserManager.InsertYLHUserInfo(ylhUserInfo);
                            }
                            catch (Exception ex)
                            {
                                for (int i = 0; i < dr.ItemArray.Length; i++)
                                {
                                    failRow[i] = dr[i];
                                }
                                failData.Rows.Add(failRow);
                                WebLog.LogException(ex);
                                break;
                            }
                            #endregion

                            //插入的用户记录字典
                            if (!insertUsers.ContainsKey(dr["会员手机"].ToString().Trim()))
                            {
                                insertUsers.Add(dr["会员手机"].ToString().Trim(), newGuid);
                            }
                        }
                        //主表存在手机用户数据
                        //插入YLH表用户数据
                        else
                        {
                            var tempPKID = YLHUserManager.GetYLHUserInfoPKID(tempUserId);
                            if (tempPKID < 0)
                            {
                                YLHUserInfoModel ylhUserInfo = new YLHUserInfoModel();

                                #region generate ylh_UserInfo
                                ylhUserInfo.u_user_id  = tempUserId;
                                ylhUserInfo.MemberName = (null == dr["会员姓名"] || string.IsNullOrWhiteSpace(dr["会员姓名"].ToString().Trim()) || "NULL" == dr["会员姓名"].ToString().Trim().ToUpper())
                                    ? dr["会员手机"].ToString().Trim() : dr["会员姓名"].ToString().Trim();
                                ylhUserInfo.MemberNumber   = dr["会员卡号"].ToString().Trim();
                                ylhUserInfo.MemberPhone    = dr["会员手机"].ToString().Trim();
                                ylhUserInfo.Tag            = "武汉光谷一路店";
                                ylhUserInfo.CreatedTime    = DateTime.Now;
                                ylhUserInfo.UpdatedTime    = DateTime.Now;
                                ylhUserInfo.MemberBirthday = DateTime.Now;
                                ylhUserInfo.MemberAddress  = string.Empty;
                                ylhUserInfo.Integration    = 0;
                                #endregion
                                #region 插入到数据库,如果插入失败,加入脏数据表,否则加入正常数据表
                                try
                                {
                                    YLHUserManager.InsertYLHUserInfo(ylhUserInfo);
                                }
                                catch (Exception ex)
                                {
                                    for (int i = 0; i < dr.ItemArray.Length; i++)
                                    {
                                        failRow[i] = dr[i];
                                    }
                                    failData.Rows.Add(failRow);
                                    WebLog.LogException(ex);
                                    break;
                                }
                                #endregion
                            }

                            //插入的用户记录字典
                            if (!insertUsers.ContainsKey(dr["会员手机"].ToString().Trim()))
                            {
                                insertUsers.Add(dr["会员手机"].ToString().Trim(), new Guid(tempUserId));
                            }
                        }
                        #endregion

                        #region step 2: 插入优惠券
                        if (!string.IsNullOrWhiteSpace(dr["服务项目"].ToString().Trim()) && insertUsers.ContainsKey(dr["会员手机"].ToString().Trim()))
                        {
                            var promotions = promotionItems.Where(_item => _item.ProductName == dr["服务项目"].ToString().Trim()).ToList();
                            if (promotions != null && promotions.Any() && promotions.Count > 0)
                            {
                                foreach (var promotion in promotions)
                                {
                                    int count = Convert.ToInt32(dr["数量"].ToString().Trim());
                                    for (int i = 0; i < count; i++)
                                    {
                                        #region generation promotionCode
                                        PromotionCode code = new PromotionCode();
                                        code.UserID        = insertUsers[dr["会员手机"].ToString().Trim()];
                                        code.StartTime     = DateTime.Now;
                                        code.EndTime       = Convert.ToDateTime("2018-12-31 00:00:00");
                                        code.PromotionName = promotion.PromotionName;
                                        code.Description   = promotion.Description;
                                        code.RuleID        = promotion.RuleID;
                                        code.Discount      = promotion.Discount;
                                        code.MinMoney      = promotion.MinMoney;
                                        code.CodeChannel   = promotion.CodeChannel;
                                        code.Creater       = "*****@*****.**";
                                        code.Issuer        = "*****@*****.**";
                                        #endregion

                                        #region 塞券
                                        try
                                        {
                                            YLHUserManager.CreatePromotionCode(code);
                                        }
                                        catch (Exception ex)
                                        {
                                            sendPromotionCodeFail = true;
                                            WebLog.LogException(ex);
                                            break;
                                        }
                                        #endregion
                                    }

                                    if (sendPromotionCodeFail)
                                    {
                                        break;
                                    }
                                }
                            }

                            if (sendPromotionCodeFail)
                            {
                                for (int j = 0; j < dr.ItemArray.Length; j++)
                                {
                                    failRow[j] = dr[j];
                                }
                                failData.Rows.Add(failRow);
                            }
                            else
                            {
                                for (int j = 0; j < dr.ItemArray.Length; j++)
                                {
                                    finishRow[j] = dr[j];
                                }
                                finishData.Rows.Add(finishRow);
                            }
                        }
                        else
                        {
                            for (int j = 0; j < dr.ItemArray.Length; j++)
                            {
                                finishRow[j] = dr[j];
                            }
                            finishData.Rows.Add(finishRow);
                            break;
                        }
                        #endregion
                    }

                    Response.Clear();
                    Response.Charset         = "UTF-8";
                    Response.Buffer          = true;
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                    Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode("永隆行用户导入失败记录", System.Text.Encoding.UTF8) + ".xls\"");
                    Response.ContentType = "application/ms-excel";
                    string    colHeaders = string.Empty;
                    string    ls_item    = string.Empty;
                    DataRow[] myRow      = failData.Select();
                    int       cl         = failData.Columns.Count;
                    foreach (DataRow row in myRow)
                    {
                        for (int i = 0; i < cl; i++)
                        {
                            if (i == (cl - 1))
                            {
                                ls_item += row[i].ToString() + "\n";
                            }
                            else
                            {
                                ls_item += row[i].ToString() + "\t";
                            }
                        }
                        Response.Output.Write(ls_item);
                        ls_item = string.Empty;
                    }
                    Response.Output.Flush();
                    Response.End();

                    return(Json(new { Status = -1, Error = "全部写入完成" }, "text/html"));
                }
                return(Json(new { Status = -1, Error = "请选择文件" }, "text/html"));
            }
            catch (Exception ex)
            {
                WebLog.LogException(ex);
                return(Json(new { Status = -2, Error = ex }, "text/html"));
            }
        }
Esempio n. 25
0
 public static int CreatePromotionCodeNew(PromotionCode model)
 {
     return(DALPromotion.CreatePromotionCodeNew(model));
 }
Esempio n. 26
0
 public static int InsertPromotionCode(SqlDbHelper dbhelper, PromotionCode PC)
 {
     return(DalPromotionCode.InsertPromotionCode(dbhelper, PC));
 }
Esempio n. 27
0
        public static int CreatePromotionCode(PromotionCode model)
        {
            DalYLHUser dal = new DalYLHUser();

            return(dal.CreatePromotionCode(model));
        }
Esempio n. 28
0
        public ActionResult SendBooking(MBookTour model)
        {
            string status = "success";

            try
            {
                using (var db = new MyDbDataContext())
                {
                    Tour  tour  = db.Tours.FirstOrDefault(a => a.ID == model.TourId);
                    Hotel hotel = CommentController.DetailHotel(Request.Cookies["LanguageID"].Value);

                    SendEmail sendEmail =
                        db.SendEmails.FirstOrDefault(
                            a => a.Type == TypeSendEmail.BookTour);
                    if (tour == null)
                    {
                        ViewBag.Messages = sendEmail.Error;
                        return(View("Messages"));
                    }

                    //xác định xem tour có phải là option không
                    string  inforBooking = "";
                    decimal price        = 0;
                    if (tour.HotelService == true)
                    {
                        switch (model.Option)
                        {
                        case 1:
                            inforBooking = "3-Star Hotels - " + tour.Title;
                            price        = (decimal)tour.ThreeStar;
                            break;

                        case 2:
                            inforBooking = "4-Star Hotels - " + tour.Title;
                            price        = (decimal)tour.FourStar;
                            break;

                        case 3:
                            inforBooking = "5-Star Hotels - " + tour.Title;
                            price        = (decimal)tour.FiveStar;
                            break;

                        default:
                            ViewBag.Messages = sendEmail.Error;
                            return(View("Messages"));
                        }
                    }
                    else
                    {
                        #region
                        ////xác định lịch trình
                        var tabTour = db.TabTours.FirstOrDefault(a => a.TourID == model.TabTourID);
                        if (tabTour == null)
                        {
                            inforBooking = tour.Title;
                            price        = (decimal)tour.PriceSale;
                        }
                        else
                        {
                            if (db.TabTours.Where(a => a.TourID == model.TourId).Count() > 0)
                            {
                                inforBooking = tour.Title + ", Itinerariy: " + tabTour.TitleTab;
                            }
                            else
                            {
                                inforBooking = tour.Title;
                            }
                            price = (decimal)tabTour.Price;
                        }

                        #endregion
                    }
                    //Check Promotion code

                    double   rate  = 0;
                    DateTime today = DateTime.Now;
                    if (string.IsNullOrEmpty(model.PromotionCode) == false)
                    {
                        PromotionCode Pcode = db.PromotionCodes.FirstOrDefault(c => c.Code == model.PromotionCode && today <= c.EndDay && today >= c.StartDay && c.Status == true);

                        if (Pcode != null)
                        {
                            /*
                             * 1-het ma
                             * 2-ok co ma va con luot dung
                             * 3-loi ko co ma nao
                             */
                            if (Pcode.Used >= Pcode.Total)
                            {
                                rate = 0;
                            }
                            else
                            {
                                rate       = Pcode.Rate / 100;
                                Pcode.Used = Pcode.Used + 1;
                                db.SubmitChanges();
                            }
                        }
                    }


                    //tính giá tour

                    price = price * model.Adult - (price * model.Adult * (decimal)0.6);
                    decimal deposit = 0;
                    decimal Balance = 0;

                    if (model.TypePayment == 1)
                    {
                        deposit = price * ((decimal)tour.Deposit / 100);
                    }
                    Balance = price - deposit;

                    string codeBooking = hotel.CodeBooking + "1";
                    if (db.BookTours.Any())
                    {
                        codeBooking = hotel.CodeBooking + db.BookTours.OrderByDescending(a => a.ID).FirstOrDefault().ID + 1;
                    }

                    BookTour bookTour = new BookTour();
                    bookTour.Departure  = model.Departure;
                    bookTour.Code       = codeBooking;
                    bookTour.CreateDate = DateTime.Now;
                    bookTour.Gender     = model.Gender;
                    bookTour.FullName   = model.FullName;
                    //bookTour.SocialMedia = model.SocialMedia;
                    bookTour.Tel         = model.Tel;
                    bookTour.RoomType    = model.RoomType;
                    bookTour.Country     = model.Country;
                    bookTour.Email       = model.Email;
                    bookTour.Request     = model.Request;
                    bookTour.Adult       = model.Adult;
                    bookTour.InfoBooking = inforBooking;
                    bookTour.Total       = (float)price;
                    //bookTour.Deposit = (float)deposit;
                    bookTour.Balance = (float)Balance;
                    bookTour.TourId  = model.TourId;

                    db.BookTours.InsertOnSubmit(bookTour);
                    db.SubmitChanges();

                    sendEmail.Title = sendEmail.Title.Replace("{HotelName}", hotel.Name);
                    string content = sendEmail.Content;
                    content = content.Replace("{HotelName}", hotel.Name);
                    content = content.Replace("{Deposit}", deposit.ToString());
                    content = content.Replace("{Balance}", Balance.ToString());
                    content = content.Replace("{Code}", bookTour.Code);
                    content = content.Replace("{Departure}", bookTour.Departure.ToString());
                    content = content.Replace("{InfoBooking}", bookTour.InfoBooking);
                    content = content.Replace("{Adult}", bookTour.Adult.ToString());
                    content = content.Replace("{TitleTour}", tour.Title);
                    content = content.Replace("{Price}", price.ToString());
                    content = content.Replace("{Gender}", model.Gender);
                    content = content.Replace("{FullName}", model.FullName);
                    content = content.Replace("{SocialMedia}", model.SocialMedia);
                    content = content.Replace("{Tel}", model.Tel);
                    content = content.Replace("{RoomType}", model.RoomType);
                    content = content.Replace("{Country}", model.Country);
                    content = content.Replace("{Email}", model.Email);
                    content = content.Replace("{Request}", model.Request);

                    if (rate != 0)
                    {
                        content = content.Replace("{Promotion}", model.PromotionCode + "/Rate: " + rate * 100 + " %");
                    }
                    else
                    {
                        content = content.Replace("{Promotion}", "No");
                    }
                    content = content.Replace("{Request}", model.Request);

                    //infor Hotel
                    content = content.Replace("{Add}", hotel.Address);
                    content = content.Replace("{Hotline}", hotel.Hotline);
                    content = content.Replace("{EmailHotel}", hotel.Email);
                    content = content.Replace("{Website}", hotel.Website);

                    MailHelper.SendMail(model.Email, sendEmail.Title, content);
                    MailHelper.SendMail(hotel.Email, hotel.Name + " (" + bookTour.Code + ")- Booking tour of " + model.FullName, content);

                    if (model.TypePayment == 1)
                    {
                        price = price * ((decimal)tour.Deposit / 100);
                        return(RedirectToAction("SubmitInvoidOnePay",
                                                new
                        {
                            idOrder = bookTour.Code,
                            deposit = (Math.Round(price * (decimal)CodeHelper.GetExrate(), 0)) * 100
                        }));
                    }
                    else
                    {
                        return(Redirect("/BookTour/Messages?status=" + status));
                    }
                }
            }
            catch (Exception ex)
            {
                status = "error";
            }

            return(Redirect("/BookTour/Messages?status=" + status));
        }
        public void CreatesPromotionCode()
        {
            var result = PromotionCode.Create("ADDIDAS-123");

            result.IsSuccess.Should().BeTrue();
        }
        public void CreatesPurchaseApplication()
        {
            var request = BuildPurchaseApplicationRequest();

            createPurchaseApplicationCommandHandler
            .Setup(x => x.Create(It.IsAny <CreatePurchaseApplicationCommand>()))
            .Returns(() => PurchaseApplicationBuilder.Build());

            var response = controller.Create(request) as StatusCodeResult;

            response.StatusCode.Should().Be(StatusCodes.Status200OK);
            createPurchaseApplicationCommandHandler
            .Verify(x => x.Create(It.Is <CreatePurchaseApplicationCommand>(y =>
                                                                           y.Products.Count == request.Products.Count &&
                                                                           y.Products.First().Link == Link.Create(request.Products.First().Link).IfFail(() => null) &&
                                                                           y.Products.First().Units == Units.Create(request.Products.First().Units).IfFail(() => null) &&
                                                                           y.Products.First().AdditionalInformation == AdditionalInformation.Create(request.Products.First().AdditionalInformation).IfFail(() => null) &&
                                                                           y.Products.First().PromotionCode == PromotionCode.Create(request.Products.First().PromotionCode).IfFail(() => null) &&
                                                                           y.ClientProp.Email == Email.Create(request.Client.Email).IfFail(() => null) &&
                                                                           y.ClientProp.PhoneNumber == PhoneNumber.Create(request.Client.PhoneNumber).IfFail(() => null) &&
                                                                           y.ClientProp.Name == Name.Create(request.Client.Name).IfFail(() => null) &&
                                                                           y.AdditionalInformation == AdditionalInformation.Create(request.AdditionalInformation).IfFail(() => null))),
                    Times.Once);
        }