public void LookupCouponInvoice()
        {
            var discounts = new Dictionary<string, int> { { "USD", 1000 } };
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), discounts);
            coupon.Create();

            var plan = new Plan(GetMockPlanCode(), GetMockPlanCode())
            {
                Description = "Test Lookup Coupon Invoice"
            };
            plan.UnitAmountInCents.Add("USD", 1500);
            plan.Create();
            PlansToDeactivateOnDispose.Add(plan);

            var account = CreateNewAccountWithBillingInfo();

            var redemption = account.RedeemCoupon(coupon.CouponCode, "USD");

            var sub = new Subscription(account, plan, "USD", coupon.CouponCode);
            sub.Create();

            // TODO complete this test

            var invoices = account.GetInvoices();

            invoices.Should().NotBeEmpty();

            var invoice = Invoices.Get(invoices.First().InvoiceNumber);
            var fromInvoice = invoice.GetRedemption();

            redemption.Should().Be(fromInvoice);
        }
Exemplo n.º 2
5
        public void Coupon_plan_must_exist()
        {
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), 10);
            coupon.Plans.Add("notrealplan");

            Action create = coupon.Create;
            create.ShouldThrow<ValidationException>();
        }
Exemplo n.º 3
3
        public void AddCoupon(Coupon coupon)
        {
            coupon.CreateDate = DateTime.Now;
            coupon.UpdateDate = DateTime.Now;

            _couponRepository.Add(coupon);
        }
Exemplo n.º 4
1
 /// <summary>
 /// Applies the coupon.
 /// </summary>
 /// <param name="couponCode">The coupon code.</param>
 /// <param name="order">The order.</param>
 public void ApplyCoupon(string couponCode, Order order)
 {
     Coupon coupon = new Coupon(Coupon.Columns.CouponCode, couponCode);
       if(coupon.CouponId > 0) {
     if(coupon.ExpirationDate > DateTime.UtcNow) {
       ICouponProvider couponProvider = new Serializer().DeserializeObject(coupon.ValueX, coupon.Type) as ICouponProvider;
       couponProvider.ApplyCoupon(order);
     }
       }
 }
Exemplo n.º 5
1
        public void CanAddCoupon()
        {
            // arrange
            var coupon = new Coupon();

            // act
            _order.AddCoupon(coupon);

            // assert
            Assert.Equal(1, _order.Coupons.Count);
        }
Exemplo n.º 6
1
        public void CouponsCanBeCreated()
        {
            var discounts = new Dictionary<string, int> {{"USD", 100}};
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), discounts)
            {
                MaxRedemptions = 1
            };
            coupon.Create();
            coupon.CreatedAt.Should().NotBe(default(DateTime));

            var coupons = Coupons.List().All;
            coupons.Should().Contain(coupon);
        }
Exemplo n.º 7
0
        public void CreateCouponPercent()
        {
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), 10);
            coupon.Create();

            coupon.CreatedAt.Should().NotBe(default(DateTime));

            coupon = Coupons.Get(coupon.CouponCode);

            coupon.Should().NotBeNull();
            coupon.DiscountPercent.Should().Be(10);
            coupon.DiscountType.Should().Be(Coupon.CouponDiscountType.Percent);
        }
Exemplo n.º 8
0
        public List<Coupon> GetCouponList(string sc)
        {
            List<Coupon> list = new List<Coupon>();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MSSqlServer"].ConnectionString))
            {
                string commString = "select c.Name,c.HitNum,c.ImageUrl,c.ImageSmallUrl,c.Description,c.ID,c.HairShopID,c.ExpiredDate,c.Discount,c.PhoneNumber,hs.HairShopName,hz.HotZoneName,hs.POSTID from Coupon c inner join HairShop hs on c.hairshopid=hs.hairshopid inner join HotZone hz on hz.HotZoneID = hs.HairShopHotZoneID "+sc+" order by Convert(int,c.discount) asc";
                using (SqlCommand comm = new SqlCommand())
                {
                    comm.CommandText = commString;
                    comm.Connection = conn;
                    conn.Open();

                    using (SqlDataReader sdr = comm.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            Coupon coupon = new Coupon();
                            string couponName = string.Empty;
                            string hitNum = string.Empty;
                            string picSmallUrl = string.Empty;
                            string picUrl = string.Empty;
                            string description = string.Empty;

                            coupon.Name = sdr["Name"].ToString();
                            coupon.HitNum = int.Parse(sdr["HitNum"].ToString());
                            coupon.ImageSmallUrl = sdr["ImageSmallUrl"].ToString();
                            coupon.ImageUrl = sdr["ImageUrl"].ToString();
                            coupon.Description = sdr["Description"].ToString();
                            coupon.ID = int.Parse(sdr["ID"].ToString());
                            coupon.HairShopID = int.Parse(sdr["HairShopID"].ToString());
                            coupon.ExpiredDate = sdr["ExpiredDate"].ToString();
                            coupon.Discount = sdr["Discount"].ToString();
                            coupon.PhoneNumber = sdr["PhoneNumber"].ToString();
                            coupon.HairShopName = sdr["HairShopName"].ToString();
                            coupon.HotZoneName = sdr["HotZoneName"].ToString();
                            if (sdr["POSTID"].ToString() != string.Empty)
                            {
                                coupon.PostID = int.Parse(sdr["postid"].ToString());
                            }
                            else
                            {
                                coupon.PostID = 0;
                            }

                            list.Add(coupon);
                        }
                    }
                }
            }
            return list;
        }
Exemplo n.º 9
0
        public void CreateCouponDollars()
        {
            var discounts = new Dictionary<string, int> {{"USD", 100}, {"EUR", 50}};
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), discounts);

            coupon.Create();
            coupon.CreatedAt.Should().NotBe(default(DateTime));

            coupon = Coupons.Get(coupon.CouponCode);

            coupon.Should().NotBeNull();
            coupon.DiscountInCents.Should().Equal(discounts);
            coupon.DiscountType.Should().Be(Coupon.CouponDiscountType.Dollars);
        }
        public void RedeemCoupon()
        {
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), 10);
            coupon.Create();

            var account = CreateNewAccount();
            account.CreatedAt.Should().NotBe(default(DateTime));

            var redemption = account.RedeemCoupon(coupon.CouponCode, "USD");

            redemption.Should().NotBeNull();
            redemption.Currency.Should().Be("USD");
            redemption.AccountCode.Should().Be(account.AccountCode);
            redemption.CreatedAt.Should().NotBe(default(DateTime));
        }
        public void RemoveCoupon()
        {
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), 10);
            coupon.Create();

            var account = CreateNewAccount();
            account.CreatedAt.Should().NotBe(default(DateTime));

            var redemption = account.RedeemCoupon(coupon.CouponCode, "USD");
            redemption.Should().NotBeNull();

            redemption.Delete();

            var activeRedemption = account.GetActiveRedemption();
            activeRedemption.Should().Be(null);
        }
Exemplo n.º 12
0
        public void CreateCouponPlan()
        {
            var plan = new Plan(GetMockPlanCode("coupon plan"), "Coupon Test");
            plan.SetupFeeInCents.Add("USD", 500);
            plan.UnitAmountInCents.Add("USD", 5000);
            plan.Create();
            PlansToDeactivateOnDispose.Add(plan);

            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), new Dictionary<string, int>());
            coupon.DiscountInCents.Add("USD", 100);
            coupon.Plans.Add(plan.PlanCode);

            Action a = coupon.Create;
            a.ShouldNotThrow();
            Assert.Equal(1, coupon.Plans.Count);

            //plan.Deactivate(); BaseTest.Dispose() handles this
        }
