Ejemplo n.º 1
0
        public bool UpdateOrderDiscount(OrderDiscount orderDiscount)
        {
            int result = 0;

            result = ExecuteUpdate("UpdateOrderDiscount", orderDiscount);
            return(result > 0);
        }
        public ActionResult Save()
        {
            var orderDiscount = new OrderDiscount().BindData(DATA);

            if (!IsValidate(orderDiscount))
            {
                return(GetResultOrReferrerDefault(defauthPath));
            }
            var eventMoney     = Utils.GetString(DATA, "EventMoney").Replace(",", string.Empty);
            var totalMoney     = Utils.GetString(DATA, "TotalMoney").Replace(",", string.Empty);
            var realTotalMoney = Utils.GetString(DATA, "RealTotalMoney").Replace(",", string.Empty);
            var idOrders       = Utils.GetInts(DATA, "IDOrder", IsAjax);

            orderDiscount.Event     = long.Parse(eventMoney);
            orderDiscount.Total     = long.Parse(totalMoney);
            orderDiscount.RealTotal = long.Parse(realTotalMoney);
            orderDiscount.IDOrders  = Utils.GetStringJoin(",", idOrders);
            if (OrderDiscountRepository.UseInstance.Insert(orderDiscount))
            {
                SetSuccess("Tạo đơn chiết khấu hóa thành công");
            }
            else
            {
                SetError("Tạo mới đon chiết khấu không thành công");
            }
            return(GetResultOrReferrerDefault(defauthPath));
        }
Ejemplo n.º 3
0
        public bool DeleteOrderDiscount(Guid orderId, Guid discountId)
        {
            var orderDiscount = new OrderDiscount()
            {
                OrderId    = orderId,
                DiscountId = discountId,
                Quantity   = 1
            };
            string jsonBody = JsonConvert.SerializeObject(orderDiscount);
            var    request  = new RestRequest("api/crud/OrderDiscount");

            request.AddHeader("sessionId", SessionId);
            request.AddParameter("application/json; charset=utf-8", jsonBody, ParameterType.RequestBody);
            var response = Client.Delete(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(true);
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                Console.WriteLine("Brak uprawnień");
                return(false);
            }
            else
            {
                Console.WriteLine("Błędne parametry");
                return(false);
            }
        }
        public void GivenAnOrderDiscount_WhenApplyToNonOrder_ThenShouldReturnZero()
        {
            var sut = new OrderDiscount("d", 1);
            var line = new Line(new Bike(string.Empty, string.Empty, 1), 1);

            Assert.AreEqual(0, sut.Apply(line));
        }
 private bool IsValidate(OrderDiscount orderDiscount)
 {
     if (orderDiscount.IDCustomer <= 0)
     {
         SetError("Bạn chưa chọn khách hàng");
     }
     return(!HasError);
 }
        public void Setup()
        {
            IOC.IntegrationTest();

            _orderInfo = DefaultFactoriesAndSharedFunctionality.CreateIncompleteOrderInfo(DefaultFactoriesAndSharedFunctionality.CreateProductInfo(1000, 1));

            _orderDiscount = DefaultFactoriesAndSharedFunctionality.CreateDefaultOrderDiscountWithAmount(195, DiscountOrderCondition.None, 0);
        }
        public static DiscountOrder ToDiscountOrder(this OrderDiscount orderDiscount)
        {
            //return new OrderDiscount { OriginalId = 1235, DiscountType = DiscountType.Amount, DiscountValue = amountInCents, CouponCode = "", NumberOfItemsCondition = setSize, Condition = orderCondition, RequiredItemIds = new List<int> { }, MemberGroups = new List<string>(), MinimalOrderAmount = 0, AffectedOrderlines = new List<int>() };

            return(new DiscountOrder {
                AffectedOrderlines = orderDiscount.AffectedOrderlines, Id = orderDiscount.Id, Condition = orderDiscount.Condition, CounterEnabled = orderDiscount.CounterEnabled, CouponCode = orderDiscount.CouponCode, DiscountType = orderDiscount.DiscountType, DiscountValue = orderDiscount.DiscountValue, Disabled = orderDiscount.Disabled, NumberOfItemsCondition = orderDiscount.NumberOfItemsCondition, MemberGroups = orderDiscount.MemberGroups, RequiredItemIds = orderDiscount.RequiredItemIds, MinimalOrderAmount = orderDiscount.MinimalOrderAmount, Localization = orderDiscount.Localization
            });
        }
        public void GivenAnOrderDiscount_WhenApplyToOrder_ThenShouldReturnOrderSubTotalTimesPercentage()
        {
            var sut = new OrderDiscount("d", 1);
            var order = new Order(string.Empty);

            order.AddLine(new Line(new Bike(string.Empty, string.Empty, 1), 1));

            Assert.AreEqual(order.CalculateSubTotal() * sut.Percentage, sut.Apply(order));
        }
