Ejemplo n.º 1
0
        public async Task <RedirectToRouteResult> DeleteAddress(int addressId)
        {
            ShoppingAddress address = addressRepository.FindById(addressId);
            String          userId  = address.UserID;

            addressRepository.Delete(address);
            await addressRepository.Save();

            return(RedirectToAction("List", new { userId = userId }));
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> Add(ShoppingAddress address)
        {
            if (ModelState.IsValid)
            {
                addressRepository.Add(address);
                await addressRepository.Save();

                return(RedirectToAction("Confirm", "Order", new { addressId = address.ShoppingAddressID }));
            }

            return(View(address));
        }
        public async Task Cannot_Add_Invalid_Address()
        {
            AddressController addressCtrl = new AddressController(addressRepo);

            addressCtrl.ModelState.AddModelError("error", "error message");
            ViewResult result = await addressCtrl.Add(new ShoppingAddress
            {
                ShoppingAddressID = 11,
                UserID            = "#939521",
                Line1             = "Pine Rd"
            }) as ViewResult;

            Assert.IsNotNull(result);

            ShoppingAddress address = (ShoppingAddress)result.Model;

            Assert.AreEqual(11, address.ShoppingAddressID);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 添加地址
        /// </summary>
        /// <param name="mod"></param>
        /// <returns></returns>
        public ShoppingAddress AddAddress(User_AddressDTO mod, string userId)
        {
            var             li   = EF.UserInfos.FirstOrDefault(a => a.UserID == userId);
            ShoppingAddress amod = new ShoppingAddress()
            {
                UserId   = mod.UserID,
                Name     = mod.Name,
                Phone    = mod.Phone,
                Address  = mod.Address,
                IsDelect = true
            };

            EF.ShoppingAddresses.Add(amod);
            if (EF.SaveChanges() > 0)
            {
                return(amod);
            }
            return(null);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 根据重量生成配送方式(集合)
        /// </summary>
        /// <param name="orderProducts"></param>
        /// <param name="ShippingAddressID"></param>
        /// <returns></returns>
        public Dictionary <long, string> GenerateDeliveryModes(List <JsonOrderProduct> orderProducts, long ShippingAddressID)
        {
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                //用户收货地址
                ShoppingAddress shippingAddress = s.Get <ShoppingAddress>(ShippingAddressID);
                if (shippingAddress == null)
                {
                    throw new Exception("不存在该用户收货地址");
                }

                int weight = 0;

                foreach (JsonOrderProduct jop in orderProducts)
                {
                    ProductSku sku = s.Get <ProductSku>("where dbo.fn_check_specset(specset,@0) = 1 and product_id = @1", (jop.specset ?? ""), jop.product_id);
                    weight += sku.weight * jop.qty;
                }

                //配送方式实体类
                List <DeliveryMode> modes = s.List <DeliveryMode>("", "");

                //配送方式以及运费集合
                Dictionary <long, string> deliveryMode = new Dictionary <long, string>();
                decimal price = 0, first_price = 0, add_price = 0;

                foreach (DeliveryMode m in modes)
                {
                    //获取当前配送方式运费模板
                    FreightTemplate fTemplate = s.Get <FreightTemplate>(m.freight_template_id);

                    if (fTemplate != null)
                    {
                        //默认首重价格
                        first_price = fTemplate.default_first_price;
                        //默认续重价格
                        add_price = fTemplate.default_add_price;

                        //特殊地区按特殊地区价格算
                        FreightRegion fRegion = s.Get <FreightRegion>("where region_name like '%'+@0+'%' and freight_template_id = @1 ", shippingAddress.province, fTemplate.id);
                        if (fRegion != null)
                        {
                            if (weight < fRegion.first_weight)
                            {
                                price = fRegion.first_price;
                            }
                            else
                            {
                                decimal t = (((weight - fRegion.first_weight) / fRegion.add_weight) + ((weight - fRegion.first_weight) % fRegion.add_weight) == 0 ? 0 : 1) * fRegion.add_price;
                                price = weight <= fRegion.first_weight ? fRegion.first_price : t + fRegion.first_price;
                            }
                        }
                        else
                        {
                            if (weight < fTemplate.first_weight)
                            {
                                price = fTemplate.default_first_price;
                            }
                            else
                            {
                                decimal tmp = (((weight - fTemplate.first_weight) / fTemplate.add_weight) + ((weight - fTemplate.first_weight) % fTemplate.add_weight) == 0 ? 0 : 1) * add_price;
                                price = weight <= fTemplate.first_weight ? first_price : Math.Ceiling((decimal)(weight - fTemplate.first_weight) / (decimal)fTemplate.add_weight) * add_price + first_price;
                            }
                        }

                        deliveryMode.Add(m.id, string.Format("{0}: {1}", m.name, price.ToString("f2")));
                    }
                }
                return(deliveryMode);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 根据重量生成配送方式(最小运费)
        /// </summary>
        /// <param name="orderProducts"></param>
        /// <param name="shippingAddressID"></param>
        /// <returns></returns>
        public string GetDeliveryModeFreight(List <JsonOrderProduct> orderProducts, long shippingAddressID)
        {
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                //用户收货地址
                ShoppingAddress shippingAddress = s.Get <ShoppingAddress>(shippingAddressID);
                if (shippingAddress == null)
                {
                    throw new Exception("不存在该用户收货地址");
                }

                decimal price = 0, first_price = 0, add_price = 0;
                decimal pricetmp = 0;
                long    defaultModeID = 0, modeID = 0, weight = 0;

                foreach (JsonOrderProduct jop in orderProducts)
                {
                    Product pdt = s.Get <Product>(jop.product_id);
                    //排除包邮商品
                    if (pdt != null && !pdt.is_postage)
                    {
                        ProductSku sku = s.Get <ProductSku>("where dbo.fn_check_specset(specset,@0) = 1 and product_id = @1", jop.specset ?? "", jop.product_id);
                        weight += sku.weight * jop.qty;
                    }
                }

                //配送方式实体类
                List <DeliveryMode> modes = s.List <DeliveryMode>("", "");

                foreach (DeliveryMode m in modes)
                {
                    //记录当前配送方式ID
                    modeID = m.id;

                    //获取当前配送方式运费模板
                    FreightTemplate fTemplate = s.Get <FreightTemplate>(m.freight_template_id);

                    if (fTemplate != null)
                    {
                        //默认首重价格
                        first_price = fTemplate.default_first_price;
                        //默认续重价格
                        add_price = fTemplate.default_add_price;

                        //获取特殊区域
                        FreightRegion fRegion = s.Get <FreightRegion>("where region_name like '%'+@0+'%' and freight_template_id = @1 ", shippingAddress.province, fTemplate.id);
                        if (fRegion != null)
                        {
                            if (weight < fRegion.first_weight)
                            {
                                pricetmp = fRegion.first_price;
                            }
                            else
                            {
                                decimal t = (((weight - fRegion.first_weight) / fRegion.add_weight) + ((weight - fRegion.first_weight) % fRegion.add_weight) == 0 ? 0 : 1) * fRegion.add_price;
                                pricetmp = weight <= fRegion.first_weight ? fRegion.first_price : t + fRegion.first_price;
                            }
                        }

                        if (weight < fTemplate.first_weight)
                        {
                            price = fTemplate.default_first_price;
                        }
                        else
                        {
                            decimal tmp = (((weight - fTemplate.first_weight) / fTemplate.add_weight) + ((weight - fTemplate.first_weight) % fTemplate.add_weight) == 0 ? 0 : 1) * add_price;
                            price = weight <= fTemplate.first_weight ? first_price : Math.Ceiling((decimal)(weight - fTemplate.first_weight) / (decimal)fTemplate.add_weight) * add_price + first_price;
                        }

                        //最小价格
                        if (price < pricetmp)
                        {
                            pricetmp      = price;
                            defaultModeID = m.id;
                        }
                    }
                }

                defaultModeID = defaultModeID == 0 ? modeID : defaultModeID;
                price         = price < pricetmp ? price : pricetmp == 0 ? price : pricetmp;

                return(defaultModeID + "#" + (int)price);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 根据重量生成配送方式
        /// 默认配送方式
        /// </summary>
        /// <param name="orderProducts"></param>
        /// <param name="shippingAddressID"></param>
        /// <returns></returns>
        public StateCode GetDefaultFreight(List <JsonOrderProduct> orderProducts, long shippingAddressID, out string result)
        {
            result = "";
            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                //用户收货地址
                ShoppingAddress shippingAddress = s.Get <ShoppingAddress>(shippingAddressID);
                if (shippingAddress == null)
                {
                    return(StateCode.State_252);
                }

                //配送方式实体类
                DeliveryMode mode = s.Get <DeliveryMode>("where is_default = @0", true);
                if (mode == null)
                {
                    return(StateCode.State_251);
                }

                decimal price = 0, first_price = 0, add_price = 0;
                long    weight = 0;

                foreach (JsonOrderProduct jop in orderProducts)
                {
                    Product pdt = s.Get <Product>(new string[] { "id", "is_postage" }, "where id = @0", jop.product_id);
                    //排除包邮商品
                    if (pdt != null && !pdt.is_postage)
                    {
                        ProductSku sku = s.Get <ProductSku>("where dbo.fn_check_specset(specset,@0) = 1 and product_id = @1", jop.specset ?? "", jop.product_id);
                        weight += sku.weight * jop.qty;
                    }
                }

                //获取当前配送方式运费模板
                FreightTemplate fTemplate = s.Get <FreightTemplate>(mode.freight_template_id);

                if (fTemplate != null && weight > 0)
                {
                    //默认首重价格
                    first_price = fTemplate.default_first_price;
                    //默认续重价格
                    add_price = fTemplate.default_add_price;

                    //特殊地区按特殊地区价格算
                    FreightRegion fRegion = s.Get <FreightRegion>("where region_name like '%'+@0+'%' and freight_template_id = @1 ", shippingAddress.province, fTemplate.id);
                    if (fRegion != null)
                    {
                        if (weight < fRegion.first_weight)
                        {
                            price = fRegion.first_price;
                        }
                        else
                        {
                            decimal t = (((weight - fRegion.first_weight) / fRegion.add_weight) + (((weight - fRegion.first_weight) % fRegion.add_weight) == 0 ? 0 : 1)) * fRegion.add_price;
                            price = weight <= fRegion.first_weight ? fRegion.first_price : t + fRegion.first_price;
                        }
                    }
                    else
                    {
                        if (weight < fTemplate.first_weight)
                        {
                            price = fTemplate.default_first_price;
                        }
                        else
                        {
                            decimal tmp = (((weight - fTemplate.first_weight) / fTemplate.add_weight) + (((weight - fTemplate.first_weight) % fTemplate.add_weight) == 0 ? 0 : 1)) * add_price;
                            price = weight <= fTemplate.first_weight ? first_price : Math.Ceiling((decimal)(weight - fTemplate.first_weight) / (decimal)fTemplate.add_weight) * add_price + first_price;
                        }
                    }
                }

                result = mode.id + "#" + price;

                return(StateCode.State_200);
            }
        }
Ejemplo n.º 8
0
        public void TestInitializer()
        {
            ShoppingAddress address1 = new ShoppingAddress
            {
                ShoppingAddressID = 1,
                Name    = "Jason",
                UserID  = "123456",
                Line1   = "Orchard Rd",
                City    = "Seattle",
                State   = "WA",
                Country = "US",
                Zip     = "91823",
                Orders  = new List <Order>()
                {
                    new Order {
                        OrderID = 1, ShoppingAddressID = 1, Date = Convert.ToDateTime("01/02/2016")
                    },
                    new Order {
                        OrderID = 3, ShoppingAddressID = 1, Date = Convert.ToDateTime("05/10/2016")
                    }
                }
            };

            ShoppingAddress address2 = new ShoppingAddress
            {
                ShoppingAddressID = 2,
                Name    = "Jason",
                UserID  = "123456",
                Line1   = "Smith St",
                City    = "Tacoma",
                State   = "WA",
                Country = "US",
                Zip     = "94323",
                Orders  = new List <Order>()
                {
                    new Order {
                        OrderID = 4, ShoppingAddressID = 2, Date = Convert.ToDateTime("08/12/2016")
                    }
                }
            };

            ShoppingAddress address3 = new ShoppingAddress
            {
                ShoppingAddressID = 5,
                UserID            = "556293",
                Name    = "Smith",
                Line1   = "Lake Way",
                City    = "San Jose",
                State   = "CA",
                Country = "US",
                Zip     = "34823",
                Orders  = new List <Order>()
                {
                    new Order {
                        OrderID = 2, ShoppingAddressID = 5, Date = Convert.ToDateTime("03/02/2016")
                    }
                }
            };

            IQueryable <User> userData = new List <User>()
            {
                new User {
                    Id = "123456", UserName = "******", Addresses = new List <ShoppingAddress>()
                    {
                        address1, address2
                    }
                },
                new User {
                    Id = "556293", UserName = "******", Addresses = new List <ShoppingAddress>()
                    {
                        address3
                    }
                }
            }.AsQueryable();

            Mock <DbSet <User> > userMockSet = new Mock <DbSet <User> >();

            userMockSet.As <IDbAsyncEnumerable <User> >().Setup(m => m.GetAsyncEnumerator())
            .Returns(new TestDbAsyncEnumerator <User>(userData.GetEnumerator()));
            userMockSet.As <IQueryable <User> >().Setup(m => m.Provider)
            .Returns(new TestDbAsyncQueryProvider <User>(userData.Provider));
            userMockSet.As <IQueryable <User> >().Setup(m => m.Expression).Returns(userData.Expression);
            userMockSet.As <IQueryable <User> >().Setup(m => m.ElementType).Returns(userData.ElementType);
            userMockSet.As <IQueryable <User> >().Setup(m => m.GetEnumerator()).Returns(userData.GetEnumerator());

            userMockSet.Setup(m => m.FindAsync(It.IsAny <object[]>())).
            Returns <object[]>(x => {
                return(Task.FromResult(userData.FirstOrDefault(b => b.Id == (String)x[0])));
            });

            orderData = new List <Order>()
            {
                new Order {
                    OrderID = 1, ShoppingAddressID = 1, Date = Convert.ToDateTime("01/02/2016"), Status = OrderStatus.Processing
                },
                new Order {
                    OrderID = 2, ShoppingAddressID = 5, Date = Convert.ToDateTime("03/02/2016"), Status = OrderStatus.Received
                },
                new Order {
                    OrderID = 3, ShoppingAddressID = 1, Date = Convert.ToDateTime("05/10/2016"), Status = OrderStatus.Processing
                },
                new Order {
                    OrderID = 4, ShoppingAddressID = 2, Date = Convert.ToDateTime("08/12/2016"), Status = OrderStatus.Shipped
                }
            }.AsQueryable();

            orderMockSet = new Mock <DbSet <Order> >();
            orderMockSet.Setup(x => x.Add(It.IsAny <Order>())).Verifiable();
            orderMockSet.Setup(x => x.Find(It.IsAny <Object[]>())).
            Returns <Object[]>(x => orderData.FirstOrDefault(o => o.OrderID == (int)x[0]));

            mockContext = new Mock <StoreDbContext>();
            mockContext.Setup(x => x.Users).Returns(userMockSet.Object);
            mockContext.Setup(x => x.Orders).Returns(orderMockSet.Object);

            orderRepo = new OrderRepository(mockContext.Object);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 新增定单
        /// </summary>
        /// <param name="orderProduct"></param>
        /// <param name="isShoppingCart"></param>
        /// <param name="productOrder"></param>
        /// <param name="addressID"></param>
        /// <returns></returns>
        public StateCode Save(List <JsonOrderProduct> orderProduct, ProductOrder productOrder, long addressID, bool isShoppingCart)
        {
            string  freight_str    = "";
            decimal freight        = 0;
            long    deliveryModeID = 0;

            //如果是自提则不计算运费
            if (productOrder.logistic_method == 0)
            {
                StateCode code = ServiceIoc.Get <DeliveryModeService>().GetDefaultFreight(orderProduct, addressID, out freight_str);
                if (code != StateCode.State_200)
                {
                    return(code);
                }
                //运费
                freight = decimal.Parse(freight_str.Split('#')[1]);
                //运费模板ID
                deliveryModeID = int.Parse(freight_str.Split('#')[0]);
            }

            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                try
                {
                    s.StartTransaction();

                    //订单商品较验
                    foreach (var op in orderProduct)
                    {
                        //较验商品规格是否存在
                        ProductSku sku = s.Get <ProductSku>("where product_id = @0 and dbo.fn_check_specset(specset,@1) = 1 ", op.product_id, op.specset);
                        if (sku == null)
                        {
                            productOrder = null;
                            s.RollBack();
                            return(StateCode.State_1);
                        }

                        //较验商品是否存在
                        Product product = s.Get <Product>("where id = @0 ", sku.product_id);
                        if (product == null)
                        {
                            productOrder = null;
                            s.RollBack();
                            return(StateCode.State_1);
                        }

                        //较验商品库存
                        if (op.qty > sku.stock)
                        {
                            productOrder = null;
                            s.RollBack();
                            return(StateCode.State_502);
                        }

                        //较验商品状态
                        if (!((bool)product.is_shelves && !(bool)product.is_delete && (DateTime.Now > product.shelves_sdate && DateTime.Now < product.shelves_edate)))
                        {
                            productOrder = null;
                            s.RollBack();
                            return(StateCode.State_505);
                        }

                        //商品库存处理
                        sku.stock = sku.stock - op.qty;
                        s.Update <ProductSku>(sku);
                    }

                    //创建订单
                    productOrder.serial_no        = AlgorithmHelper.CreateNo();
                    productOrder.status           = OrderStatus.WaitingPayment;
                    productOrder.delete_status    = 0;
                    productOrder.created_date     = DateTime.Now;
                    productOrder.total_amount     = 0;
                    productOrder.actual_amount    = 0;
                    productOrder.cost_price       = 0;
                    productOrder.delivery_mode_id = deliveryModeID;
                    s.Insert <ProductOrder>(productOrder);

                    //总金额,成本价,优惠卷金额
                    decimal totalProdutPrice = 0, costProdutPrice = 0;

                    //商品的总重量,包邮商品的总重量
                    int total_weight = 0, sum_total_weight = 0;

                    int index = 0;

                    foreach (var op in orderProduct)
                    {
                        //商品规格
                        ProductSku sku = s.Get <ProductSku>("where product_id = @0 and dbo.fn_check_specset(specset,@1) = 1", op.product_id, op.specset);
                        //商品
                        Product product = s.Get <Product>(sku.product_id);

                        string[]      arr      = StringHelper.StringToArray(sku.specset);
                        StringBuilder specinfo = new StringBuilder();
                        foreach (string i in arr)
                        {
                            int specname_id  = 0;
                            int specvalue_id = 0;
                            if (i.IndexOf("_") != -1)
                            {
                                int.TryParse(i.Split('_')[0], out specname_id);
                                int.TryParse(i.Split('_')[1], out specvalue_id);

                                SpecName  specname  = s.Get <SpecName>("where id = @0 ", specname_id);
                                SpecValue specvalue = s.Get <SpecValue>("where id = @0 ", specvalue_id);

                                if (specname != null && specvalue != null)
                                {
                                    specinfo.Append(string.Format("{0}:{1}; ", specname.name, specvalue.val));
                                }
                                else
                                {
                                    throw new Exception("商品规格信息异常");
                                }
                            }
                        }

                        //当前当商品成本
                        decimal cost_sum = sku.cost_price * op.qty;

                        //押金
                        decimal sum = sku.sale_price * op.qty;

                        totalProdutPrice += sum;
                        costProdutPrice  += cost_sum;

                        //该商品是否包邮
                        if (!product.is_postage)
                        {
                            sum_total_weight += sku.weight * op.qty;
                        }

                        //计算重量
                        total_weight += sku.weight * op.qty;

                        //获取产品主图片
                        string     mainPic  = "";
                        List <Img> pictures = s.List <Img>("where biz_type = @0 and biz_id = @1", ImgType.Product_Cover, product.id);
                        Img        img      = pictures.Where(p => p.is_main).SingleOrDefault();
                        if (img != null)
                        {
                            mainPic = img.is_webimg ? img.webimg_url : img.getThmImgUrl();
                        }

                        //创建订单明细
                        ProductOrderDetail orderDetail = new ProductOrderDetail()
                        {
                            order_id        = productOrder.id,
                            product_id      = product.id,
                            specset         = op.specset,
                            product_name    = product.name,
                            product_en_name = product.en_name,
                            product_img_url = mainPic,
                            spec_msg        = specinfo.ToString().Trim(),
                            unit_price      = sku.sale_price,
                            count           = op.qty,
                            total_weight    = sku.weight * op.qty,
                            order_index     = ++index,
                            cost_price      = cost_sum,
                            total_amount    = sum,
                            actual_amount   = sum
                        };
                        s.Insert(orderDetail);

                        //购物车删除商品
                        if (isShoppingCart)
                        {
                            s.ExcuteUpdate("delete tb_ord_shoppingcart where user_id = @0 and product_id = @1 and dbo.fn_check_specset(specset,@2) = 1", productOrder.created_user_id, orderDetail.product_id, orderDetail.specset ?? "");
                        }
                    }

                    #region 会员折扣模块

                    //会员折扣优惠金额
                    decimal discount = 0;
                    //累计消费金额
                    object user_total_amount = s.ExecuteScalar("select COALESCE(SUM(total_amount),0) from tb_odr_order where created_user_id = @0 and is_pay = @1", productOrder.created_user_id, true);
                    //累计消费金额
                    decimal amount = decimal.Parse(user_total_amount.ToString());

                    //获取等级列表
                    List <MemberLevelSetting> levels = s.List <MemberLevelSetting>("order by total_amount desc");
                    foreach (var level in levels)
                    {
                        if (amount >= level.total_amount)
                        {
                            discount = totalProdutPrice * (100 - level.discount) / 100;
                            break;
                        }
                    }

                    //会员折扣
                    productOrder.discount_amount = discount;
                    #endregion

                    #region 优惠卷模块

                    if (productOrder.user_coupon_id != 0)
                    {
                        //存在未使用的优惠卷
                        string     coupon_sql = "where id = @0 and is_used = @1 and full_amount <= @2";
                        UserCoupon userCoupon = s.Get <UserCoupon>(coupon_sql, productOrder.user_coupon_id, false, totalProdutPrice);
                        if (userCoupon != null)
                        {
                            //优惠卷金额
                            productOrder.coupon_amount = userCoupon.coupon_amount;
                            //修改会员优惠卷状态
                            s.ExcuteUpdate("update tb_user_aty_coupon set is_used = @0 where id = @1", true, userCoupon.id);
                        }
                    }

                    #endregion

                    #region 发货单

                    ShoppingAddress sa = s.Get <ShoppingAddress>(addressID);
                    if (sa == null)
                    {
                        throw new Exception("收货地址不存在");
                    }

                    //订单发货信息
                    OrderDelivery orderDelivery = new OrderDelivery();
                    orderDelivery.order_id    = productOrder.id;
                    orderDelivery.province    = sa.province;
                    orderDelivery.city        = sa.city;
                    orderDelivery.area        = sa.area;
                    orderDelivery.address     = sa.address;
                    orderDelivery.contact     = sa.contact;
                    orderDelivery.mobile      = sa.mobile;
                    orderDelivery.postal_code = sa.postal_code;
                    orderDelivery.tel         = sa.tel;

                    s.Insert <OrderDelivery>(orderDelivery);
                    #endregion

                    //总计金额(商品总金额+物流费用)
                    var totalPrice = totalProdutPrice + freight;
                    //成本价
                    productOrder.cost_price = costProdutPrice;
                    //配送费
                    productOrder.freight = freight;
                    //总金额
                    productOrder.total_amount = totalPrice;
                    //实付金额
                    productOrder.actual_amount = totalPrice - productOrder.coupon_amount - discount;
                    //总重量
                    productOrder.total_weight = total_weight;
                    //更新订单
                    s.Update <ProductOrder>(productOrder);

                    s.Commit();

                    return(StateCode.State_200);
                }
                catch (Exception ex)
                {
                    s.RollBack();
                    return(StateCode.State_500);
                }
            }
        }