Exemplo n.º 13
0
    public static bool UseCoupon(string code, int orderId)
    {
        if (CheckCouponCodeExists(code))
        {
            Order order = new Order(orderId);
            Coupon coupon = new Coupon(code);
            if (!coupon.Used && coupon.ExpireDate >= DateTime.Now && order.Amount >= coupon.EffectAmount )
            {
                

                KeyValuePair<string, KeyValuePair<SqlDbType, object>>[] updateParameters
                    = new KeyValuePair<string, KeyValuePair<SqlDbType, object>>[4];
                updateParameters[0] = new KeyValuePair<string, KeyValuePair<SqlDbType, object>>("is_used",
                    new KeyValuePair<SqlDbType, object>(SqlDbType.Int, (object)1));
                updateParameters[1] = new KeyValuePair<string, KeyValuePair<SqlDbType, object>>("used_uid",
                    new KeyValuePair<SqlDbType, object>(SqlDbType.Int, (object)order.UserId));
                updateParameters[2] = new KeyValuePair<string, KeyValuePair<SqlDbType, object>>("used_order_id",
                    new KeyValuePair<SqlDbType, object>(SqlDbType.Int, (object)orderId));
                updateParameters[3] = new KeyValuePair<string, KeyValuePair<SqlDbType, object>>("used_date",
                    new KeyValuePair<SqlDbType, object>(SqlDbType.DateTime, (object)DateTime.Now));
                KeyValuePair<string, KeyValuePair<SqlDbType, object>>[] keyParameters
                    = new KeyValuePair<string, KeyValuePair<SqlDbType, object>>[1];
                keyParameters[0] = new KeyValuePair<string, KeyValuePair<SqlDbType, object>>("id",
                    new KeyValuePair<SqlDbType, object>(SqlDbType.Int, (object)coupon.Id));
                int i = DBHelper.UpdateData("coupon", updateParameters, keyParameters, Util.ConnectionStringMall);
                if (i == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
Exemplo n.º 14
0
    //按鈕產生QRCode & 寫入資料庫
    protected void btnQRCode_Click(object sender, EventArgs e)
    {
        string strTitle = txtTitle.Text;
        string strContent = txtContent.Text;
        int couponID = 0;
        try
        {
            couponID = db.Coupon.OrderByDescending(cpID => cpID.couponID).FirstOrDefault().couponID+1;
        }
        catch (Exception)
        {
            couponID = 10010;
        }

        string docupath = Request.PhysicalApplicationPath; //抓取實際目錄路徑
        if (strTitle != "" && strContent != "") //判斷使用者輸入
        {
            string mContent = txtContent.Text;
            string mTime = DateTime.Now.Millisecond.ToString(); //取得當亂數

            lblMsg.Text = "qr_" + couponID + ".png"; //顯示檔名
            QRCodeEncoder mEncoder = new QRCodeEncoder(); //建立 encoder
            System.Drawing.Bitmap qrcode = mEncoder.Encode(couponID.ToString()); //將內容轉碼成 QR code

            qrcode.Save(docupath + "mPic\\qrcode\\qr_" + couponID + ".jpg"); //把 QRcode 另存為 jpg 圖檔,並放置於 images 資料夾底下
            imgQRCode.ImageUrl = "~\\mPic\\qrcode\\qr_" + couponID + ".jpg"; //設定組件 Image 的來源
        }
        else // txtContent 沒內容就不轉 QRcode + 提示訊息
        {
            lblMsg.Text = "請輸入資料!!";
            lblMsg.Visible = true;
            return;
        }

        //LINQ寫入資料庫
        Coupon coupon = new Coupon();
        coupon.title = strTitle;
        coupon.content = strContent;
        coupon.qrCode = "qrcode/qr_" + couponID + ".jpg";
        coupon.facilityID = (int)Session[CDictionary.SESSION_FACILITY_ID];
        db.Coupon.InsertOnSubmit(coupon);
        db.SubmitChanges();
    }
Exemplo n.º 15
0
        public void ListCouponsMaxedOut()
        {
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName("Maxed Out test"), 10)
            {
                MaxRedemptions = 1
            };
            coupon.Create();
            coupon.CreatedAt.Should().NotBe(default(DateTime));

            var account = CreateNewAccountWithBillingInfo();

            var redemption = account.RedeemCoupon(coupon.CouponCode, "USD");
            redemption.CreatedAt.Should().NotBe(default(DateTime));

            var fromService = Coupons.Get(coupon.CouponCode);
            fromService.Should().NotBeNull();

            var expiredCoupons = Coupons.List(Coupon.CouponState.Expired);
            expiredCoupons.Should().NotContain(coupon,
                    "the Recurly service marks this expired coupon as \"Inactive\", which cannot be searched for.");
        }
Exemplo n.º 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddCoupon_Click(object sender, EventArgs e)
        {
            try
            {
                Coupon CouponEntity = new Coupon(0, tbCouponName.Text.Trim(), Int32.Parse(ddlShopList.SelectedItem.Value), tbDiscount.Text.Trim(),
                    tbExpired.Text.Trim(), tbPhone.Text.Trim(), tbTag.Text.Trim(), tbDesc.Text.Trim(),this.img.ImageUrl.ToString(),0,this.imgSmall.ImageUrl.ToString());

                InfoAdmin.AddCoupon(CouponEntity);

                string couponID = "";

                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MSSqlServer"].ConnectionString))
                {
                    string commString = "update HairShop set couponNum = couponNum +1 where HairShopID=" + this.ddlShopList.SelectedItem.Value;
                    using (SqlCommand comm = new SqlCommand())
                    {
                        comm.CommandText = commString;
                        comm.Connection = conn;
                        conn.Open();
                        try
                        {
                            comm.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message);
                        }
                    }
                }

                MessageObject.Show("数据添加成功!");
                ResetControlState();
            }
            catch (System.Data.SqlClient.SqlException sqlEx)
            {
                throw new ArgumentException("位置错误", sqlEx.Message);
            }
            this.Response.Redirect("CouponAddSwitch.aspx?id="+this.Request.QueryString["id"].ToString());
        }
Exemplo n.º 17
0
 public static void AddCoupon(this Coupon coupon)
 {
 }
Exemplo n.º 18
0
        private Models.Basket GetUpsertPromotionResult(ApiResult <Models.Basket> apiResult, Coupon coupon, string basketId)
        {
            try
            {
                return(apiResult.GetDataOrContextException("notValidPromotionCode"));
            }
            catch (ContextApiException e)
            {
                throw new InvalidPromoCodeException(e, coupon);
            }
            catch (ApiException e)
            {
                switch (e.ResponseCode)
                {
                case HttpStatusCode.NotFound:
                    throw new BasketNotFoundException(e, basketId);

                case HttpStatusCode.BadRequest:
                    throw new BasketCannotBeModifiedException(e, basketId);

                default:
                    throw;
                }
            }
        }
Exemplo n.º 19
0
        public void testCachedValues()
        {
            //("Testing Bermudan swaption against cached values...");

            CommonVars vars = new CommonVars();

            vars.today = new Date(15, Month.February, 2002);

            Settings.setEvaluationDate(vars.today);

            vars.settlement = new Date(19, Month.February, 2002);
            // flat yield term structure impling 1x5 swap at 5%
            vars.termStructure.linkTo(Utilities.flatRate(vars.settlement,
                                                         0.04875825,
                                                         new Actual365Fixed()));

            double atmRate = vars.makeSwap(0.0).fairRate();

            VanillaSwap itmSwap = vars.makeSwap(0.8 * atmRate);
            VanillaSwap atmSwap = vars.makeSwap(atmRate);
            VanillaSwap otmSwap = vars.makeSwap(1.2 * atmRate);

            double          a = 0.048696, sigma = 0.0058904;
            ShortRateModel  model         = new HullWhite(vars.termStructure, a, sigma);
            List <Date>     exerciseDates = new List <Date>();
            List <CashFlow> leg           = atmSwap.fixedLeg();

            for (int i = 0; i < leg.Count; i++)
            {
                Coupon coupon = (Coupon)(leg[i]);
                exerciseDates.Add(coupon.accrualStartDate());
            }

            Exercise       exercise   = new BermudanExercise(exerciseDates);
            IPricingEngine treeEngine = new TreeSwaptionEngine(model, 50);
            IPricingEngine fdmEngine  = new FdHullWhiteSwaptionEngine(model as HullWhite);

#if QL_USE_INDEXED_COUPON
            double itmValue = 42.2413, atmValue = 12.8789, otmValue = 2.4759;
            double itmValueFdm = 42.2111, atmValueFdm = 12.8879, otmValueFdm = 2.44443;
#else
            double itmValue = 42.2470, atmValue = 12.8826, otmValue = 2.4769;
            double itmValueFdm = 42.2091, atmValueFdm = 12.8864, otmValueFdm = 2.4437;
#endif

            double tolerance = 1.0e-4;

            Swaption swaption = new Swaption(itmSwap, exercise);
            swaption.setPricingEngine(treeEngine);
            if (Math.Abs(swaption.NPV() - itmValue) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached in-the-money swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + itmValue);
            }

            swaption.setPricingEngine(fdmEngine);
            if (Math.Abs(swaption.NPV() - itmValueFdm) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached in-the-money swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + itmValueFdm);
            }

            swaption = new Swaption(atmSwap, exercise);
            swaption.setPricingEngine(treeEngine);
            if (Math.Abs(swaption.NPV() - atmValue) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached at-the-money swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + atmValue);
            }
            swaption.setPricingEngine(fdmEngine);
            if (Math.Abs(swaption.NPV() - atmValueFdm) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached at-the-money swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + atmValueFdm);
            }

            swaption = new Swaption(otmSwap, exercise);
            swaption.setPricingEngine(treeEngine);
            if (Math.Abs(swaption.NPV() - otmValue) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached out-of-the-money "
                             + "swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + otmValue);
            }
            swaption.setPricingEngine(fdmEngine);
            if (Math.Abs(swaption.NPV() - otmValueFdm) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached out-of-the-money "
                             + "swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + otmValueFdm);
            }

            for (int j = 0; j < exerciseDates.Count; j++)
            {
                exerciseDates[j] = vars.calendar.adjust(exerciseDates[j] - 10);
            }
            exercise = new BermudanExercise(exerciseDates);

#if QL_USE_INDEXED_COUPON
            itmValue = 42.1917; atmValue = 12.7788; otmValue = 2.4388;
#else
            itmValue = 42.1974; atmValue = 12.7825; otmValue = 2.4399;