Ejemplo n.º 9
0
 private InvoiceDiscount GetInvoiceDiscount(OrderDiscount orderDiscount)
 {
     return(new InvoiceDiscount
     {
         DiscountType = orderDiscount.DiscountType,
         DiscountCode = orderDiscount.DiscountCode,
         DiscountComment = orderDiscount.DiscountComment,
         Discount = orderDiscount.Discount
     });
 }
Ejemplo n.º 10
0
        private bool ModifyForOrder(List <OrderPayoff> orderPayoffList, decimal paymentMoney, decimal needChangePay)
        {
            //填充Order
            Order order = new Order();

            order.OrderID         = m_SalesOrder.order.OrderID;
            order.TotalSellPrice  = m_TotalPrice;
            order.ActualSellPrice = m_ActualPayMoney;
            order.DiscountPrice   = m_Discount;
            order.CutOffPrice     = m_CutOff;
            order.ServiceFee      = m_ServiceFee;
            order.PaymentMoney    = paymentMoney;
            order.NeedChangePay   = needChangePay;
            order.EmployeeID      = ConstantValuePool.CurrentEmployee.EmployeeID;
            //填充OrderDetails\OrderDiscount
            List <OrderDetails>  orderDetailsList  = new List <OrderDetails>();
            List <OrderDiscount> orderDiscountList = new List <OrderDiscount>();

            for (int i = 0; i < dgvGoodsOrder.RowCount; i++)
            {
                Discount itemDiscount = dgvGoodsOrder.Rows[i].Cells["GoodsDiscount"].Tag as Discount;
                if (itemDiscount != null)
                {
                    decimal itemDiscountPrice = Convert.ToDecimal(dgvGoodsOrder.Rows[i].Cells["GoodsDiscount"].Value);

                    OrderDetails orderDetails = CopyExtension.Clone <OrderDetails>(m_SalesOrder.orderDetailsList[i]);
                    orderDetails.TotalDiscount = itemDiscountPrice;
                    orderDetailsList.Add(orderDetails);
                    //OrderDiscount
                    OrderDiscount orderDiscount = new OrderDiscount();
                    orderDiscount.OrderDiscountID = Guid.NewGuid();
                    orderDiscount.OrderID         = m_SalesOrder.order.OrderID;
                    orderDiscount.OrderDetailsID  = orderDetails.OrderDetailsID;
                    orderDiscount.DiscountID      = itemDiscount.DiscountID;
                    orderDiscount.DiscountName    = itemDiscount.DiscountName;
                    orderDiscount.DiscountType    = itemDiscount.DiscountType;
                    orderDiscount.DiscountRate    = itemDiscount.DiscountRate;
                    orderDiscount.OffFixPay       = itemDiscount.OffFixPay;
                    orderDiscount.OffPay          = Math.Abs(itemDiscountPrice);
                    orderDiscount.EmployeeID      = ConstantValuePool.CurrentEmployee.EmployeeID;
                    orderDiscountList.Add(orderDiscount);
                }
            }
            ModifiedPaidOrder modifiedPaidOrder = new ModifiedPaidOrder();

            modifiedPaidOrder.order             = order;
            modifiedPaidOrder.orderDetailsList  = orderDetailsList;
            modifiedPaidOrder.orderDiscountList = orderDiscountList;
            modifiedPaidOrder.orderPayoffList   = orderPayoffList;
            return(ModifyOrderService.GetInstance().ModifyForOrder(modifiedPaidOrder));
        }