#endif

            swaption = new Swaption(itmSwap, exercise);
            swaption.setPricingEngine(treeEngine);
            if (Math.Abs(swaption.NPV() - itmValue) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached in-the-money swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + itmValue);
            }

            swaption = new Swaption(atmSwap, exercise);
            swaption.setPricingEngine(treeEngine);
            if (Math.Abs(swaption.NPV() - atmValue) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached at-the-money swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + atmValue);
            }

            swaption = new Swaption(otmSwap, exercise);
            swaption.setPricingEngine(treeEngine);
            if (Math.Abs(swaption.NPV() - otmValue) > tolerance)
            {
                QAssert.Fail("failed to reproduce cached out-of-the-money "
                             + "swaption value:\n"
                             + "calculated: " + swaption.NPV() + "\n"
                             + "expected:   " + otmValue);
            }
        }
 public async Task <ActionResult <Coupon> > UpdateDiscount([FromBody] Coupon coupon)
 {
     return(Ok(await _repository.UpdateDiscount((coupon))));
 }
Exemplo n.º 21
0
        public void Setup()
        {
            _bar1 = new Bar()
            {
                Address          = "FakeAddress",
                AgeLimit         = 18,
                AvgRating        = 0,
                BarName          = "FakeBar",
                CVR              = 12345678,
                Educations       = "FakeEdu",
                Email            = "*****@*****.**",
                Image            = "FakeImg",
                PhoneNumber      = 88888888,
                ShortDescription = "Fake Short Desc",
                LongDescription  = "Fake Long Desc",
            };
            _bar2 = new Bar()
            {
                Address          = "FakeAddress2",
                AgeLimit         = 21,
                AvgRating        = 4,
                BarName          = "FakeBar2",
                CVR              = 12345679,
                Educations       = "FakeEdu2",
                Email            = "*****@*****.**",
                Image            = "FakeImg2",
                PhoneNumber      = 88888889,
                ShortDescription = "Fake Short Desc2",
                LongDescription  = "Fake Long Desc2",
            };

            _drink1 = new Drink()
            {
                BarName    = "Katrines Kælder",
                DrinksName = "Fadoel",
                Price      = 20,
            };

            _review1 = new Review()
            {
                BarName     = "FakeBar",
                BarPressure = 5,
                Username    = "******",
            };

            _review2 = new Review()
            {
                BarName     = "FakeBar",
                BarPressure = 3,
                Username    = "******",
            };

            _barEvent = new BarEvent()
            {
                BarName   = "Katrines Kælder",
                Date      = new DateTime(2019, 5, 29),
                EventName = "FakeEvent",
            };

            _barRepresentative = new BarRepresentative()
            {
                BarName  = "Katrines Kælder",
                Name     = "FakeBarRepresentative",
                Username = "******",
            };

            _coupon = new Coupon()
            {
                BarName        = "Katrines Kælder",
                CouponID       = "FakeCouponID",
                ExpirationDate = new DateTime(2019, 12, 12),
            };

            _customer = new Customer()
            {
                DateOfBirth   = new DateTime(1997, 2, 5),
                Email         = "*****@*****.**",
                FavoriteDrink = "Beer",
                FavoriteBar   = "Katrines Kælder",
                Name          = "Andreas Vorgaard",
            };
            _connection = new SqliteConnection("Datasource=:memory:");
            _connection.Open();
            _options =
                new DbContextOptionsBuilder <BarOMeterContext>().UseSqlite(_connection).Options;
            _uut = new UnitOfWork(_options);
        }
Exemplo n.º 22
0
 public async Task UpdateAsync(Coupon entity)
 {
     couponRepository.Update(entity);
     await unitOfWork.SaveChangesAsync();
 }
Exemplo n.º 23
0
        protected void btnRegister_Click(string email, string username)
        {
            try
            {
                User             user                = new User();
                UserRepository   userrepo            = new UserRepository();
                UserActivation   objUserActivation   = new UserActivation();
                Coupon           objCoupon           = new Coupon();
                CouponRepository objCouponRepository = new CouponRepository();
                SocioBoard.Helper.SessionFactory.configfilepath = Server.MapPath("~/hibernate.cfg.xml");
                try
                {
                    user.PaymentStatus    = "unpaid";
                    user.AccountType      = AccountType.Premium.ToString();
                    user.CreateDate       = DateTime.Now;
                    user.ExpiryDate       = DateTime.Now.AddMonths(1);
                    user.Id               = Guid.NewGuid();
                    user.UserName         = username;
                    user.Password         = this.MD5Hash("Sb1234!@#$");
                    user.EmailId          = email;
                    user.UserStatus       = 1;
                    user.ActivationStatus = "1";

                    if (!userrepo.IsUserExist(user.EmailId))
                    {
                        UserRepository.Add(user);


                        Session["LoggedUser"]              = user;
                        objUserActivation.Id               = Guid.NewGuid();
                        objUserActivation.UserId           = user.Id;
                        objUserActivation.ActivationStatus = "1";
                        UserActivationRepository.Add(objUserActivation);

                        //add package start

                        UserPackageRelation           objUserPackageRelation           = new UserPackageRelation();
                        UserPackageRelationRepository objUserPackageRelationRepository = new UserPackageRelationRepository();
                        PackageRepository             objPackageRepository             = new PackageRepository();

                        Package objPackage = objPackageRepository.getPackageDetails(user.AccountType);
                        objUserPackageRelation.Id            = new Guid();
                        objUserPackageRelation.PackageId     = objPackage.Id;
                        objUserPackageRelation.UserId        = user.Id;
                        objUserPackageRelation.ModifiedDate  = DateTime.Now;
                        objUserPackageRelation.PackageStatus = true;

                        objUserPackageRelationRepository.AddUserPackageRelation(objUserPackageRelation);

                        //end package

                        //SocioBoard.Helper.MailSender.SendEMail(txtFirstName.Text, txtPassword.Text, txtEmail.Text, user.AccountType.ToString(), user.Id.ToString());
                    }
                    else
                    {
                        //lblerror.Text = "Email Already Exists " + "<a href=\"Default.aspx\">login</a>";
                    }
                }

                catch (Exception ex)
                {
                    logger.Error(ex.StackTrace);
                    // lblerror.Text = "Please Insert Correct Information";
                    Console.WriteLine(ex.StackTrace);
                    //Response.Redirect("Home.aspx");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.StackTrace);

                Console.WriteLine(ex.StackTrace);
                //Response.Redirect("Home.aspx");
            }
        }
Exemplo n.º 24
0
 partial void DeleteCoupon(Coupon instance);
Exemplo n.º 25
0
 partial void UpdateCoupon(Coupon instance);
Exemplo n.º 26
0
 partial void InsertCoupon(Coupon instance);
Exemplo n.º 27
0
	private void detach_Coupons(Coupon entity)
	{
		this.SendPropertyChanging();
		entity.CouponsSite = null;
	}
Exemplo n.º 28
0
	private void attach_Coupons(Coupon entity)
	{
		this.SendPropertyChanging();
		entity.CouponsSite = this;
	}
Exemplo n.º 29
0
    protected void BtnSave_Click(object sender, EventArgs e)
    {
        LblErr.Text = "";
        LblOk.Text = "";

        try
        {
            Coupon o1 = new Coupon();
            if (base.CurrentId == 0)
            {
                form2obj(o1);
                o1 = new CouponsManager().Insert(o1);
            }
            else
            {
                o1 = new CouponsManager().GetByKey(base.CurrentId);  //precarico i campi esistenti e nn gestiti dal form
                form2obj(o1);
                new CouponsManager().Update(o1);
            }
            Grid1.DataBind();
            LblOk.Text = RenderSuccess(Utility.GetLabel("RECORD_SAVED_MSG"));
            MultiView1.ActiveViewIndex = 0;
        }
        catch (Exception e1)
        {
            LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString());
        }
        finally
        {
        }
    }
Exemplo n.º 30
0
    private void obj2form(Coupon obj)
    {
        ChkEnabled.Checked = obj.Enabled;
        TxtCode.Text = obj.Code;
        TxtAmount.Text = obj.Amount.ToString();
        TxtMinAmount.Text = obj.MinOrderAmount.ToString();
        ChkPercentage.Checked = obj.IsPercentage;
        TxtMaxUses.Text = obj.MaxUses.ToString();
        this.ValidFrom = obj.ValidFrom;
        this.ValidTo = obj.ValidTo;

        Utility.SetListBoxByValues(ListCategories, obj.CategoriesIdList);
        Utility.SetListBoxByValues(ListItems, obj.ItemsIdList);
    }
Exemplo n.º 31
0
 public static Coupon ModifyCoupon(Coupon coupon)
 {
     return(null);
 }
Exemplo n.º 32
0
        internal static void ValidateModel(Controller controller, BookingViewModel model, int?offerid, string couponcode, out IEnumerable <RestaurantMenuItem> restaurantMenuItems,
                                           out IEnumerable <RestaurantTable> restaurantTables, out SeasonalOffer restaurantOffer, out Coupon restaurantCoupon)
        {
            ValidateModel(controller, model, offerid, out restaurantMenuItems, out restaurantTables, out restaurantOffer);
            restaurantCoupon = null;
            if (couponcode.IsNullOrEmpty())
            {
                return;
            }
            var result = new OfferBaseRepository().FindCouponByCode(couponcode.Trim());

            if (result != null)
            {
                if (result.ValidTill.ToUniversalTime() > DateTime.UtcNow)
                {
                    restaurantCoupon = result;
                    return;
                }
                controller.ModelState.AddModelError("addstatus", "Coupon Code has expired !");
                return;
            }
            controller.ModelState.AddModelError("addstatus", "Invalid Coupon code provided.");
        }