Ejemplo n.º 11
0
 public void Setup()
 {
     IOC.UnitTest();
     IOC.SettingsService.InclVat();
     _discountCalculationService = IOC.DiscountCalculationService.Actual().Resolve();
     _discount = DefaultFactoriesAndSharedFunctionality.CreateDefaultOrderDiscountWithPercentage(50);
     _discount.MemberGroups = new List <string> {
         "testGroup"
     };
     _orderInfo = DefaultFactoriesAndSharedFunctionality.CreateOrderInfo(
         DefaultFactoriesAndSharedFunctionality.CreateProductInfo(1000, 1));
     DefaultFactoriesAndSharedFunctionality.SetDiscountsOnOrderInfo(_orderInfo, _discount);
     _mock = IOC.AuthenticationProvider.SetupNewMock();
 }
Ejemplo n.º 12
0
 public void CreateOrderDiscount(OrderDiscount orderDiscount)
 {
     try
     {
         _daoManager.OpenConnection();
         _orderDiscountDao.CreateOrderDiscount(orderDiscount);
     }
     catch (Exception exception)
     {
         LogHelper.GetInstance().Error(string.Format("[CreateOrderDiscount]参数:orderDiscount_{0}", JsonConvert.SerializeObject(orderDiscount)), exception);
     }
     finally
     {
         _daoManager.CloseConnection();
     }
 }
Ejemplo n.º 13
0
        private void CreateOrderDiscount()
        {
            var rnd          = new Random();
            var percentValue = rnd.Next(1, 99);

            OrderDiscount = new OrderDiscount(
                Fixture.Create <string>(),
                Fixture.Create <string>(),
                Fixture.Create <string>(),
                Fixture.Create <string>(),
                percentValue,
                DateTime.Now,
                DateTime.Now.AddDays(5),
                Fixture.Create <string>()
                );
        }
        public async Task AddAsync(string name, string nameEng, string description, string descriptionEng, int percentValue,
                                   DateTime availableFrom, DateTime availableTo, string code)
        {
            var existingDiscount = await orderDiscountRepository.GetByCodeAsync(code);

            if (existingDiscount != null)
            {
                throw new StreetwoodException(ErrorCode.DiscountWithThisCodeExistAlready);
            }

            var discount = new OrderDiscount(name, nameEng, description, descriptionEng, percentValue,
                                             availableFrom, availableTo, code);

            await orderDiscountRepository.AddAsync(discount);

            await orderDiscountRepository.SaveChangesAsync();
        }
Ejemplo n.º 15
0
        public bool UpdateOrderDiscount(OrderDiscount orderDiscount)
        {
            bool result = false;

            try
            {
                _daoManager.OpenConnection();
                result = _orderDiscountDao.UpdateOrderDiscount(orderDiscount);
            }
            catch (Exception exception)
            {
                LogHelper.GetInstance().Error(string.Format("[UpdateOrderDiscount]参数:orderDiscount_{0}", JsonConvert.SerializeObject(orderDiscount)), exception);
            }
            finally
            {
                _daoManager.CloseConnection();
            }
            return(result);
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            Order order1 = new Order("Zakup ciągnika ", 2000.0, true);
            Order order2 = new Order("Zakup walca ", 3000.0, false);
            Order order3 = new Order("Zakup glebogryzarki", 80.0, true);

            OrderDiscount discount     = new OrderDiscount();
            FileLogger    fileLogger   = new FileLogger();
            OrderService  orderService = new OrderService(discount, fileLogger);

            orderService.Add(order1);
            orderService.Add(order2);
            orderService.Add(order3);

            Console.WriteLine(orderService.GetAll());
            Console.WriteLine(fileLogger.ReadLogs());

            Console.ReadLine();
        }
        public List <OrderDiscount> GetOrderDiscountList()
        {
            List <OrderDiscount> result = new List <OrderDiscount>();

            using var connection = GetOpenedSqlConnection();
            var command = connection.CreateCommand();

            command.CommandType = CommandType.Text;
            command.CommandText = @"
                SELECT 
                    Id, 
                    Discount 
                FROM dbo.[Order] 
                ORDER BY Id ASC";

            using SqlDataReader reader = command.ExecuteReader();

            if (!reader.HasRows)
            {
                return(result);
            }

            int idColumnIndex       = reader.GetOrdinal("Id");
            int discountColumnIndex = reader.GetOrdinal("Discount");

            while (reader.Read())
            {
                var id = reader.GetInt32(idColumnIndex);

                double discount = 0;
                if (!reader.IsDBNull(discountColumnIndex))
                {
                    discount = reader.GetDouble(discountColumnIndex);
                }

                var orderDiscount = new OrderDiscount(id, discount);
                result.Add(orderDiscount);
            }

            return(result);
        }
        public async Task <Order> AddAsync(User user, IList <ProductOrder> productOrders, Shipment shipment,
                                           OrderDiscount orderDiscount, string comment, Address address)
        {
            var productNames = string.Join(", ", productOrders.Select(s => s.Product).Select(s => s.Name));

            logger.Info($"Creating new order for products: {productNames}");

            if (!productOrders.Any())
            {
                throw new StreetwoodException(ErrorCode.NoProductsForNewOrder);
            }

            var basePrice = productOrders.Sum(s => (s.CurrentProductPrice + s.CharmsPrice) * s.Amount);

            if (basePrice <= 0)
            {
                throw new StreetwoodException(ErrorCode.OrderBasePriceBelowZero);
            }

            var finalPrice = productOrders.Sum(s => s.FinalPrice * s.Amount);

            if (orderDiscount != null)
            {
                var discountValue = (orderDiscount.PercentValue / 100M) * finalPrice;
                finalPrice -= discountValue;
            }

            var order = new Order(user, productOrders, orderDiscount, shipment, basePrice, finalPrice, comment, address);

            logger.Info($"Trying add order {order.Id}, with base price {basePrice}...");

            await orderRepository.AddAsync(order);

            await orderRepository.SaveChangesAsync();

            logger.Info($"Order id: {order.Id} added successfully !!!");

            return(order);
        }