Exemplo n.º 33
0
 public async Task <ActionResult <bool> > CreateDiscount([FromBody] Coupon coupon)
 {
     return(Ok(await _repository.CreateDiscount(coupon)));
 }
Exemplo n.º 34
0
 public void SetUp()
 {
     coupon = CouponService.CreateCoupon(minAmount, amount, type);
 }
Exemplo n.º 35
0
        public async Task <IActionResult> Create([Bind("LimitPerCoupon,LimitUse,LimitPerUser,DiscountType,CouponCode,Description,CouponAmount,AllowFreeShipping,ExpirationDate,MinimumSpending,MaximumSpending,OnlyIndividualUse,ExcludeDiscountProduct,RestrictedEmails,Id,CreateDate,CreatedBy,UpdateDate,UpdatedBy,AppTenantId")] Coupon coupon, long[] CouponProductId, long[] ExcludeCouponProductId, long[] CouponCategoryId, long[] ExcludeCouponCategoryId)
        {
            if (ModelState.IsValid)
            {
                coupon.CreatedBy   = User.Identity.Name ?? "username";
                coupon.CreateDate  = DateTime.Now;
                coupon.UpdatedBy   = User.Identity.Name ?? "username";
                coupon.UpdateDate  = DateTime.Now;
                coupon.AppTenantId = tenant.AppTenantId;
                _context.Add(coupon);
                await _context.SaveChangesAsync();

                coupon = _context.Coupons.Include(i => i.CouponProducts).Include(i => i.ExcludeCouponProducts).Include(i => i.CouponProductCategories).Include(i => i.ExcludeCouponProductCategories).FirstOrDefault(f => f.Id == coupon.Id);
                coupon.CouponProducts.Clear();
                await _context.SaveChangesAsync();

                foreach (var item in CouponProductId)
                {
                    coupon.CouponProducts.Add(new CouponProduct()
                    {
                        CouponId = coupon.Id, ProductId = item
                    });
                }
                await _context.SaveChangesAsync();

                coupon.ExcludeCouponProducts.Clear();
                await _context.SaveChangesAsync();

                foreach (var item in ExcludeCouponProductId)
                {
                    coupon.ExcludeCouponProducts.Add(new ExcludeCouponProduct()
                    {
                        CouponId = coupon.Id, ProductId = item
                    });
                }
                await _context.SaveChangesAsync();

                coupon.CouponProductCategories.Clear();
                await _context.SaveChangesAsync();

                foreach (var item in CouponCategoryId)
                {
                    coupon.CouponProductCategories.Add(new CouponProductCategory()
                    {
                        CouponId = coupon.Id, ProductCategoryId = item
                    });
                }
                await _context.SaveChangesAsync();

                coupon.ExcludeCouponProductCategories.Clear();
                await _context.SaveChangesAsync();

                foreach (var item in ExcludeCouponCategoryId)
                {
                    coupon.ExcludeCouponProductCategories.Add(new ExcludeCouponProductCategory()
                    {
                        CouponId = coupon.Id, ProductCategoryId = item
                    });
                }
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            ViewBag.Products          = new MultiSelectList(_context.Products.ToList(), "Id", "Name");
            ViewBag.ProductCategories = new MultiSelectList(_context.ProductCategories.ToList(), "Id", "Name");
            return(View(coupon));
        }
Exemplo n.º 36
0
    private void form2obj(Coupon obj)
    {
        obj.Id = base.CurrentId;
        obj.Enabled = ChkEnabled.Checked;
        obj.Code = TxtCode.Text;
        decimal amount = 0m;
        if (!string.IsNullOrEmpty(TxtAmount.Text))
        {
            decimal.TryParse(TxtAmount.Text, out amount);
        }
        if (amount > 0)
        {
            obj.Amount = amount;
        }
        decimal minAmount = 0m;
        if (!string.IsNullOrEmpty(TxtMinAmount.Text))
        {
            decimal.TryParse(TxtMinAmount.Text, out minAmount);
        }
        if (minAmount > 0)
        {
            obj.MinOrderAmount = minAmount;
        }
        obj.IsPercentage = ChkPercentage.Checked;
        obj.ValidFrom = this.ValidFrom;
        obj.ValidTo = this.ValidTo;
        int maxUses = 0;
        int.TryParse(TxtMaxUses.Text, out maxUses);
        obj.MaxUses = maxUses;

        obj.CategoriesIdListString = String.Join(",",
            ListCategories.Items.Cast<ListItem>()
                .Where(i => i.Selected && i.Value != "0")
                .Select(i => i.Value)
                .ToArray());

        obj.ItemsIdListString = String.Join(",",
            ListItems.Items.Cast<ListItem>()
                .Where(i => i.Selected && i.Value != "0")
                .Select(i => i.Value)
                .ToArray());
    }
Exemplo n.º 37
0
        public void DeactivateCoupon()
        {
            var discounts = new Dictionary<string, int> { { "USD", 100 }, { "EUR", 50 } };
            var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), discounts);
            coupon.Create();
            coupon.CreatedAt.Should().NotBe(default(DateTime));

            coupon.Deactivate();

            coupon = Coupons.Get(coupon.CouponCode);
            coupon.Should().NotBeNull();
            coupon.State.Should().Be(Coupon.CouponState.Inactive);
        }
        public async Task <IActionResult> Put(long id, [FromBody] CartRuleForm model)
        {
            if (ModelState.IsValid)
            {
                var cartRule = await _cartRuleRepository.Query()
                               .Include(x => x.Coupons)
                               .Include(x => x.Products)
                               .FirstOrDefaultAsync(x => x.Id == id);

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

                cartRule.Name                  = model.Name;
                cartRule.Description           = model.Description;
                cartRule.StartOn               = model.StartOn;
                cartRule.EndOn                 = model.EndOn;
                cartRule.IsActive              = model.IsActive;
                cartRule.IsCouponRequired      = model.IsCouponRequired;
                cartRule.RuleToApply           = model.RuleToApply;
                cartRule.DiscountAmount        = model.DiscountAmount;
                cartRule.DiscountStep          = model.DiscountStep;
                cartRule.MaxDiscountAmount     = model.MaxDiscountAmount;
                cartRule.UsageLimitPerCoupon   = model.UsageLimitPerCoupon;
                cartRule.UsageLimitPerCustomer = model.UsageLimitPerCustomer;

                if (model.IsCouponRequired && !string.IsNullOrWhiteSpace(model.CouponCode))
                {
                    var coupon = cartRule.Coupons.FirstOrDefault();
                    if (coupon == null)
                    {
                        coupon = new Coupon
                        {
                            CartRule = cartRule,
                            Code     = model.CouponCode
                        };

                        cartRule.Coupons.Add(coupon);
                    }
                    else
                    {
                        coupon.Code = model.CouponCode;
                    }
                }

                foreach (var item in model.Products)
                {
                    var cartRuleProduct = cartRule.Products.FirstOrDefault(x => x.ProductId == item.Id);
                    if (cartRuleProduct == null)
                    {
                        cartRuleProduct = new CartRuleProduct
                        {
                            CartRule  = cartRule,
                            ProductId = item.Id
                        };
                        cartRule.Products.Add(cartRuleProduct);
                    }
                }

                var modelProductIds = model.Products.Select(x => x.Id);
                var deletedProducts = cartRule.Products.Where(x => !modelProductIds.Contains(x.ProductId)).ToList();
                foreach (var item in deletedProducts)
                {
                    item.CartRule = null;
                    cartRule.Products.Remove(item);
                }

                await _cartRuleRepository.SaveChangesAsync();

                return(Accepted());
            }
            return(BadRequest(ModelState));
        }