Ejemplo n.º 19
0
        public async Task <Order> CreateOrderAsync(User user, IList <ProductOrder> productOrders, Shipment shipment, Payment payment,
                                                   OrderDiscount orderDiscount, string comment, Address address)
        {
            if (!productOrders.Any())
            {
                throw new ArgumentException("Empty product orders");
            }

            var productNames = string.Join(", ", productOrders.Select(s => s.Product).Select(s => s.Name));

            logger.LogInformation($"Creating new order for products: {productNames}");

            var basePrice = productOrders.Sum(s => (s.CurrentProductPrice + s.CharmsPrice) * s.Amount);

            if (basePrice <= 0)
            {
                throw new Exception("Order base price is below 0.");
            }

            var finalPrice = productOrders.Sum(s => s.FinalPrice * s.Amount);

            if (orderDiscount != null)
            {
                var discountValue = (orderDiscount.PercentValue / 100M) * finalPrice;
                finalPrice -= discountValue;
            }

            var order = new Order(user, productOrders, orderDiscount, shipment, payment, basePrice, finalPrice, comment, address);

            logger.LogInformation($"Trying add order {order.Id}, with base price {basePrice}...");

            await ordersRepository.AddAsync(order);

            await ordersRepository.SaveChangesAsync();

            logger.LogInformation($"Order id: {order.Id} added successfully !!!");

            return(order);
        }
        private static Order CreateOrder()
        {
            var fixture       = new Fixture();
            var discountStart = fixture.Create <DateTime>();
            var orderDiscount = new OrderDiscount(
                fixture.Create <string>(),
                fixture.Create <string>(),
                fixture.Create <string>(),
                fixture.Create <string>(),
                fixture.Create <int>(),
                discountStart,
                discountStart.AddDays(5),
                fixture.Create <string>());

            return(new Order(
                       fixture.Create <User>(),
                       fixture.Create <IEnumerable <ProductOrder> >(),
                       orderDiscount,
                       fixture.Create <Shipment>(),
                       fixture.Create <decimal>(),
                       fixture.Create <decimal>(),
                       fixture.Create <string>(),
                       fixture.Create <Address>()));
        }
        public void GivenAnOrderDiscount_WhenIsApplicableOnNonOrder_ThenShouldReturnFalse()
        {
            var sut = new OrderDiscount("d", 1);

            Assert.IsFalse(sut.IsApplicable(new Line(new Bike(string.Empty, string.Empty, 1), 1)));
        }
        public void GivenAnOrderDiscount_WhenIsApplicableOnOrder_ThenShouldReturnTrue()
        {
            var sut = new OrderDiscount("d", 1);

            Assert.IsTrue(sut.IsApplicable(new Order(string.Empty)));
        }