Exemplo n.º 39
0
    protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var item = new Coupon();
            item = (Coupon)e.Row.DataItem;

            var LnkTitle = (LinkButton)e.Row.FindControl("LnkTitle");
            LnkTitle.Text = "<i class='fa fa-pgn_edit fa-fw'></i>";
            LnkTitle.Text += Utility.Html.GetTextPreview(item.Code, 50, "");
            if (string.IsNullOrEmpty(LnkTitle.Text))
                LnkTitle.Text += Utility.GetLabel("NO_VALUE", "<no value>");
            if (Roles.IsUserInRole("debug"))
                LnkTitle.Text += " [" + item.Id.ToString() + "]";

            var LitCouponInfo = e.Row.FindControl("LitCouponInfo") as Literal;
            LitCouponInfo.Text += "max uses: "
                + (item.MaxUses > 0 ? item.MaxUses.ToString() : "unlimited")
                + " times <br>";
            LitCouponInfo.Text += "used: " + item.UsesCounter + " times <br>";
            if (item.CategoriesIdList.Count > 0)
                LitCouponInfo.Text += item.CategoriesIdList.Count + " filters on categories<br>";
            if (item.ItemsIdList.Count > 0)
                LitCouponInfo.Text += item.ItemsIdList.Count + " filters on items<br>";

            //if percentage show percent, also the default
            Literal LitValueAmount = e.Row.FindControl("LitValueAmount") as Literal;
            if (item.IsPercentage)
            {
                LitValueAmount.Text = (item.Amount * 100).ToString() + "%";
            }
            else
            {
                LitValueAmount.Text = shopSettings.CurrencyDefault.Symbol + " " + item.Amount.ToString("0.00");
            }

            //Published
            if (item.Enabled)
            {
                var img1 = e.Row.FindControl("ImgEnabledOk");
                img1.Visible = true;
            }
            else
            {
                var img1 = e.Row.FindControl("ImgEnabledKo");
                img1.Visible = true;
            }

            var LitValidForm = e.Row.FindControl("LitValidFrom") as Literal;
            var LitValidTo = e.Row.FindControl("LitValidTo") as Literal;

            if (item.ValidFrom != DateTime.MinValue)
                LitValidForm.Text = item.ValidFrom.ToShortDateString();
            if (item.ValidTo != DateTime.MinValue)
                LitValidTo.Text = item.ValidTo.ToShortDateString();

        }
    }
    public async Task <ActionResult <Coupon> > CreateDiscount([FromBody] Coupon coupon)
    {
        await _repository.CreateDiscount((coupon));

        return(CreatedAtRoute("GetDiscount", new { coupon.ProductName }, coupon));
    }
    public string GetCouponErrorMessage(Coupon coupon, CartItemGroup cartItemGroup)
    {
        HideAllControls();

        return(GetFormattedError(coupon, cartItemGroup));
    }