Ejemplo n.º 23
0
        public async Task<int> AddOrder(Order order, List<Cart> cartItems, string shoppingCartId, string currentUserId)
        {
            int memberId = 0;
            int fatherMeberId = 0;
            int motherMemberId = 0;
            List<int> childMemberIds = new List<int>();
            using (var dbContextTransaction = _db.Database.BeginTransaction())
            {
                try
                {
                    decimal orderTotal = 0;
                    var dbOrder = CreateOrder(order);
                    dbOrder.AspNetUserId = currentUserId;
                    _db.Orders.Add(dbOrder);
                    await _db.SaveChangesAsync();
                    order.OrderId = dbOrder.OrderId;
                    //List<OrderDetail> orderDetails;
                    foreach (var item in cartItems)
                    {
                        var js = item.ToJson();
                        
                         var orderDetail = CreateOrderDetail(order, item);
                        order.OrderDetails.Add(orderDetail);
                        // Set the order total of the shopping cart
                        orderTotal += (item.Count * item.ItemPrice);
                        
                        //order.OrderDetails.Add(orderDetail);
                        await SaveOrderDetails(orderDetail);

                        cfcusaga.domain.Membership.Member aMember = null;
                        if (item.CategoryId == (int)Enums.CategoryTypeEnum.Registration && !item.MemberId.HasValue)
                        {
                            aMember = CreateMember(item);
                            if (item.RelationToMemberTypeId == (int)Enums.RelationToMe.Self)
                            {
                                if (aMember.AspNetUserId == null)
                                {
                                    aMember.AspNetUserId = currentUserId;
                                }
                            }
                            await AddMemberDetails(aMember);
                            if (item.RelationToMemberTypeId == (int) Enums.RelationToMe.Self || item.RelationToMemberTypeId == (int)Enums.RelationToMe.Spouse)
                            {
                                memberId = aMember.Id;
                                if (item.Gender == "M")
                                {
                                    fatherMeberId = memberId;
                                }
                                if (item.Gender == "F")
                                {
                                    motherMemberId = memberId;
                                }

                                //UpdateCurrentUserMemberId(aMember.Id);
                            }
                            else if (item.RelationToMemberTypeId == (int)Enums.RelationToMe.Child)
                            {
                                childMemberIds.Add(aMember.Id);
                            }
                        }
                        if (item.CategoryId == (int)Enums.CategoryTypeEnum.Registration && aMember != null)
                        {
                            await AddEventRegistrations(aMember, order, item);
                        }
                        // _svc.RemoveItemRegistration(item.Id
                    }
                    foreach (var childMemberId in childMemberIds)
                    {
                        UpdateChildMemberParentIds(childMemberId, motherMemberId, fatherMeberId);
                    }
                    UpdateHeadOfFamily(fatherMeberId, motherMemberId);
                    UpdateSpouseId(motherMemberId, fatherMeberId);
                    // Set the order's total to the orderTotal count
                    order.Total = orderTotal;

                    var member = await  GetMemberInfoFromAspNetUserId(currentUserId);
                    if (member != null)
                    {
                        dbOrder.MemberId = member.Id;
                    }

                    var discounts = await GetCartDiscounts(shoppingCartId);
                    decimal discountsTotal = 0;
                    foreach (var discount in discounts)
                    {
                        var orderDiscount = new OrderDiscount()
                        {
                            OrderId = order.OrderId,
                            DiscountId = discount.DiscountId,
                            Name = discount.Name,
                            Discount = discount.Discount,
                            Quantity =  discount.Quantity
                        };
                        order.OrderDiscounts.Add(orderDiscount);
                        await AddOrderDiscounts(order, discount);
                         discountsTotal = (discount.Discount*discount.Quantity);
                    }

                    //TODO: Clean the 
                    //order.OrderDetails
                    order.Total = order.Total - discountsTotal;
                    dbOrder.Total = order.Total;
                    await SaveChangesAsync();
                    // Empty the shopping cart
                    EmptyCart(shoppingCartId);


                    dbContextTransaction.Commit();
                }
                catch (Exception ex)
                {
                    var msg = ex.Message;
                    dbContextTransaction.Rollback();
                    throw;
                }
            }
            return memberId;
        }
Ejemplo n.º 24
0
 public void CreateOrderDiscount(OrderDiscount orderDiscount)
 {
     ExecuteInsert("InsertOrderDiscount", orderDiscount);
 }