Exemplo n.º 42
0
        /// <summary>
        /// 处理回复消息
        /// "text":回复文本消息处理,MsgValue对应回复的文本
        /// "sub_auto_coupon":回复订阅自动优惠券处理,MsgValue对应回复的图文消息ID
        /// "auto_news_article":根据文章自动生成图文消息进行回复,MsgValue为类别ID
        /// "news":回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
        /// </summary>
        /// <param name="replyMsgType"></param>
        /// <param name="replyMsgValue"></param>
        /// <param name="customParams"></param>
        /// <returns></returns>
        private string ProcessReply(RequestMsgModel msgModel, string replyMsgType, string replyMsgValue)
        {
            string res = string.Empty;

            try
            {
                switch (replyMsgType.ToLower())
                {
                case "text":
                    //回复文本消息处理,MsgValue对应回复的文本
                    TextResponseMsgModel textMsg = new TextResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                    };
                    res = textMsg.ToString();
                    break;

                case "voice":
                    //回复语音消息处理,MsgValue对应回复的文本
                    VoiceResponseMsgModel voiceMsg = new VoiceResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                    };
                    Media media = MediaDAL.CreateInstance().GetMediaByID(replyMsgValue);
                    if (media != null && !string.IsNullOrEmpty(media.MediaID))
                    {
                        voiceMsg.MediaId = media.MediaID;
                    }
                    res = voiceMsg.ToString();
                    break;

                case "wxpay_test":
                    //用于微信支付测试
                    TextResponseMsgModel textMsgx = new TextResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        Content      = string.Format("<a href='{0}/Payment/wxpay/wxpayDemo.aspx?openid={1}'>微信支付测试</a>", GetSiteUrl(), msgModel.FromUserName)
                    };
                    res = textMsgx.ToString();
                    break;

                case "transfer_customer_service":
                    //将消息转发到多客服
                    TransferCustomerServiceResponseMsgModel transferMsg = new TransferCustomerServiceResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                    };
                    res = transferMsg.ToString();
                    break;

                case "sub_auto_coupon":
                    //回复订阅自动优惠券处理,MsgValue对应回复的优惠券图文消息ID
                    //SubscribeCouponActHandle sch = new SubscribeCouponActHandle();
                    SiteActivityDAL dal      = new SiteActivityDAL();
                    SiteActivity    activity = dal.GetSiteAct(siteCode, "Coupon");
                    if (activity != null)
                    {
                        CouponDAL cdal = new CouponDAL();
                        if (!cdal.ExistCoupon(siteCode, activity.ID, msgModel.FromUserName))
                        {
                            Coupon coupon = new Coupon()
                            {
                                SiteCode       = siteCode,
                                SiteActivityID = activity.ID,
                                OpenID         = msgModel.FromUserName,
                                //CouponCode = msgModel.FromUserName,
                                CouponStatus = 0
                            };
                            cdal.InsertInfo(coupon);
                        }
                    }
                    CouponNewsDAL nmDAL = new CouponNewsDAL();
                    CouponNews    nm    = nmDAL.GetCouponNews(replyMsgValue);
                    if (nm != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        articles.Add(new Article()
                        {
                            Title       = nm.Title,
                            Description = nm.Description,
                            PicUrl      = GetPicUrl(nm.PicUrl),
                            Url         = TransformUrl(nm.Url, msgModel)
                        });
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_coupon_category":
                    SiteActivityDAL dalCatList  = new SiteActivityDAL();
                    SiteActivity    activityCat = dalCatList.GetSiteAct(siteCode, "Coupon");
                    if (activityCat != null)
                    {
                        CouponDAL cdal = new CouponDAL();
                        if (!cdal.ExistCoupon(siteCode, activityCat.ID, msgModel.FromUserName))
                        {
                            Coupon coupon = new Coupon()
                            {
                                SiteCode       = siteCode,
                                SiteActivityID = activityCat.ID,
                                OpenID         = msgModel.FromUserName,
                                //CouponCode = msgModel.FromUserName,
                                CouponStatus = 0
                            };
                            cdal.InsertInfo(coupon);
                        }
                    }
                    ArticleDAL catDal = new ArticleDAL();
                    DataSet    cdsCat = catDal.GetCategoryList(siteCode, replyMsgValue);
                    if (cdsCat != null && cdsCat.Tables.Count > 0 && cdsCat.Tables[0] != null && cdsCat.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in cdsCat.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 30),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_news_article":
                    //根据文章自动生成图文消息进行回复,MsgValue为文章ID
                    ArticleDAL aDal = new ArticleDAL();
                    DataSet    ds   = aDal.GetArticleDetail(replyMsgValue);
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 100),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_news_category":
                    //根据类别自动生成图文消息进行回复,MsgValue为类别ID
                    ArticleDAL cDal = new ArticleDAL();
                    DataSet    cds  = cDal.GetCategoryList(siteCode, replyMsgValue);
                    if (cds != null && cds.Tables.Count > 0 && cds.Tables[0] != null && cds.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in cds.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 30),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "coupon":
                    //回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
                    NewsMsgDAL nmDAL1 = new NewsMsgDAL();
                    NewsMsg    nms    = nmDAL1.GetNewsMsg(replyMsgValue);
                    if (nms != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        articles.Add(new Article()
                        {
                            Title       = nms.Title,
                            Description = nms.Description,
                            PicUrl      = GetPicUrl(nms.PicUrl),
                            Url         = TransformUrl(nms.Url, msgModel)
                        });
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "news":
                    //回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
                    NewsMsgDAL      nmDALs   = new NewsMsgDAL();
                    IList <NewsMsg> newsMsgs = nmDALs.GetNewsMsgs(replyMsgValue);
                    if (newsMsgs != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (NewsMsg msg in newsMsgs)
                        {
                            articles.Add(new Article()
                            {
                                Title       = msg.Title,
                                Description = msg.Description,
                                PicUrl      = GetPicUrl(msg.PicUrl),
                                Url         = TransformUrl(msg.Url, msgModel)
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "url":
                    //根据文章自动生成图文消息进行回复,MsgValue为文章ID
                    DAL.SYS.AccountDAL dalUrl = new DAL.SYS.AccountDAL();
                    DataSet            dsUrl  = dalUrl.GetAccountExtData(replyMsgValue);
                    if (dsUrl != null && dsUrl.Tables.Count > 0 && dsUrl.Tables[0] != null && dsUrl.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in dsUrl.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Name"].ToString(),
                                Description = dr["Summary"].ToString(),
                                PicUrl      = GetPicUrl(dr["Photo"].ToString()),
                                Url         = GetSiteInfo(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "hp_photo_text":
                    //为当前hp_photo对应的照片附加文字信息
                    PhotoDAL photoDal = new PhotoDAL();
                    if (photoDal.ExistPhoto(siteCode, msgModel.FromUserName, 0))
                    {
                        TextRequestMsgModel temp = msgModel as TextRequestMsgModel;
                        string text = temp.Content.Replace("#ms", "");
                        //附加图片文字
                        photoDal.UpdateAttachText(siteCode, msgModel.FromUserName, text);
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                        };
                        res = textMsg2.ToString();
                    }
                    else
                    {
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = "对不起,您暂未参加图片打印活动!"
                        };
                        res = textMsg2.ToString();
                    }
                    break;

                case "hp_photo_ticket":
                    //对当前hp_photo对应的照片进行打印认证
                    PrintCodeDAL        printCodeDAL = new PrintCodeDAL();
                    TextRequestMsgModel temp1        = msgModel as TextRequestMsgModel;
                    string printCode = temp1.Content.Replace("#dy", "");
                    string clientID  = printCodeDAL.GetClientIDByPrintCode(printCode, siteCode);
                    ExceptionLogDAL.InsertExceptionLog(new ExceptionLog()
                    {
                        Message = clientID
                    });
                    if (!string.IsNullOrEmpty(clientID))
                    {
                        PhotoDAL photoDal1 = new PhotoDAL();
                        photoDal1.UpdatePrintInfo(printCode, clientID, siteCode, msgModel.FromUserName);
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                        };
                        res = textMsg2.ToString();
                        //TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        //{
                        //    ToUserName = msgModel.FromUserName,
                        //    FromUserName = msgModel.ToUserName,
                        //    CreateTime = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        //    Content = "照片打印中,请稍侯..."
                        //};
                        //res = textMsg2.ToString();
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                ExceptionLogDAL.InsertExceptionLog(ex);
            }
            return(res);
        }
Exemplo n.º 43
0
        //If SPM is configured to use Standalone Payment Processor, This will do refund instead of voiding
        private void btnVoid_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(_hostOrderID))
            {
                MessageBox.Show("Host Order ID not set.");
                return;
            }

            _request = new Request();
            _request.Clear();
            _request.ClerkID        = "1";
            _request.PosVersion     = "1.0";
            _request.PosStoreNumber = "crdnt400";

            Order voidOrder = _request.Order;

            //to void addpoint

            foreach (Card oldcard in _oldrequest.Cards)
            {
                if (oldcard.IsPromo) //there should be only one promo card in cards collection
                {
                    Card rewardcard = new Card();
                    rewardcard.GetSubwayCardData(SpmEnums.TransactionTypes.VoidPointsSubwayCard); // to get the card account ID which might not be saved in SubwayPOS
                    rewardcard.VoidReferenceNumber = oldcard.VoidReferenceNumber;
                    _request.AddCardPromo(rewardcard);
                }
            }

            //build line Item

            foreach (LineItem oldLineItem in _oldOrder.LineItems)
            {
                LineItem voidLineItem = voidOrder.LineItems.NewLineItem();
                voidLineItem.Amount   = oldLineItem.Amount;
                voidLineItem.PLU      = oldLineItem.PLU;
                voidLineItem.Currency = oldLineItem.Currency;
                //this may be ommitted if POS not uses
                foreach (AddOn oldAddon in oldLineItem.AddOns)
                {
                    voidLineItem.AddOns.Add(oldAddon.Key, oldAddon.Name, oldAddon.Value);
                }

                if (oldLineItem.LineItemType == SpmEnums.LineItemTypes.AddGift)
                {
                    voidLineItem.LineItemType = SpmEnums.LineItemTypes.AddGift;
                    Card voidgiftcard = new Card();
                    voidgiftcard.GetSubwayCardData(SpmEnums.TransactionTypes.GenericSubwayCard);
                    voidgiftcard.VoidReferenceNumber = oldLineItem.Card.VoidReferenceNumber;
                    voidLineItem.SetCard(voidgiftcard);
                }
                else if (oldLineItem.LineItemType == SpmEnums.LineItemTypes.Merchandise)
                {
                    voidLineItem.LineItemType = SpmEnums.LineItemTypes.Merchandise;
                }
                else
                {
                    voidLineItem.LineItemType = SpmEnums.LineItemTypes.Tax;
                }

                voidOrder.LineItems.AddLineItem(voidLineItem);
            }

            // build payments

            foreach (Payment oldPayment in _oldOrder.Payments)
            {
                Payment voidPayment = voidOrder.Payments.NewPayment();
                voidPayment.Currency   = oldPayment.Currency;
                voidPayment.Amount     = oldPayment.Amount;
                voidPayment.TenderType = oldPayment.TenderType;
                if (oldPayment.TenderType == TenderType.Cash)
                {
                }
                else if (oldPayment.TenderType == TenderType.CouponVoucher)
                {
                    Coupon voidcoupon = new Coupon();
                    voidcoupon.VoidReferenceNumber = oldPayment.Coupon.VoidReferenceNumber;
                    voidPayment.SetCoupon(voidcoupon);
                }
                else
                {
                    //credit card, debitcard , subway reward card for redeeming points, subway gift card set all here
                    if (!voidPayment.GetCardData(true)) // set IsVoid parameter to TRUE
                    {
                        MessageBox.Show("Failed");
                    }

                    if (oldPayment.TenderType == TenderType.GiftCard || oldPayment.TenderType == TenderType.RewardsCard)
                    {
                        if (voidPayment.Card.AccountIDLast4 != oldPayment.Card.AccountIDLast4)
                        {
                            //error handle here for only subway reward/gift cards incase there were multiple gift card used. you may wanna re prompt getcarddata or display error message
                            MessageBox.Show("Card number in not matched");
                        }
                    }

                    voidPayment.Card.VoidReferenceNumber = oldPayment.Card.VoidReferenceNumber;
                }

                voidOrder.Payments.AddPayment(voidPayment);
            }

            if (_request.VoidOrder())
            {
                MessageBox.Show(SPM.Resources.Strings.VoidTest_ResultStateVoidSuccess + _request.Response.ResultStatus.ToString() + "\n " + _request.Response.get_ReceiptText());
            }
            else
            {
                MessageBox.Show("Failed");
            }
        }
Exemplo n.º 44
0
        public IActionResult DetailsCoupon(int id)
        {
            Coupon coupon = _admin.GetCoupon(id);

            return(View(coupon));
        }
Exemplo n.º 45
0
        private static IList <OrderAdjustment> GetAdjustments(ICollection <Product> products, Coupon coupon, CreditCardType creditCardType)
        {
            var adjustments = new List <OrderAdjustment>();

            // Set up expected adjustments.

            var price         = products.Sum(product => product.Price);
            var initialPrice  = price;
            var adjustedPrice = price;

            if (coupon != null)
            {
                if (coupon.ProductIds != null)
                {
                    foreach (var product in products)
                    {
                        if (coupon.ProductIds.Contains(product.Id))
                        {
                            adjustedPrice = initialPrice - coupon.Discount.GetDiscount(product.Price);
                            adjustments.Add(new CouponAdjustment {
                                InitialPrice = initialPrice, AdjustedPrice = adjustedPrice, Amount = new PercentageAdjustmentAmount {
                                    PercentageChange = ((PercentageCouponDiscount)coupon.Discount).Percentage
                                }, CouponCode = coupon.Code, ProductId = product.Id
                            });
                            break;
                        }
                    }
                }
                else
                {
                    adjustedPrice = initialPrice - coupon.Discount.GetDiscount(initialPrice);
                    adjustments.Add(
                        new CouponAdjustment
                    {
                        InitialPrice  = initialPrice,
                        AdjustedPrice = adjustedPrice,
                        Amount        = coupon.Discount is PercentageCouponDiscount
                                    ? (AdjustmentAmount) new PercentageAdjustmentAmount {
                            PercentageChange = ((PercentageCouponDiscount)coupon.Discount).Percentage
                        }
                                    : new FixedAdjustmentAmount {
                            FixedChange = ((FixedCouponDiscount)coupon.Discount).Amount
                        },
                        CouponCode = coupon.Code
                    });
                }
            }

            if (products.Count > 1)
            {
                initialPrice  = adjustedPrice;
                adjustedPrice = initialPrice + (-1 * BundleDiscount * price);
                adjustments.Add(new BundleAdjustment {
                    InitialPrice = initialPrice, AdjustedPrice = adjustedPrice, Percentage = BundleDiscount
                });
            }

            initialPrice  = adjustedPrice;
            adjustedPrice = (1 + TaxRate) * adjustedPrice;
            adjustments.Add(new TaxAdjustment {
                InitialPrice = initialPrice, AdjustedPrice = adjustedPrice, TaxRate = TaxRate
            });

            if (creditCardType == CreditCardType.Amex)
            {
                initialPrice  = adjustedPrice;
                adjustedPrice = (1 + AmexSurcharge) * initialPrice;
                adjustments.Add(new SurchargeAdjustment {
                    InitialPrice = initialPrice, AdjustedPrice = adjustedPrice, Surcharge = AmexSurcharge, CreditCardType = creditCardType
                });
            }

            return(adjustments);
        }
Exemplo n.º 46
0
 public static void RemoveCoupon(this Coupon coupon)
 {
 }
Exemplo n.º 47
0
 public void Add(Coupon newCoupon)
 {
     _context.Coupons.Add(newCoupon);
     _context.SaveChanges();
 }
Exemplo n.º 48
0
        internal static BookingBill GetBookingBill(IEnumerable <RestaurantMenuItem> restaurantMenuItems, IEnumerable <RestaurantTable> restaurantTables, SeasonalOffer restaurantOffer, Coupon restaurantcoupon, int bookedslots)
        {
            var     discountamt = 0M;
            decimal grossamount = restaurantTables.Sum(restaurantTable => restaurantTable.Price * bookedslots);

            grossamount = restaurantMenuItems.Aggregate(grossamount, (current, restaurantMenuItem) => (int)(current + restaurantMenuItem.Price));

            var offer = (restaurantcoupon as OfferBase) ?? (restaurantOffer);

            var netamount = grossamount;

            if (offer != null)
            {
                switch (offer.Type)
                {
                case OfferBase.OfferType.DiscountAmount:
                {
                    discountamt = offer.Value;
                    netamount   = grossamount - discountamt;
                    if (netamount < 0)
                    {
                        netamount = 0;
                    }
                    break;
                }

                case OfferBase.OfferType.DiscountPercent:
                {
                    discountamt = (grossamount * offer.Value) / 100M;
                    netamount   = grossamount - discountamt;
                    break;
                }

                case OfferBase.OfferType.FreeServing:
                {
                    discountamt = new RestaurantMenuItemRepository().Find(offer.Value).Price;
                    netamount   = grossamount - discountamt;
                    break;
                }
                }
            }

            if (netamount < 0)
            {
                throw new InvalidOperationException("Discount amount cannot be more than the total amount of the Bill");
            }
            return(new BookingBill
            {
                DiscountAmount = discountamt,
                GrossAmount = grossamount,
                NetAmount = netamount
            });
        }
Exemplo n.º 49
0
 public void Edit(Coupon couponToEdit)
 {
     _context.Entry(couponToEdit).State = EntityState.Modified;
     _context.SaveChanges();
 }
Exemplo n.º 50
0
        private void ApplyCoupon()
        {
            ValidCouponMessage.Visible = false;
            string couponCode            = StringHelper.StripHtml(Request.Form[CouponCode.UniqueID]);
            Coupon coupon                = CouponDataSource.LoadForCouponCode(couponCode);
            String couponValidityMessage = String.Empty;

            InvalidCouponMessage.Text = "Invalid coupon code.";
            if (coupon != null)
            {
                ICouponCalculator couponCalculator = AbleContext.Resolve <ICouponCalculator>();
                if (!couponCalculator.IsCouponAlreadyUsed(AbleContext.Current.User.Basket, coupon))
                {
                    if (couponCalculator.IsCouponValid(AbleContext.Current.User.Basket, coupon, out couponValidityMessage))
                    {
                        Basket       basket       = AbleContext.Current.User.Basket;
                        BasketCoupon recentCoupon = new BasketCoupon(AbleContext.Current.User.Basket, coupon);
                        recentCoupon.AppliedDate = LocaleHelper.LocalNow;
                        basket.BasketCoupons.Add(recentCoupon);
                        // APPLY COUPON COMBINE RULE
                        //THE RULE:
                        //If most recently applied coupon is marked "do not combine", then all previously
                        //entered coupons must be removed from basket.

                        //If most recently applied coupon is marked "combine", then remove any applied
                        //coupon that is marked "do not combine".  (Logically, in this instance there
                        //could be at most one other coupon of this type...)
                        string previousCouponsRemoved = "";

                        if (recentCoupon.Coupon.AllowCombine)
                        {
                            //IF ALLOW COMBINE, REMOVE ALL PREVIOUS NOCOMBINE COUPONS
                            for (int i = (basket.BasketCoupons.Count - 1); i >= 0; i--)
                            {
                                if (!basket.BasketCoupons[i].Coupon.AllowCombine)
                                {
                                    if (previousCouponsRemoved.Length > 0)
                                    {
                                        previousCouponsRemoved += "," + basket.BasketCoupons[i].Coupon.Name;
                                    }
                                    else
                                    {
                                        previousCouponsRemoved = basket.BasketCoupons[i].Coupon.Name;
                                    }

                                    basket.BasketCoupons.DeleteAt(i);
                                }
                            }
                        }
                        else
                        {
                            //IF NOT ALLOW COMBINE, REMOVE ALL EXCEPT THIS COUPON
                            for (int i = (basket.BasketCoupons.Count - 1); i >= 0; i--)
                            {
                                if (basket.BasketCoupons[i] != recentCoupon)
                                {
                                    if (previousCouponsRemoved.Length > 0)
                                    {
                                        previousCouponsRemoved += "," + basket.BasketCoupons[i].Coupon.Name;
                                    }
                                    else
                                    {
                                        previousCouponsRemoved = basket.BasketCoupons[i].Coupon.Name;
                                    }
                                    basket.BasketCoupons.DeleteAt(i);
                                }
                            }
                        }

                        basket.Save();
                        IBasketService preCheckoutService = AbleContext.Resolve <IBasketService>();
                        preCheckoutService.Recalculate(basket);
                        if (previousCouponsRemoved.Length > 0)
                        {
                            if (recentCoupon.Coupon.AllowCombine)
                            {
                                CombineCouponRemoveMessage.Text    = String.Format(CombineCouponRemoveMessage.Text, recentCoupon.Coupon.Name, previousCouponsRemoved, previousCouponsRemoved);
                                CombineCouponRemoveMessage.Visible = true;
                            }
                            else
                            {
                                NotCombineCouponRemoveMessage.Text    = String.Format(NotCombineCouponRemoveMessage.Text, recentCoupon.Coupon.Name, previousCouponsRemoved);
                                NotCombineCouponRemoveMessage.Visible = true;
                            }
                        }
                        ValidCouponMessage.Visible = true;
                    }
                    else
                    {
                        InvalidCouponMessage.Text = couponValidityMessage + "<br /><br />";
                    }
                }
                else
                {
                    InvalidCouponMessage.Text = string.Format(InvalidCouponMessage.Text, "The coupon code you've entered is already in use.");
                }
            }
            else
            {
                InvalidCouponMessage.Text = string.Format(InvalidCouponMessage.Text, "The coupon code you've entered is invalid.");
            }
            InvalidCouponMessage.Visible = !ValidCouponMessage.Visible;
        }
Exemplo n.º 51
0
 public bool Exist(Coupon newCoupon)
 {
     return(_context.Coupons.Where(c => c.Id != newCoupon.Id).Any(c => c.Code == newCoupon.Code));
 }
Exemplo n.º 52
0
        public async Task OnGet()
        {
            CategoryDTO categoryDTO = new CategoryDTO()
            {
                Tittle = "Food2"
            };
            Category category = new Category(_mapper, _categoryEFService);

            categoryDTO.CategoryId = await category.CreateNewCategoryAsync(categoryDTO);

            ProductDTO productAppleDTO = new ProductDTO()
            {
                CategoryId = categoryDTO.CategoryId,
                Price      = 100,
                Tittle     = "Apple"
            };

            ProductDTO productAlmondDTO = new ProductDTO()
            {
                CategoryId = categoryDTO.CategoryId,
                Price      = 150,
                Tittle     = "Almond"
            };

            Product product = new Product(_mapper, _productEFService);

            productAppleDTO.ProductId = await product.CreateProductAsync(productAppleDTO);

            productAlmondDTO.ProductId = await product.CreateProductAsync(productAlmondDTO);

            Cart cart = new Cart(_cartEFService, _mapper, _productEFService, _categoryEFService);

            CartDetailDTO cartDetailDTO1 = new CartDetailDTO()
            {
                ProductId       = productAlmondDTO.ProductId,
                ProductQuantity = 3
            };

            CartDetailDTO cartDetailDTO2 = new CartDetailDTO()
            {
                ProductId       = productAppleDTO.ProductId,
                ProductQuantity = 1
            };

            CartDTO cartDTO = new CartDTO()
            {
                CustomerId = 1
            };

            cartDTO.CartId = await cart.CreateCartAsync(cartDTO);

            await cart.AddItemAsync(cartDTO.CartId, productAppleDTO, 3);

            List <CampaignDTO> campaigns = new List <CampaignDTO>();

            CampaignDTO campaignDTO1 = new CampaignDTO()
            {
                CategoryId   = categoryDTO.CategoryId,
                Discount     = 20,
                DiscountType = DiscountType.Rate,
                Quantity     = 3
            };
            CampaignDTO campaignDTO2 = new CampaignDTO()
            {
                CategoryId   = categoryDTO.CategoryId,
                Discount     = 50,
                DiscountType = DiscountType.Rate,
                Quantity     = 5
            };
            CampaignDTO campaignDTO3 = new CampaignDTO()
            {
                CategoryId   = categoryDTO.CategoryId,
                Discount     = 5,
                DiscountType = DiscountType.Amount,
                Quantity     = 5
            };

            Campaign campaign = new Campaign(_mapper, _campaignEFService);

            campaignDTO1.CampaignId = await campaign.CreateCampaignAsync(campaignDTO1);

            campaignDTO2.CampaignId = await campaign.CreateCampaignAsync(campaignDTO2);

            campaignDTO3.CampaignId = await campaign.CreateCampaignAsync(campaignDTO3);

            campaigns.Add(campaignDTO1);
            campaigns.Add(campaignDTO2);
            campaigns.Add(campaignDTO3);

            await cart.ApplyCampaignDiscountAsync(cartDTO, campaigns);

            CouponDTO couponDTO = new CouponDTO()
            {
                Discount        = 10,
                DiscountType    = ECommerce.Business.Models.DiscountType.Rate,
                MinimumCartCost = 100
            };

            Coupon coupon = new Coupon(_mapper, _couponEFService);

            couponDTO.CouponId = await coupon.CreateNewCouponAsync(couponDTO);

            await cart.ApplyCouponDiscountAsync(cartDTO, couponDTO);

            Delivery delivery        = new Delivery(_deliveryEFService, _cartEFService, _productEFService, _categoryEFService, _mapper);
            double   costPerDelivery = _configuration.GetValue <double>("CostPerDelivery");
            double   costPerProduct  = _configuration.GetValue <double>("CostPerProduct");
            double   fixedCost       = _configuration.GetValue <double>("FixedCost");
            double   deliveryCost    = await delivery.CalculateDeliveryCostAndCountAsync(cartDTO.CartId, costPerDelivery, costPerProduct, fixedCost);

            double cartAmount = await cart.GetTotalAmountAfterDiscountsAsync(cartDTO);

            double couponDiscount = await cart.GetCouponDiscountAsync(cartDTO);

            double campaignDiscount = await cart.GetCampaignDiscountAsync(cartDTO);

            double getDeliveryCost = await delivery.GetDeliveryCostAsync(cartDTO);

            IList <PrintModel> printModels = await cart.PrintAsync(cartDTO);
        }
Exemplo n.º 53
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Coupon obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Exemplo n.º 54
0
 public async Task InsertAsync(Coupon entity)
 {
     couponRepository.Insert(entity);
     await unitOfWork.SaveChangesAsync();
 }
        public async Task <IActionResult> CheckoutBasketAsync([FromBody] BasketCheckout basketCheckout)
        {
            try
            {
                //based on basket checkout, fetch the basket lines from repo
                var basket = await basketRepository.GetBasketById(basketCheckout.BasketId);

                if (basket == null)
                {
                    return(BadRequest());
                }

                var basketCheckoutMessage = mapper.Map <BasketCheckoutMessage>(basketCheckout);
                basketCheckoutMessage.BasketLines = new List <BasketLineMessage>();
                int total = 0;

                foreach (var b in basket.BasketLines)
                {
                    var basketLineMessage = new BasketLineMessage
                    {
                        BasketLineId = b.BasketLineId,
                        Price        = b.Price,
                        TicketAmount = b.TicketAmount
                    };

                    total += b.Price * b.TicketAmount;

                    basketCheckoutMessage.BasketLines.Add(basketLineMessage);
                }

                //apply discount by talking to the discount service
                Coupon coupon = null;

                //var userId = basketCheckout.UserId;

                // var userId = Guid.Parse(HttpContext.Request.Headers["CurrentUser"][0]);

                var userId = Guid.Parse(User.Claims.FirstOrDefault(c => c.Type == "sub")?.Value);

                if (!(userId == Guid.Empty))
                {
                    coupon = await discountService.GetCoupon(userId);
                }

                if (coupon != null)
                {
                    basketCheckoutMessage.BasketTotal = total - coupon.Amount;
                }
                else
                {
                    basketCheckoutMessage.BasketTotal = total;
                }

                var incomingToken = await HttpContext.GetTokenAsync("access_token");

                var accessTokenForOrderingService = await tokenExchangeService.GetTokenAsync(
                    incomingToken,
                    "ordering.fullaccess");

                basketCheckoutMessage.SecurityContext.AccessToken = accessTokenForOrderingService;

                try
                {
                    await messageBus.PublishMessage(basketCheckoutMessage, "checkoutmessage");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }

                await basketRepository.ClearBasket(basketCheckout.BasketId);

                return(Accepted(basketCheckoutMessage));
            }
            catch (BrokenCircuitException ex)
            {
                string message = ex.Message;
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.StackTrace));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, e.StackTrace));
            }
        }
    private string GetApplicableProductListText(Coupon coupon, string productListType)
    {
        string message = String.Empty;

        switch (productListType)
        {
        case "all_product":
        {
            message = "<ul>";
            foreach (Product product in coupon.GetApplicableProducts(StoreContext.Culture))
            {
                if (!String.IsNullOrEmpty(product.Name))
                {
                    message += "<li>" + product.Name + "</li> ";
                }
            }
            message += "</ul>";
        }
        break;

        case "match_product":
        {
            if (GetCouponDiscount(coupon) > 0)
            {
                ICartItem[] cart = StoreContext.ShoppingCart.GetCartItems();
                int         productDiscoutableItemCount = 0;

                if (coupon.ProductFilter != Coupon.ProductFilterEnum.All)
                {
                    message = "<ul>";
                    for (int i = 0; i < cart.Length; i++)
                    {
                        if (coupon.IsProductDiscountable(cart[i].Product) &&
                            cart[i].DiscountGroupID == "0" &&
                            cart[i].Quantity > coupon.MinimumQuantity)
                        {
                            message += "<li>"
                                       + cart[i].GetName(StoreContext.Culture, StoreContext.Currency)
                                       + "</li>";
                            productDiscoutableItemCount++;
                        }
                    }
                    message += "</ul>";
                    if (productDiscoutableItemCount == cart.Length)
                    {
                        message = string.Empty;
                    }
                }
            }
        }
        break;

        case "not_match_product":
        {
            if (GetCouponDiscount(coupon) == 0)
            {
                ICartItem[] cart = StoreContext.ShoppingCart.GetCartItems();

                message = "<ul>";
                for (int i = 0; i < cart.Length; i++)
                {
                    if (coupon.IsProductDiscountable(cart[i].Product) &&
                        cart[i].DiscountGroupID == "0")
                    {
                        message += "<li>"
                                   + cart[i].GetName(StoreContext.Culture, StoreContext.Currency)
                                   + "</li>";
                    }
                }
                message += "</ul>";
            }
        }
        break;
        }
        return(message);
    }
Exemplo n.º 57
0
    private void editRow(int recordId)
    {
        LblOk.Text = "";
        LblErr.Text = "";

        clearForm();
        base.CurrentId = recordId;
        if (base.CurrentId > 0)
        {
            Coupon obj = new Coupon();
            obj = new CouponsManager().GetByKey(base.CurrentId);
            obj2form(obj);
        }
        MultiView1.ActiveViewIndex = 1;
    }
Exemplo n.º 58
0
 public void GotCouponNotification(Coupon p0, TrackingInfo p1)
 {
     Console.WriteLine("GotCouponNotification ", p0.NotificationMessage);
 }
Exemplo n.º 59
-1
        public void Coupon_Create()
        {
            // Arrange
            var productFamily = Chargify.GetProductFamilyList().Values.FirstOrDefault();
            string couponCode = Guid.NewGuid().ToString().Replace("-",string.Empty).ToUpperInvariant().Substring(0, 8);
            var newCoupon = new Coupon()
            {
                AllowNegativeBalance = false,
                Code = couponCode,
                Description = couponCode + " description",
                DurationPeriodCount = 2,
                EndDate = DateTime.Today.AddDays(5),
                IsRecurring = true,
                Name = "coupon " + couponCode,
                Percentage = 50,
                AmountInCents = 0
            };

            // Act
            var createdCoupon = Chargify.CreateCoupon(newCoupon, productFamily.ID);

            // Assert
            Assert.IsNotNull(createdCoupon);
            //Assert.IsInstanceOfType(createdCoupon, typeof(ICoupon));
            Assert.IsTrue(createdCoupon.AllowNegativeBalance == newCoupon.AllowNegativeBalance);
            Assert.IsTrue(createdCoupon.Name == newCoupon.Name);
            Assert.IsTrue(createdCoupon.Description == newCoupon.Description);
            Assert.IsTrue(createdCoupon.Code == newCoupon.Code);
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try {
            int couponId = 0;
            int.TryParse(lblCouponId.Text, out couponId);
            Coupon coupon;
            if(couponId == 0) {
              coupon = new Coupon();
            }
            else {
              coupon = new Coupon(couponId);
            }

            PercentOffCouponProvider percentOffCouponProvider = new PercentOffCouponProvider();
            decimal percentOff = 0M;
            decimal.TryParse(txtPercentOff.Text, out percentOff);
            percentOffCouponProvider.PercentOff = percentOff;
            if (string.IsNullOrEmpty(txtCouponCode.Text)) {
              coupon.CouponCode = CoreUtility.GenerateRandomString(8);
            }
            else {
              coupon.CouponCode = txtCouponCode.Text;
            }
            DateTime expirationDate = DateTime.UtcNow;
            DateTime.TryParse(txtExpirationDate.Text, out expirationDate);
            coupon.ExpirationDate = expirationDate;
            coupon.IsSingleUse = chkIsSingleUse.Checked;
            coupon.Type = percentOffCouponProvider.GetType().AssemblyQualifiedName;
            coupon.ValueX = new Serializer().SerializeObject(percentOffCouponProvider, typeof(PercentOffCouponProvider));
            coupon.Save(WebUtility.GetUserName());
            Response.Redirect("~/admin/coupons.aspx", true);
              }
              catch(Exception ex) {
            Logger.Error(typeof(percentoffconfiguration).Name + ".btnSave_Click", ex);
            base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message);
              }
        }